Re: [Tutor] basics of passing arguments to make a graph

2007-03-23 Thread Alan Gauld
"Che M" <[EMAIL PROTECTED]> wrote

> I've been trying to make basic plots (line graphs)
> using the pyplot module  in wxPython.

> class PlotPanel(wx.lib.plot.PlotCanvas):
> def __init__(self, *args, **kwargs):
>  wx.lib.plot.PlotCanvas.__init__(self, *args, **kwargs)
> self.Draw(self._drawGraph())
>
>def _drawGraph(self):   #this
> points = [(1,1), (3,4), (5,7), (7,14)] #just 
> four points

This is the critical bit you need to change.
points is only defined inside this method,
you need to move the list into the class so
that you can access it as self.points. Also
you can set the list to a new value, add
new points etc.

To do that you should add new methods
to your class such as addPoints(), removePoints(),
replacePoints() etc. Also you should probably add
a list of points to your init method so you can pass
in an initial list - and set a default value of the
empty list. Like this:

 def __init__(self, points=[], *args, **kwargs):
  wx.lib.plot.PlotCanvas.__init__(self, *args, **kwargs)
 self.points = points
 self.Draw(self._drawGraph())

addPoints will be something very simple like:

 def addPoints(self, points):
  self.points += points

Now you just modify your drawGraph to use self.points:

> m=[]
> m.append(wx.lib.plot.PolyLine(points))

   m.append(wx.lib.plot.PolyLine(self.points))
etc.

> I get the sense that the idea is to pass a list of points
> to the drawGraph function.  Is that right?

If we were working with functions the answer would be yes,
but becausese we have a class we can store thelist as an
attribute of the class which allows us to manage the list
internally.

Another approach would be to create a points list class
and pass that to the drawGraph function. But in this case
the thing that cares about the points list is the PlotPanel
so it's reasonable that it should manage the points list.

>  Mostly because I don't understand argument passing
>  well at all (like the *args, **kwargs stuff is still mysterious
>  to me).

If you understand normal parameters/arguments then don't
worry too much about  *args/**kwargs. I've been using Python
for about 10 years and have only used those features in my
own code a couple of times. Most of the time you don't
need them. In this case so long as you keep them at the
end of your parameter list in init you can pretty much ignnore
them - they just pass any options you give to your class on to
the parent class.

In fact, I consider them sufficiently advanced that I don't even
discuss them in my tutor topic on functions. I probably should
introduce them somewhere I guess, but it will be in an
advanced topic somewhere...

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Another string question

2007-03-23 Thread Andre Engels

2007/3/22, Jay Mutter III <[EMAIL PROTECTED]>:


I wanted the following to check each line and if it ends in a right
parentheses then write the entire line to one file and if not then
write the line to anther.
It wrote all of the ) to one file and the rest of the line (ie minus
the ) to the other file.



The line:
print "There are ", count, 'lines to process in this file'
should give you a hint - don't you think this number was rather high?

The problem is that if you do "for line in text" with text being a string,
it will not loop over the _lines_  in the string, but over the _characters_
in the string.

The easiest solution would be to replace
text = in_file.read()
by
text = in_file.readlines()

in_filename = raw_input('What is the COMPLETE name of the file you

would like to process?')
in_file = open(in_filename, 'rU')
text = in_file.read()
count = len(text.splitlines())
print "There are ", count, 'lines to process in this file'
out_filename1 = raw_input('What is the COMPLETE name of the file in
which you would like to save Companies?')
companies = open(out_filename1, 'aU')
out_filename2 = raw_input('What is the COMPLETE name of the file in
which you would like to save Inventors?')
patentdata = open(out_filename2, 'aU')
for line in text:
 if line[-1] in ')':
 companies.write(line)
 else:
 patentdata.write(line)
in_file.close()
companies.close()
patentdata.close()

Thanks

jay
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor





--
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] a very simple question

2007-03-23 Thread Carson Wendy
ok, i just started python and i'm stuck on this, could use some help :D
a='test'
def f():
 a=a+'gg'

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] sorting data from multiple arrays

2007-03-23 Thread Kent Johnson
Jeff Peery wrote:
> ... what is '*' in '*temp'? thanks!

Say you have a function of 3 arguments:
In [1]: def add(a, b, c):
...: return a+b+c

Normally to call it, you just specify the three arguments:
In [2]: add(1, 2, 3)
Out[2]: 6

Suppose the arguments were already in a list, what would you do? You 
can't just pass the list, that is a single argument and you need three:
In [3]: data=[1, 2, 3]
In [4]: add(data)

Traceback (most recent call last):
   File "", line 1, in 
: add() takes exactly 3 arguments (1 given)

You could unpack the data yourself:
In [5]: a, b, c = data
In [6]: add(a, b, c)
Out[6]: 6

Or you can use the * notation, which basically means, "treat each 
element of this list as a separate argument", or "use this list as the 
argument list directly":
In [7]: add(*data)
Out[7]: 6

If the length of the argument list (data, in the example above) can 
change, manually unpacking the list won't work and the * syntax is the 
only alternative.

Kent

> Decorate-sort-undecorate
> (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52234)
> to the rescue:
> 
> In [12]: a = [3,2,1,4]
> In [13]: b = ['hi', 'my','name', 'is']
> In [14]: c = [5,2,4,2]
> In [15]: temp = zip(a, b, c)
> In [16]: temp
> Out[16]: [(3, 'hi', 5), (2, 'my', 2), (1, 'name', 4), (4, 'is', 2)]
> In [17]: temp.sort()
> In [18]: _, b, c = zip(*temp)
> In [19]: b
> Out[19]: ('name', 'my', 'hi', 'is')
> In [20]: c
> Out[20]: (4, 2, 5, 2)

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Another string question

2007-03-23 Thread Jay Mutter III


On Mar 23, 2007, at 5:30 AM, Andre Engels wrote:


2007/3/22, Jay Mutter III <[EMAIL PROTECTED]>:
I wanted the following to check each line and if it ends in a right
parentheses then write the entire line to one file and if not then
write the line to anther.
It wrote all of the ) to one file and the rest of the line (ie minus
the ) to the other file.

The line:
 print "There are ", count, 'lines to process in this file'
should give you a hint - don't you think this number was rather high?

The problem is that if you do "for line in text" with text being a  
string, it will not loop over the _lines_  in the string, but over  
the _characters_ in the string.


The easiest solution would be to replace
 text = in_file.read()
by
 text = in_file.readlines()



Thanks for the response
Actually the number of lines this returns is the same number of lines  
given when i put it in a text editor (TextWrangler).
Luke had mentioned the same thing earlier but when I do change read  
to readlines  i get the following



Traceback (most recent call last):
  File "extract_companies.py", line 17, in ?
count = len(text.splitlines())
AttributeError: 'list' object has no attribute 'splitlines'




in_filename = raw_input('What is the COMPLETE name of the file you
would like to process?')
in_file = open(in_filename, 'rU')
text = in_file.read()
count = len(text.splitlines())
print "There are ", count, 'lines to process in this file'
out_filename1 = raw_input('What is the COMPLETE name of the file in
which you would like to save Companies?')
companies = open(out_filename1, 'aU')
out_filename2 = raw_input('What is the COMPLETE name of the file in
which you would like to save Inventors?')
patentdata = open(out_filename2, 'aU')
for line in text:
 if line[-1] in ')':
 companies.write(line)
 else:
 patentdata.write(line)
in_file.close()
companies.close()
patentdata.close()

Thanks

jay
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor



--
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: Another string question

2007-03-23 Thread Andre Engels

2007/3/23, Jay Mutter III <[EMAIL PROTECTED]>:



On Mar 23, 2007, at 5:30 AM, Andre Engels wrote:

2007/3/22, Jay Mutter III < [EMAIL PROTECTED]>:
>
> I wanted the following to check each line and if it ends in a right
> parentheses then write the entire line to one file and if not then
> write the line to anther.
> It wrote all of the ) to one file and the rest of the line (ie minus
> the ) to the other file.


The line:
 print "There are ", count, 'lines to process in this file'
should give you a hint - don't you think this number was rather high?

The problem is that if you do "for line in text" with text being a string,
it will not loop over the _lines_  in the string, but over the _characters_
in the string.

The easiest solution would be to replace
 text = in_file.read()
by
 text = in_file.readlines()


Thanks for the response
Actually the number of lines this returns is the same number of lines
given when i put it in a text editor (TextWrangler).
Luke had mentioned the same thing earlier but when I do change read to
readlines  i get the following


Traceback (most recent call last):
  File "extract_companies.py", line 17, in ?
count = len(text.splitlines())
AttributeError: 'list' object has no attribute 'splitlines'




Ah, yes, there you DO split in lines, but later you don't. You'll have to do
the same thing twice, that is either:

text = in_file.readlines()
count = len(text) # (instead of count = len(text.splitlines())

OR

text = in_file.read()
for line in text.splitlines(): # (instead of for line in text:)

in_filename = raw_input('What is the COMPLE

>
 TE name of the file you
> would like to process?')
> in_file = open(in_filename, 'rU')
> text = in_file.read()
> count = len(text.splitlines())
> print "There are ", count, 'lines to process in this file'
> out_filename1 = raw_input('What is the COMPLETE name of the file in
> which you would like to save Companies?')
> companies = open(out_filename1, 'aU')
> out_filename2 = raw_input('What is the COMPLETE name of the file in
> which you would like to save Inventors?')
> patentdata = open(out_filename2, 'aU')
> for line in text:
>  if line[-1] in ')':
>  companies.write(line)
>  else:
>  patentdata.write(line)
> in_file.close()
> companies.close ()
> patentdata.close()
>
> Thanks
>
> jay
> ___
> Tutor maillist  -   Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>



--
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels






--
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] a very simple question

2007-03-23 Thread Kent Johnson
Carson Wendy wrote:
> ok, i just started python and i'm stuck on this, could use some help :D
> a='test'
> def f():
>  a=a+'gg'

What is your question? What happens when you run this code? What did you 
expect to happen? What are you trying to do?

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Another string question

2007-03-23 Thread Kent Johnson
Jay Mutter III wrote:
> Thanks for the response
> Actually the number of lines this returns is the same number of lines 
> given when i put it in a text editor (TextWrangler).
> Luke had mentioned the same thing earlier but when I do change read to 
> readlines  i get the following
> 
> 
> Traceback (most recent call last):
>   File "extract_companies.py", line 17, in ?
> count = len(text.splitlines())
> AttributeError: 'list' object has no attribute 'splitlines'

I think maybe you are confused about the difference between "all the 
text of a file in a single string" and "all the lines of a file in a 
list of strings."

When you open() a file and read() the contents, you get all the text of 
a file in a single string. len() will give you the length of the string 
(the total file size) and iterating over the string gives you one 
character at at time.

Here is an example of a string:
In [1]: s = 'This is text'
In [2]: len(s)
Out[2]: 12
In [3]: for i in s:
...: print i
...:
...:
T
h
i
s

i
s

t
e
x
t

On the other hand, if you open() the file and then readlines() from the 
file, the result is a list of strings, each of with is the contents of 
one line of the file, up to and including the newline. len() of the list 
is the number of lines in the list, and iterating the list gives each 
line in turn.

Here is an example of a list of strings:
In [4]: l = [ 'line1', 'line2' ]
In [5]: len(l)
Out[5]: 2
In [6]: for i in l:
...: print i
...:
...:
line1
line2

Notice that s and l are *used* exactly the same way with len() and for, 
but the results are different.

As a further wrinkle, there are two easy ways to get all the lines in a 
file and they give slightly different results.

open(...).readlines() returns a list of lines in the file and each line 
includes the final newline if it was in the file. (The last line will 
not include a newline if the last line of the file did not.)

open(...).read().splitlines() also gives a list of lines in the file, 
but the newlines are not included.

HTH,
Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] a very simple question

2007-03-23 Thread Senthil_OR
Carson Wendy wrote:
> ok, i just started python and i'm stuck on this, could use some help
> :D 
> a='test'
> def f():
>  a=a+'gg'

Look for the definition of  'global'
And try this:
>>> a = 'test'
>>> def f()
global a
a = a + 'gg'
print a
>>>f()


-- 
Senthil


Dish of the Day: Good evening, madame and gentlemen. I am the main dish
of the day. May I interest you in parts of my body? 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help me and ill love u!!! :)

2007-03-23 Thread Rikard Bosnjakovic
On 3/21/07, p l <[EMAIL PROTECTED]> wrote:

> im a new python programmer and iv been given a task to get as much details 
> that i can on my system memory...

Since this is very low level hacking, you need to specify which
operating system you use.


-- 
- Rikard - http://bos.hack.org/cv/
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] a very simple question

2007-03-23 Thread Alan Gauld
"Carson Wendy" <[EMAIL PROTECTED]> wrote in

> ok, i just started python and i'm stuck on this, could use some help 
> :D
> a='test'
> def f():
> a=a+'gg'

Welcome to the world of Python.

As a rule when you have a problem tell us what the problem is,
we aren't psychic. Specifically, if you get an error message cut
and paste that error into your email.

Usually the answer to your question will be in the error text,
once you know what to look for.

In your case the answer is that you are defining a new variable
 'a' inside your function, but it depends on 'a' for its value. But
since 'a' (in your function) doesn't exist yet, Python can't give 'a'
a value and complains.

Read the 'Whats in a name?' topic in my tutor for more about this
and how to deal with it.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Should I use python for parsing text?

2007-03-23 Thread Jay Mutter III
First thanks for all of the help
I am actually starting to see the light.

On Mar 22, 2007, at 7:51 AM, Kent Johnson wrote:

> Jay Mutter III wrote:
>> Kent;
>> Thanks for the reply on tutor-python.
>> My data file which is just a .txt file created under WinXP by an  
>> OCR program contains lines like:
>> A.-C. Manufacturing Company. (See Sebastian, A. A.,
>> and Capes, assignors.)
>> A. G. A. Railway Light & Signal Co. (See Meden, Elof
>> H„ assignor.)
>> A-N Company, The. (See Alexander and Nasb, as-
>> signors.;
>> AN Company, The. (See Nash, It. J., and Alexander, as-
>> signors.)
>> I use an intel imac running OS x10.4.9 and when I used python to  
>> append one file to another I got a file that opened in OS X's
>> TexEdit program with characters that looked liked Japanese/Chinese  
>> characters.
>> When i pasted them into my mail client (OS X's mail) they were  
>> then just a sequence of question marks so I am not sure what  
>> happened.
>> Any thoughts???
>
> For some reason, after you run the Python program, TexEdit thinks  
> the file is not ascii data; it seems to think it is utf-8 or a  
> Chinese encoding. Your original email was utf-8 which points in  
> that direction but is not conclusive.
>
> If you zip up and send me the original file and the cleandata.txt  
> file *exactly as it is produced* by the Python program - not edited  
> in any way - I will take a look and see if I can guess what is  
> going on.
>>

You are correct that it was utf-8
Multiple people were scanning pages and converting to text, some  
saved as ascii and some saved as unicode
The sample used above was utf-8 so after your comment i checked all,  
put everything as ascii, combined all pieces into one file and  
normalized the line endings to unix style


>> And i tried  using the following on the above data:
>> in_filename = raw_input('What is the COMPLETE name of the file you  
>> want to open:')
>> in_file = open(in_filename, 'r')
>
> It wouldn't hurt to use universal newlines here since you are  
> working cross-platform:
>   open(in_filename, 'Ur')
>

corrected this

>> text = in_file.readlines()
>> num_lines = text.count('\n')
>
> Here 'text' is a list of lines, so text.count('\n') is counting the  
> number of blank lines (lines containing only a newline) in your  
> file. You should use
>   num_lines = len(text)
>

changed


>> print 'There are', num_lines, 'lines in the file', in_filename
>> output = open("cleandata.txt","a")# file for writing data to  
>> after stripping newline character
>
> I agree with Luke, use 'w' for now to make sure the file has only  
> the output of this program. Maybe something already in the file is  
> making it look like utf-8...
>
>> # read file, copying each line to new file
>> for line in text:
>> if len(line) > 1 and line[-2] in ';,-':
>> line = line.rstrip()
>> output.write(line)
>> else: output.write(line)
>> print "Data written to cleandata.txt."
>> # close the files
>> in_file.close()
>> output.close()
>> As written above it tells me that there are 0 lines which is  
>> surprising because if I run the first part by itself it tells  
>> there are 1982 lines ( actually 1983 so i am figuring EOF)
>> It copies/writes the data to the cleandata file but it does not  
>> strip out CR and put data on one line ( a sample of what i am  
>> trying to get is next)
>> A.-C. Manufacturing Company. (See Sebastian, A. A., and Capes,  
>> assignors.)
>> My apologies if i have intruded.
>
> Please reply on-list in the future.
>
> Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Invoking a procedure with an uknown number of arguments...

2007-03-23 Thread Lars Erik Gullerud
Hello list,

I have the following problem; I have a list with an unknown number of 
strings, like so:

   MyList = ['string1', 'string2', 'string3'..'stringN']

Now, I need to call a procedure from a 3rd party module (which is just a 
wrapper around a C library), where each of these strings must be passed 
as a separate argument, i.e.

   MyProc(arg1, arg2, arg3..argN)

So, the question is basically, how can I invoke this procedure and pass 
each of these list elements as separate arguments, when I don't know in 
advance how many elements there will be? Had this been e.g. a case with 3 
elements, I could hardcode it like:

   MyProc(MyList[0], MyList[1], MyList[2])

...however this is obviously not possible when the number of elements is 
not known in advance.

Any tips?

/leg
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Invoking a procedure with an uknown number of arguments...

2007-03-23 Thread Kent Johnson
Lars Erik Gullerud wrote:
> Hello list,
> 
> I have the following problem; I have a list with an unknown number of 
> strings, like so:
> 
>MyList = ['string1', 'string2', 'string3'..'stringN']
> 
> Now, I need to call a procedure from a 3rd party module (which is just a 
> wrapper around a C library), where each of these strings must be passed 
> as a separate argument, i.e.
> 
>MyProc(arg1, arg2, arg3..argN)
> 
> So, the question is basically, how can I invoke this procedure and pass 
> each of these list elements as separate arguments, when I don't know in 
> advance how many elements there will be?

MyProc(*MyList)

More details here:
http://mail.python.org/pipermail/tutor/2007-March/053435.html

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] threading and gui programming

2007-03-23 Thread Ben

Hi Tony,

Thank you very much for your pointer. I think I understand what are you
explaining to me. Do you mind give me some code examples? I am still trying
to grasp the gui programming overall. And it is really over my head. I
really appreciate your help. Thank you

-Ben

On 3/23/07, Tony Cappellini <[EMAIL PROTECTED]> wrote:


Hi Ben,

I've just started gui programming in Python, and my first app needed a
little threading.
It's over my head, so a friend gave me an example, and I integrated it.

The reason for threading in my example- is the same as what Kent
mentioned.

My app is a gui front end to another python program which processes files.
The file processor outputs text, and my gui displays it in a text box.
If it were not for threading, my app would freeze until the app that
I'm calling finished.

Another way to think of it- is using yourself for an example/.
If you were eating dinner, and someone in the room called your name-
you would probably turn your head or walk over to them while you were
chewing a mouthfull :-)

If you didn't respond to them until you were finished eating, they
could not finish what they were doing either.

Does that make sense?

You may not always need threading in a gui app. It just depends on
what you ar edoing, and how long it takes.



Message: 1
Date: Tue, 20 Mar 2007 14:49:50 -0400
From: Ben <[EMAIL PROTECTED]>
Subject: [Tutor] threading and gui programming
To: tutor@python.org
Message-ID:
   <[EMAIL PROTECTED]>
Content-Type: text/plain; charset="iso-8859-1"

Hi all,

I am curious about one thing. I have been doing research on gui
programming.
One thing that I don't understand is why there are some examples uses
threading in the gui examples. Is there any benefits or advantages for
using
the threading in the gui programming? Thanks.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Another string question

2007-03-23 Thread Jay Mutter III

Andre;

Thanks again for the assistance.

I have corrected the splitlines error and it works ( well that part  
of anyway) correctly now.


On Mar 23, 2007, at 5:30 AM, Andre Engels wrote:


2007/3/22, Jay Mutter III <[EMAIL PROTECTED]>:
I wanted the following to check each line and if it ends in a right
parentheses then write the entire line to one file and if not then
write the line to anther.
It wrote all of the ) to one file and the rest of the line (ie minus
the ) to the other file.

The line:
 print "There are ", count, 'lines to process in this file'
should give you a hint - don't you think this number was rather high?

The problem is that if you do "for line in text" with text being a  
string, it will not loop over the _lines_  in the string, but over  
the _characters_ in the string.


The easiest solution would be to replace
 text = in_file.read()
by
 text = in_file.readlines()

in_filename = raw_input('What is the COMPLETE name of the file you
would like to process?')
in_file = open(in_filename, 'rU')
text = in_file.read()
count = len(text.splitlines())
print "There are ", count, 'lines to process in this file'
out_filename1 = raw_input('What is the COMPLETE name of the file in
which you would like to save Companies?')
companies = open(out_filename1, 'aU')
out_filename2 = raw_input('What is the COMPLETE name of the file in
which you would like to save Inventors?')
patentdata = open(out_filename2, 'aU')
for line in text:
 if line[-1] in ')':
 companies.write(line)
 else:
 patentdata.write(line)
in_file.close()
companies.close()
patentdata.close()

Thanks

jay
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor



--
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Why is it...

2007-03-23 Thread Jay Mutter III

Got it - it needs the blank line to signal that code block has ended.
Thanks

On Mar 22, 2007, at 3:05 PM, Jason Massey wrote:


In the interpreter this doesn't work:

>>> f = open(r"c:\python24\image.dat")
>>> line = f.readline()
>>> while line:
... line = f.readline()
... f.close()
Traceback (  File "", line 3
f.close()
^
SyntaxError: invalid syntax

But this does:

>>> f = open(r"c:\python24\image.dat")
>>> line = f.readline()
>>> while line:
... line = f.readline()
...
>>> f.close()
>>>

Note the differing placement of the f.close() statement, it's not  
part of the while.



On 3/22/07, Kent Johnson <[EMAIL PROTECTED]> wrote:
Jay Mutter III wrote:
> Why is it that when I run the following interactively
>
> f = open('Patents-1920.txt')
> line = f.readline()
> while line:
>  print line,
>  line = f.readline()
> f.close()
>
> I get an error message
>
> File "", line 4
>  f.close()
>  ^
> SyntaxError: invalid syntax
>
> but if i run it in a script there is no error?

Can you copy/paste the actual console transcript?

BTW a better way to write this is
f = open(...)
for line in f:
 print line,
f.close()

Kent

>
> Thanks
>
> Jay
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] passing arguments to a make a graph

2007-03-23 Thread Che M

Thank you, Alan.   I started by adding a method called addPoints() to my 
class as you recommend.  But now I don't know how to pass a list of points 
to the addPoints() method.  Here's the relevant code, adding in your 
suggestions:

class PlotPanel(wx.lib.plot.PlotCanvas):
def __init__(self, points=[], *args, **kwargs):
wx.lib.plot.PlotCanvas.__init__(self, *args, **kwargs)
self.points = points
self.Draw(self._drawGraph())
self.SetEnableDrag(True)
#self.SetEnableGrid(True)

def addPoints(self, points):
self.points += points

def _drawGraph(self):
m=[]
m.append(wx.lib.plot.PolyLine(self.points))
m.append(wx.lib.plot.PolyMarker(self.points))
return wx.lib.plot.PlotGraphics(m, "Title)",
"x axis", "")

#this button tells it to make a graph using "mypoints".

def OnGraphButton(self, event):
mypoints = [(3,4), (5,6)] #these to be used 
in the plot
PlotPanel.addPoints(PlotPanel,mypoints)
self.notebook1.AddPage(imageId=-1, page=PlotPanel(self.notebook1), 
select=True,
  text='Weight')


The error I get using it this way is:

TypeError:  unbound method addPoints() must be called with PlotPanel 
instance as first argument (got type instance instead)

I'm lost.  Also, what does "self.points += points" mean?  What is the += 
operator?

Thanks,
Che

_
Mortgage refinance is hot 1) Rates near 30-yr lows 2) Good credit get 
intro-rate 4.625%* 
https://www2.nextag.com/goto.jsp?product=10035&url=%2fst.jsp&tm=y&search=mortgage_text_links_88_h2a5f&s=4056&p=5117&disc=y&vers=743

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] passing arguments to a make a graph

2007-03-23 Thread Alan Gauld

"Che M" <[EMAIL PROTECTED]> wrote
> Thank you, Alan.   I started by adding a method called addPoints() 
> to my
> class as you recommend.  But now I don't know how to pass a list of 
> points
> to the addPoints() method.

You need to create an instance of a PlotPanel.

> class PlotPanel(wx.lib.plot.PlotCanvas):
>def __init__(self, points=[], *args, **kwargs):
>def addPoints(self, points):
>def _drawGraph(self):

> #this button tells it to make a graph using "mypoints".
>
> def OnGraphButton(self, event):
>mypoints = [(3,4), (5,6)]   #these to be used
>PlotPanel.addPoints(PlotPanel,mypoints)

Instead of using the class create an instance(aka object)

   self.plotPanel = PlotPanel(mypoints,self.notebook1)

That creates an instance passing the mypoints list in
to youir init method along with the notebook1 that you
pass when you create an instance later(see below).

>self.notebook1.AddPage(imageId=-1, 
> page=PlotPanel(self.notebook1),
>  select=True, 
> text='Weight')

This should use the plotPanel instance:

 self.notebook1.AddPage(imageId=-1, page=self.plotPanel,
  select=True,  text='Weight')

> The error I get using it this way is:
>
> TypeError:  unbound method addPoints() must be called with PlotPanel
> instance as first argument (got type instance instead)

Yep, You gotta have an instance to call the methods.
See my OOP topic for more on classes, objects etc.

> I'm lost.  Also, what does "self.points += points" mean?  What is 
> the +=
> operator?

x += 5

is shorthand for

x = x + 5

The same applies to -/* etc.
See my raw Materials topic for more info on operators.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Developing a GUI application

2007-03-23 Thread Terry Carroll
I'm pretty much just a dabbler in Python.

Up to now I've mostly been doing line-oriented programs, but I have a 
small app I want to write that I think would be a good candidate to write 
as a GUI-based app.

I'd like advice from the more seasoned programmers here: how do you 
approach a GUI-based app?  

I figure one way to do it is to write the nuts and bolts of it using plain
old line oriented techniques; and then write the GUI, calling the
functions already written.

The other way would be to write a GUI shell with all the controls, but 
calling dummy functions; then write the functions to do the tasks.

What's the general wisdom here?

(If it matters: I'm going to use wxPython; and my app is yet another CDROM 
database program; more details available if it matters.)

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Parsing text file with Python

2007-03-23 Thread Jay Mutter III
Script i have to date is below and
Thanks to your help i can see some daylight  but I still have a few  
questions

1.)  Are there better ways to write this?
2.) As it writes out the one group to the new file for companies it  
is as if it leaves blank lines behind for if I don't have the elif len 
(line) . 1 the
   inventor's file has blank lines in it.
3.) I reopened the inventor's file to get a count of lines but is  
there a better way to do this?

Thanks



in_filename = raw_input('What is the COMPLETE name of the file you  
would like to process?')
in_file = open(in_filename, 'rU')
text = in_file.readlines()
count = len(text)
print "There are ", count, 'lines to process in this file'
out_filename1 = raw_input('What is the COMPLETE name of the file in  
which you would like to save Companies?')
companies = open(out_filename1, 'aU')
out_filename2 = raw_input('What is the COMPLETE name of the file in  
which you would like to save Inventors?')
patentdata = open(out_filename2, 'aU')
for line in text:
 if line.endswith(')\n'):
 companies.write(line)
 elif line.endswith(') \n'):
 companies.write(line)
  elif len(line) > 1:
 patentdata.write(line)
in_file.close()
companies.close()
patentdata.close()
in_filename2 = raw_input('What was the name of the inventor\'s  
file ?')
in_file2 = open(in_filename2, 'rU')
text2 = in_file2.readlines()
count = len(text2)
print "There are - well until we clean up more - approximately ",  
count, 'inventor\s in this file'
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Developing a GUI application

2007-03-23 Thread Luke Paireepinart
Terry Carroll wrote:
> I'm pretty much just a dabbler in Python.
>
> Up to now I've mostly been doing line-oriented programs, but I have a 
> small app I want to write that I think would be a good candidate to write 
> as a GUI-based app.
>
> I'd like advice from the more seasoned programmers here: how do you 
> approach a GUI-based app?  
>
> I figure one way to do it is to write the nuts and bolts of it using plain
> old line oriented techniques; and then write the GUI, calling the
> functions already written.
>
> The other way would be to write a GUI shell with all the controls, but 
> calling dummy functions; then write the functions to do the tasks.
>   
In either case, what you're intending to end up with is a decoupling of 
the GUI code and the program logic.

For example, in a command-line program, something like this:
print  "%i is your number!" % int(raw_input( "Please enter a number to 
be squared! " )) ** 2

Has the display code and the program logic all tangled up.
A much better version would be:
def squareNum(anint):  return anint ** 2

num = int(raw_input("enter a number to be squared, please! "))
print "Your number squared is: " + str(squareNum(num))

Because if later you want to reuse your function in a GUI app, you'd 
just change your value inputs but the functions would remain the same.

So essentially, when you write your GUI app, try to keep all 
calculations in functions with no GUI involvement.  It makes your 
functions more reusable and also it's good practice, as well as easier 
to maintain ( not having to look through GUI code to find where your 
calculations are.)

I'd say that it'd be best to make it a command-line app first, so that 
you can test the functionality of your code.  Essentially, the GUI is 
just an interface to the functions of your program that lets people use 
your program  easier, and there's no reason to write that part first 
(IMHO of course).
It would be a good idea to sketch out your GUI on a sheet of paper, so 
you have ideas of what kind of paramaters your functions will need to 
use before you write them.  For example, you might want function 
DisplayCDInfo to take an artist and an album, and write the function for 
that, then later realize that you wanted your GUI to give them the 
ability to show the track number as well.  It's nice to know (generally) 
what requirements you want before you start writing a program.
> (If it matters: I'm going to use wxPython; and my app is yet another CDROM 
> database program; more details available if it matters.)
Sounds pretty interesting, mind elaborating a bit?  Is it just for 
retrieving the CD info from freecddb and whatnot and display it?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Developing a GUI application

2007-03-23 Thread Terry Carroll
On Fri, 23 Mar 2007, Luke Paireepinart wrote:

> In either case, what you're intending to end up with is a decoupling of 
> the GUI code and the program logic.

Absolutely.  I try to do that in any case, even in non-GUI.

[other good advice snipped] 

> > (If it matters: I'm going to use wxPython; and my app is yet another CDROM 
> > database program; more details available if it matters.)
>
> Sounds pretty interesting, mind elaborating a bit?  Is it just for 
> retrieving the CD info from freecddb and whatnot and display it?

It's planned to be a database for data CDs, rather than audio ones; the
main advantage over the many DBs I've already encountered is to store an
MD5 checksum of the file, so that I can check to see if a new file I have
is a duplicate of something I already have and have archived off to CDROM, 
without having to find the CDROM.

I've also thought of having a twist here for MP3 files, specifically,
distinguishing between the files' audio frames and identification info
frames, and checksumming only the audio portion; so that two otherwise
identical MP3 files with different ID3 data would nonetheless have the
same audio checksum and show up as identical; but that's an idea for the
future.

I've also thought of, for image files, to store a thumbnail in the
database, too.

In any case, dabbler that I am (and given the fact that I have two
daughters, one 2 years and one only 3 weeks, which substantially cuts into
my hacking time), I'll probably finish this up, oh, sometime in 2008.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Developing a GUI application

2007-03-23 Thread Andrei
Hi Terry,

Terry Carroll wrote:
> I'd like advice from the more seasoned programmers here: how do you 
> approach a GUI-based app?

Approaches differ in formality and order of execution and opinions at 
any point in time vary - and they vary with time as well. I'm assuming 
this is a hobby-level project with yourself acting as developer and most 
important customer. So I'll suggest an approach that I think will keep 
you motivated and will help avoid getting bogged down in looking for the 
perfect decision at every step.

It helps if you start with some concrete ideas of what you'll want to be 
able to do with the application. It's not necessary to go all PowerPoint 
on it, but writing down some keywords and sketching interface ideas may 
help you explore your goals. You can even do quick real interface 
designs using e.g. wxGlade - it's often motivating to have *something* 
tangible available. These are not supposed to be final, set-in-stone and 
complete designs - just generic sketches.

> I figure one way to do it is to write the nuts and bolts of it using plain
> old line oriented techniques; and then write the GUI, calling the
> functions already written.

Having two interfaces is a way to make sure you don't accidentally 
couple your interface code to your internal model/storage. There's a 
nicer way to help achieving this: unit tests. However, you may not 
appreciate their advantages until you have more experience. Personally I 
have never used the two-interfaces approach.

> The other way would be to write a GUI shell with all the controls, but 

I would choose for a vertical development: implement everything you need 
(interface, storage, logic) to achieve some small part of the 
functionality - e.g. start by having a list of CD-ROM names and burn 
dates. This should work in the GUI, in the model and in your storage 
parts. Once that is tested and OK, add the next bit of functionality, etc.

You will invariably encounter problems due to previous decisions when 
doing this, but all beginners' applications - as well as most 
professionals' applications :) - eventually end up in a state of 
unmaintainable mess anyway. Making mistakes is a very good way of 
learning and even truly dumb and ugly mistakes can usually be worked 
around or refactored away; software is very malleable, particularly if 
you don't have outside constraints.
With a bit of luck, your software will be almost continuously in a 
usable state and using it will give you new ideas all the time, which 
you had not thought of beforehand.

> calling dummy functions; then write the functions to do the tasks.

You should look into objects - if you don't have at least a basic 
understanding of them, GUI development with wxPython will prove 
difficult and confusing. They are also pretty much essential for well 
structured Python programs.

> (If it matters: I'm going to use wxPython; and my app is yet another CDROM 
> database program; more details available if it matters.)

-- 
Yours,

Andrei

=
Mail address in header catches spam. Real contact info:
''.join([''.join(s) for s in zip(
"[EMAIL PROTECTED] pmfe!Pes ontuei ulcpss  edtels,s hr' one oC.",
"rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")])

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] passing arguments to a make a graph

2007-03-23 Thread Che M


>Instead of using the class create an instance(aka object)
>
>self.plotPanel = PlotPanel(mypoints,self.notebook1)
>
>That creates an instance passing the mypoints list in
>to youir init method along with the notebook1 that you
>pass when you create an instance later (see below).

This worked great, thanks!  One question:  you mention that in this way it 
is passing in the mypoints list and also the notebook1.  What I am unclear 
is, why are you allowed to pass in the notebook?  If you look at the 
original class PlotPanel():

class PlotPanel(wx.lib.plot.PlotCanvas):
def __init__(self, points=[], *args, **kwargs):
wx.lib.plot.PlotCanvas.__init__(self, *args, **kwargs)
self.points = points

[some methods deleted]

...in the __init__ function, it has parameters for self, points, *args, and 
**kwargs.  But you are passing it the notebook1, so how does it know which 
"slot" of these four parameters notebook1 refers to?

>See my OOP topic for more on classes, objects etc.

I will look at it, and it should make even more sense given this example.

Gracias,
Che

_
The average US Credit Score is 675. The cost to see yours: $0 by Experian. 
http://www.freecreditreport.com/pm/default.aspx?sc=660600&bcd=EMAILFOOTERAVERAGE

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] My Python project - an update

2007-03-23 Thread Dave S
Just to say thank you.

Over the last few months I have been asking a lot of dumb questions about 
python (and qt on the qt mailing list) ... anyhow I finished my pet project, 
all 5500 lines of it. I previously explained what it was but to recap ...

I developed a QT Python app that scans both configuration and data collected 
from remote security systems, up to 80,000 data attributes per site.

After scanning it reports any inconsistencies or errors via a GUI giving them 
a severity level and an option to correct the error or acknowledge and enter 
override text.

It generates a certificate PDF with an embedded md5 authentication string when 
the site has been audited.
 
>From its analysis of the data it also generates both a detailed user 
reference PDF and a detailed engineer reference PDF specifically for the 
site.

In my field this has never been done before - lots of very impressed people 
after several demonstrations. I released it under the GPL but apparently my 
terms of employment state that it belongs my employer ... who does not want 
it on sourceforge ...

Where is it now ... its being integrated into a proprietary application as a 
groundbreaking audit/commissioning  function (still running my Python code as 
a back end) and apparently I am due some kind of company reward ...

My thoughts on my first Python QT project ... would have been nice if I could 
have given it to the community ... wonder what they will pay me ? ...

Dave





___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] pruning and ordering a list of lists

2007-03-23 Thread Bob Gailer
William O'Higgins Witteman wrote:
> I have a list of lists derived from a log file that I want to create a
> summary of, but I am not sure of an approach to do what I need.
>
> Here's a sample of the data:
>
> [["user1","18/Mar/2007:07:52:38 -0400"],["user1","18/Mar/2007:07:52:40 
> -0400"],["user2","18/Mar/2007:07:52:42 -0400"],["user3","18/Mar/2007:07:52:42 
> -0400"],["user2","18/Mar/2007:07:52:43 -0400"]]
>
> What I want as output is something like this:
>
> [["first user alphabetically","most recent timestamp for this user"],["second 
> user alphabetically","most recent timestamp for this user"], ...]
>
> Can anyone suggest an approach for this?  Thanks.
>   
# following code is untested
# assume your data is in variable log:
userData = {} # setup a dictionary to collect latest timestamp for each user
for user, timestamp in log:
  if user not in userData or timestamp > userData[user]
# note that we need a way to compare timestamps
# the current representation does not support this
userData[user] = timestamp
userData2 = userData.items().sorted()

-- 
Bob Gailer
510-978-4454

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] passing arguments to a make a graph

2007-03-23 Thread Alan Gauld
"Che M" <[EMAIL PROTECTED]> wrote

>>Instead of using the class create an instance(aka object)
>>self.plotPanel = PlotPanel(mypoints,self.notebook1)

> This worked great, thanks!  One question:  you mention that in this 
> way it
> is passing in the mypoints list and also the notebook1.  What I am 
> unclear
> is, why are you allowed to pass in the notebook?  If you look at the
> original class PlotPanel():
>
> class PlotPanel(wx.lib.plot.PlotCanvas):
>def __init__(self, points=[], *args, **kwargs):
>wx.lib.plot.PlotCanvas.__init__(self, *args, **kwargs)

OK, It always amazes me how the same basic topic comes
up all at once in this group. Kent gave a good explanation
of *args/**kwargs earlier this week, look back for it.

But basically what those two magic words do is take all of
the arguments passed in and bundle them up into those two
collections(kw args is keyword arguments and args is the rest(*))
So then when you call PlotCanvas.__init__() you are just passing
on everything that was passed into your init. You don;t know
nor care how many other arguments were gibemn, you just
pass them onto the superclass to deal with.

But you do care about points, so you put that as the first parameter.
Then when your init gets called Python peels off the first value
and puts it in points, the rest get put into args/kwargs.

(*)You recall that if a function has all of its parameters take
default values you can call it using keywords like this:

def f(a=1,b=2,c=3,d=4,e=3,f=2,g=1):
   pass

f(b=7,g=2)
f(c=4,a=0)

etc

Those are the keyword arguments
But I can also call it with plain values provided I use the right 
order:

f(9,8,7)  # a=9,b=8,c=7,d=4,e=3,f=2,g=1

Those are the args
Now I can use both techniques too:

f(7,8,e=0,g=2)  # a=7,b=8,c=3,d=4,e=0,f=2,g=2

Here args is 7,8
kwargs is e=0,g=2

Is that clearer?

> **kwargs.  But you are passing it the notebook1, so how does it know 
> which
> "slot" of these four parameters notebook1 refers to?

It doesn't, it passes notebook1 as the first value in args to the 
superclass init.
It then gets unpacked as the first parameter(after self) of the 
superclass' init.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Parsing text file with Python

2007-03-23 Thread Alan Gauld
"Jay Mutter III" <[EMAIL PROTECTED]> wrote
> 1.)  Are there better ways to write this?

There are always other ways, as to which is better depends
on your judgement criteria. Your way works.

> 2.) As it writes out the one group to the new file for companies it
> is as if it leaves blank lines behind for if I don't have the elif 
> len
> (line) . 1 the
>   inventor's file has blank lines in it.

I'm not sure what you mean here can you elaborate,
maybe with some sample data?

> 3.) I reopened the inventor's file to get a count of lines but is
> there a better way to do this?

You could track the numbers of items being written as you go.
The only disadvantage of your technique is the time invloved
in opening the file and rereading the data then counting it.
On a really big file that could take a long time. But it has
the big advantage of simplicity.

A couple of points:

> in_filename = raw_input('What is the COMPLETE name of the file you
> would like to process?')
> in_file = open(in_filename, 'rU')

You might want to put your file opening code inside a try/except
in case the file isn't there or is locked.

> text = in_file.readlines()
> count = len(text)
> print "There are ", count, 'lines to process in this file'

Unless this is really useful info you could simplify by
omitting the readlines and count and just iterating over
the file. If you use enumerate you even get the final
count for free at the end.

for count,line in enumerate(in_file):
 # count is the line number, line the data

> for line in text:
> if line.endswith(')\n'):
> companies.write(line)
> elif line.endswith(') \n'):
> companies.write(line)

You could use a boolean or to combine these:

 if line.endswith(')\n') or line.endswith(') \n'):
 companies.write(line)

> in_filename2 = raw_input('What was the name of the inventor\'s
> file ?')

Given you opened it surely you already know?
It should be stored in patentdata so you don't need
to ask again?

Also you could use flush() and then seek(0) and then readlines()
before closing the file to get the count. but frankly thats being 
picky.


> in_file2 = open(in_filename2, 'rU')
> text2 = in_file2.readlines()
> count = len(text2)

Well done,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Developing a GUI application

2007-03-23 Thread Alan Gauld
"Terry Carroll" <[EMAIL PROTECTED]> wrote

> I figure one way to do it is to write the nuts and bolts of it using 
> plain
> old line oriented techniques; and then write the GUI, calling the
> functions already written.

Absolutely, taking care to put the code the GUI will use in separate
functions, ideally in a separate module, with no UI elements (GUI
or otherwise). You might also think about bundling functions and
data into classes at this stage too.

Its much easier to get a command line version working than
to get a GUI vesion right. Once you know the core works
OK then add the GUI gloss.

> The other way would be to write a GUI shell with all the controls, 
> but
> calling dummy functions; then write the functions to do the tasks.

I do this if the GUI is the bulk of the work. That is, if there will 
be
lots of forms and complex navigation between them and the
core processing is just fetching data from a database, say.

But for any significant processing of data I always write a CLI first.

Incidentally the same applies if I'm writing a networked app, first
get it running locally, then add the client/server gloss then finally
recast the client as a GUI, or the server as a web app as needed.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] pruning and ordering a list of lists

2007-03-23 Thread William O'Higgins Witteman
On Fri, Mar 23, 2007 at 05:31:51PM -0700, Bob Gailer wrote:
>William O'Higgins Witteman wrote:
>>I have a list of lists derived from a log file that I want to create a
>>summary of, but I am not sure of an approach to do what I need.
>>
>>Here's a sample of the data:
>>
>>[["user1","18/Mar/2007:07:52:38 -0400"],["user1","18/Mar/2007:07:52:40 
>>-0400"],["user2","18/Mar/2007:07:52:42 
>>-0400"],["user3","18/Mar/2007:07:52:42 
>>-0400"],["user2","18/Mar/2007:07:52:43 -0400"]]
>>
>>What I want as output is something like this:
>>
>>[["first user alphabetically","most recent timestamp for this 
>>user"],["second user alphabetically","most recent timestamp for this 
>>user"], ...]
>>
>>Can anyone suggest an approach for this?  Thanks.
>>  
># following code is untested
># assume your data is in variable log:
>userData = {} # setup a dictionary to collect latest timestamp for each user
>for user, timestamp in log:
> if user not in userData or timestamp > userData[user]
>   # note that we need a way to compare timestamps
>   # the current representation does not support this
>   userData[user] = timestamp
>userData2 = userData.items().sorted()

Thank you.  I found a similar solution myself while waiting.  I was
stuck with thinking about the output being a list of lists, but once I
thought of it as a dictionary the solution came much more easily.
Here's the code, including timestamp conversions:

#!/usr/bin/python

import time

def userlists(usertimepairs):
  
  userandtoptimes = {}
  for line in usertimepairs:
line[0] = line[0].lower()
if userandtoptimes.has_key(line[0]):
  a = time.strptime(userandtoptimes[line[0]],"%d/%b/%Y:%H:%M:%S")
  prevtime = time.mktime(a)
  b = time.strptime(line[1],"%d/%b/%Y:%H:%M:%S -0400")
  thistime = time.mktime(b)
  if thistime > prevtime:
c = time.gmtime(thistime)
d = time.strftime("%d/%b/%Y:%H:%M:%S",c)
userandtoptimes[line[0]] = d
  else:
pass
else:
  e = time.strptime(line[1],"%d/%b/%Y:%H:%M:%S -0400")
  f = time.strftime("%d/%b/%Y:%H:%M:%S",e)
  userandtoptimes[line[0]] = f

  #debug print(userandtoptimes)

  # Output to CSV file
  for user, timestamp in userandtoptimes.iteritems():
op.write(user + "," + timestamp + "\n")

The time is not perfect, because of the discarded GMT offset, but it is
good enough, and by converting to seconds since the epoch the
comparisons are much simpler.  Thanks again.
-- 

yours,

William
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Developing a GUI application

2007-03-23 Thread R. Alan Monroe
> On Fri, 23 Mar 2007, Luke Paireepinart wrote:

> I've also thought of having a twist here for MP3 files, specifically,
> distinguishing between the files' audio frames and identification info
> frames, and checksumming only the audio portion; so that two otherwise
> identical MP3 files with different ID3 data would nonetheless have the
> same audio checksum and show up as identical; but that's an idea for the
> future.

I suspect this would run into problems if you used a Fraunhoffer
encoder and I used the LAME encoder, for instance, even if we both
ripped from the same cd to start with.

Alan

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Developing a GUI application

2007-03-23 Thread Luke Paireepinart
R. Alan Monroe wrote:
>> On Fri, 23 Mar 2007, Luke Paireepinart wrote:
>> 
>
>   
>> I've also thought of having a twist here for MP3 files, specifically,
>> distinguishing between the files' audio frames and identification info
>> frames, and checksumming only the audio portion; so that two otherwise
>> identical MP3 files with different ID3 data would nonetheless have the
>> same audio checksum and show up as identical; but that's an idea for the
>> future.
>> 
>
> I suspect this would run into problems if you used a Fraunhoffer
> encoder and I used the LAME encoder, for instance, even if we both
> ripped from the same cd to start with.
>   
Yeah, also if it were the same song with a different 
bitrate/frequency/(stereo/mono/dual)/ etc.

I think the point of it was that, if I have a song with messed up tags, 
and I back it up, but later fix the tags,
if it were governed just by the md5 of the whole file, these two 
wouldn't be considered identical.
Remember this program is to help him keep track of backups.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Developing a GUI application

2007-03-23 Thread Kent Johnson
Terry Carroll wrote:
> I'm pretty much just a dabbler in Python.
> 
> Up to now I've mostly been doing line-oriented programs, but I have a 
> small app I want to write that I think would be a good candidate to write 
> as a GUI-based app.
> 
> I'd like advice from the more seasoned programmers here: how do you 
> approach a GUI-based app?  
> 
> I figure one way to do it is to write the nuts and bolts of it using plain
> old line oriented techniques; and then write the GUI, calling the
> functions already written.
> 
> The other way would be to write a GUI shell with all the controls, but 
> calling dummy functions; then write the functions to do the tasks.
> 
> What's the general wisdom here?

I usually alternate between writing the functional code and hooking it 
up to a GUI. I will write a bit of code that does something useful and 
write unit tests for it so I am confident that it works. Then I will 
write the GUI to drive that bit of function and test that (by hand, 
usually). Repeat as needed.

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] pruning and ordering a list of lists

2007-03-23 Thread Kent Johnson
William O'Higgins Witteman wrote:
> Thank you.  I found a similar solution myself while waiting.  I was
> stuck with thinking about the output being a list of lists, but once I
> thought of it as a dictionary the solution came much more easily.
> Here's the code, including timestamp conversions:
> 
> #!/usr/bin/python
> 
> import time
> 
> def userlists(usertimepairs):
>   
>   userandtoptimes = {}
>   for line in usertimepairs:

You can say
   for user, timestamp in usertimepairs:
and then refer to user and timestamp instead of line[0] and line[1]; it 
makes the code much more readable.

> line[0] = line[0].lower()
> if userandtoptimes.has_key(line[0]):
>   a = time.strptime(userandtoptimes[line[0]],"%d/%b/%Y:%H:%M:%S")
>   prevtime = time.mktime(a)

You might consider keeping prevtime in the dictionary instead of 
converting to and from strings all the time. You can convert them back 
to strings when you write them out. Then the above two lines would just be
   prevtime = userndtoptimes[user]

>   b = time.strptime(line[1],"%d/%b/%Y:%H:%M:%S -0400")
>   thistime = time.mktime(b)
>   if thistime > prevtime:
> c = time.gmtime(thistime)
> d = time.strftime("%d/%b/%Y:%H:%M:%S",c)
> userandtoptimes[line[0]] = d

This could just be
   userandtoptimes[user] = thistime

>   else:
> pass
> else:
>   e = time.strptime(line[1],"%d/%b/%Y:%H:%M:%S -0400")
>   f = time.strftime("%d/%b/%Y:%H:%M:%S",e)
>   userandtoptimes[line[0]] = f
> 
>   #debug print(userandtoptimes)
> 
>   # Output to CSV file
>   for user, timestamp in userandtoptimes.iteritems():
> op.write(user + "," + timestamp + "\n")

Here you would have to convert to a string.

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor