[Tutor] Can someone help me start learning how to code?

2018-03-30 Thread Deniz Baydemir
I want to know where to start and if i can get assigned homework maybe?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Indexing values as a step in mesa model?

2018-03-30 Thread S L
 Hi all,

Very new to this so please excuse my errors.

I want to create an agent based model using the mesa package (Python 3.6.3)
to model solar generation, electricity use and grid exports. Ultimately I
would like agents (households) to interact (ie trading energy between
homes).

For the first iteration of the model I want to show outcomes **without**
interaction between agents, using a sample of real consumption and
generation data. I.e. for each step (i), each household (j) will
generate/use electricity based on the real world data series, i.e.,
indexing the corresponding consumption and generation values for that
particular household at time period i.

Here is a snippet of the dataframes with consumption and generation data
(gen values are all zero because time periods are at night):

>>con
  Customer  1  2
0 1  0.287  1.207
1 2  0.278  0.193
2 3  0.051  0.063


>>gen
   Customer  Capacity123
0 1  3.78  0.0  0.0  0.0
1 2  1.62  0.0  0.0  0.0
2 3  1.00  0.0  0.0  0.0

Column headings refer to time periods (t=1, t=2, etc). Capacity = battery
capacity (which I will ignore for the moment).

How do I define a 'step' such that for each customer number (unique id) and
time period, the model indexes the appropriate consumption and generation
values for that time period, and adds them to that agent? The correct row
will always be the customer's unique id - 1, but the column will change
with each step (i.e. for customer 1, at t=1 the consumption value should be
0.287, at t=2 it should be 1.207 and so on.


Here is a sample of my code so far:

class PowerAgent(Agent):
def __init__(self, unique_id, model):
super().__init__(unique_id, model)
self.use = 0
self.gen = 0

def step(self):
self.use += con.iloc[unique_id-1, <>]
self.gen += gen.iloc[unique_id-1, <> ]


Would appreciate pointers. I'm new to Python and mesa so all help is
welcomed with much gratitude.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] XML parsing

2018-03-30 Thread Asif Iqbal
On Thu, Mar 29, 2018 at 3:41 PM, Peter Otten <__pete...@web.de> wrote:

> Asif Iqbal wrote:
>
> > On Thu, Mar 29, 2018 at 3:56 AM, Peter Otten <__pete...@web.de> wrote:
> >
> >> Asif Iqbal wrote:
> >>
> >> > I am trying to extract all the *template-name*s, but no success yet
> >> >
> >> > Here is a sample xml file
> >> >
> >> > http://tail-f.com/ns/rest";>
> >> >   http://networks.com/nms";>
> >> > ALLFLEX-BLOOMINGTON
> >> > post-staging
> >> > full-mesh
> >> > ALLFLEX
> >> > http://networks.com/nms";>
> >> >   advanced-plus
> >> >   1000
> >> >   true
> >> >   true
> >> > 
> >> > 
> >> > 
> >> >
> >> > with open('/tmp/template-metadata') as f:
> >> > import xml.etree.ElementTree as ET
> >> > root = ET.fromstring(f.read())
> >> >
> >> > print len(root)
> >> > print root[0][0].text
> >> > for l in root.findall('template-metadata'):
> >> > print l
> >> >
> >> >
> >> > 392
> >> > ALLFLEX-BLOOMINGTON
> >> >
> >> >
> >> > It prints the length of the tree and the first element of the first
> >> child,
> >> > but when I try to loop through to find all the 'template-name's
> >> > it does not print anything.
> >> >
> >> > What am I doing wrong?
> >>
> >> You have to include the namespace:
> >>
> >> for l in root.findall('{http://networks.com/nms}template-metadata'):
> >>
> >
> > How do I extract the 'template-name' ?
>
> I hoped you'd get the idea.
>
> > This is what I tried
> >
> >  for l in root.findall('{http://networks.com/nms}template-metadata'):
>
> Rinse and repeat:
>
> > print l.find('template-name').text
>
> should be
>
> print l.find('{http://networks.com/nms}template-name').text
>
> >
> > I am following the doc
> > https://docs.python.org/2/library/xml.etree.elementtree.html section
> > 19.7.1.3 findall example
> >
> > I get this error attribute error 'NoneType' object has no attribute text.
> > I do not understand why l.find('template-name') is NoneType.
>
> Take the time to read
>
> https://docs.python.org/2/library/xml.etree.elementtree.
> html#parsing-xml-with-namespaces


Thanks for the links and hints.

I got it working now

I used ns = { 'nms' : 'http://networks.com/nms
' }

And then l.find('nms:template-name', ns)

I also want to extract the namespace and I see this gets me the namespace

  str(root[0]).split('{')[1].split('}')[0]

Is there a better way to extract the name space?




>
>
> > Here is complete code with output.
> >
> >
> > import xml.etree.ElementTree as ET
> >
> > xmlfile='''
> > http://tail-f.com/ns/rest";>
> >   http://networks.com/nms";>
> > ALLFLEX-BLOOMINGTON
> > post-staging
> > full-mesh
> > ALLFLEX
> > http://networks.com/nms";>
> >   advanced-plus
> >   1000
> >   true
> >   true
> > '''
> >
> > root = ET.fromstring(xmlfile)
> > print root.tag
> > print root[0][0].text
> > for l in root.findall('{http://networks.com/nms}template-metadata'):
> > print l.find('template-name').text
> >
> > collection
> > ALLFLEX-BLOOMINGTON
> >
> >
> 
> ---
> AttributeError
> >Traceback (most recent call
> > last) in () 19 print
> > root[0][0].text 20 for l in
> > root.findall('{http://networks.com/nms}template-metadata'):---> 21
> > print l.find('template-name').text
> > AttributeError: 'NoneType' object has no attribute 'text'
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



-- 
Asif Iqbal
PGP Key: 0xE62693C5 KeyServer: pgp.mit.edu
A: Because it messes up the order in which people normally read text.
Q: Why is top-posting such a bad thing?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] XML parsing

2018-03-30 Thread Asif Iqbal
On Thu, Mar 29, 2018 at 9:40 PM, Asif Iqbal  wrote:

>
>
> On Thu, Mar 29, 2018 at 3:41 PM, Peter Otten <__pete...@web.de> wrote:
>
>> Asif Iqbal wrote:
>>
>> > On Thu, Mar 29, 2018 at 3:56 AM, Peter Otten <__pete...@web.de> wrote:
>> >
>> >> Asif Iqbal wrote:
>> >>
>> >> > I am trying to extract all the *template-name*s, but no success yet
>> >> >
>> >> > Here is a sample xml file
>> >> >
>> >> > http://tail-f.com/ns/rest";>
>> >> >   http://networks.com/nms";>
>> >> > ALLFLEX-BLOOMINGTON
>> >> > post-staging
>> >> > full-mesh
>> >> > ALLFLEX
>> >> > http://networks.com/nms";>
>> >> >   advanced-plus
>> >> >   1000
>> >> >   true
>> >> >   true
>> >> > 
>> >> > 
>> >> > 
>> >> >
>> >> > with open('/tmp/template-metadata') as f:
>> >> > import xml.etree.ElementTree as ET
>> >> > root = ET.fromstring(f.read())
>> >> >
>> >> > print len(root)
>> >> > print root[0][0].text
>> >> > for l in root.findall('template-metadata'):
>> >> > print l
>> >> >
>> >> >
>> >> > 392
>> >> > ALLFLEX-BLOOMINGTON
>> >> >
>> >> >
>> >> > It prints the length of the tree and the first element of the first
>> >> child,
>> >> > but when I try to loop through to find all the 'template-name's
>> >> > it does not print anything.
>> >> >
>> >> > What am I doing wrong?
>> >>
>> >> You have to include the namespace:
>> >>
>> >> for l in root.findall('{http://networks.com/nms}template-metadata'):
>> >>
>> >
>> > How do I extract the 'template-name' ?
>>
>> I hoped you'd get the idea.
>>
>> > This is what I tried
>> >
>> >  for l in root.findall('{http://networks.com/nms}template-metadata'):
>>
>> Rinse and repeat:
>>
>> > print l.find('template-name').text
>>
>> should be
>>
>> print l.find('{http://networks.com/nms}template-name').text
>>
>> >
>> > I am following the doc
>> > https://docs.python.org/2/library/xml.etree.elementtree.html section
>> > 19.7.1.3 findall example
>> >
>> > I get this error attribute error 'NoneType' object has no attribute
>> text.
>> > I do not understand why l.find('template-name') is NoneType.
>>
>> Take the time to read
>>
>> https://docs.python.org/2/library/xml.etree.elementtree.html
>> #parsing-xml-with-namespaces
>
>
> Thanks for the links and hints.
>
> I got it working now
>
> I used ns = { 'nms' : 'http://networks.com/nms
> ' }
>
> And then l.find('nms:template-name', ns)
>
> I also want to extract the namespace and I see this gets me the namespace
>
>   str(root[0]).split('{')[1].split('}')[0]
>
> Is there a better way to extract the name space?
>
>
>
This worked

ns = { 'nms' : root[0].tag.split('}')[0].split('{')[1] }

for l in root.findall('nms:template-metadata', ns):
print l.find('nms:template-name', ns).text

Although I think manually creating the ns dictionary looks cleaner :-)





>
>>
>>
>> > Here is complete code with output.
>> >
>> >
>> > import xml.etree.ElementTree as ET
>> >
>> > xmlfile='''
>> > http://tail-f.com/ns/rest";>
>> >   http://networks.com/nms";>
>> > ALLFLEX-BLOOMINGTON
>> > post-staging
>> > full-mesh
>> > ALLFLEX
>> > http://networks.com/nms";>
>> >   advanced-plus
>> >   1000
>> >   true
>> >   true
>> > '''
>> >
>> > root = ET.fromstring(xmlfile)
>> > print root.tag
>> > print root[0][0].text
>> > for l in root.findall('{http://networks.com/nms}template-metadata'):
>> > print l.find('template-name').text
>> >
>> > collection
>> > ALLFLEX-BLOOMINGTON
>> >
>> >
>> 
>> ---
>> AttributeError
>> >Traceback (most recent call
>> > last) in () 19 print
>> > root[0][0].text 20 for l in
>> > root.findall('{http://networks.com/nms}template-metadata'):---> 21
>> > print l.find('template-name').text
>> > AttributeError: 'NoneType' object has no attribute 'text'
>>
>>
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> https://mail.python.org/mailman/listinfo/tutor
>>
>
>
>
> --
> Asif Iqbal
> PGP Key: 0xE62693C5 KeyServer: pgp.mit.edu
> A: Because it messes up the order in which people normally read text.
> Q: Why is top-posting such a bad thing?
>
>


-- 
Asif Iqbal
PGP Key: 0xE62693C5 KeyServer: pgp.mit.edu
A: Because it messes up the order in which people normally read text.
Q: Why is top-posting such a bad thing?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] pythonic

2018-03-30 Thread Alan Gauld via Tutor
On 30/03/18 03:48, Pat Martin wrote:

> the "right" way to do it in python?

More or less, a couple of comments below...

> def Main():

Python function names begin with a lowercase letter by convention.

> """Run if run as a program."""
> parser = argparse.ArgumentParser()
...

> 
> now = datetime.datetime.now()
> slug = args.title.replace(" ", "-").lower()
> 
> with open("{}.md".format(slug), 'w') as f:
> f.write("Title: {}\n".format(args.title))
> f.write("Date: {}-{}-{} {}:{}\n".format(now.year,
> now.month,
> now.day,
> now.hour,
> now.minute))

Formatting of dates and times is usually done using
the time.strftime function which is specifically
designed for that. It might be worth taking a peek
at the docs on that one. You can call it directly
on a datetime object - 'now' in your case:

fmt="%Y-%m-%d %H:%M\n"
f.write(now.strftime(fmt))


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] XML parsing

2018-03-30 Thread Stefan Behnel
Asif Iqbal schrieb am 30.03.2018 um 03:40:
> On Thu, Mar 29, 2018 at 3:41 PM, Peter Otten wrote:
>> Asif Iqbal wrote:
>>> On Thu, Mar 29, 2018 at 3:56 AM, Peter Otten wrote:
 Asif Iqbal wrote:
> Here is a sample xml file
>
> http://tail-f.com/ns/rest";>
>   http://networks.com/nms";>
> ALLFLEX-BLOOMINGTON
> post-staging
> full-mesh
> ALLFLEX
> http://networks.com/nms";>
>   advanced-plus
>   1000
>   true
>   true
> 
> 
> 
>
> with open('/tmp/template-metadata') as f:
> import xml.etree.ElementTree as ET
> root = ET.fromstring(f.read())

Don't use fromstring() here, use "parse(f).getroot()". The first loads the
whole file step by step into a string in memory, then parses it, and then
throws the string away. The second directly loads and parses the file step
by step.


> I also want to extract the namespace and I see this gets me the namespace
> 
>   str(root[0]).split('{')[1].split('}')[0]
> 
> Is there a better way to extract the name space?

Yes: don't. ;)

Normally, you write code *for* concrete XML namespaces, not code that
extracts arbitrary namespaces from XML. I'm saying that because people
misunderstand this up all the time, and assume that they need to extract
information from namespaces (or even from namespace prefixes!). But without
knowing the namespace upfront, the XML data is actually meaningless. And if
you know the namespace anyway, why would you need to extract it from the data?

I admit that I'm being a bit strict here, there are certainly cases where
parsing the namespace from a tag is a sensible thing to do. I'm really just
saying that most of the time, when you feel the need to do that, it's worth
reconsidering (or asking) if you are doing the right thing.

Stefan

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] pythonic

2018-03-30 Thread Peter Otten
Pat Martin wrote:

> I have written the following program. It generates a template for Pelican
> web site static generator. It works just fine, it generates the template
> and then I put the info in it to customize. But I was wondering, is this
> the "right" way to do it in python?

You may rewrite the code creating the output as a loop:

now_str = now.replace(microsecond=0).isoformat(" ")
with open("{}.md".format(slug), 'w') as f:
for name, value in [
("Title", args.title),
("Date", now_str),
("Modified", now_str),
("Category", args.category),
("Slug", slug),
("Authors", args.author),
("Summary", ""),
]:
print(name, value, sep=": ", file=f)


If you want to format more than one date the same way you should put the 
code into a function, no matter whether you pick your, my, or Alan's much 
more common way to implement it

def format_time(dt):
   return ...

...
("Date", format_time(now)),
("Modified", format_time(modified)),
...

The idea behind my suggestions is the DRY (don't repeat yourself) principle 
which applies to code written in any language.

> #!/usr/bin/env python3
> """Generate a Pelican markdown base page."""
> 
> import argparse
> import datetime
> 
> 
> def Main():
> """Run if run as a program."""
> parser = argparse.ArgumentParser()
> parser.add_argument("-T", "--title", type=str, required=True,
> help='Title for site, also generates the slug',
> metavar="")
> parser.add_argument("-c", "--category", required=True,
> help='Category or categories of post', metavar="")
> parser.add_argument("-t", "--tags", type=str, required=True,
> help="Tags for post", metavar="")
> parser.add_argument("-a", "--author", type=str, default="Pat Martin",
> help="Author of post", metavar="")
> args = parser.parse_args()
> 
> now = datetime.datetime.now()
> slug = args.title.replace(" ", "-").lower()
> 
> with open("{}.md".format(slug), 'w') as f:
> f.write("Title: {}\n".format(args.title))
> f.write("Date: {}-{}-{} {}:{}\n".format(now.year,
> now.month,
> now.day,
> now.hour,
> now.minute))
> f.write("Modified: {}-{}-{} {}:{}\n".format(now.year,
> now.month,
> now.day,
> now.hour,
> now.minute))
> f.write("Category: {}\n".format(args.category))
> f.write("Slug: {}\n".format(slug))
> f.write("Authors: {}\n".format(args.author))
> f.write("Summary: \n")
> 
> 
> if __name__ == "__main__":
> Main()


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Indexing values as a step in mesa model?

2018-03-30 Thread Steven D'Aprano
On Fri, Mar 30, 2018 at 02:06:15PM +1100, S L wrote:
>  Hi all,
> 
> Very new to this so please excuse my errors.
> 
> I want to create an agent based model using the mesa package (Python 3.6.3)

Unfortunately, when you start asking questions about third-party 
libraries, especially fairly niche technical ones like mesa, you're 
unlikely to get a good answer on generic mailing lists or forums like 
this.

You might be lucky and get a good response from a mesa expert, but I'd 
never even heard of it before now, so it won't be me, sorry.

I suggest that while you wait for an answer, you also try googling for a 
specialised mesa forum.

Good luck!


-- 
Steve
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] pythonic

2018-03-30 Thread George Fischhof
2018-03-30 4:48 GMT+02:00 Pat Martin :

> Hello all,
>
> I have written the following program. It generates a template for Pelican
> web site static generator. It works just fine, it generates the template
> and then I put the info in it to customize. But I was wondering, is this
> the "right" way to do it in python?
>
> #!/usr/bin/env python3
> """Generate a Pelican markdown base page."""
>
> import argparse
> import datetime
>
>
> def Main():
> """Run if run as a program."""
> parser = argparse.ArgumentParser()
> parser.add_argument("-T", "--title", type=str, required=True,
> help='Title for site, also generates the slug',
> metavar="")
> parser.add_argument("-c", "--category", required=True,
> help='Category or categories of post', metavar="")
> parser.add_argument("-t", "--tags", type=str, required=True,
> help="Tags for post", metavar="")
> parser.add_argument("-a", "--author", type=str, default="Pat Martin",
> help="Author of post", metavar="")
> args = parser.parse_args()
>
> now = datetime.datetime.now()
> slug = args.title.replace(" ", "-").lower()
>
> with open("{}.md".format(slug), 'w') as f:
> f.write("Title: {}\n".format(args.title))
> f.write("Date: {}-{}-{} {}:{}\n".format(now.year,
> now.month,
> now.day,
> now.hour,
> now.minute))
> f.write("Modified: {}-{}-{} {}:{}\n".format(now.year,
> now.month,
> now.day,
> now.hour,
> now.minute))
> f.write("Category: {}\n".format(args.category))
> f.write("Slug: {}\n".format(slug))
> f.write("Authors: {}\n".format(args.author))
> f.write("Summary: \n")
>
>
> if __name__ == "__main__":
> Main()
>
>
>
> Thanks for any input.
>
> WP
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



Hi Pat,

my thoughts:


1.)
def Main():

function names are written with small letter with underscore between the
words
check PEP-8
https://www.python.org/dev/peps/pep-0008/
http://docs.python-guide.org/en/latest/writing/style/

It is better to name the functions according to what they do, in this case
for example: create_template() or something like that


2.)
argparse

it is good, but you can write more Pythonic code using click
https://pypi.python.org/pypi/click/
it is also Pythonic to use / know the Python ecosystem (the packages)


3.)
with open("{}.md".format(slug), 'w') as f:
   f.write("Date: {}-{}-{} {}:{}\n".format(now.year,
now.month,

Python is mainly about readability
https://www.python.org/dev/peps/pep-0020/

you can use more meaningful variable names: template_file instead of f
if you have Python 3.6, you can use the newest formatting method, which is
more readable:
template_file.write(f"Date: {now.moth}-{now.day}") etc

https://www.python.org/dev/peps/pep-0498/

the more readable open:
slug_file_name = f"{slug}.md"
with open(slug_file_name, "w") as slug_file:

and if you use Python 3, the open should contain encoding:
with open(slug_file_name, "w", encoding="UTF-8") as slug_file:


BR,
George
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] XML parsing

2018-03-30 Thread Neil Cerutti
On 2018-03-30, Stefan Behnel  wrote:
> I admit that I'm being a bit strict here, there are certainly
> cases where parsing the namespace from a tag is a sensible
> thing to do. I'm really just saying that most of the time, when
> you feel the need to do that, it's worth reconsidering (or
> asking) if you are doing the right thing.

Namespaces hurt my head when I try to imagine a use for them. The
only one's I've encountered are just applied to an entire
document, making parsing more inconvenient but providing no other
benefit I can see.

-- 
Neil Cerutti

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] pythonic

2018-03-30 Thread Pat Martin
Thank you all for the ideas and comments, it is appreciated.

I have some refactoring to do now.

On Fri, Mar 30, 2018 at 2:22 AM, Peter Otten <__pete...@web.de> wrote:

> Pat Martin wrote:
>
> > I have written the following program. It generates a template for Pelican
> > web site static generator. It works just fine, it generates the template
> > and then I put the info in it to customize. But I was wondering, is this
> > the "right" way to do it in python?
>
> You may rewrite the code creating the output as a loop:
>
> now_str = now.replace(microsecond=0).isoformat(" ")
> with open("{}.md".format(slug), 'w') as f:
> for name, value in [
> ("Title", args.title),
> ("Date", now_str),
> ("Modified", now_str),
> ("Category", args.category),
> ("Slug", slug),
> ("Authors", args.author),
> ("Summary", ""),
> ]:
> print(name, value, sep=": ", file=f)
>
>
> If you want to format more than one date the same way you should put the
> code into a function, no matter whether you pick your, my, or Alan's much
> more common way to implement it
>
> def format_time(dt):
>return ...
>
> ...
> ("Date", format_time(now)),
> ("Modified", format_time(modified)),
> ...
>
> The idea behind my suggestions is the DRY (don't repeat yourself) principle
> which applies to code written in any language.
>
> > #!/usr/bin/env python3
> > """Generate a Pelican markdown base page."""
> >
> > import argparse
> > import datetime
> >
> >
> > def Main():
> > """Run if run as a program."""
> > parser = argparse.ArgumentParser()
> > parser.add_argument("-T", "--title", type=str, required=True,
> > help='Title for site, also generates the slug',
> > metavar="")
> > parser.add_argument("-c", "--category", required=True,
> > help='Category or categories of post',
> metavar="")
> > parser.add_argument("-t", "--tags", type=str, required=True,
> > help="Tags for post", metavar="")
> > parser.add_argument("-a", "--author", type=str, default="Pat Martin",
> > help="Author of post", metavar="")
> > args = parser.parse_args()
> >
> > now = datetime.datetime.now()
> > slug = args.title.replace(" ", "-").lower()
> >
> > with open("{}.md".format(slug), 'w') as f:
> > f.write("Title: {}\n".format(args.title))
> > f.write("Date: {}-{}-{} {}:{}\n".format(now.year,
> > now.month,
> > now.day,
> > now.hour,
> > now.minute))
> > f.write("Modified: {}-{}-{} {}:{}\n".format(now.year,
> > now.month,
> > now.day,
> > now.hour,
> > now.minute))
> > f.write("Category: {}\n".format(args.category))
> > f.write("Slug: {}\n".format(slug))
> > f.write("Authors: {}\n".format(args.author))
> > f.write("Summary: \n")
> >
> >
> > if __name__ == "__main__":
> > Main()
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] XML parsing

2018-03-30 Thread Stefan Behnel
Neil Cerutti schrieb am 30.03.2018 um 15:50:
> On 2018-03-30, Stefan Behnel wrote:
>> I admit that I'm being a bit strict here, there are certainly
>> cases where parsing the namespace from a tag is a sensible
>> thing to do. I'm really just saying that most of the time, when
>> you feel the need to do that, it's worth reconsidering (or
>> asking) if you are doing the right thing.
> 
> Namespaces hurt my head when I try to imagine a use for them. The
> only one's I've encountered are just applied to an entire
> document, making parsing more inconvenient but providing no other
> benefit I can see.

Actually, namespaces give meaning to data, and they allow combining
different XML languages into one document. Without them, it would be
impossible to tell, for example, that what a document contains is an author
name in Dublin Core metadata and not an image subtitle. Or a base64 encoded
inline image. Or anything. They allow you to cleanly extract an SVG image
from an ODF document without implementing the OpenDocument standard first.

Namespaces enable reuse of well defined semantics, in the same way that you
would structure your code in functions and modules, instead of stuffing
everything in the main module as plain top-level code.

Stefan

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] really basic py/regex

2018-03-30 Thread bruce
Hi.

Trying to quickly get the re.match()  to extract the groups from the string.

x="MATH 59900/40 [47490] - THE "

The regex has to return MATH, 59900, 40,, and 47490

d=re.match(r'(\D+)...) gets the MATH...

But I can't see (yet) how to get the rest of what I need...

Pointers would be useful.

Thanks
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] XML parsing

2018-03-30 Thread Neil Cerutti
On 2018-03-30, Stefan Behnel  wrote:
> Neil Cerutti schrieb am 30.03.2018 um 15:50:
>> On 2018-03-30, Stefan Behnel wrote:
>>> I admit that I'm being a bit strict here, there are certainly
>>> cases where parsing the namespace from a tag is a sensible
>>> thing to do. I'm really just saying that most of the time, when
>>> you feel the need to do that, it's worth reconsidering (or
>>> asking) if you are doing the right thing.
>> 
>> Namespaces hurt my head when I try to imagine a use for them. The
>> only one's I've encountered are just applied to an entire
>> document, making parsing more inconvenient but providing no other
>> benefit I can see.
>
> Actually, namespaces give meaning to data, and they allow
> combining different XML languages into one document. Without
> them, it would be impossible to tell, for example, that what a
> document contains is an author name in Dublin Core metadata and
> not an image subtitle. Or a base64 encoded inline image. Or
> anything. They allow you to cleanly extract an SVG image from
> an ODF document without implementing the OpenDocument standard
> first.
>
> Namespaces enable reuse of well defined semantics, in the same
> way that you would structure your code in functions and
> modules, instead of stuffing everything in the main module as
> plain top-level code.

Thanks for the explanation.

-- 
Neil Cerutti

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] creating a connection class

2018-03-30 Thread Glenn Schultz

All,

I can create a connection as follows and it works but I think it is best to 
have a connection class that opens and closes.  I create the connection class 
as outline below.  However, it does not work - meaning that it does not return 
a connection rather it returns 
<__main__.modelingdb at 0x40dfbb0>

Any help getting the connection class to work is greatly appreciated.

Glenn

model_prod_conn = pyodbc.connect(
driver = '{ODBC Driver 13 for SQL Server}',
server = 'foo',
database = 'foo',
username = 'foo',
password = 'foo',
trusted_connection = 'yes')


class modelingdb(object):
  def __init__(self):
   self._db_connection = pyodbc.connect(
   driver = '{ODBC Driver 13 for SQL Server}',
   server = 'foo',
   database = 'foo',
   username = 'foo',
   password = 'foo',
   trusted_connection = 'yes')
   self._db_cur = self._db_connection.cursor()

def __del__(self):
self._db_connection.close()


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] creating a connection class

2018-03-30 Thread Alan Gauld via Tutor
On 30/03/18 15:55, Glenn Schultz wrote:

> I can create a connection as follows and it works 

Well done, so you get a connection object back as a result.

> but I think it is best to have a connection class that opens and closes.  

Why? You already have a connection object.
Classes are created so that you can create instances.
What would an instance of your Connection class offer
that the API connection object does not?

Creating classes introduces significant effort and
overhead, if you don't need them don't build them.
If the instances of your class don't contribute
some new functionality what is their point? The
more code you create the more likely that there
is a bug.

> model_prod_conn = pyodbc.connect(
> driver = '{ODBC Driver 13 for SQL Server}',
> server = 'foo',
> database = 'foo',
> username = 'foo',
> password = 'foo',
> trusted_connection = 'yes')
> 
> 
> class modelingdb(object):
>   def __init__(self):
>    self._db_connection = pyodbc.connect(
>    driver = '{ODBC Driver 13 for SQL Server}',
>    server = 'foo',
>    database = 'foo',
>    username = 'foo',
>    password = 'foo',
>    trusted_connection = 'yes')
>    self._db_cur = self._db_connection.cursor()
> 
> def __del__(self):
> self._db_connection.close()

There is a great talk somewhere on YouTube that
provides guidance on when not to create a class.
One of the cases is when you only have constructor
and destructor.

You may want to continue as an academic exercise in
wrapping an API object. That's fair enough. But your
current class offers nothing that the API does not.
(The db_cur attribute doesn't really count since
it's just a call to the connection object anyway.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] creating a connection class

2018-03-30 Thread Steven D'Aprano
On Fri, Mar 30, 2018 at 02:55:14PM +, Glenn Schultz wrote:
> All,
> 
> I can create a connection as follows and it works but I think it is best to 
> have a connection class that opens and closes.

You already have one: that's what pyodbc.connect is.

The documentation is pretty poor:

https://github.com/mkleehammer/pyodbc/wiki/Connection

but as far as I can tell, pyodbc is a helper function which chooses the 
correct class to instantiate depending on the database you connect 
to, and returns an instance of that class.

In Design Pattern terms, I think that counts as an Abstract Factory.

> I create the connection 
> class as outline below.  However, it does not work - meaning that it does 
> not return a connection rather it returns 
> <__main__.modelingdb at 0x40dfbb0>

When you call the class, you get back an instance of that class. That's 
exactly what you have there: an instance of your modelingdb class.


> class modelingdb(object):
>   def __init__(self):
>    self._db_connection = pyodbc.connect(
>    driver = '{ODBC Driver 13 for SQL Server}',
>    server = 'foo',
>    database = 'foo',
>    username = 'foo',
>    password = 'foo',
>    trusted_connection = 'yes')
>    self._db_cur = self._db_connection.cursor()
> 
> def __del__(self):
> self._db_connection.close()

The indentation on this is wrong, so that code won't work.

Also, you cannot rely on __del__ in Python classes. This is totally the 
wrong way to use this.

Can I guess that you're a Java or C++ programmer trying to learn Python? 
Wrapping the connection object in another object is not helpful: you're 
just duplicating (poorly) what's already been done.

If you are new to Python from a Java background, you might find some 
things take a bit of getting used to. These things may help:


Python is not Java.

http://dirtsimple.org/2004/12/python-is-not-java.html

And Java is not Python either.

http://dirtsimple.org/2004/12/java-is-not-python-either.html)

Classes are not the centre of the Python universe:

https://www.youtube.com/watch?v=o9pEzgHorH0

We try to use more functional and even procedural techniques, but don't 
worry, classes are still okay

http://lucumr.pocoo.org/2013/2/13/moar-classes/

its just the crazy-extreme attitude that *everything* must *always* be a 
class that we object to.

http://steve-yegge.blogspot.com.au/2006/03/execution-in-kingdom-of-nouns.html


-- 
Steve
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor