Re: [Tutor] Verifying My Troublesome Linkage Claim between Python and Win7

2010-02-28 Thread Alan Gauld


"Wayne Watson"  wrote
incoherency.  For what it's worth, and that's about zero, I'm working 
with my old XP and W7 machine's keyboards, mice and monitors 
side-by-side. I have several times found my self using the wrong device.


In that situation I find it useful to make the old environment as hostile 
as possible.

So I'd make the resolution on the XP box something like 800x600 and set the
wallpaper to a garish colour like red. That way I never mistake which 
machine

I'm on!

FWIW I do the same with the root account on Unix boxes...

That makes sure I spend as little time as possible in the environment
that I don't want to stay in.

HTH,


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 



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


[Tutor] CGI File Uploads

2010-02-28 Thread Giorgio
Hi,

today i need some help with the python manual.

I've found this fileupload example
http://webpython.codepoint.net/cgi_file_upload on that site.

It's taking from fileitem attributes like filename and file.

Where is the complete list of those attributes or methods?

Thankyou

-- 
--
AnotherNetFellow
Email: anothernetfel...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Verifying My Troublesome Linkage Claim between Python and Win7

2010-02-28 Thread Dave Angel



Wayne Watson wrote:



You tell us to "try this" and give a folder structure:

Folder1
 track1.py
 data1.txt
 data2.txt
 data3.txt
Folder2
 track1.py
 dset1.txt
 dset2.txt
 ...
 dset8.txt



Maybe one simple test at a time will get better responses.  Since you 
wouldn't tell me what tabs you saw in Explorer when you did properties, 
maybe you'll tell me what you see in CMD.


Go to a cmd prompt (DOS prompt), change to the Folder2 directory, and 
type dir.   paste that result, all of it, into a message.  I suspect 
you'll see that you don't have track1.py there at all, but track1.py.lnk


If so, that's a shortcut.  The only relevant change in Win7 that I know 
of is that Explorer shows shortcuts as "link" rather than "shortcut."



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


[Tutor] Any Tutor there ? Removing redundant parameters in a models file having include files.

2010-02-28 Thread Karim Liateni


Hello Tutor,

Since Friday I get no answers to my first post.
So I re-post it was missed by the numerous arriving email:

This is my first program in python.

I am doing electrical simulation in spectre (spice like).
I have a models file which holds many parameters and
include files of parameters. But in batch mode the automatic
construction (by the simulator) of this file is not correct.
It concatenates both parameters and include files with the same
parameters definitions. That trigs errors during simulation and
it complains about parameters double definition.

The program must removes includes files of already existing parameters 
in the models file.


The file format is shown below:

// --
// Mismatch Variations Selection
// --
parameters param1=0
parameters param2=0
parameters param3=0
parameters param4=0
// --
// Global Flags Definition
// --
parameters gflag_param = 0
// --
// Models Library Files References
// --
include "/project/hvt.scs" section=TT
include "/project/lvt.scs" section=TT
include "/project/svt.scs" section=TT
include "/project/veriloga.scs"  section=typ
include "/project/switch_all.scs" section=no
---

Now my code is shown below:
___

#!/usr/bin/env python
# File: correctCorners K.Liateni 2010-02-25

import re

# ---
#  Functions Declaration
# ---

def copy(infile, outfile):
  """Copy of the content of an input file to an outputfile."""
  fout = open(outfile, 'w')
  fout.writelines(getLines(infile))
  fout.close()

def cat(lines, outfile):
  """Concat the content of a strings list to an outputfile."""
  f = open(outfile, 'w')
  f.writelines(lines)
  f.close()

def getLines(file):
  """Get the content of a file in a lines list form."""
  f = open(file, 'r')
  lines = f.readlines()
  f.close()
  return lines

def isParamExist(file, pattern, parameters):
  """Check if a particular regex pattern parameter is existing in a 
parameters file."""

  lines = getLines(file)
  paramExpressions = [ e for e in lines if pattern.search(e) ]
  matchParam   = [ e for e in paramExpressions if 
pattern.search(e).group(1) in parameters ]

  if matchParam:
return True
  else:
return False

# ---
#  Main Start here
# ---

parRe = '^[ \t]*(parameters[ \t]+[^ \t]+)[ \t]*='
comRe = '^[ \t]*//'

include = re.compile(incRe)
param   = re.compile(parRe)
comment = re.compile(comRe)

lines = getLines("models.scs")

linesWithNoInclude = [ e for e in lines if not include.search(e) ]
linesWithNoParam   = [ e for e in lines if not param.search(e) and not 
comment.search(e) ]


parameters   = [ param.search(e).group(1)   for e in linesWithNoInclude 
if param.search(e) ]

includeFiles = [ include.search(e).group(1) for e in linesWithNoParam ]

includeFilesToWrite = [ e for e in includeFiles if not 
isParamExist(e, param, parameters) ]
includeFilesToWrite = [ e for e in linesWithNoParam if 
include.search(e).group(3) in includeFilesToWrite ]


cat(linesWithNoInclude+includeFilesToWrite, "models_modified.scs")
copy("models_modified.scs", "models.scs"):

# --- end of file --- #

The code works well but I am not fully happy with it. 
includeFilesToWrite is computed in 2 steps.
I am pretty sure that it can be simplify by using a dictionnary with the 
full path file as the key
and the string 'include' nominal line expression as the value to 
construct the final file with filtered include.
I am using python 2.2 so I have not use latest feature I want my code to 
run on old Solaris too (linux user).


I use as much as possible list comprehension following your advices.

I don't like the part:
 if matchParam:
return True
  else:
return False
Is there an easy way to do the same behavior. I am not sure but I saw 
one time something like using
the int value of True (1) and False (0) to select return value in a list 
of 2 elements 'return [False,True](matchParam)'

Is it correct?

Thanks a lot
Karim


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

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


Re: [Tutor] Omitting lines matching a list of strings from a file

2010-02-28 Thread galaxywatcher
 One formatting detail: there is a blank line after each line  
printed, how do I ged rid of the extra blank lines?


lines = [line.strip() for line in infile if line[146:148] not in  
omit_states]

print '\n'.join(lines)


This approach stripped leading blank spaces introducing errors into my  
fixed width file.



or alternatively

lines = [line for line in infile if line[146:148] not in omit_states]
print ''.join(lines)


This works beautifully leaving leading blank spaces intact. Thanks.

Just remember that doing a list comprehension like that on a large  
file will drastically reduce the speed of your application as well  
as introduce memory bloat.


Processing a file with well over 1 million records worked very  
quickly, several seconds. Did not notice excessive memory bloat. I do  
have 2 gigs of ram on my Macbook  Pro however.


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


Re: [Tutor] Any Tutor there ? Removing redundant parameters in a models file having include files.

2010-02-28 Thread Alan Gauld

"Karim Liateni"  wrote


It concatenates both parameters and include files with the same
parameters definitions. That trigs errors during simulation and
it complains about parameters double definition.


I'd suggest you construct a dictionary based on the param names
You can check before you add ca param if one already exists.
Or alternatively make a Set of param names and check that
for existence before adding a new one.


def copy(infile, outfile):
  """Copy of the content of an input file to an outputfile."""
  fout = open(outfile, 'w')
  fout.writelines(getLines(infile))
  fout.close()


Its probably easier tyo use shutil.copyfile()


def cat(lines, outfile):
  """Concat the content of a strings list to an outputfile."""
  f = open(outfile, 'w')
  f.writelines(lines)
  f.close()




def getLines(file):
  """Get the content of a file in a lines list form."""
  f = open(file, 'r')
  lines = f.readlines()
  f.close()
  return lines


I'm not sure these functions add enough value to ghave them. I';d probably 
just use


try: open(outfile,'w').writelines(lines)
except IOError: #handle error

try: lines = open(filename).readlines()
except IOError: #handle error

The close will be done automatically since you don't hold a reference to 
the file



def isParamExist(file, pattern, parameters):
  """Check if a particular regex pattern parameter is existing in a 
parameters file."""

  lines = getLines(file)
  paramExpressions = [ e for e in lines if pattern.search(e) ]
  matchParam   = [ e for e in paramExpressions if 
pattern.search(e).group(1) in parameters ]

  if matchParam:
return True
  else:
return False


return bool(matchParam) instead of the if/else


I am pretty sure that it can be simplify by using a dictionnary with the 
full path file as the key
and the string 'include' nominal line expression as the value to 
construct the final file with filtered include.


I think dictionaries or Sets could improve things


I don't like the part:
 if matchParam:
return True
  else:
return False


See the note above.

HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 



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


Re: [Tutor] CGI File Uploads

2010-02-28 Thread Alan Gauld


"Giorgio"  wrote


It's talking from fileitem attributes like filename and file.

Where is the complete list of those attributes or methods?


Probably on a web page somewhere but you are probably 
better using the help() function and dir() to examine an 
instance from the >>> prompt.


HTH,


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/

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


Re: [Tutor] CGI File Uploads

2010-02-28 Thread Giorgio
Alan, i don't know how to use it in this case.

import cgi
form = cgi.FieldStorage()
fileitem = form['file']
fileitem.file.read()

Function dir() lists all functions in a module, i could only use it for
"cgi" O_O.

Thankyou

2010/2/28 Alan Gauld 

>
> "Giorgio"  wrote
>
>  It's talking from fileitem attributes like filename and file.
>>
>>
>> Where is the complete list of those attributes or methods?
>>
>
> Probably on a web page somewhere but you are probably better using the
> help() function and dir() to examine an instance from the >>> prompt.
>
> HTH,
>
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
--
AnotherNetFellow
Email: anothernetfel...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Any Tutor there ? Removing redundant parameters in a models file having include files.

2010-02-28 Thread Lie Ryan
On 03/01/10 01:12, Alan Gauld wrote:
> 
>> def getLines(file):
>>   """Get the content of a file in a lines list form."""
>>   f = open(file, 'r')
>>   lines = f.readlines()
>>   f.close()
>>   return lines
> 
> I'm not sure these functions add enough value to ghave them. I';d
> probably just use
> 
> try: open(outfile,'w').writelines(lines)
> except IOError: #handle error
> 
> try: lines = open(filename).readlines()
> except IOError: #handle error
> 
> The close will be done automatically since you don't hold a reference to
> the file

Remember why we have the new with-block? It's precisely because files
will be automagically closed only if we're running on CPython; Python
the language and thus alternative implementations doesn't guarantee
automatic closing. I'd agree with the function having minimal utility
value though:

with open(file) as f:
lines = f.readlines()
# f.close() will be called by the context manager

and if you're just copying to another file:

from contextlib import nested
with nested(open(infile), open(outfile, 'w')) as (fin, fout):
fout.write(fin.read())

or even better, as Alan suggested, using shutil.copyfile().

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


Re: [Tutor] Any Tutor there ? Removing redundant parameters in a models file having include files.

2010-02-28 Thread Karim Liateni


Hello Alan,


Alan Gauld wrote:

"Karim Liateni"  wrote


It concatenates both parameters and include files with the same
parameters definitions. That trigs errors during simulation and
it complains about parameters double definition.


I'd suggest you construct a dictionary based on the param names
You can check before you add ca param if one already exists.
Or alternatively make a Set of param names and check that
for existence before adding a new one.

Yes if I made it with Awk I would definitely use dictionary.
I was focused on list comprehension...First I wanted it to work
even if the method is 'awkward'. Now I will improve it for efficiency.




def copy(infile, outfile):
  """Copy of the content of an input file to an outputfile."""
  fout = open(outfile, 'w')
  fout.writelines(getLines(infile))
  fout.close()


Its probably easier tyo use shutil.copyfile().


Thank you I was certain the function already exist!
But I did not know in which package.




def cat(lines, outfile):
  """Concat the content of a strings list to an outputfile."""
  f = open(outfile, 'w')
  f.writelines(lines)
  f.close()




def getLines(file):
  """Get the content of a file in a lines list form."""
  f = open(file, 'r')
  lines = f.readlines()
  f.close()
  return lines


I'm not sure these functions add enough value to have them. I';d 
probably just use


try: open(outfile,'w').writelines(lines)
except IOError: #handle error

try: lines = open(filename).readlines()
except IOError: #handle error

The close will be done automatically since you don't hold a reference 
to the file




I don't like to repeat code. Is it ok to take your corrections and write 
something like (not exactly the final code but approaching:


def cat(lines, outfile):
 """Concat the content of a strings list to an outputfile."""
 try: open(outfile,'w').writelines(lines)
 except IOError: #handle error

def getLines(file):
 """Get the content of a file in a lines list form."""
 try: lines = open(filename).readlines() ; return lines
 except IOError: #handle error


But In the first form I understand the close is not needed but in the 
second 'lines = open(filename).readlines()'
I don't hold indirectly a reference to the file? Please, could you 
explain more this point?



def isParamExist(file, pattern, parameters):
  """Check if a particular regex pattern parameter is existing in a 
parameters file."""

  lines = getLines(file)
  paramExpressions = [ e for e in lines if pattern.search(e) ]
  matchParam   = [ e for e in paramExpressions if 
pattern.search(e).group(1) in parameters ]

  if matchParam:
return True
  else:
return False


return bool(matchParam) instead of the if/else


One more times thanks! That was I have been searching for.




I am pretty sure that it can be simplify by using a dictionnary with 
the full path file as the key
and the string 'include' nominal line expression as the value to 
construct the final file with filtered include.


I think dictionaries or Sets could improve things


My next goal.




I don't like the part:
 if matchParam:
return True
  else:
return False


See the note above.

HTH,


Alan, I am your obligé. Your remarks are very instructive.

Regards
Karim


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


Re: [Tutor] Any Tutor there ? Removing redundant parameters in a models file having include files.

2010-02-28 Thread Karim Liateni

Lie Ryan wrote:

On 03/01/10 01:12, Alan Gauld wrote:
  

def getLines(file):
  """Get the content of a file in a lines list form."""
  f = open(file, 'r')
  lines = f.readlines()
  f.close()
  return lines
  

I'm not sure these functions add enough value to ghave them. I';d
probably just use

try: open(outfile,'w').writelines(lines)
except IOError: #handle error

try: lines = open(filename).readlines()
except IOError: #handle error

The close will be done automatically since you don't hold a reference to
the file



Remember why we have the new with-block? It's precisely because files
will be automagically closed only if we're running on CPython; Python
the language and thus alternative implementations doesn't guarantee
automatic closing. I'd agree with the function having minimal utility
value though:

with open(file) as f:
lines = f.readlines()
# f.close() will be called by the context manager

and if you're just copying to another file:

from contextlib import nested
with nested(open(infile), open(outfile, 'w')) as (fin, fout):
fout.write(fin.read())

or even better, as Alan suggested, using shutil.copyfile().

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

  
Thank you Lie but I have a restriction on the python version I must use 
v2.2.

This feature is available only on later version 2.5 I believe.

Regards
Karim

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


Re: [Tutor] CGI File Uploads

2010-02-28 Thread ALAN GAULD


> Alan, i don't know how to use it in this case.
> 

> import cgi
> form = cgi.FieldStorage()
> fileitem = form['file']


> Function dir() lists all functions in a module, i could only use it for "cgi" 

It will list all the names in any kind of object not just a module.
If you type the code above at the >>> prompt you should be 
able to do:


>>> import cgi
>>> form = cgi.FieldStorage()
>>> help(form)

OR, You could go more directly using

>>> import cgi
>>> help(cgi.FieldStorage)


HTH

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


Re: [Tutor] Any Tutor there ? Removing redundant parameters in a models file having include files.

2010-02-28 Thread Lie Ryan
On 03/01/10 02:49, Karim Liateni wrote:
> Lie Ryan wrote:
>> On 03/01/10 01:12, Alan Gauld wrote:
>>   
 def getLines(file):
   """Get the content of a file in a lines list form."""
   f = open(file, 'r')
   lines = f.readlines()
   f.close()
   return lines
   
>>> I'm not sure these functions add enough value to ghave them. I';d
>>> probably just use
>>>
>>> try: open(outfile,'w').writelines(lines)
>>> except IOError: #handle error
>>>
>>> try: lines = open(filename).readlines()
>>> except IOError: #handle error
>>>
>>> The close will be done automatically since you don't hold a reference to
>>> the file
>>> 
>>
>> Remember why we have the new with-block? It's precisely because files
>> will be automagically closed only if we're running on CPython; Python
>> the language and thus alternative implementations doesn't guarantee
>> automatic closing. I'd agree with the function having minimal utility
>> value though:
>>
>> with open(file) as f:
>> lines = f.readlines()
>> # f.close() will be called by the context manager
>>
>> and if you're just copying to another file:
>>
>> from contextlib import nested
>> with nested(open(infile), open(outfile, 'w')) as (fin, fout):
>> fout.write(fin.read())
>>
>> or even better, as Alan suggested, using shutil.copyfile().
>>
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>   
> Thank you Lie but I have a restriction on the python version I must use
> v2.2.
> This feature is available only on later version 2.5 I believe.

Then you should at the least use the try-finally block, I think that one
has been there since 2.2? If you didn't use try-finally, there is no
guarantee that f.close() would be called if an exception happened in the
middle of reading/writing (e.g. KeyboardInterrupt, or perhaps user
plugging off the thumbdrive, or bit more realistic having a full
harddisk or exceeded some disk quota)

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


Re: [Tutor] Any Tutor there ? Removing redundant parameters in a models file having include files.

2010-02-28 Thread Karim Liateni

Lie Ryan wrote:

On 03/01/10 02:49, Karim Liateni wrote:
  

Lie Ryan wrote:


On 03/01/10 01:12, Alan Gauld wrote:
  
  

def getLines(file):
  """Get the content of a file in a lines list form."""
  f = open(file, 'r')
  lines = f.readlines()
  f.close()
  return lines
  
  

I'm not sure these functions add enough value to ghave them. I';d
probably just use

try: open(outfile,'w').writelines(lines)
except IOError: #handle error

try: lines = open(filename).readlines()
except IOError: #handle error

The close will be done automatically since you don't hold a reference to
the file



Remember why we have the new with-block? It's precisely because files
will be automagically closed only if we're running on CPython; Python
the language and thus alternative implementations doesn't guarantee
automatic closing. I'd agree with the function having minimal utility
value though:

with open(file) as f:
lines = f.readlines()
# f.close() will be called by the context manager

and if you're just copying to another file:

from contextlib import nested
with nested(open(infile), open(outfile, 'w')) as (fin, fout):
fout.write(fin.read())

or even better, as Alan suggested, using shutil.copyfile().

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

  
  

Thank you Lie but I have a restriction on the python version I must use
v2.2.
This feature is available only on later version 2.5 I believe.



Then you should at the least use the try-finally block, I think that one
has been there since 2.2? If you didn't use try-finally, there is no
guarantee that f.close() would be called if an exception happened in the
middle of reading/writing (e.g. KeyboardInterrupt, or perhaps user
plugging off the thumbdrive, or bit more realistic having a full
harddisk or exceeded some disk quota)

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

  

Thank you Lie.
Yes, in fact I did it all the time during my years of Java development.
In perl I used or open() or die( "msg" ) structure.
I bypassed it because I wanted to construct the blocs very quickly like 
a 'beginner'.
I was excited to make it work as fast as ossible to see if I can program 
something

decent in Python. (gaining confidence? haaa human nature!).

I definitely enjoy python (and not very far in spirit my loving Lisp).
I definitely HATE tcl, java.

Now I will improve quality and robustness.

Thanks a lot!

Karim

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


[Tutor] Over-riding radians as default for trig calculations

2010-02-28 Thread AG

After importing the math module and running

math.cos( x )

the result is in radians.

Is there a way of setting this so that it results in degrees?  I don't 
want to over-ride this permanently for my Python settings, so am happy 
to specifically do it per equation or per program.


Thanks in advance.

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


Re: [Tutor] Over-riding radians as default for trig calculations

2010-02-28 Thread Hugo Arts
On Sun, Feb 28, 2010 at 8:39 PM, AG  wrote:
> After importing the math module and running
>
> math.cos( x )
>
> the result is in radians.
>
> Is there a way of setting this so that it results in degrees?  I don't want
> to over-ride this permanently for my Python settings, so am happy to
> specifically do it per equation or per program.
>
> Thanks in advance.
>

There is no setting to override, but you could easily define your own
function to do a conversion for you. The wikipedia page on radians
explains how to convert between the two, and writing a function to do
that should be quite trivial.

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


Re: [Tutor] Over-riding radians as default for trig calculations

2010-02-28 Thread Steven D'Aprano
On Mon, 1 Mar 2010 06:39:10 am AG wrote:
> After importing the math module and running
>
> math.cos( x )
>
> the result is in radians.

It certainly is not. The *result* of cos is a unitless number, not an 
angle.

What you mean is that the *input* to cos, x, has to be supplied in 
radians. No, you can't change that anywhere, but you can do this:

>>> math.cos(math.radians(45))
0.70710678118654757

So of course you can write your own function:

def cos(x):
return math.cos(math.radians(x))

and call that.



-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] OOD - Another class question

2010-02-28 Thread James Reynolds
I have another question related to OOD. What I have is a module with one
parent class and two child classes. Some stuff is done to the object that is
passed to the function in one of the child classes and this then calls a
function from the global class passing local variables (from the child
class).

When I do this, I am told: AttributeError: 'HillBuilder' object has no
attribute 'MountainBuilder'

The question is, what am I doing wrong?

Here is an example:

class MountainBuilder(object):
def __init__(self, mountain):
self.mountain = mountain
self.mountain_func
   self.pinetree_func


  def pinetree_func(self, knoll)
do stuff to knoll
return knoll


  def mountain_func(self, hill)
knoll = hill * 2
pinetree = pintree_func(knoll)
return hill


class HillBuilder(MountainBuilder):
def __init__(self, mountain):
  OptionLoad.__init__(self, mountain)
  self.MountainBuilder.mountain_func
  self.hill_func


  def hill_func(self)
hill= do stuff to self.mountain
grassyknoll = MountainBuilder.mountain_func(hill)

return grassy knoll


do stuff with grassy knoll
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] OOD - Another class question

2010-02-28 Thread Steve Willoughby
On Sun, Feb 28, 2010 at 06:24:09PM -0500, James Reynolds wrote:
> I have another question related to OOD. What I have is a module with one
> parent class and two child classes. Some stuff is done to the object that is
> passed to the function in one of the child classes and this then calls a
> function from the global class passing local variables (from the child
> class).

I think you're confusing containers with inheritance.

> class MountainBuilder(object):
> def __init__(self, mountain):
> self.mountain = mountain
> self.mountain_func <--- what's this?
>self.pinetree_func  <--- what's this?
> 
> class HillBuilder(MountainBuilder):
> def __init__(self, mountain):
>   OptionLoad.__init__(self, mountain)
>   self.MountainBuilder.mountain_func

There is no MountainBuilder attribute in HillBuilder.  Rather,
HillBuilder is a refined type of a MountainBuilder, and inherits
everything MountainBuilders have, plus what you change or add
to that base in HillBuilder.  

You're treating it like it's a separate class which contains
a MountainBuilder object inside it as an attribute.

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


Re: [Tutor] Any Tutor there ? Removing redundant parameters in a models file having include files.

2010-02-28 Thread Alan Gauld


"Karim Liateni"  wrote


def getLines(file):
  try: lines = open(filename).readlines() ; return lines
  except IOError: #handle error


but in the second 'lines = open(filename).readlines()'
I don't hold indirectly a reference to the file? Please, could you 
explain more this point?


Sure, the lines variable holds a reference to the list returned by 
readlines.

There is no variable referring to the file object so immediately after
readlines completes the file will be ready to be closed (at least in
CPython as already pointed out by Lie)

HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 



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


Re: [Tutor] OOD - Another class question

2010-02-28 Thread Alan Gauld


"James Reynolds"  wrote

parent class and two child classes. Some stuff is done to the object that 
is

passed to the function in one of the child classes and this then calls a
function from the global class passing local variables (from the child
class).


You really need to tighten up on the terminology because the
imprecision is part of your problems understanding the concepts.

You pass an object to a method of a child class which calls
a method in the parent class. You pass instance variables
of the child class as arguments to the parent class method..


When I do this, I am told: AttributeError: 'HillBuilder' object has no
attribute 'MountainBuilder'



The question is, what am I doing wrong?


Confusing inheritance with composition.
Your child class does not have an attribute MountainBuilder,
it *is* a MountainBuilder. self within the method referes to your
subclass of MountainBuilder so you only need self.


class MountainBuilder(object):
 def pinetree_func(self, knoll)
   do stuff to knoll
   return knoll
 def mountain_func(self, hill)
   knoll = hill * 2
   pinetree = pintree_func(knoll)
   return hill

class HillBuilder(MountainBuilder):
def __init__(self, mountain):
 OptionLoad.__init__(self, mountain)
 self.MountainBuilder.mountain_func


This should be
   self.mountain_func(mountain)


 def hill_func(self)
   hill= do stuff to self.mountain
   grassyknoll = MountainBuilder.mountain_func(hill)


And this should be
 grassyknoll = self.mountain_func(hill)

mountain func as a method of MountainBuilder is also
a method of HillBuilder (thats what inheritance means)
so you access it through self.


Take a look at the BankAccount example in the OOP
topic of my tutor for more examples of subclasses
calling superclass methods

HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 



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


Re: [Tutor] Verifying My Troublesome Linkage Claim between Python and Win7

2010-02-28 Thread Wayne Watson

I just posted the details a moment ago to Steven.

On 2/28/2010 3:46 AM, Dave Angel wrote:



Wayne Watson wrote:



You tell us to "try this" and give a folder structure:

Folder1
 track1.py
 data1.txt
 data2.txt
 data3.txt
Folder2
 track1.py
 dset1.txt
 dset2.txt
 ...
 dset8.txt



Maybe one simple test at a time will get better responses.  Since you 
wouldn't tell me what tabs you saw in Explorer when you did 
properties, maybe you'll tell me what you see in CMD.


Go to a cmd prompt (DOS prompt), change to the Folder2 directory, and 
type dir.   paste that result, all of it, into a message.  I suspect 
you'll see that you don't have track1.py there at all, but track1.py.lnk


If so, that's a shortcut.  The only relevant change in Win7 that I 
know of is that Explorer shows shortcuts as "link" rather than 
"shortcut."






--
   Wayne Watson (Watson Adventures, Prop., Nevada City, CA)

 (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
  Obz Site:  39° 15' 7" N, 121° 2' 32" W, 2700 feet

   Stop the illegal killing of dolphins and porpoises.
 
  Wrest the control of the world's fisheries from Japan.

Web Page:

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


Re: [Tutor] Top posters for 2009

2010-02-28 Thread Christian Witts

Kent Johnson wrote:

It's not really about keeping score :-), but once again I've compiled
a list of the top 20 posters to the tutor list for the last year. For
2009, the rankings are

2009 (7730 posts, 709 posters)

Alan Gauld 969 (12.5%)
Kent Johnson 804 (10.4%)
Dave Angel 254 (3.3%)
spir 254 (3.3%)
Wayne Watson 222 (2.9%)
bob gailer 191 (2.5%)
Lie Ryan 186 (2.4%)
David 127 (1.6%)
Emile van Sebille 115 (1.5%)
Wayne 112 (1.4%)
Sander Sweers 111 (1.4%)
Serdar Tumgoren 100 (1.3%)
Luke Paireepinart 99 (1.3%)
wesley chun 99 (1.3%)
W W 74 (1.0%)
Marc Tompkins 72 (0.9%)
A.T.Hofkamp 71 (0.9%)
Robert Berman 68 (0.9%)
vince spicer 63 (0.8%)
Emad Nawfal 62 (0.8%)

Alan, congratulations, you pulled ahead of me for the first time in
years! You posted more than in 2008, I posted less. Overall posts are
up from last year, which was the slowest year since I started
measuring (2003).

Thank you to everyone who asks and answers questions here!

The rankings are compiled by scraping the monthly author pages from
the tutor archives, using Beautiful Soup to extract author names. I
consolidate counts for different capitalizations of the same name but
not for different spellings. The script is below.

Kent

''' Counts all posts to Python-tutor by author'''
# -*- coding: latin-1 -*-
from datetime import date, timedelta
import operator, urllib2
from BeautifulSoup import BeautifulSoup

today = date.today()

for year in range(2009, 2010):
startDate = date(year, 1, 1)
endDate = date(year, 12, 31)
thirtyOne = timedelta(days=31)
counts = {}

# Collect all the counts for a year by scraping the monthly author
archive pages
while startDate < endDate and startDate < today:
dateString = startDate.strftime('%Y-%B')

url = 'http://mail.python.org/pipermail/tutor/%s/author.html'
% dateString
data = urllib2.urlopen(url).read()
soup = BeautifulSoup(data)

li = soup.findAll('li')[2:-2]

for l in li:
name = l.i.string.strip()
counts[name] = counts.get(name, 0) + 1

startDate += thirtyOne

# Consolidate names that vary by case under the most popular spelling
nameMap = dict() # Map lower-case name to most popular name

# Use counts.items() so we can delete from the dict.
for name, count in sorted(counts.items(),
key=operator.itemgetter(1), reverse=True):
   lower = name.lower()
   if lower in nameMap:
  # Add counts for a name we have seen already and remove the duplicate
  counts[nameMap[lower]] += count
  del counts[name]
   else:
  nameMap[lower] = name

totalPosts = sum(counts.itervalues())
posters = len(counts)

print
print '%s (%s posts, %s posters)' % (year, totalPosts, posters)
print ''
for name, count in sorted(counts.iteritems(),
key=operator.itemgetter(1), reverse=True)[:20]:
pct = round(100.0*count/totalPosts, 1)
print '%s %s (%s%%)' % (name.encode('utf-8',
'xmlcharrefreplace'), count, pct)
print
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

  

Nice script Kent.
Keep up the good signal-to-noise ratio guys.

--
Kind Regards,
Christian Witts


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


Re: [Tutor] Verifying My Troublesome ...+Properties

2010-02-28 Thread Dave Angel

Wayne Watson wrote:
(I sent the msg below to Steven and the list a moment ago, since msgs 
going to the list with attachments either don't post or take lots of 
time to post, I'm sending both of you this copy.)


Steven, attached are three jpg files showing the properties of the two 
py files. The two files are identical in name, ReportingToolA.py,  and 
content, but are in folders .../Events2008_NovWW and .../events. Two 
of the jpg files are for the General Tab and Shortcut Tab of the py 
file in ../events. The other jpg is for the file in 
.../Events2008_NovWW, which has no shortcut tab. In previous 
descriptions, this is like:


Folder1 is Events2008_NovWW
Folder2 is events

I developed RT.py (ReportingToolA.py) in the .../Events2008_NovWW 
folder and copied it to ../events. The shortcut shows the events 
folder RT.py file is really in Events20008_WW


I have no idea why the RT.py file shows a shortcut. I just took a file 
called junk.jpg, and right-clicked on it. I selected Shortcut from the 
list, and it produced a file junk.jpg-shortcut. It is quite obvious 
the file name is different. If I select Copy instead, and paste the 
file into a folder called  Junk, there is no shortcut created. A drag 
and drop results in a move,and not a copy, so that's out of the picture.


I have no idea how the RT.py file ever got to be a shortcut.
As I said many messages ago, if your Properties dialog has a tab called 
Shortcut, then this is a shortcut file, not a python file.  I still 
don't know how you created it, but that's your "anomaly," not Windows 7, 
and certainly not Python.  Further, the name isn't  RT.py, since 
shortcuts have other extensions (such as .lnk) that Explorer hides from 
you, in its infinite "helpfulness."  It does give you several clues, 
however, such as the little arrow in the icon.  You can see that without 
even opening the properties window, but it's repeated in that window as 
well.


And Explorer is just a tool.  The command prompt should be your home 
base as a programmer.  When something goes wrong running a program from 
the either other ways, always check it at the command prompt, because 
every other tool has quirks it introduces into the equation.


My best guess on how you created that shortcut was by using Alt-Drag.  
As you point out, drag does a move by default, if it's on the same 
drive.  Ctrl-Drag will force a copy, even on the same drive.  And 
Shift-Drag will force a move, even if it's on a different drive.


These rules didn't change between XP and Windows 7, as far as I know, 
although in some places Explorer calls it "Link" instead of 
"Shortcut".   But that's just a self inconsistency.


DaveA

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