From darnold02 at sprynet.com  Thu Jan  1 01:17:34 2004
From: darnold02 at sprynet.com (don arnold)
Date: Thu Jan  1 01:17:45 2004
Subject: [Tutor] Questor
References: <20031230195457.54072.qmail@web13607.mail.yahoo.com>
Message-ID: <070201c3d02e$f320c530$ce11ba3f@don2uvsu54fwiq>

----- Original Message -----
From: "moore william" <red_necks25@yahoo.com>
To: "Python" <Tutor@python.org>
Sent: Tuesday, December 30, 2003 1:54 PM
Subject: [Tutor] Questor


> Did anyone every find the anwser to Questor.py?

Since no one has responded yet, I'll bite: What is Questor.py, and what was
the question?

Don


From from_python_tutor at SSokolow.com  Thu Jan  1 01:20:23 2004
From: from_python_tutor at SSokolow.com (SSokolow)
Date: Thu Jan  1 01:20:25 2004
Subject: [Tutor] Modfying Proxy, HTTP 1.1, and chunked mode
Message-ID: <3FF3BC27.9070201@SSokolow.com>

I enjoy reading the Anime Addventure ( 
http://addventure.bast-enterprises.de ) but the sheer size of it makes 
it difficult to track where I've been. After finding that my usual 
method (write a CGI Proxy in Perl) was unsatisfactory, I decided to 
start into python.

After a few failed attempts to write a proxy from scratch ( no surprise 
considering that it's my first project ), I managed to find Munchy by 
Neil Schemenauer and Tiny HTTP Proxy by Suzuki Hisao. I decided to use 
Tiny HTTP Proxy and I've completely commented the code (great learning 
experience) and made some improvements.

I did manage to implement the non-expiring page history but I don't want 
to limit the proxy to HTTP 1.0 and I don't know of any easy way to 
modify a HTTP 1.1 chunked data stream. My goal is to wrap any link I've 
already visited in <strike></strke> tags but all I can do so far is have 
the Python console print "You have already been to %s".

*My question:*
   Is there any simple way to apply the requred changes to Tiny HTTP 
Proxy (  
http://mail.python.org/pipermail/python-list/2003-June/168957.html ) or 
do I have to go with one of the more complicated proxies on sourceforge? 
I just want something that will give me a secondary non-expiring history 
list within the confines of addventure.bast-enterprises.de and provide a 
platform for some other features in the future.

You can get the sources as 
http://leary.csoft.net/~ssokolow/python/pyAddWrap.zip since I thought 
that they were a little too long to be attached inline and I don't know 
what happens to attachments which are sent to the mailing list. (this is 
my first time on a mailing list of ANY kind) If you lose the URL, you 
can also just go to www.ssokolow.com and browse to the Python section.

Thanks in advance and sorry for the length

Stephan Sokolow

From alan.gauld at blueyonder.co.uk  Thu Jan  1 05:24:35 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Thu Jan  1 05:24:18 2004
Subject: [Tutor] Saving Data
References: <20031230180835.74569.qmail@web13608.mail.yahoo.com>
Message-ID: <005701c3d051$73f23f50$6401a8c0@xp>


> I am lookign for a toutorial on how to save data
> created in a program so that it can be used when the
> parogram is started again. 

Try looking at the file handling topic in my tutor.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld

From alan.gauld at blueyonder.co.uk  Thu Jan  1 05:33:40 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Thu Jan  1 05:33:24 2004
Subject: [Tutor] mistake naming class
References: <1072815723.7933.0.camel@quercus>
Message-ID: <006601c3d052$b94b95a0$6401a8c0@xp>

> class open(object):
>         def __init__(world, person, animal):
>                 open('foo.txt', 'r')
>
> Any solutions other then renaming my class, because going through
the
> code looking for calls to class open is not going to be fun

It might not be fun but you really should do it. Naming a class
after a system name is a big problem(unless you really want to
hide the system name and provide alternative functionality. Even
then its probably better to do it with an alias.

Conventionally class names start with an uppercase letter. If
you had followed the convention this problem would not have
arisen. As to changing it, use a search tool like grep to find
all of the occurences. You will have to manually validate whether
it should be a call to your class or to the system open()

Incidentally its very unusualy to name a class after a verb.
Objects are things so the class name is usually a noun. Are
you sure you need a class and not just a function? Just a
thought...

[BTW there are several modules with an open function in them,
but they are doing so deliberately, usualky with 'file-like'
objects and are a good example of why you should never use
the from foo import * style...]

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


From alan.gauld at blueyonder.co.uk  Thu Jan  1 05:41:27 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Thu Jan  1 05:41:07 2004
Subject: [Tutor] Lambdas
References: <1072815771.7933.2.camel@quercus>
Message-ID: <006b01c3d053$cf3536e0$6401a8c0@xp>


> Okay well I guess I chose I bad example for lambdas, but i cant find
any
> good tutorials on them on the web.

They are covered briefly in my titor in the functional
programming topic. But for a more in depth coverage you
will need to turn to tutorials on Lisp/Scheme or other
functional languages like Haskell.

Thre is a also whole branch of math dedicated to this too, known
as lamda calculus, and it is the theoretical underpinning of
functional programming (and indeed most other programming styles too)
It depends just how dep you want to go...

> Where is an in depth tutorial on lambdas. Even though there not all
that
> necessary

lambdas are fundamental and essential, but you don't need
to use the work "lambda" to create one. In Python most
function definitions can be thought of as a lambda:

def f(x): return g(x)

is identical to the lambda form

f = lambda x: g(x)

After either we can assign the function object to another variable:

h = f

and call h(5) or whatever. We can also pass the function object
to another function as a parameter etc... So the only use of lambda
in Python is for anonymous functions, and they can always be
got around with traditional function declarations.

But understanding the ideas behind lambdas is vitally important to
understanding the principles of good programming, in any language.

Alan G.


From alan.gauld at blueyonder.co.uk  Thu Jan  1 05:45:54 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Thu Jan  1 05:45:35 2004
Subject: [Tutor] writing a program in Python
References: <20031230233033.26483.qmail@web12403.mail.yahoo.com>
Message-ID: <007401c3d054$6e8bc5b0$6401a8c0@xp>

> How do you actually write a program in Python?  I know
> how to use IDLE to manipulate data, but how do I write
> several lines of code that goes out and does stuff.

Can you give us an example of what you thoink of as a 
real program? Most real programs just "manipulate data".
What do you think is missing? What else would you like 
to do?

As for how to write the program physically, just use the 
File->New menu to create a blank text editor window. 
Type the code into that window and save it as a file 
of type .py. Double clicking the file in Explorer 
will run it. (You can also run it within Idle using 
the Edit->Run menu, which is handy when fixing bugs)

HTH,

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld

From alan.gauld at blueyonder.co.uk  Thu Jan  1 05:48:30 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Thu Jan  1 05:48:09 2004
Subject: [Tutor] Looking for a Python IDE
References: <742DADBF-3B28-11D8-9C38-00039314F97E@mac.com>
Message-ID: <007901c3d054$cb6e2750$6401a8c0@xp>


> hi everybody, can someone please suggest me a good python IDE for
Mac
> Os X ?

There's nothing as good as Pythonwin that I've seen.
You can run IDLE under X windows with some fussing around
with Tcl/Tk and fink.

But to be honest I just use the standard Mac IDE even though
its a bit primitive. Mostly I use vim (or BBEdit) and just run
the code from a Terminal session.

Alan G


From alan.gauld at blueyonder.co.uk  Thu Jan  1 06:01:08 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Thu Jan  1 06:00:47 2004
Subject: [Tutor] Are there any free project to download for studying?
References: <200312301324625.SM01292@chenren>
Message-ID: <00dd01c3d056$8f1a0d80$6401a8c0@xp>

>  But I want to see what else Python can do.

For serious projects go to sourceforge.net
and search for projects where the
development language is Python
- there are dozens(hundreds?)

> So I want to see other good programs and
> project.

If you want to read the code then a collection of smaller programs is
found at the Useless Python
website. It is explicitly aimed at providing
beginners with little sample programs to study.

Alan G.





From alan.gauld at blueyonder.co.uk  Thu Jan  1 06:03:26 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Thu Jan  1 06:03:04 2004
Subject: [Tutor] How to store key->multiple values?
References: <5.2.0.9.0.20031230224251.02ce9df0@mbox.jaring.my>
Message-ID: <00ea01c3d056$e1c477a0$6401a8c0@xp>

> I thought of using a dictionary but I found that dictionary only
allows one > value per key.

But the value can be a list :-)

> Can I use lists instead? How do I create a multidimensional
> list or tuple? How would I insert the values into a
> multidimensional list?

Have a look at the Raw Materials topic in my tutor.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


From matteolovatti at mac.com  Thu Jan  1 08:03:46 2004
From: matteolovatti at mac.com (matteo)
Date: Thu Jan  1 08:03:57 2004
Subject: [Tutor] Looking for a Python IDE
In-Reply-To: <007901c3d054$cb6e2750$6401a8c0@xp>
References: <742DADBF-3B28-11D8-9C38-00039314F97E@mac.com>
	<007901c3d054$cb6e2750$6401a8c0@xp>
Message-ID: <EEFCDB0B-3C5A-11D8-AB11-00039314F97E@mac.com>


On 01/gen/04, at 11:48, Alan Gauld wrote:

>
>> hi everybody, can someone please suggest me a good python IDE for
> Mac
>> Os X ?
>
> There's nothing as good as Pythonwin that I've seen.
> You can run IDLE under X windows with some fussing around
> with Tcl/Tk and fink.
>
> But to be honest I just use the standard Mac IDE even though
> its a bit primitive. Mostly I use vim (or BBEdit) and just run
> the code from a Terminal session.

Yesterday i've found this..
http://mail.python.org/pipermail/pythonmac-sig/2003-August/008468.html
it's similar to the carbon versione but at least has syntax-coloring !

matteo.


From brian at coolnamehere.com  Thu Jan  1 08:22:00 2004
From: brian at coolnamehere.com (Brian Wisti)
Date: Thu Jan  1 08:21:59 2004
Subject: [Tutor] Looking for a Python IDE
In-Reply-To: <007901c3d054$cb6e2750$6401a8c0@xp>
References: <742DADBF-3B28-11D8-9C38-00039314F97E@mac.com>
	<007901c3d054$cb6e2750$6401a8c0@xp>
Message-ID: <3FF41EF8.2090801@coolnamehere.com>

Hi,

Alan Gauld wrote:

>>hi everybody, can someone please suggest me a good python IDE for
>>    
>>
>Mac
>  
>
>>Os X ?
>>    
>>
>
>There's nothing as good as Pythonwin that I've seen.
>You can run IDLE under X windows with some fussing around
>with Tcl/Tk and fink.
>
>But to be honest I just use the standard Mac IDE even though
>its a bit primitive. Mostly I use vim (or BBEdit) and just run
>the code from a Terminal session.
>
>Alan G
>
>  
>
Thought I'd mention.  There are a few sorts of options, if you are 
looking at the concept of fiddling with things:

    - http://pythonmac.org/wiki/XcodeIntegration
      Folks are working on integrating OS X 10.3's nifty XCode tool with 
Python.

    - http://homepages.cwi.nl/~jack/macpython/download.html
       This binary download of Python includes a Carbonized version of 
Tkinter and IDLE.  No tweaking needed, but it's noticeably slow.

I'm sure there are more options, but those popped right into my head.  
If you're feeling less bold, I'd go for the Carbonized MacPython.

Kind Regards,
Brian Wisti
http://coolnamehere.com/



From ubabu at cse.iitk.ac.in  Thu Jan  1 10:59:26 2004
From: ubabu at cse.iitk.ac.in (Uppala Babu)
Date: Thu Jan  1 10:56:44 2004
Subject: [Tutor] Tkinter - How to get multilple windows
In-Reply-To: <3FF41EF8.2090801@coolnamehere.com>
Message-ID: <Pine.LNX.4.44.0401012122110.30901-100000@cselinux1.cse.iitk.ac.in>


I have one window which has some buttons and menus. On clicking the button
, how can i get a new window which has some other buttons and menus.


Window has "Options" button. On cliking it, i need one more window which 
has check boxes, buttons ..(widgets) etc.

Can any one please tell me how to do it in Tkinter

-- Babu

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
" Character is repeated habits and
      Only repeated habits can reform the Character "

			 - Swami Vivekananda.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
U Babu
M.Tech (Y211107) , CSE
Indian Institute of  Technology
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


From alan.gauld at blueyonder.co.uk  Thu Jan  1 13:29:38 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Thu Jan  1 13:29:12 2004
Subject: [Tutor] Tkinter - How to get multilple windows
References: <Pine.LNX.4.44.0401012122110.30901-100000@cselinux1.cse.iitk.ac.in>
Message-ID: <014901c3d095$3707fa00$6401a8c0@xp>

> I have one window which has some buttons and menus. 
> On clicking the button, how can i get a new window 
> which has some other buttons and menus.

Instantiate a new window object which inherits from 
TopLevel rather than a simple Frame.

Alan g.

From ubabu at cse.iitk.ac.in  Thu Jan  1 13:42:36 2004
From: ubabu at cse.iitk.ac.in (Uppala Babu)
Date: Thu Jan  1 13:39:45 2004
Subject: [Tutor] Tkinter - How to get multilple windows
In-Reply-To: <014901c3d095$3707fa00$6401a8c0@xp>
Message-ID: <Pine.LNX.4.44.0401020007260.27061-100000@cselinux1.cse.iitk.ac.in>

>> I have one window which has some buttons and menus. 
>> On clicking the button, how can i get a new window 
>> which has some other buttons and menus.

>Instantiate a new window object which inherits from 
>TopLevel rather than a simple Frame.



from Tkinter import *  # Interface to TK Widgets


#class which has the test button only
#oncliking the test button i need the One more window but here it is 
coming befo
class App(Frame):
        global quitButton , master
        def __init__(self, master=None):
                Frame.__init__(self,master)
                self.grid()
                self.createWidgets()

        def createWidgets(self):
                self.quitButton = 
Button(self,text="Test",command=self.openNew()
                self.quitButton.grid()


        def openNew(self):
                app1 = App1(self)
                app1.mainloop()


#quit class
class App1(Toplevel):
        def __init__(self,master=None):
                Toplevel.__init__(self,master)
                self.grid()
                self.createWidgets()

        def createWidgets(self):
                textButton = Button(self,text="Quit",command=self.quit)
                textButton.grid()
app = App()     #instance of the Application
app.master.title("Sample program")
app.mainloop()          #wait for the events




1. I am getting two windows
2. I want only the object of APP1 to quit not the entire program.

Can any please help me?



-- 

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
" Character is repeated habits and
      Only repeated habits can reform the Character "

			 - Swami Vivekananda.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
U.Babu
Parvathi Puram (village)
Madhavaram - 1 (post)
Sidhout (Mandal)
Kadapa (Dist) AP - 516247
----------------------------------------------------
Phones  : 08589-270716(Home)
	  0512-2597592 (Off)
Mail IDs: uppala_babu@yahoo.co.in
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


From missive at hotmail.com  Thu Jan  1 17:53:08 2004
From: missive at hotmail.com (Lee Harr)
Date: Thu Jan  1 17:53:13 2004
Subject: [Tutor] Re: Tkinter - How to get multilple windows
Message-ID: <BAY2-F15190SHMIVqGZ0005d440@hotmail.com>

from Tkinter import *  # Interface to TK Widgets


#class which has the test button only
#oncliking the test button i need the
#One more window but here it is coming befo
class App(Frame):
        global quitButton, master
        def __init__(self, master=None):
                Frame.__init__(self, master)
                self.grid()
                self.createWidgets()

        def createWidgets(self):
                self.createNewButton = Button(self, text="Create New 
Window",
                                            command=self.openNew)
                self.createNewButton.grid()

                self.quitButton = Button(self, text="Quit Application",
                                            command=self.quit)
                self.quitButton.grid()

        def openNew(self):
                self.app1 = App1(self)
                #app1.mainloop()


#quit class
class App1(Toplevel):
        def __init__(self, master=None):
                Toplevel.__init__(self, master)
                self.grid()
                self.createWidgets()

        def createWidgets(self):
                textButton = Button(self, text="Close This Window",
                                        command=self.destroy)
                textButton.grid()


app = App()     #instance of the Application
app.master.title("Sample program")
app.mainloop()          #wait for the events

_________________________________________________________________
Add photos to your messages with MSN 8. Get 2 months FREE*. 
http://join.msn.com/?page=features/featuredemail


From klappnase at freenet.de  Thu Jan  1 17:19:09 2004
From: klappnase at freenet.de (Michael Lange)
Date: Thu Jan  1 19:45:15 2004
Subject: [Tutor] Tkinter - How to get multilple windows
In-Reply-To: <Pine.LNX.4.44.0401020007260.27061-100000@cselinux1.cse.iitk.ac.in>
References: <014901c3d095$3707fa00$6401a8c0@xp>
	<Pine.LNX.4.44.0401020007260.27061-100000@cselinux1.cse.iitk.ac.in>
Message-ID: <20040101231909.7b477a94.klappnase@freenet.de>

On Fri, 2 Jan 2004 00:12:36 +0530 (IST)
Uppala Babu <ubabu@cse.iitk.ac.in> wrote:

> >> I have one window which has some buttons and menus. 
> >> On clicking the button, how can i get a new window 
> >> which has some other buttons and menus.
> 
> >Instantiate a new window object which inherits from 
> >TopLevel rather than a simple Frame.
> 
> 
> 
> from Tkinter import *  # Interface to TK Widgets
> 
> 
> #class which has the test button only
> #oncliking the test button i need the One more window but here it is 
> coming befo
> class App(Frame):
>         global quitButton , master
>         def __init__(self, master=None):
>                 Frame.__init__(self,master)
>                 self.grid()
>                 self.createWidgets()
> 
>         def createWidgets(self):
>                 self.quitButton = 
> Button(self,text="Test",command=self.openNew()
>                 self.quitButton.grid()
> 
> 
>         def openNew(self):
>                 app1 = App1(self)
>                 app1.mainloop()
> 
> 
> #quit class
> class App1(Toplevel):
>         def __init__(self,master=None):
>                 Toplevel.__init__(self,master)
>                 self.grid()
>                 self.createWidgets()
> 
>         def createWidgets(self):
>                 textButton = Button(self,text="Quit",command=self.quit)
>                 textButton.grid()
> app = App()     #instance of the Application
> app.master.title("Sample program")
> app.mainloop()          #wait for the events
> 
> 
> 
> 
> 1. I am getting two windows
> 2. I want only the object of APP1 to quit not the entire program.
> 
> Can any please help me?
> 
> 
> 

1. In your createWidgets method you defined the button with the "command=self.openNew()" option;
the brackets after "openNew" were the mistake, if the command option is specified this way,
the command will be executed the moment the button is created. Use "command=self.openNew" instead.

2. The "quit" command exits the mainloop and "quits" the application this way; if you just want to
"destroy" one widget (like a Toplevel window) use its "destroy" method instead:
	textButton = Button(self,text="Quit",command=self.destroy)
(BTW , you do not need an own mainloop() for your Toplevel window as you defined in your App.openNew() method.)

I hope this helps

Good luck

Michael

From matteolovatti at mac.com  Thu Jan  1 21:32:40 2004
From: matteolovatti at mac.com (matteo)
Date: Thu Jan  1 21:32:48 2004
Subject: [Tutor] keeping the program alive
Message-ID: <EF9F1AA4-3CCB-11D8-AA97-00039314F97E@mac.com>

hi everybody!

i've put this in my small program, just to keep it running continuosly

while 1:
	connect_to_server() #it does some things..
  	sleep(120)

i execute the program with "python script.py &"
it runs well for about 5 minutes but then it quits.
how can i fix it ?

thanks

matteo
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: text/enriched
Size: 344 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20040102/e05df8e9/attachment.bin
From missive at hotmail.com  Thu Jan  1 22:18:40 2004
From: missive at hotmail.com (Lee Harr)
Date: Thu Jan  1 22:18:45 2004
Subject: [Tutor] Re: keeping the program alive
Message-ID: <BAY2-F156uPDVniSnRM00000e4e@hotmail.com>

>i've put this in my small program, just to keep it running continuosly
>
>while 1:
>       connect_to_server() #it does some things..
>       sleep(120)
>
>i execute the program with "python script.py &"
>it runs well for about 5 minutes but then it quits.
>how can i fix it ?


We're going to need a bit more ...

Try running it without the & and see if you get an error message.

_________________________________________________________________
Tired of spam? Get advanced junk mail protection with MSN 8. 
http://join.msn.com/?page=features/junkmail


From from_python_tutor at SSokolow.com  Fri Jan  2 02:55:13 2004
From: from_python_tutor at SSokolow.com (SSokolow)
Date: Fri Jan  2 02:55:18 2004
Subject: [Tutor] Best way to alter sections of a string which match
	dictionary keys?
Message-ID: <3FF523E1.6060702@SSokolow.com>

I have a proxy which stores a list of URLs visited withing a certain 
server as keys in a dictionary and currently all the values are just set 
to 1 (I have some ideas for future expansion though.) Originally this 
was just because it was the easiest way to prevent duplication of entries.

Example: {'/2048.html': 1, '/index.html': 1, '/1.html': 1}

My problem is that I want to add <img src="_proxy/checkmark.png" /> 
beside every hyperlinked block of text which links to one of these URLs. 
A while ago when I made the Perl CGI version (aborted), the only way I 
could find was to waste resources using this code:

while( ($key, $value)=each %viewedEpisodes) {
  $file=~s/(.*)<a(.*)href="($key)"(.*)>(.*)/$1<img 
src="$imgDir\/check.png"><a$2href="$3"$4>$5/ig;
}

which is roughly equivalent to: (I didn't have time to test this)

for URL in viewedEpisodes|.keys()
    file = re.sub(r'||(?i)||(<a.*?href="' + URL + r'".*?)', file, 
||r'<img src="' + imgDir + r'/check.png">\1')


|I could just use that code in Python (It would work, right?) but it 
would be a complete waste of processor cycles.
What would be the best way to accomplish the task without wasting so 
much time looping?

Thanks

Stephan Sokolow

From piir at earthlink.net  Fri Jan  2 08:43:37 2004
From: piir at earthlink.net (Todd G. Gardner)
Date: Fri Jan  2 08:43:42 2004
Subject: [Tutor] to/from binary to/from integer (i.e.'01010101' = 85)
Message-ID: <IIEDILADJDCBOHAJNADIMEAPCCAA.piir@earthlink.net>

Hello everyone,

I was wondering if anyone happens to know how to convert to/from binary
to/from integer (i.e.'01010101' = 85)

Thanks for any pointers,

Todd


From carroll at tjc.com  Fri Jan  2 12:03:45 2004
From: carroll at tjc.com (Terry Carroll)
Date: Fri Jan  2 12:03:51 2004
Subject: [Tutor] to/from binary to/from integer (i.e.'01010101' = 85)
In-Reply-To: <IIEDILADJDCBOHAJNADIMEAPCCAA.piir@earthlink.net>
Message-ID: <Pine.LNX.4.44.0401020853400.5627-100000@mauve.rahul.net>

On Fri, 2 Jan 2004, Todd G. Gardner wrote:

> I was wondering if anyone happens to know how to convert to/from binary
> to/from integer (i.e.'01010101' = 85)

Here's a quick and dirty, with no error checking:

def binstring2dec(str):
    result = 0
    for i in range(0,len(str)):
        result = (result*2)+(str[i]=="1")
    return result

It just loops through the string, multiplying an accumulated result by two 
each time, and incrementing it when a 1 is detected.

As I said, it does no error checking; it assumes that each character in
the string is either a "1" or a "0", so a bug is that if you send it a
noncompliant string, any non-1 character will be treated as a zero:

>>> binstring2dec("01010101")
85
>>> binstring2dec("21212121")
85
>>> binstring2dec("x1x1x1x1")
85

Come to think of it, here's better one, that's a little cleaner (it 
doesn't depend on True == 1), and will choke on bad data:

def binstring2dec(str):
    result = 0
    lookup = {'0':0, '1':1}
    for i in range(0,len(str)):
        result = (result*2)+lookup[str[i]]
    return result

>>> binstring2dec("01010101")
85
>>> binstring2dec("21212121")
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "bintest.py", line 11, in binstring2dec
    result = (result*2)+lookup[str[i]]
KeyError: '2'

-- 
Terry Carroll
Santa Clara, CA
carroll@tjc.com 


From darnold02 at sprynet.com  Fri Jan  2 12:17:02 2004
From: darnold02 at sprynet.com (don arnold)
Date: Fri Jan  2 12:17:54 2004
Subject: [Tutor] to/from binary to/from integer (i.e.'01010101' = 85)
References: <IIEDILADJDCBOHAJNADIMEAPCCAA.piir@earthlink.net>
Message-ID: <018801c3d154$507a5b80$7710ba3f@don2uvsu54fwiq>

----- Original Message -----
From: "Todd G. Gardner" <piir@earthlink.net>
To: "Tutor@Python. Org" <tutor@python.org>
Sent: Friday, January 02, 2004 7:43 AM
Subject: [Tutor] to/from binary to/from integer (i.e.'01010101' = 85)


> Hello everyone,
>
> I was wondering if anyone happens to know how to convert to/from binary
> to/from integer (i.e.'01010101' = 85)
>
> Thanks for any pointers,
>
> Todd

The int() function will do the conversion from binary (and other bases)
for you if you supply the optional base parameter:

>>> int('1111111',2)
127
>>> int('001',2)
1
>>> int('17',8)
15

I _thought_ there was a function somewhere to convert an int to a binary
string,
but I couldn't find it. So, here's a function that will convert an int to
string of any
base up to 36:

import string

digits = string.digits + string.ascii_uppercase

def convert(num, base):
    res = []

    divisor = 1
    while num >= divisor * base:
        divisor *= base

    remainder = num

    while divisor >= 1:
        index, remainder = divmod(remainder,divisor)
        res.append(digits[index])
        divisor /= base

    res = ''.join(res)

    if int(res, base) != num:
        raise 'bad conversion!'

    return res

if __name__ == '__main__':
    while 1:
        num = raw_input('number to convert: ')
        if num == '':
            break
        num = int(num)
        base = int(raw_input('base             : '))
        print '%d in base %d is %s' % (num, base, convert(num,base))
        print


[example output:]

number to convert: 255
base             : 2
255 in base 2 is 11111111

number to convert: 255
base             : 16
255 in base 16 is FF

number to convert: 255
base             : 10
255 in base 10 is 255

number to convert: 255
base             : 8
255 in base 8 is 377

number to convert:


HTH,
Don


From carroll at tjc.com  Fri Jan  2 12:43:20 2004
From: carroll at tjc.com (Terry Carroll)
Date: Fri Jan  2 12:43:26 2004
Subject: [Tutor] to/from binary to/from integer (i.e.'01010101' = 85)
In-Reply-To: <018801c3d154$507a5b80$7710ba3f@don2uvsu54fwiq>
Message-ID: <Pine.LNX.4.44.0401020942170.5627-100000@mauve.rahul.net>

On Fri, 2 Jan 2004, don arnold wrote:

> The int() function will do the conversion from binary (and other bases)
> for you if you supply the optional base parameter:
> 
> >>> int('1111111',2)
> 127

Well, heck, that takes all the fun out of it.  :-)


-- 
Terry Carroll
Santa Clara, CA
carroll@tjc.com 


From bgailer at alum.rpi.edu  Fri Jan  2 13:24:17 2004
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Fri Jan  2 13:24:26 2004
Subject: [Tutor] Best way to alter sections of a string which match
	dictionary keys?
In-Reply-To: <3FF523E1.6060702@SSokolow.com>
References: <3FF523E1.6060702@SSokolow.com>
Message-ID: <6.0.0.22.0.20040102105052.034f56e0@mail.mric.net>

At 12:55 AM 1/2/2004, SSokolow wrote:

>I have a proxy which stores a list of URLs visited withing a certain 
>server as keys in a dictionary and currently all the values are just set 
>to 1 (I have some ideas for future expansion though.) Originally this was 
>just because it was the easiest way to prevent duplication of entries.
>
>Example: {'/2048.html': 1, '/index.html': 1, '/1.html': 1}
>
>My problem is that I want to add <img src="_proxy/checkmark.png" /> beside 
>every hyperlinked block of text which links to one of these URLs. A while 
>ago when I made the Perl CGI version (aborted), the only way I could find 
>was to waste resources using this code:
>
>while( ($key, $value)=each %viewedEpisodes) {
>  $file=~s/(.*)<a(.*)href="($key)"(.*)>(.*)/$1<img 
> src="$imgDir\/check.png"><a$2href="$3"$4>$5/ig;
>}
>
>which is roughly equivalent to: (I didn't have time to test this)
>
>for URL in viewedEpisodes|.keys()
>    file = re.sub(r'||(?i)||(<a.*?href="' + URL + r'".*?)', file, ||r'<img 
> src="' + imgDir + r'/check.png">\1')

I am reluctant to answer this question (since it takes some time and energy 
to construct a thoughtful reply), but since no one else has...

This question is hard to tackle for the following reasons. I hope you will 
be able to restructure the question so we can really help you, and that in 
the future you will be able to ask questions that are clear and to the point.

1) many of us do not know Perl. so including Perl code does not help us.

2) "I didn't have time to test this" is obvious since the code does not 
compile. Please either present tested code or ask questions without code. 
It is also unclear what you want from the vertical bars in the re match 
string (vertical bars are used as OR operators to separate regular expressions.

3) what would be most useful is to give us a before and after example e.g. 
'/2048.html becomes blahblahblah (I have no idea what the desired outcome is)

4) file is a built-in function. It is inadvisable to rebind the name to a 
string.

>I could just use that code in Python (It would work, right?) but it would 
>be a complete waste of processor cycles.
>What would be the best way to accomplish the task without wasting so much 
>time looping?

5) How much time is "wasted"? Did you measure it? Processing multiple items 
requires looping. The alternatives to for statements in Python is list 
comprehension and while.

6) usually we like to write code that does the job, then assess the 
efficiency aspect. Often the code we write does the job in less time than 
we thought, and is OK as is.

Bob Gailer
bgailer@alum.rpi.edu
303 442 2625 home
720 938 2625 cell 
-------------- next part --------------

---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.556 / Virus Database: 348 - Release Date: 12/26/2003
From anschau at shaw.ca  Fri Jan  2 14:41:49 2004
From: anschau at shaw.ca (Anschau Gesicht)
Date: Fri Jan  2 14:45:13 2004
Subject: [Tutor] Segmentation Fault Problem
Message-ID: <20040102134149.54596999.anschau@shaw.ca>

I continue on my endless(and seemingly futile)attempt to learn a
programming language.  Currently I'm attempting small scripts in
Python/Tkinter.  The particular script is a textbox script at follows

#!/usr/lib/python2.2

from Tkinter import *
from ScrolledText import *
import sys

def die(event):
  sys.exit(0)

root = Tk()
f = Frame(root)
f.pack(expand=1, fill=BOTH)
button = Button(f, width=25)
button["text"] = "Button"
button.bind("<Button>",die)
button.pack()

st = ScrolledText(f,background="white")
st.pack()

root.mainloop()

Very simple and straight forward but if I mouseclick in the text window
the program seg faults.  Can anyone tell me why?  As an aside, I cannot
use idle (a text editor) because it seg faults everytime I try to
initialize.  

Eve

P.S. My platform is RedHat Linux v 9 and Python v2.2

From klappnase at freenet.de  Fri Jan  2 16:09:43 2004
From: klappnase at freenet.de (Michael Lange)
Date: Fri Jan  2 16:17:18 2004
Subject: [Tutor] Segmentation Fault Problem
In-Reply-To: <20040102134149.54596999.anschau@shaw.ca>
References: <20040102134149.54596999.anschau@shaw.ca>
Message-ID: <20040102220943.7d31e7f1.klappnase@freenet.de>

On Fri, 02 Jan 2004 13:41:49 -0600
Anschau Gesicht <anschau@shaw.ca> wrote:

> I continue on my endless(and seemingly futile)attempt to learn a
> programming language.  Currently I'm attempting small scripts in
> Python/Tkinter.  The particular script is a textbox script at follows
> 
> #!/usr/lib/python2.2
> 
> from Tkinter import *
> from ScrolledText import *
> import sys
> 
> def die(event):
>   sys.exit(0)
> 
> root = Tk()
> f = Frame(root)
> f.pack(expand=1, fill=BOTH)
> button = Button(f, width=25)
> button["text"] = "Button"
> button.bind("<Button>",die)
> button.pack()
> 
> st = ScrolledText(f,background="white")
> st.pack()
> 
> root.mainloop()
> 
> Very simple and straight forward but if I mouseclick in the text window
> the program seg faults.  Can anyone tell me why?  As an aside, I cannot
> use idle (a text editor) because it seg faults everytime I try to
> initialize.  
> 
> Eve
> 
> P.S. My platform is RedHat Linux v 9 and Python v2.2
> 
Hi,

there is obviously something wrong with your python and/or tk installation; 
might this have something to do with the shebang line you use here??
Maybe it is just a typo, the shebang should point to your python executable,
probably #!/usr/bin/python or if you don't know the exact path #!/usr/bin/env python .
Anyway, your code should work (so should IDLE); do you use RedHat's default tk version
(which?)? Just a guess, it looks to me a little like python was trying to use another
tk version as it has been compiled for, maybe there's a problem with python2.2 and tk8.4?
I have also heard of people having problems with multiple tk versions installed.

Good luck

Michael

From nullpointer at heartoftn.net  Fri Jan  2 16:46:30 2004
From: nullpointer at heartoftn.net (Null Pointer)
Date: Fri Jan  2 16:47:36 2004
Subject: [Tutor] Segmentation Fault Problem
In-Reply-To: <20040102220943.7d31e7f1.klappnase@freenet.de>
References: <20040102134149.54596999.anschau@shaw.ca>
	<20040102220943.7d31e7f1.klappnase@freenet.de>
Message-ID: <200401021646.30015.nullpointer@heartoftn.net>

On Fri, 02 Jan 2004 13:41:49 -0600
Anschau Gesicht <anschau@shaw.ca> wrote:

> I continue on my endless(and seemingly futile)attempt to learn
> a programming language.  Currently I'm attempting small scripts
> in Python/Tkinter.  The particular script is a textbox script
> at follows
> 
> #!/usr/lib/python2.2

[Snip]

This might be caused by a library incompatibility.  I had a similar 
problem (not with TKinter, though) that was fixed by changing the 
script's first line to:

#!/usr/lib/python2.1 

If you have 2.1 installed alongside 2.2, you might give it a try.

N.P.




From dyoo at hkn.eecs.berkeley.edu  Fri Jan  2 17:11:37 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri Jan  2 17:11:42 2004
Subject: [Tutor] to/from binary to/from integer (i.e.'01010101' = 85)
In-Reply-To: <IIEDILADJDCBOHAJNADIMEAPCCAA.piir@earthlink.net>
Message-ID: <Pine.LNX.4.44.0401021406460.25606-100000@hkn.eecs.berkeley.edu>



On Fri, 2 Jan 2004, Todd G. Gardner wrote:

> Hello everyone,
>
> I was wondering if anyone happens to know how to convert to/from binary
> to/from integer (i.e.'01010101' = 85).

Hi Todd,

But how do you know '01010101' in binary is 85 in decimal?  Show us the
process you're "doing by hand"  to find that out.  That may help you write
a program to do the same thing.

(People have already started showing you Python builtins that will
automagically do the base conversion, but is that what you're looking
for?)


From from_python_tutor at SSokolow.com  Fri Jan  2 17:16:33 2004
From: from_python_tutor at SSokolow.com (SSokolow)
Date: Fri Jan  2 17:16:41 2004
Subject: [Tutor] Clarified: Best way to alter sections of a string which
 match dictionary keys?
In-Reply-To: <6.0.0.22.0.20040102105052.034f56e0@mail.mric.net>
References: <3FF523E1.6060702@SSokolow.com>
	<6.0.0.22.0.20040102105052.034f56e0@mail.mric.net>
Message-ID: <3FF5EDC1.3070007@SSokolow.com>

OK. Here's my attempt at fixing my question:
I am making a modified version of amit's proxy 4 
(http://theory.stanford.edu/~amitp/proxy.html) in order to provide some 
client-side enhancements to the Anime Addventure 
(http://addventure.bast-enterprises.de/) such as non-expiring page history.

It does currently work and here's the tested functional code to put a 
checkmark beside each visited link:

        for url_key in episodesViewed.keys():
            string = re.sub(r'(?i)(<a.*?href="' + url_key[1:] + 
r'".*?)', r'<img src="http://_proxy/checkmark.png">\1', string)

each key in episodesViewed is a URL such as "/10523.html" and the 
variable name string is not my choice. It is a standard convention for 
all transport-level decoding modules in proxy 4 (I haven't figured out 
how to hook this code in at the content level so I'm improvising)

The reason that this will take too long with the regular expression 
shown is because it will run once for every item in the dictionary. This 
will be a scalability problem since the dictionary will grow to contain 
over 15,000 URLs. I haven't been able to time it but I do know that 
running dictionary.has_key() for no more than 10 substrings is a lot 
faster than running that regular expression 15,000 times.

The result is that a hyperlink such as <a href="10523.html">Episode 
10523</a> will become <img src="http://_proxy/checkmark.png"><a 
href="10523.html">Episode 10523</a> but only if /10523.html is a key in 
the episodesViewed dictionary.

Currently, the code runs the regular expression for each item in the 
dictionary (which, as I said, will grow to be over 15,000 keys). What I 
want is some code that loops through each link in the page (the string 
variable holds the contents of an HTML file) and uses 
everMemory.has_key() to figure out whether it should put <img 
src="http://_proxy/checkmark.png"> beside the link.

Hope this is a little more understandable

Stephan Sokolow

From tim at johnsons-web.com  Fri Jan  2 17:25:25 2004
From: tim at johnsons-web.com (Tim Johnson)
Date: Fri Jan  2 17:23:45 2004
Subject: [Tutor] Segmentation Fault Problem
In-Reply-To: <20040102134149.54596999.anschau@shaw.ca>
References: <20040102134149.54596999.anschau@shaw.ca>
Message-ID: <20040102222525.GI32756@johnsons-web.com>

* Anschau Gesicht <anschau@shaw.ca> [040102 10:58]:
> I continue on my endless(and seemingly futile)attempt to learn a
> programming language.  Currently I'm attempting small scripts in
> Python/Tkinter.  The particular script is a textbox script at follows
> 
> #!/usr/lib/python2.2
> 
> from Tkinter import *
> from ScrolledText import *
> import sys
> 
> def die(event):
>   sys.exit(0)
> 
> root = Tk()
> f = Frame(root)
> f.pack(expand=1, fill=BOTH)
> button = Button(f, width=25)
> button["text"] = "Button"
> button.bind("<Button>",die)
> button.pack()
> 
> st = ScrolledText(f,background="white")
> st.pack()
> 
> root.mainloop()
> 
> Very simple and straight forward but if I mouseclick in the text window
> the program seg faults.  Can anyone tell me why?  As an aside, I cannot
> use idle (a text editor) because it seg faults everytime I try to
> initialize.  
> 
> Eve
> 
> P.S. My platform is RedHat Linux v 9 and Python v2.2
 
 I'm using the same. And in my case is an upgrade from
 a RH 7.2 fresh install, our experience is that upgrades
 on RH can get messy.

 Here's a couple of things that I would do:
 From a console
 execute as follows:
 [tim@linus tim]$ /usr/lib/python2.2
 # result on my machine:
 bash: /usr/lib/python2.2: is a directory
 # Hmm! Not pointing to an executable

 Try this also
 [tim@linus tim]$ which python
 # result: the executable at path below.
 /usr/local/bin/python

 Execute the the which path, just to see what version it
 is:
[tim@linus tim]$ /usr/local/bin/python
Python 2.2.2 (#1, Nov  2 2003, 13:27:48)
[GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

 You might want to try a simple "helloworld" approach
 as in below (caution untested code with psuedo-tag)

 #!<path result from $ which python>
 print "hello"

 See what happens then...
 If that works, then try the simplest possible
 tk call, if it breaks, as has been suggested by others,
 you may need to confirm what version of tk/tkinter
 you're using.

 tim

-- 
Tim Johnson <tim@johnsons-web.com>
      http://www.alaska-internet-solutions.com

From anschau at shaw.ca  Fri Jan  2 17:20:23 2004
From: anschau at shaw.ca (Anschau Gesicht)
Date: Fri Jan  2 17:27:42 2004
Subject: [Tutor] Segmentation Fault Problem
In-Reply-To: <20040102220943.7d31e7f1.klappnase@freenet.de>
References: <20040102134149.54596999.anschau@shaw.ca>
	<20040102220943.7d31e7f1.klappnase@freenet.de>
Message-ID: <20040102162023.5dbd0f68.anschau@shaw.ca>

On Fri, 02 Jan 2004 22:09:43 +0100
Michael Lange <klappnase@freenet.de> wrote:

<snip>

> Hi,
> 
> there is obviously something wrong with your python and/or tk
> installation; might this have something to do with the shebang line
> you use here?? 

Good guess.  I fixed that but the problem persists.

Maybe it is just a typo, the shebang should point to
> your python executable, probably #!/usr/bin/python or if you don't
> know the exact path #!/usr/bin/env python . Anyway, your code should
> work (so should IDLE); do you use RedHat's default tk version(which?)?
> Just a guess, it looks to me a little like python was trying to use
> another tk version as it has been compiled for, maybe there's a
> problem with python2.2 and tk8.4? 

I recently did a new install of RedHat 9.  The version of Python and tk
are standard with Redhat 9 (python v 2.2.3-26 and tk-8.3.1-45mlx). I
don't have multiple version installed

I have also heard of people having
> problems with multiple tk versions installed.

I may be way off base here but is it possible that it has something to
do with the version of gcc installed.  Redhat 9 includes both
gcc-3.2.2-5v and gcc296. I know that many of Python's libraries are
written in c and I've been having trouble compiling c code too.  If this
is the problem, how do I correct it?

Eve

From piir at earthlink.net  Fri Jan  2 14:52:33 2004
From: piir at earthlink.net (Todd G. Gardner)
Date: Fri Jan  2 17:51:03 2004
Subject: [Tutor] to/from binary to/from integer (i.e.'01010101' = 85)
In-Reply-To: <018801c3d154$507a5b80$7710ba3f@don2uvsu54fwiq>
Message-ID: <IIEDILADJDCBOHAJNADIAEBICCAA.piir@earthlink.net>

Don,

I am not positive if I should give you the greatly deserved thank you so if
I am wrong I apologize, but THANK YOU.

I thank you SO much for this code.  int and convert functions it seems to
work perfectly all bases that I need!

Thanks again,

Todd
-----Original Message-----
From: don arnold [mailto:darnold02@sprynet.com]
Sent: Friday, January 02, 2004 12:17 PM
To: Todd G. Gardner; Tutor@Python. Org
Subject: Re: [Tutor] to/from binary to/from integer (i.e.'01010101' =
85)


----- Original Message -----
From: "Todd G. Gardner" <piir@earthlink.net>
To: "Tutor@Python. Org" <tutor@python.org>
Sent: Friday, January 02, 2004 7:43 AM
Subject: [Tutor] to/from binary to/from integer (i.e.'01010101' = 85)


> Hello everyone,
>
> I was wondering if anyone happens to know how to convert to/from binary
> to/from integer (i.e.'01010101' = 85)
>
> Thanks for any pointers,
>
> Todd

The int() function will do the conversion from binary (and other bases)
for you if you supply the optional base parameter:

>>> int('1111111',2)
127
>>> int('001',2)
1
>>> int('17',8)
15

I _thought_ there was a function somewhere to convert an int to a binary
string,
but I couldn't find it. So, here's a function that will convert an int to
string of any
base up to 36:

import string

digits = string.digits + string.ascii_uppercase

def convert(num, base):
    res = []

    divisor = 1
    while num >= divisor * base:
        divisor *= base

    remainder = num

    while divisor >= 1:
        index, remainder = divmod(remainder,divisor)
        res.append(digits[index])
        divisor /= base

    res = ''.join(res)

    if int(res, base) != num:
        raise 'bad conversion!'

    return res

if __name__ == '__main__':
    while 1:
        num = raw_input('number to convert: ')
        if num == '':
            break
        num = int(num)
        base = int(raw_input('base             : '))
        print '%d in base %d is %s' % (num, base, convert(num,base))
        print


[example output:]

number to convert: 255
base             : 2
255 in base 2 is 11111111

number to convert: 255
base             : 16
255 in base 16 is FF

number to convert: 255
base             : 10
255 in base 10 is 255

number to convert: 255
base             : 8
255 in base 8 is 377

number to convert:


HTH,
Don


From klappnase at freenet.de  Fri Jan  2 18:54:37 2004
From: klappnase at freenet.de (Michael Lange)
Date: Fri Jan  2 19:02:10 2004
Subject: [Tutor] Segmentation Fault Problem
In-Reply-To: <20040102162023.5dbd0f68.anschau@shaw.ca>
References: <20040102134149.54596999.anschau@shaw.ca>
	<20040102220943.7d31e7f1.klappnase@freenet.de>
	<20040102162023.5dbd0f68.anschau@shaw.ca>
Message-ID: <20040103005437.717be6ee.klappnase@freenet.de>

On Fri, 02 Jan 2004 16:20:23 -0600
Anschau Gesicht <anschau@shaw.ca> wrote:


> 
> I may be way off base here but is it possible that it has something to
> do with the version of gcc installed.  Redhat 9 includes both
> gcc-3.2.2-5v and gcc296. I know that many of Python's libraries are
> written in c and I've been having trouble compiling c code too.  If this
> is the problem, how do I correct it?
> 

I can hardly imagine that this is gcc's fault, unless you have compiled python / tk yourself.
Maybe the default packages are broken, maybe it is worth a try to get the original sources
from python.org and scriptics and reinstall both python and tcl/tk (in case you get your compiler working).
I have seen a recent thread on comp.lang.python where someone had similar problems with RedHat9; he tended
to blame the kernel:

http://groups.google.de/groups?dq=&hl=de&lr=&ie=UTF-8&threadm=slrnbvb568.uoq.Markus.Franke%40herein.hrz.tu-chemnitz.de&prev=/groups%3Fhl%3Dde%26lr%3D%26ie%3DUTF-8%26group%3Dcomp.lang.python

I used RedHat9 a while ago, but probably not exact the same version, because Tkinter seemed to work, however tix was broken.
A new install from the developer's sources seemed to fix the problem, however I did not much testing and uninstalled the 
whole thing.

Cheers

Michael

From pxlpluker at cfl.rr.com  Fri Jan  2 20:38:32 2004
From: pxlpluker at cfl.rr.com (pxlpluker)
Date: Fri Jan  2 20:39:30 2004
Subject: [Tutor] Help with IDE please
In-Reply-To: <20040102134149.54596999.anschau@shaw.ca>
References: <20040102134149.54596999.anschau@shaw.ca>
Message-ID: <3FF61D18.2040109@cfl.rr.com>

To date i have been using the pythonwin IDE buts its acting real flakey 
lately. How is idle or DrPython. and where can i find a tutorial on IDLE?

tia

Fred


From anschau at shaw.ca  Fri Jan  2 21:04:32 2004
From: anschau at shaw.ca (Anschau Gesicht)
Date: Fri Jan  2 21:04:37 2004
Subject: [Tutor] Segmentation Fault Problem
In-Reply-To: <20040102134149.54596999.anschau@shaw.ca>
References: <20040102134149.54596999.anschau@shaw.ca>
Message-ID: <20040102200432.4d9f1117.anschau@shaw.ca>

On Fri, 02 Jan 2004 13:41:49 -0600
Anschau Gesicht <anschau@shaw.ca> wrote:

> I continue on my endless(and seemingly futile)attempt to learn a
> programming language.  Currently I'm attempting small scripts in
> Python/Tkinter.  The particular script is a textbox script at follows
> 
> #!/usr/bin/python2.3
> 
> from Tkinter import *
> from ScrolledText import *
> import sys
> 
> def die(event):
>   sys.exit(0)
> 
> root = Tk()
> f = Frame(root)
> f.pack(expand=1, fill=BOTH)
> button = Button(f, width=25)
> button["text"] = "Button"
> button.bind("<Button>",die)
> button.pack()
> 
> st = ScrolledText(f,background="white")
> st.pack()
> 
> root.mainloop()
> 
> Very simple and straight forward but if I mouseclick in the text
> window the program seg faults.  Can anyone tell me why?  As an aside,
> I cannot use idle (a text editor) because it seg faults everytime I
> try to initialize.  

I have solved my problem and I think it may have been mismatched
versions of python and tkinter.  Because I had a fairly recent install
of Redhat 9 I thought I had the original installs of both python and
tkinter.  It looks as though I may have upgraded python but not tkinter.
I've installed 2.3 version of each now and my script works as does idle.

Thanks everyone for pointing me in the right direction.

Eve

From sigurd at 12move.de  Fri Jan  2 22:22:27 2004
From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=)
Date: Fri Jan  2 22:22:17 2004
Subject: [Tutor] Clarified: Best way to alter sections of a string which
	match dictionary keys?
In-Reply-To: <3FF5EDC1.3070007@SSokolow.com> (SSokolow's message of "Fri, 02
	Jan 2004 17:16:33 -0500")
References: <3FF523E1.6060702@SSokolow.com>
	<6.0.0.22.0.20040102105052.034f56e0@mail.mric.net>
	<3FF5EDC1.3070007@SSokolow.com>
Message-ID: <m3d6a1zr2l.fsf@hamster.pflaesterer.de>

On  2 Jan 2004, SSokolow <- from_python_tutor@SSokolow.com wrote:

> It does currently work and here's the tested functional code to put a
> checkmark beside each visited link:

>         for url_key in episodesViewed.keys():
>             string = re.sub(r'(?i)(<a.*?href="' + url_key[1:] +
>             r'".*?)', r'<img src="http://_proxy/checkmark.png">\1',
>             string)

> each key in episodesViewed is a URL such as "/10523.html" and the
> variable name string is not my choice. It is a standard convention for
> all transport-level decoding modules in proxy 4 (I haven't figured out
> how to hook this code in at the content level so I'm improvising)
[...]
> The result is that a hyperlink such as <a href="10523.html">Episode
> 10523</a> will become <img src="http://_proxy/checkmark.png"><a
> href="10523.html">Episode 10523</a> but only if /10523.html is a key
> in the episodesViewed dictionary.

> I want is some code that loops through each link in the page (the
> string variable holds the contents of an HTML file) and uses
> everMemory.has_key() to figure out whether it should put <img
> src="http://_proxy/checkmark.png"> beside the link.

> Hope this is a little more understandable

Yes it is. here is an attempt to achieve what you want.  Perhaps you
have to frob the regexp a bit but I think it will match.

********************************************************************
import sre

reg = sre.compile(
                  r"""
                  (?P<preanchor>.*?)
                  (?P<anchor><a.*?href=(?:\"|')
                  (?P<ref>.*?)
                  (?:\"|').*?</a>)
                  """, sre.I | sre.S |sre.X)

episodesViewed = {} # fill it with your values

def sub_if_in_hash(matcho):
    dic = matcho.groupdict()
    if dic['ref'] in episodesViewed:
        return dic['preanchor'] + '<img src="_proxy/checkmark.png" />"' + dic['anchor']
    else:
        return dic['preanchor'] + dic['anchor']
    
string = reg.sub(sub_if_in_hash, string)

********************************************************************

To the regexp
-------------

It has three parts:
(?P<preanchor>.*?)
        Here the part before an anchor is found
(?P<anchor><a.*?href=(?:\"|')
        Here we find an anchor
(?P<ref>.*?)
        Here we grab the reference
(?:\"|').*?</a>)
        This closes our groups

All groups get names; that makes it nicer to work with matching groups
IMO.

The function gets calles with every match found.  It checks if the
reference is in the hash table; if yes it returns a changed version of
the match; if not the match is returned unchanged.

The string is processed only once and the lookups in the dictionary are
pretty fast.  Test it with real data maybe you have to change the regexp
a bit.

You could have one problem: if there was an HTML page without any links
the regexp would fail.  Best is you check that first (but on the other
hand; which HTML site does not have at least one link?).



   Karl
-- 
Please do *not* send copies of replies to me.
I read the list


From from_python_tutor at SSokolow.com  Sat Jan  3 01:42:00 2004
From: from_python_tutor at SSokolow.com (SSokolow)
Date: Sat Jan  3 01:42:04 2004
Subject: [Tutor] Clarified: Best way to alter sections of a string which
	match dictionary keys?
In-Reply-To: <m3d6a1zr2l.fsf@hamster.pflaesterer.de>
References: <3FF523E1.6060702@SSokolow.com>	<6.0.0.22.0.20040102105052.034f56e0@mail.mric.net>	<3FF5EDC1.3070007@SSokolow.com>
	<m3d6a1zr2l.fsf@hamster.pflaesterer.de>
Message-ID: <3FF66438.6060300@SSokolow.com>

Thanks. (more like 'my eternal gratitude')

 It's much faster and I would have never thought of it. I'm still 
thinking mostly in intermediate Perl and that means I never considered 
the possibility that the replacement expression could be anything more 
than a plain vanilla string.

Stephan Sokolow


From piir at earthlink.net  Sat Jan  3 02:27:56 2004
From: piir at earthlink.net (Todd G. Gardner)
Date: Sat Jan  3 05:26:24 2004
Subject: [Tutor] Difference between >>> import modulex and >>> from modulex
	import *?
Message-ID: <IIEDILADJDCBOHAJNADIOEBMCCAA.piir@earthlink.net>

Hello Everyone,

I have some questions that I must have skipped the answers in the tutorial.
Pardon me if they are obvious.

1) What is the difference between ">>> import modulex" and ">>> from modulex
import *"?

2) What happens when the command reads ">>> from modulex import something"?
    2a) Is something a function that is imported from modulex?

Thank in advance,

Thank you,

Todd


From exnihilo at myrealbox.com  Sat Jan  3 07:15:43 2004
From: exnihilo at myrealbox.com (exnihilo@myrealbox.com)
Date: Sat Jan  3 07:15:55 2004
Subject: [Tutor] Difference between >>> import modulex and >>> from modulex
In-Reply-To: <IIEDILADJDCBOHAJNADIOEBMCCAA.piir@earthlink.net>
References: <IIEDILADJDCBOHAJNADIOEBMCCAA.piir@earthlink.net>
Message-ID: <3FF6B26F.9090905@myrealbox.com>

hi Todd,

Todd G. Gardner wrote:

>Hello Everyone,
>
>I have some questions that I must have skipped the answers in the tutorial.
>Pardon me if they are obvious.
>
>1) What is the difference between ">>> import modulex" and ">>> from modulex
>import *"?
>
>  
>
Others will certainly give you more definitive answers, but as I 
understand it, the difference is in whether the contents of the module 
get imported or the module as a whole gets imported into the current 
namespace. This is clearer when you consider how you refer to what was 
imported in the two cases.

If there were a function foo in modulex, then after doing "import 
modulex", I call the function by doing something like "modulex.foo()". 
The import added an entry for modulex to the symbol table for the 
current module, so to access something in modulex, i do 
"modulex.something".

If, on the other hand, I had done "from modulex import foo", then that 
would have added foo to the current namespace (and not added an entry 
for the module as in the previous example). The foo function would be 
part of the current namespace, and i could call it with just "foo()" 
(modulex.foo() would not work). The same goes for any kind of attribute 
within the module i'm importing, whether they're functions, classes, 
constants, or whatever.

Here is a little illustration (with some # comments):
 >>> import urllib2 # this doesn't import the contents of urllib2 into 
the current namespace, it just adds an entry for the module to the 
symbol table of this module
 >>> f = urllib2.urlopen('http://www.google.com')  # so i have to refer 
to the urlopen function of the module as urllib2.urlopen
 >>> googlehtml = f.read()
 >>> f.close()
 >>> # print googlehtml would show all the html code i just downloaded 
from google
If i used "from module import attribute", then it would be as follows:
 >>> from urllib2 import urlopen
 >>> f = urlopen('http://google.com') # i can now use urlopen unprefixed 
by its module name
 >>> googlehtml = f.read()
 >>> f.close()

>2) What happens when the command reads ">>> from modulex import something"?
>    2a) Is something a function that is imported from modulex?
>
>  
>
I'm not sure exactly what you're refering to in 2), but "from modulex 
import something" would import into the current namespace whatever 
something refers to (this will often be a class), and you would be able 
to refer to it with just 'something' (without the quotes), instead of 
modulex.something

I hope this helps. If not, don't worry, clearer explanations will follow...

-n.


From darnold02 at sprynet.com  Sat Jan  3 08:01:10 2004
From: darnold02 at sprynet.com (don arnold)
Date: Sat Jan  3 08:01:25 2004
Subject: [Tutor] Difference between >>> import modulex and >>> from
	moduleximport *?
References: <IIEDILADJDCBOHAJNADIOEBMCCAA.piir@earthlink.net>
Message-ID: <02c601c3d1f9$a953f720$7710ba3f@don2uvsu54fwiq>


----- Original Message -----
From: "Todd G. Gardner" <piir@earthlink.net>
To: "Tutor@Python. Org" <tutor@python.org>
Sent: Saturday, January 03, 2004 1:27 AM
Subject: [Tutor] Difference between >>> import modulex and >>> from
moduleximport *?


> Hello Everyone,
>
> I have some questions that I must have skipped the answers in the
tutorial.
> Pardon me if they are obvious.
>
> 1) What is the difference between ">>> import modulex" and ">>> from
modulex
> import *"?

'import modulex' imports everything in that module into a namespace called
'modulex'.
You then access that module's attributes (functions and variables) by using
the fully-
qualified identifier:

a = modulex.funca( )
b = modulex.someconst

'from modulex import *' pulls the module's contents into the current
namespace, so
you access them without a namespace qualifier:

a = funca( )
b = someconst

Although this might seem like a good way to save some typing, using 'from
modulex
import *' can lead to namespace pollution and conflicts. For example, if
modulea and
moduleb each define somefunction( ), this:

from modulea import *
from moduleb import *

a = somefunction( )

won't behave the same if you switch the order of the import statements. The
module
that was imported last will dictate which version of somefunction you 'see'.
You avoid
this problem when you leave the functions in their own namespaces:

import modulea
import moduleb

a1 = modulea.somefuntion( )
a2 = moduleb.somefunction( )


> 2) What happens when the command reads ">>> from modulex import
something"?

This works just like 'from modulex import *', except that the only
'something' gets imported
into the current namespace.

>     2a) Is something a function that is imported from modulex?

It's some attribute that modulex defined, whether it's a function or some
other object.

>
> Thank in advance,
>
> Thank you,
>
> Todd

HTH,
Don


From sigurd at 12move.de  Sat Jan  3 10:21:29 2004
From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=)
Date: Sat Jan  3 10:25:28 2004
Subject: [Tutor] Clarified: Best way to alter sections of a string which
	match dictionary keys?
In-Reply-To: <3FF66438.6060300@SSokolow.com> (SSokolow's message of "Sat, 03
	Jan 2004 01:42:00 -0500")
References: <3FF523E1.6060702@SSokolow.com>
	<6.0.0.22.0.20040102105052.034f56e0@mail.mric.net>
	<3FF5EDC1.3070007@SSokolow.com>
	<m3d6a1zr2l.fsf@hamster.pflaesterer.de>
	<3FF66438.6060300@SSokolow.com>
Message-ID: <m3llopax0w.fsf@hamster.pflaesterer.de>

On  3 Jan 2004, SSokolow <- from_python_tutor@SSokolow.com wrote:

>  It's much faster and I would have never thought of it. I'm still
>  thinking mostly in intermediate Perl and that means I never
>  considered the possibility that the replacement expression could be
>  anything more than a plain vanilla string.

I thought of another solution (I found the problem interesting); it may
be a bit slower (since it processes the string more often) but it's much
safer

********************************************************************
from HTMLParser import HTMLParser
import sre
     
class MyHTMLParser(HTMLParser):
    def __init__(self):
        HTMLParser.__init__(self)
        self.val = []
        self.va = self.val.append
        self.hsh = {} # insert your hash here ore use a function which
                      # returns the hash table 
        self.reg = sre.compile(r'(\.|\^|\$|\*|\+|\?)')
    def regexp_quote(self, s):
        return self.reg.sub(r'\\\1', s)
    def handle_starttag(self, tag, attrs):
         if tag == "a":
             for elem in attrs:
                 if 'href' in elem and elem[1] in self.hsh:
                     data = r"%s" % (self.get_starttag_text())
                     self.va((r"%s%s" %
                              ('<img src="http://_proxy/checkmark.png">', data),
                              self.regexp_quote(data)))
                     break
    def change(self, stream):
        self.reset()
        self.val = []
        self.feed(stream)
        for exp, reg in self.val:
            stream = sre.sub(reg, exp, stream)
        return stream
********************************************************************

I'm sure something like the function regexp_quote does exist somewhere
(in XEmacs it's a builtin function) for Python.  Perhaps you have to
augment it a bit.

For above code you only have to instantiate a MyHTMLParser object once.
You can use it then to process all pages.

It's used like that:

>>> parser = MyHTMLParser()
>>> string = ''.join(open('index.html').readlines())
>>> string2 = ''.join(open('kontakt.html').readlines())
>>> string2 = parser.change(string2)
>>> string = parser.change(string)

etc.

As I said it will be a bit slower but since it uses HTMLParser you can
hope that less false matches will happen.


   Karl
-- 
Please do *not* send copies of replies to me.
I read the list


From sigurd at 12move.de  Sat Jan  3 11:35:52 2004
From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=)
Date: Sat Jan  3 11:39:38 2004
Subject: [Tutor] Clarified: Best way to alter sections of a string which
	match dictionary keys?
In-Reply-To: <m3llopax0w.fsf@hamster.pflaesterer.de> (Karl
	=?iso-8859-1?q?Pfl=E4sterer's?= message of "Sat,
	03 Jan 2004 16:21:29 +0100")
References: <3FF523E1.6060702@SSokolow.com>
	<6.0.0.22.0.20040102105052.034f56e0@mail.mric.net>
	<3FF5EDC1.3070007@SSokolow.com>
	<m3d6a1zr2l.fsf@hamster.pflaesterer.de>
	<3FF66438.6060300@SSokolow.com>
	<m3llopax0w.fsf@hamster.pflaesterer.de>
Message-ID: <m3oetl3smm.fsf@hamster.pflaesterer.de>

On  3 Jan 2004, Karl Pfl?sterer <- sigurd@12move.de wrote:

> On  3 Jan 2004, SSokolow <- from_python_tutor@SSokolow.com wrote:

>>  It's much faster and I would have never thought of it. I'm still
>>  thinking mostly in intermediate Perl and that means I never
>>  considered the possibility that the replacement expression could be
>>  anything more than a plain vanilla string.

> I thought of another solution (I found the problem interesting); it may
> be a bit slower (since it processes the string more often) but it's much
> safer

And had a little bug.  here is a better (and nicer formatted) solution.

********************************************************************
from HTMLParser import HTMLParser
import sre
     
class MyHTMLParser(HTMLParser):

    def __init__(self):
        HTMLParser.__init__(self)
        self.val = []
        self.found = []
        self.hsh = {} # insert your hashtable here
        self.reg = sre.compile(r'(\.|\^|\$|\*|\+|\?)')

    def regexp_quote(self, s):
        return self.reg.sub(r'\\\1', s)

    def handle_starttag(self, tag, attrs):
         if tag == "a":
             for elem in attrs:
                 link = elem[1]
                 data = r"%s" % (self.get_starttag_text())
                 if 'href' in elem and link in self.hsh and data not in self.found:
                     self.found.append(data)
                     self.val.append((r"%s%s" % ('<img src="http://_proxy/checkmark.png">', data),
                                      self.regexp_quote(data)))
                     break


    def change(self, stream):
        self.reset()
        self.val = []
        self.found = []
        self.feed(stream)
        for exp, reg in self.val:
            stream = sre.sub(reg, exp, stream)
        return stream
********************************************************************

Now multiple occurences of the same link which are furthermore written
exaktly equal won't be entered in the list of links to replace.  

I used simply a list here for the found links since I think that there
won't be a lot of them in one document.  So the overhead of building a
hash table might make make things slower compared to the slow operation
of finding a matching value in a list.  But that's guessed not measured.


   Karl
-- 
Please do *not* send copies of replies to me.
I read the list


From hcohen2 at comcast.net  Sat Jan  3 12:34:08 2004
From: hcohen2 at comcast.net (hcohen2)
Date: Sat Jan  3 12:35:16 2004
Subject: [Tutor] Difference between >>> import modulex and >>> from modulex
	import *?
In-Reply-To: <IIEDILADJDCBOHAJNADIOEBMCCAA.piir@earthlink.net>
References: <IIEDILADJDCBOHAJNADIOEBMCCAA.piir@earthlink.net>
Message-ID: <3FF6FD10.6060406@comcast.net>

Todd G. Gardner wrote:

>Hello Everyone,
>
>I have some questions that I must have skipped the answers in the tutorial.
>Pardon me if they are obvious.
>
>1) What is the difference between ">>> import modulex" and ">>> from modulex
>import *"?
>
>2) What happens when the command reads ">>> from modulex import something"?
>    2a) Is something a function that is imported from modulex?
>
>Thank in advance,
>
>Thank you,
>
>Todd
>
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>  
>
I think this will essentially repeat what was said, but perhaps more 
concisely:

In the first case you have imported every built in function of that module.

In the second you have only imported the specificly named function 
'from' that module.

In the first case you are free to execute every built in function from 
that module if you needed them.  In the second you are restricted to 
only the function you had imported.




From from_python_tutor at SSokolow.com  Sat Jan  3 16:54:20 2004
From: from_python_tutor at SSokolow.com (SSokolow)
Date: Sat Jan  3 16:54:27 2004
Subject: [Tutor] Clarified: Best way to alter sections of a string which
	match dictionary keys?
In-Reply-To: <m3oetl3smm.fsf@hamster.pflaesterer.de>
References: <3FF523E1.6060702@SSokolow.com>	<6.0.0.22.0.20040102105052.034f56e0@mail.mric.net>	<3FF5EDC1.3070007@SSokolow.com>	<m3d6a1zr2l.fsf@hamster.pflaesterer.de>	<3FF66438.6060300@SSokolow.com>	<m3llopax0w.fsf@hamster.pflaesterer.de>
	<m3oetl3smm.fsf@hamster.pflaesterer.de>
Message-ID: <3FF73A0C.6090802@SSokolow.com>

Karl Pfl?sterer wrote:

>On  3 Jan 2004, Karl Pfl?sterer <- sigurd@12move.de wrote:
>
>  
>
>>On  3 Jan 2004, SSokolow <- from_python_tutor@SSokolow.com wrote:
>>    
>>
>
>  
>
>>> It's much faster and I would have never thought of it. I'm still
>>> thinking mostly in intermediate Perl and that means I never
>>> considered the possibility that the replacement expression could be
>>> anything more than a plain vanilla string.
>>>      
>>>
>
>  
>
>>I thought of another solution (I found the problem interesting); it may
>>be a bit slower (since it processes the string more often) but it's much
>>safer
>>    
>>
>
>And had a little bug.  here is a better (and nicer formatted) solution.
>
>[snip: Code Sample]
>
>Now multiple occurences of the same link which are furthermore written
>exaktly equal won't be entered in the list of links to replace.  
>
>I used simply a list here for the found links since I think that there
>won't be a lot of them in one document.  So the overhead of building a
>hash table might make make things slower compared to the slow operation
>of finding a matching value in a list.  But that's guessed not measured.
>
>
>   Karl
>  
>
Your reply is confusing me but as I understand it, there are three 
problems with this:

1. I do want all occurrences of a recognized link to be changed. This is 
supposed to be a non-expiring version of the browser history that is 
only executed while the user is browsing 
http://addventure.bast-enterprises.de/ (the more advanced features will 
build upon this)
2. What do you mean safer? The situation may not apply to this specific 
site and speed is of the utmost importance in this case. I forgot that 
this also indexes the comments pages (the dictionary will eventually 
hold well over 40,000 entries) and will often be used to view the index 
pages (the largest index page has about 15,000 links to be checked 
against the dict and is over 1MB of HTML)

 I also forgot to mention that the variable string does not hold the 
entire file. This is run for each chunk of data as it's received from 
the server. (I don't know how to build content-layer filtering into the 
proxy code I'm extending so I hooked it in at the content layer. testing 
has shown that some links lie across chunk boundaries like this:

[continued from previous chunk]is some link text</a>
.
.
.
<a href="whatever">This is th[continued in next chunk]

and I don't know if the HTML parser might stumble on an unclosed <a> tag 
pair.

I already have a pair of regular expression substitutions converting all 
links that stay on the server into root reference relative links ( 
/where/whatever.html  as opposed to whatever.html if it's in the same 
directory) and I was planning to see if they could be safely and easily 
integrated into your first submission for extra speed.

I will also keep this code but I have been testing through normal use at 
a rate that could be considered a stress test and I have yet to see a 
problem. Since the site is a large choose-your-own-adventure book to 
which anybody can add, the proxy has to run this code almost instantly 
since I (and anyone else who would use this) wouldn't have the patience 
to wait a long time for a block of text that's 50K at most. (With the 
exception of the indices which also cannot be noticeably slower to load) 
In fact, any wait time greater than one or two seconds becomes irritating.

Thanks and I'll keep trying to find the problem with the regular 
expression you sent (as soon as I've done some more reading, err...testing.)

Stephan Sokolow
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20040103/05d05ade/attachment.html
From piir at earthlink.net  Sat Jan  3 14:59:18 2004
From: piir at earthlink.net (Todd G. Gardner)
Date: Sat Jan  3 17:57:43 2004
Subject: [Tutor] Difference between >>> import modulex and >>> from modulex
In-Reply-To: <3FF6B26F.9090905@myrealbox.com>
Message-ID: <IIEDILADJDCBOHAJNADIAECBCCAA.piir@earthlink.net>

Hello again,

Please see 'pydaq.py' below.  I will stop using 'from modulex import *' for
future code because I can see that can cause namespace conflicts and
confusion.  You all gave excellent answers that really help clear up some
confusion on this subject, so thanks.

1) Is there an easy way to change the legacy code I have to work if I change
'from modulex import foo' to 'import modulex'?

2) Is pydaq.__init__ executed if I write '>>> from pydaq import
AI_Configure'?

3) Is pydaq.__init__ executed if I write '>>> import pydaq'?

Thank you,

Todd

[BEGIN pydaq.py]
__________________________________________________________________
from Numeric import *
from ctypes import *
from string import *
from struct import *

# Create instance of traditional nidaq dll
ni=windll.nidaq32

class pydaq:
    def __init__(self):
        """variable declaration"""
        self.deviceNumber=c_int(1)
        self.chan=c_int(0)
        self.voltage=c_double(1.0)
        self.pvoltage=pointer(self.voltage)
        self.gain=c_int(-1)
        self.num=100 #Number of data points
        self.sampleRate=c_double(1000)
        self.max=10.0
        self.min=-10.0
        self.bits=12

    def AI_Configure (self, deviceNumber=c_int(1), chan=c_int(0),
inputMode=c_int(0), inputRange=c_int(10), polarity=c_int(0),
driveAIS=c_int(0)):
        """configure analong input task"""
        self.AI_ConfigureStatus = ni.AI_Configure (deviceNumber, chan,
inputMode, inputRange, polarity, driveAIS)
        #print "AI_Configure status =", self.AI_ConfigureStatus
        return self.AI_ConfigureStatus
[END pydaq.py]
__________________________________________________________________

-----Original Message-----
From: exnihilo@myrealbox.com [mailto:exnihilo@myrealbox.com]
Sent: Saturday, January 03, 2004 7:16 AM
To: Todd G. Gardner
Cc: Tutor@Python. Org
Subject: Re: [Tutor] Difference between >>> import modulex and >>> from
modulex


hi Todd,

Todd G. Gardner wrote:

>Hello Everyone,
>
>I have some questions that I must have skipped the answers in the tutorial.
>Pardon me if they are obvious.
>
>1) What is the difference between ">>> import modulex" and ">>> from
modulex
>import *"?
>
>
>
Others will certainly give you more definitive answers, but as I
understand it, the difference is in whether the contents of the module
get imported or the module as a whole gets imported into the current
namespace. This is clearer when you consider how you refer to what was
imported in the two cases.

If there were a function foo in modulex, then after doing "import
modulex", I call the function by doing something like "modulex.foo()".
The import added an entry for modulex to the symbol table for the
current module, so to access something in modulex, i do
"modulex.something".

If, on the other hand, I had done "from modulex import foo", then that
would have added foo to the current namespace (and not added an entry
for the module as in the previous example). The foo function would be
part of the current namespace, and i could call it with just "foo()"
(modulex.foo() would not work). The same goes for any kind of attribute
within the module i'm importing, whether they're functions, classes,
constants, or whatever.

Here is a little illustration (with some # comments):
 >>> import urllib2 # this doesn't import the contents of urllib2 into
the current namespace, it just adds an entry for the module to the
symbol table of this module
 >>> f = urllib2.urlopen('http://www.google.com')  # so i have to refer
to the urlopen function of the module as urllib2.urlopen
 >>> googlehtml = f.read()
 >>> f.close()
 >>> # print googlehtml would show all the html code i just downloaded
from google
If i used "from module import attribute", then it would be as follows:
 >>> from urllib2 import urlopen
 >>> f = urlopen('http://google.com') # i can now use urlopen unprefixed
by its module name
 >>> googlehtml = f.read()
 >>> f.close()

>2) What happens when the command reads ">>> from modulex import something"?
>    2a) Is something a function that is imported from modulex?
>
>
>
I'm not sure exactly what you're refering to in 2), but "from modulex
import something" would import into the current namespace whatever
something refers to (this will often be a class), and you would be able
to refer to it with just 'something' (without the quotes), instead of
modulex.something

I hope this helps. If not, don't worry, clearer explanations will follow...

-n.


From idiot1 at netzero.net  Sat Jan  3 18:24:53 2004
From: idiot1 at netzero.net (Kirk Bailey)
Date: Sat Jan  3 18:26:20 2004
Subject: [Tutor] keeping the program alive
In-Reply-To: <EF9F1AA4-3CCB-11D8-AA97-00039314F97E@mac.com>
References: <EF9F1AA4-3CCB-11D8-AA97-00039314F97E@mac.com>
Message-ID: <3FF74F45.4030200@netzero.net>

ok, before I comment, can I please see the actual code in question? Starting 
with the 'while 1:' statement, the entire loop EXACTLY bit for bit the way 
it is in the script file. Please post it on the list.

matteo wrote:

> hi everybody!
> 
> i've put this in my small program, just to keep it running continuosly
> 
> while 1:
> connect_to_server() #it does some things..
> sleep(120)
> 
> i execute the program with "python script.py &"
> it runs well for about 5 minutes but then it quits.
> how can i fix it ?
> 
One thought occring to me is what sort of a connection to the server is it, 
and will the server time out if the connection remains alive for too long? 
but until I know more, I lack a clue.

> thanks
> 
> matteo
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 


end

Blessd be.
           -Kirk D. Bailey

   think   http://www.tinylist.org/ - $FREE$ software for liberty
+-------+ http://www.pinellasintergroupsociety.org/ - In Her Service
|  BOX  | http://www.listville.net/ - $FREE$ list hosting services
+-------+ http://www.howlermonkey.net/ - $FREE$ email service
   kniht   http://www.sacredelectron.org/ - My personal SCREED pit





From sigurd at 12move.de  Sat Jan  3 18:48:16 2004
From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=)
Date: Sat Jan  3 18:52:25 2004
Subject: [Tutor] Clarified: Best way to alter sections of a string which
	match dictionary keys?
In-Reply-To: <3FF73A0C.6090802@SSokolow.com> (SSokolow's message of "Sat, 03
	Jan 2004 16:54:20 -0500")
References: <3FF523E1.6060702@SSokolow.com>
	<6.0.0.22.0.20040102105052.034f56e0@mail.mric.net>
	<3FF5EDC1.3070007@SSokolow.com>
	<m3d6a1zr2l.fsf@hamster.pflaesterer.de>
	<3FF66438.6060300@SSokolow.com>
	<m3llopax0w.fsf@hamster.pflaesterer.de>
	<m3oetl3smm.fsf@hamster.pflaesterer.de>
	<3FF73A0C.6090802@SSokolow.com>
Message-ID: <m3vfns38z9.fsf@hamster.pflaesterer.de>

On  3 Jan 2004, SSokolow <- from_python_tutor@SSokolow.com wrote:

> Your reply is confusing me but as I understand it, there are three
> problems with this:

I didn't want to confuse you.

[...]
> 2. What do you mean safer? The situation may not apply to this

The regexp isn't 100% safe against badly (or broken) written HTML.  A
match starts with a `<a' then are some attributes then somewhere is a
`href"'.  I'm not absolutley sure at the moment (I had to reread the
docs of W3C) how much the syntax may differ.  Furthermore you need to
cope with HTML and XHTML; the last should be the smaller problem as it
is much stricter but HTML may differ a lot.  That's because a lot of
people don't read the docs of W3C.  But I think you need to cope with
spaces between `href=' and the following value of the attribute.  Also
the quotes can be single or double quotes (should be double).

That's not the biggest problem all this can be handled with a regexp but
if yoou had the (pathological) case that somebody writes
   <a ....> <a       </a> ..   </a>
a regexp will fail. But maybe that never happens or only once in a
million.  If you can live with it fine.

[...]
>  I also forgot to mention that the variable string does not hold the
>  entire file. This is run for each chunk of data as it's received from
>  the server. (I don't know how to build content-layer filtering into
>  the proxy code I'm extending so I hooked it in at the content layer. 
>  testing has shown that some links lie across chunk boundaries like
>  this:

> [continued from previous chunk]is some link text</a>
> .
> .
> .
> <a href="whatever">This is th[continued in next chunk]

> and I don't know if the HTML parser might stumble on an unclosed <a>
> tag pair.

With that the parser can cope very well.  You just had to change the
code a bit but that should be possible.

But if spped matters I think the simple regexp solution might suffice.

[...]

I think the problem is interesting so post here if you know more (but
please with as much facts as possible).


   Karl
-- 
Please do *not* send copies of replies to me.
I read the list


From hcohen2 at comcast.net  Sat Jan  3 20:43:30 2004
From: hcohen2 at comcast.net (hcohen2)
Date: Sat Jan  3 20:44:34 2004
Subject: [Tutor] Difference between >>> import modulex and >>> from modulex
	import *?
In-Reply-To: <3FF74E2F.6080508@netzero.net>
References: <IIEDILADJDCBOHAJNADIOEBMCCAA.piir@earthlink.net>
	<3FF6FD10.6060406@comcast.net> <3FF74E2F.6080508@netzero.net>
Message-ID: <3FF76FC2.2000502@comcast.net>

Kirk Bailey wrote:

> ok, then let me ask:
> I wish to import the function bar from the module Fu. In it's 
> definition, it depends on another function in Fu (named janfu)I did 
> not specify in the
> "from foo import bar" statement. What comes about as a result of this?
>
> hcohen2 wrote:
>
>> Todd G. Gardner wrote:
>>
>>> Hello Everyone,
>>>
>>> I have some questions that I must have skipped the answers in the 
>>> tutorial.
>>> Pardon me if they are obvious.
>>>
>>> 1) What is the difference between ">>> import modulex" and ">>> from 
>>> modulex
>>> import *"?
>>>
>>> 2) What happens when the command reads ">>> from modulex import 
>>> something"?
>>>    2a) Is something a function that is imported from modulex?
>>>
>>> Thank in advance,
>>>
>>> Thank you,
>>>
>>> Todd
>>>
>>>
>>> _______________________________________________
>>> Tutor maillist  -  Tutor@python.org
>>> http://mail.python.org/mailman/listinfo/tutor
>>>
>>>  
>>>
>> I think this will essentially repeat what was said, but perhaps more 
>> concisely:
>>
>> In the first case you have imported every built in function of that 
>> module.
>>
>> In the second you have only imported the specificly named function 
>> 'from' that module.
>>
>> In the first case you are free to execute every built in function 
>> from that module if you needed them.  In the second you are 
>> restricted to only the function you had imported.
>>
>>
>>
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor@python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>
I would not assert this does not happen, but if it does there were some 
bad design decisions that would allowed this to occur.

I would have expected functions that were so dependent would be within a 
single module where one would: from modulex import sub_module ...  The 
specific function would not be named but would be readily executable 
because its dependency would be present.  This definitely does not seem 
to be the way I have seen it in my limited experience.

I would caution you that I am too new to Python to pretend to be an 
authority even on its basic features at this time.  Perhaps this will 
attract a much more knowledgeable comment from someone following this 
thread.


From hcohen2 at comcast.net  Sat Jan  3 20:58:18 2004
From: hcohen2 at comcast.net (hcohen2)
Date: Sat Jan  3 20:59:22 2004
Subject: [Tutor] Help with IDE please
In-Reply-To: <3FF61D18.2040109@cfl.rr.com>
References: <20040102134149.54596999.anschau@shaw.ca>
	<3FF61D18.2040109@cfl.rr.com>
Message-ID: <3FF7733A.4010002@comcast.net>

pxlpluker wrote:

> To date i have been using the pythonwin IDE buts its acting real 
> flakey lately. How is idle or DrPython. and where can i find a 
> tutorial on IDLE?
>
> tia
>
> Fred
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
Check out the earlier thread: Looking for a Python IDE


From from_python_tutor at SSokolow.com  Sat Jan  3 23:14:52 2004
From: from_python_tutor at SSokolow.com (SSokolow)
Date: Sat Jan  3 23:14:54 2004
Subject: [Tutor] Clarified: Best way to alter sections of a string which
	match dictionary keys?
In-Reply-To: <m3vfns38z9.fsf@hamster.pflaesterer.de>
References: <3FF523E1.6060702@SSokolow.com>	<6.0.0.22.0.20040102105052.034f56e0@mail.mric.net>	<3FF5EDC1.3070007@SSokolow.com>	<m3d6a1zr2l.fsf@hamster.pflaesterer.de>	<3FF66438.6060300@SSokolow.com>	<m3llopax0w.fsf@hamster.pflaesterer.de>	<m3oetl3smm.fsf@hamster.pflaesterer.de>	<3FF73A0C.6090802@SSokolow.com>
	<m3vfns38z9.fsf@hamster.pflaesterer.de>
Message-ID: <3FF7933C.1070106@SSokolow.com>

Karl Pfl?sterer wrote:

>On  3 Jan 2004, SSokolow <- from_python_tutor@SSokolow.com wrote:
>
>  
>
>>Your reply is confusing me but as I understand it, there are three
>>problems with this:
>>    
>>
>
>I didn't want to confuse you.
>
>[...]
>  
>
>>2. What do you mean safer? The situation may not apply to this
>>    
>>
>
>The regexp isn't 100% safe against badly (or broken) written HTML.  A
>match starts with a `<a' then are some attributes then somewhere is a
>`href"'.  I'm not absolutley sure at the moment (I had to reread the
>docs of W3C) how much the syntax may differ.  Furthermore you need to
>cope with HTML and XHTML; the last should be the smaller problem as it
>is much stricter but HTML may differ a lot.  That's because a lot of
>people don't read the docs of W3C.  But I think you need to cope with
>spaces between `href=' and the following value of the attribute.  Also
>the quotes can be single or double quotes (should be double).
>
>That's not the biggest problem all this can be handled with a regexp but
>if yoou had the (pathological) case that somebody writes
>   <a ....> <a       </a> ..   </a>
>a regexp will fail. But maybe that never happens or only once in a
>million.  If you can live with it fine.
>
>[...]
>  
>
>> I also forgot to mention that the variable string does not hold the
>> entire file. This is run for each chunk of data as it's received from
>> the server. (I don't know how to build content-layer filtering into
>> the proxy code I'm extending so I hooked it in at the content layer. 
>> testing has shown that some links lie across chunk boundaries like
>> this:
>>    
>>
>
>  
>
>>[continued from previous chunk]is some link text</a>
>>.
>>.
>>.
>><a href="whatever">This is th[continued in next chunk]
>>    
>>
>
>  
>
>>and I don't know if the HTML parser might stumble on an unclosed <a>
>>tag pair.
>>    
>>
>
>With that the parser can cope very well.  You just had to change the
>code a bit but that should be possible.
>
>But if spped matters I think the simple regexp solution might suffice.
>
>[...]
>
>I think the problem is interesting so post here if you know more (but
>please with as much facts as possible).
>
>
>   Karl
>  
>
Of the tens of thousands of links on the site, only maybe ten or twenty 
are not generated by scripts. All of the HTML data is either generated 
on the fly by PHP scripts (comment boards), or saved to HTML files 
whenever a change is made. Therefore I feel safe in using the Regexp.

I'll send notice when I make the completed program available on my 
website and/or send the rest of this code once I've implemented the rest 
of the features if you (or anybody else) are interested.

Stephan Sokolow
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20040103/a60d1494/attachment.html
From vibrations at cetlink.net  Sat Jan  3 23:15:26 2004
From: vibrations at cetlink.net (SGD)
Date: Sat Jan  3 23:16:01 2004
Subject: [Tutor] Help with IDE please
In-Reply-To: <3FF7733A.4010002@comcast.net>
Message-ID: <000901c3d279$74731240$8334c6d1@whiterhino2>

You might be interested in "stani's python editor" or "boa constuctor",
IMHO these two are my favorite editors. Boa is great for working with
wxpython or normal py scripting\programming, and spe is just great IMO
and real easy to extend. If it's simpisity you're looking for you might
like "pype".

http://spe.pycs.net/
http://boa-constructor.sourceforge.net/
http://pype.sourceforge.net/


I know you didn't ask about these IDE's, but I really like them better
than most others, but I do tend to find myself in pythonwin a lot. I'm
not real keen on using idle nor DrPython but that does not mean they are
not good editors.

Happy pythoning


-----Original Message-----
From: hcohen2 [mailto:hcohen2@comcast.net] 
Sent: Saturday, January 03, 2004 8:58 PM
To: pxlpluker
Cc: tutor@python.org
Subject: Re: [Tutor] Help with IDE please

pxlpluker wrote:

> To date i have been using the pythonwin IDE buts its acting real 
> flakey lately. How is idle or DrPython. and where can i find a 
> tutorial on IDLE?
>
> tia
>
> Fred
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
Check out the earlier thread: Looking for a Python IDE





From piir at earthlink.net  Sun Jan  4 02:35:30 2004
From: piir at earthlink.net (Todd G. Gardner)
Date: Sun Jan  4 05:34:12 2004
Subject: [Tutor] multithreading resources?
Message-ID: <IIEDILADJDCBOHAJNADIAECICCAA.piir@earthlink.net>

Hello all,

I would appreciate it if someone would point me toward resources so I may
research writing multithreading code in python.

Thank you,

Todd


From matteolovatti at mac.com  Sun Jan  4 09:33:44 2004
From: matteolovatti at mac.com (Lovatti Matteo)
Date: Sun Jan  4 09:33:54 2004
Subject: [Tutor] Tkinter and Macpython
Message-ID: <FFC13D27-3EC2-11D8-9F9E-00039314F97E@mac.com>

Hi, everybody, i'm trying to learn tkinter but i'm hang with a simple
example:

from Tkinter import *

root = Tk()

w = Label(root, text="Hello, world!")
w.pack()

root.mainloop()

this example make my Macpython to crash (it displays the window created 
only
for a second). Maybe i've not intalled something correctly or else ?
can someone help ? (the mac runs Os X 10.3.2, full developer tools 
installed)

thanks

Matteo
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: text/enriched
Size: 554 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20040104/664efe55/attachment.bin
From littledanehren at yahoo.com  Sun Jan  4 11:18:20 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Sun Jan  4 11:18:24 2004
Subject: [Tutor] multithreading resources?
In-Reply-To: <IIEDILADJDCBOHAJNADIAECICCAA.piir@earthlink.net>
Message-ID: <20040104161820.47354.qmail@web41801.mail.yahoo.com>

"Todd G. Gardner" wrote:
> Hello all,
> 
> I would appreciate it if someone would point me
> toward resources so I may
> research writing multithreading code in python.
> 
> Thank you,
> 
> Todd

The threading module in the standard library is what
you're looking for, but unfortunately, there is hardly
any documentation on it beyond the Python Library
reference. Here's the reference on it:
http://www.python.org/doc/current/lib/module-threading.html
.

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Find out what made the Top Yahoo! Searches of 2003
http://search.yahoo.com/top2003

From littledanehren at yahoo.com  Sun Jan  4 11:36:56 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Sun Jan  4 11:37:01 2004
Subject: [Tutor] Arbitrary precision arithmetic
Message-ID: <20040104163656.64588.qmail@web41803.mail.yahoo.com>

I am trying to make a library that will allow for
arbitrary precision arithmetic because Python's floats
are so awful. I got most of it to work for most things
by using a variant of scientific notation (where
numbers are stored as a long times 10 to an int; works
great for parsing back and forth to string), but there
are four that I can't get: exponents, division, mod,
and divmod.

I can do exponents if they are positive integer, but
otherwise, I don't know how to make it precise and
resort to float exponents

I can only do division if it is being divided by a
power of 10, otherwise I use imprecise float division.
Mod depends on division, so I can't do that either. 

I have no idea what divmod is. Could someone explain
it?

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Find out what made the Top Yahoo! Searches of 2003
http://search.yahoo.com/top2003

From piir at earthlink.net  Sun Jan  4 08:41:32 2004
From: piir at earthlink.net (Todd G. Gardner)
Date: Sun Jan  4 11:40:02 2004
Subject: [Tutor] multithreading resources?
In-Reply-To: <20040104161807.15121.qmail@web41811.mail.yahoo.com>
Message-ID: <CAENJDPIMKAJINIKKHOCEECJCCAA.piir@earthlink.net>

Hello Daniel,

Thank you!  Might you know of any example code?

Thanks again,

Todd
-----Original Message-----
From: Daniel Ehrenberg [mailto:littledanehren@yahoo.com]
Sent: Sunday, January 04, 2004 11:18 AM
To: Todd G. Gardner
Subject: Re: [Tutor] multithreading resources?


"Todd G. Gardner" wrote:
> Hello all,
> 
> I would appreciate it if someone would point me
> toward resources so I may
> research writing multithreading code in python.
> 
> Thank you,
> 
> Todd

The threading module in the standard library is what
you're looking for, but unfortunately, there is hardly
any documentation on it beyond the Python Library
reference. Here's the reference on it:
http://www.python.org/doc/current/lib/module-threading.html
.

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Find out what made the Top Yahoo! Searches of 2003
http://search.yahoo.com/top2003

From speno at isc.upenn.edu  Sun Jan  4 12:19:57 2004
From: speno at isc.upenn.edu (John P Speno)
Date: Sun Jan  4 12:20:01 2004
Subject: [Tutor] multithreading resources?
In-Reply-To: <CAENJDPIMKAJINIKKHOCEECJCCAA.piir@earthlink.net>
References: <20040104161807.15121.qmail@web41811.mail.yahoo.com>
	<CAENJDPIMKAJINIKKHOCEECJCCAA.piir@earthlink.net>
Message-ID: <20040104171957.GA21343@isc.upenn.edu>

On Sun, Jan 04, 2004 at 08:41:32AM -0500, Todd G. Gardner wrote:
> Hello Daniel,
> 
> Thank you!  Might you know of any example code?

Thanks for asking. I just put up a simple framework for using threads
on my weblog:

http://www.pycs.net/users/0000231/

I hope it helps.

Take care.

From alan.gauld at blueyonder.co.uk  Sun Jan  4 14:15:53 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Sun Jan  4 14:15:46 2004
Subject: [Tutor] Tkinter - How to get multilple windows
References: <Pine.LNX.4.44.0401020007260.27061-100000@cselinux1.cse.iitk.ac.in>
Message-ID: <004b01c3d2f7$2c690120$6401a8c0@xp>

> >Instantiate a new window object which inherits from
> >TopLevel rather than a simple Frame.

        def openNew(self):
                app1 = App1(self)
                app1.mainloop()

You don;t need the mainloop here, there is already a
mainloop running, it will send the events to your window
object OK

> #quit class
> class App1(Toplevel):
>         def __init__(self,master=None):
>                 Toplevel.__init__(self,master)
>                 self.grid()
>                 self.createWidgets()
>
>         def createWidgets(self):
>                 textButton =
Button(self,text="Quit",command=self.quit)
>                 textButton.grid()
> app = App()     #instance of the Application
> app.master.title("Sample program")
> app.mainloop()          #wait for the events

> 1. I am getting two windows

Which is what you wanted, yes? I assume the 2nd window only
comes up after pressing the button?

> 2. I want only the object of APP1 to quit not the entire program.

Only run the one mainloop. Otherwise it should be OK.
And you may not want to use self.quit - I think theres
a self.close() for TopLevel... Try a dir(TopLevel)...

Alan g


From alan.gauld at blueyonder.co.uk  Sun Jan  4 14:19:10 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Sun Jan  4 14:18:57 2004
Subject: [Tutor] Help with IDE please
References: <20040102134149.54596999.anschau@shaw.ca><3FF61D18.2040109@cfl.rr.com>
	<3FF7733A.4010002@comcast.net>
Message-ID: <008f01c3d2f7$a1b3b510$6401a8c0@xp>


> pxlpluker wrote:
> > To date i have been using the pythonwin IDE buts its acting real 
> > flakey lately. How is idle or DrPython. and where can i find a 
> > tutorial on IDLE?

Danny Yoo did a basic one and there is extensive help on the IDLE 
section of the Python web site - including a link to Danny's tutor.

For Pythonwin try a reinstall, it seems to ose the place sometimes 
but a reinstall over the old one seems to work.

Alan G.

From bgailer at alum.rpi.edu  Sun Jan  4 16:11:08 2004
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Sun Jan  4 16:11:14 2004
Subject: [Tutor] Arbitrary precision arithmetic
In-Reply-To: <20040104163656.64588.qmail@web41803.mail.yahoo.com>
References: <20040104163656.64588.qmail@web41803.mail.yahoo.com>
Message-ID: <6.0.0.22.0.20040104140633.03edca38@mail.mric.net>

Skipped content of type multipart/alternative-------------- next part --------------

---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.558 / Virus Database: 350 - Release Date: 1/2/2004
From littledanehren at yahoo.com  Sun Jan  4 21:00:16 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Sun Jan  4 21:00:24 2004
Subject: [Tutor] Arbitrary precision arithmetic
In-Reply-To: <6.0.0.22.0.20040104140633.03edca38@mail.mric.net>
Message-ID: <20040105020016.5480.qmail@web41808.mail.yahoo.com>

>   RTFM, where it says:
> 
> "divmod( a, b)
> Take two (non complex) numbers as arguments and
> return a pair of numbers 
> consisting of their quotient and remainder when
> using long division. With 
> mixed operand types, the rules for binary arithmetic
> operators apply. For 
> plain and long integers, the result is the same as
> (a / b, a % b). For 
> floating point numbers the result is (q, a % b),
> where q is usually 
> math.floor(a / b) but may be 1 less than that. In
> any case q * b + a % b is 
> very close to a, if a % b is non-zero it has the
> same sign as b, and 0 <= 
> abs(a % b) < abs(b)."
> 
> Did you already find the above and want a
> translation? or it this what you 
> were looking for?
> 
> Bob Gailer
> bgailer@alum.rpi.edu
> 303 442 2625 home
> 720 938 2625 cell 

Yes, I did RTM, but I don't understand it. I should
have said that before.

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Find out what made the Top Yahoo! Searches of 2003
http://search.yahoo.com/top2003

From littledanehren at yahoo.com  Sun Jan  4 21:07:23 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Sun Jan  4 21:07:31 2004
Subject: [Tutor] Classes vs. prototypes
Message-ID: <20040105020723.67780.qmail@web41809.mail.yahoo.com>

I found a language called Io that's purely object
oriented but very minimalistic. At first it looked
good, but it has some of the same anti-function faults
as Ruby. its OO model, using prototypes, looked much
more flexible than the mainstream classes. Is there
any reason why Python doesn't (or shouldn't) support
prototypes, apart from that they were a very recent
invention when Python was created?

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Find out what made the Top Yahoo! Searches of 2003
http://search.yahoo.com/top2003

From carroll at tjc.com  Sun Jan  4 22:49:06 2004
From: carroll at tjc.com (Terry Carroll)
Date: Sun Jan  4 22:49:11 2004
Subject: [Tutor] Arbitrary precision arithmetic
In-Reply-To: <20040105020016.5480.qmail@web41808.mail.yahoo.com>
Message-ID: <Pine.LNX.4.44.0401041946390.19539-100000@mauve.rahul.net>

On Sun, 4 Jan 2004, Daniel Ehrenberg wrote:

> > "divmod( a, b)
> 
> Yes, I did RTM, but I don't understand it. I should
> have said that before.

It's actually not that mysterious.  divmod dides the numbers and give you 
the result as a two-member tuple in the form integer-and-remainder.

Remember when you learned division in elementary school, and you 
expressed, for example, 10 / 3 as "three, remainder one"?  That's divmod:

>>> divmod(10,3)
(3, 1)
>>>

-- 
Terry Carroll
Santa Clara, CA
carroll@tjc.com 


From steegness at hotmail.com  Mon Jan  5 12:54:22 2004
From: steegness at hotmail.com (Steegness)
Date: Mon Jan  5 12:54:21 2004
Subject: [Tutor] Mailing Made Simple - Multiple Recipient Problem
Message-ID: <Law15-DAV37BZTW5k1E00001ff2@hotmail.com>

Thanks to the help of the excellent Python docs and various code snippets Google coughed up, I've been able to create a pretty decent mailing module that can accomodate attachments.  It's quite nearly done, save for one last issue I've been facing.

It doesn't seem to send to multiple recipients well.  When passed the info for its TO field, only the first recipient listed recieves an e-mail; all others are seemingly ignored.

I've been able to work around it for the time being by having the calling functions loop over the list and send e-mails one at a time, but as I will soon be needing to send larger attachments with the procedure, that overhead becomes more and more costly, and so I come and prostrate myself before the list.

To keep your inboxes cleaner, the code can be found at http://www.basicintellects.com/users/pokerface/SimpleMessage_notest.txt.

Thanks for any help you might be able to offer.
--Sean
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20040105/49d4cfca/attachment.html
From nixonron at yahoo.com  Thu Jan  1 14:31:41 2004
From: nixonron at yahoo.com (Ron Nixon)
Date: Mon Jan  5 13:47:22 2004
Subject: [Tutor] downloading files
Message-ID: <20040101193141.40507.qmail@web20311.mail.yahoo.com>

I'm fairly new at Python and I have a project where I need to scan a webpage for a list of names and then download any files associated with those names. Any utilites like that already exist out there that somone could point me to or give me some advice on how to do it?
 
Ron


---------------------------------
Do you Yahoo!?
Free Pop-Up Blocker - Get it now
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20040101/bf622992/attachment.html
From e.kotyk at shaw.ca  Fri Jan  2 14:33:20 2004
From: e.kotyk at shaw.ca (Eve)
Date: Mon Jan  5 13:47:39 2004
Subject: [Tutor] seg fault problem
Message-ID: <3FF5C780.3000307@shaw.ca>

I continue on my endless(and seemingly futile)attempt to learn a
programming language.  Currently I'm attempting small scripts in
Python/Tkinter.  The particular script is a textbox script at follows

#!/usr/lib/python2.2

from Tkinter import *
from ScrolledText import *
import sys

def die(event):
   sys.exit(0)

root = Tk()
f = Frame(root)
f.pack(expand=1, fill=BOTH)
button = Button(f, width=25)
button["text"] = "Button"
button.bind("<Button>",die)
button.pack()

st = ScrolledText(f,background="white")
st.pack()

root.mainloop()

Very simple and straight forward but if I mouseclick in the text window
the program seg faults.  Can anyone tell me why?  As an aside, I cannot
use idle (a text editor) because it seg faults everytime I try to
initialize.

Eve


From boomer4467 at yahoo.com  Fri Jan  2 18:32:35 2004
From: boomer4467 at yahoo.com (Chris Rosenboom)
Date: Mon Jan  5 13:48:44 2004
Subject: [Tutor] importing into fields
Message-ID: <20040102233235.33591.qmail@web21203.mail.yahoo.com>

I'm trying to manipulate a string to seperate before entering each seperate instance in some fields on a software program, here's an example of the script
 
f=open ("book2.txt", "r")
s=f.readline ()
while s != "":
  print s
  l = string.split(s, ",",[11])
  PlayIt.SetFieldContent ("SY012M1", "art-nr", l[0])
  PlayIt.PlayContent ("{CSB SY012M1|art-nr}{Enter}")
  PlayIt.SetFieldContent ("SY012ADM1", "001bez",  l[1])
  PlayIt.SetFieldContent ("SY012ADM1", "005agr",  l[2])
  PlayIt.SetFieldContent ("SY012ADM1", "006agr",  l[3])
  PlayIt.SetFieldContent ("SY012ADM1", "009kst",  l[4])
  PlayIt.SetFieldContent ("SY012EHM1", "005laeh",  l[5])
  PlayIt.SetFieldContent ("SY012EHM1", "006lauf",   l[6])
  PlayIt.SetFieldContent ("SY012EHM1", "011vkuf",   l[7])
  PlayIt.SetFieldContent ("SY012SDM1", "012fest",   l[8])
  PlayIt.SetFieldContent ("SY012PRM1", "001tpr",   l[9])
  PlayIt.SetFieldContent ("SY012PRM1", "002wpr",   l[10])
  PlayIt.SetFieldContent ("SY012PRM1", "003plpr",   l[11])
  PlayIt.PlayContent ("{CSB SY012M1|art-nr}{F2}")
  s=f.readline ()
f.close ()
 
this is the error returned:
 
Traceback (innermost last):
  File "<string>", line 5, in ?
NameError: string

 
I've also tried this in line 5
 
l = (s, ",",[11])
 
I get further with this I actually get the first part of the string in the first field like it should be but in the second field all i get is a comma and it freezes, Initially I've been trying to import this from a csv file and now I've been working with text files. I'm sure I just don't know how to manipulate the string and I'm having trouble finding descriptions and methods to use with a string object. Do you have any suggestions or anything that would be helpful?
Thank You,
 
Chris Rosenboom




---------------------------------
Do you Yahoo!?
Find out what made the Top Yahoo! Searches of 2003
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20040102/5ec7f14a/attachment.html
From jb at riseup.net  Sat Jan  3 21:44:17 2004
From: jb at riseup.net (jb)
Date: Mon Jan  5 13:48:46 2004
Subject: [Tutor] O_EXLOCK ?
Message-ID: <20040104024416.GA10069@mubai.polvo.sakeos.net>

hi there,

i'm with Python 2.3.3 on a openbsd.

i'm looking everywhere (or at least in all the wrong places) and i can't find
a O_EXLOCK as in open(2), grepped the sources, etc.  This seems especially 
weird since fcntl doc says there's more about locking in os.open.

can anyone tell me where is this O_EXLOCK ?  am i missing something ?

thanks for your help,
jb

From Vishwavasu.Chobari at utstar.com  Mon Jan  5 08:25:56 2004
From: Vishwavasu.Chobari at utstar.com (Vishwavasu.Chobari@utstar.com)
Date: Mon Jan  5 13:48:50 2004
Subject: [Tutor] ImportError: No module named klg..
Message-ID: <OF96E92578.FBA9BC78-ON86256E12.00496426@mw.3com.com>

Hello,
      I am Vishwa working with JCChart to create a PIE chart.
I have the following two lines in my code to use JCChart.

from com.klg.jclass.chart import *
from com.klg.jclass.chart.JCChart import *

Despite setting the python.path, python.home, sys.path et al to the jar file that contains these classes,
I get the error -


01/05/2004 18:36:16 (E) PythonScript: exception: Traceback (innermost last):
  File "schema\standard\Jobs\scheduledReports\generatePPPStatistics.py", line 23
, in ?
ImportError: No module named klg


Any clues?

Thanks in advance.
--Vishwa



From dyoo at hkn.eecs.berkeley.edu  Mon Jan  5 14:06:58 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon Jan  5 14:07:04 2004
Subject: [Tutor] ImportError: No module named klg..
In-Reply-To: <OF96E92578.FBA9BC78-ON86256E12.00496426@mw.3com.com>
Message-ID: <Pine.LNX.4.44.0401051057310.16596-100000@hkn.eecs.berkeley.edu>



On Mon, 5 Jan 2004 Vishwavasu.Chobari@utstar.com wrote:

>       I am Vishwa working with JCChart to create a PIE chart. I have the
> following two lines in my code to use JCChart.
>
> from com.klg.jclass.chart import *
> from com.klg.jclass.chart.JCChart import *
>
> Despite setting the python.path, python.home, sys.path et al to the jar
> file that contains these classes, I get the error -
>
>
> 01/05/2004 18:36:16 (E) PythonScript: exception: Traceback (innermost
> last):
>   File "schema\standard\Jobs\scheduledReports\generatePPPStatistics.py",
> line 23 , in ?
> ImportError: No module named klg


Hi Vishwa,


I am confused right now.  Are we talking about a Python module, or a Java
module?  JCChart, as far as I can tell, is a Java package,

http://java.quest.com/support/jclass/dv/docs/api/com/klg/jclass/chart/JCChart.html

so CPython won't work with it.  Instead, you can use Jython to access it.

    http://www.jython.org/

If you use Jython, then adding the JAR to your Java CLASSPATH should do
the trick.


If you have further questions about Jython, there's a mailing list
dedicated to Jython:

    http://lists.sourceforge.net/lists/listinfo/jython-users

Good luck to you.


From ATrautman at perryjudds.com  Mon Jan  5 14:23:57 2004
From: ATrautman at perryjudds.com (Alan Trautman)
Date: Mon Jan  5 14:24:03 2004
Subject: [Tutor] seg fault problem
Message-ID: <06738462136C054B8F8872D69DA140DB01C08C05@corp-exch-1.pjinet.com>

Eve,

This sounds like TK/TCL did not install properly. 

If you are using windows remove and reinstall python or go to the TK site
and install TK.

If you are using *NIX/BSD go to the same TK site and download TK and
install. 

TK site:
http://www.pythonware.com/library/tkinter/introduction/whats-tkinter.htm

Tutorial:
http://www.pythonware.com/library/tkinter/introduction/whats-tkinter.htm

Sometimes installing the windows Activestate Python can be useful if some
libraries are giving you problems.

HTH,
Alan

-----Original Message-----
From: Eve [mailto:e.kotyk@shaw.ca]
Sent: Friday, January 02, 2004 1:33 PM
To: tutor@python.org
Subject: [Tutor] seg fault problem


I continue on my endless(and seemingly futile)attempt to learn a
programming language.  Currently I'm attempting small scripts in
Python/Tkinter.  The particular script is a textbox script at follows

#!/usr/lib/python2.2

from Tkinter import *
from ScrolledText import *
import sys

def die(event):
   sys.exit(0)

root = Tk()
f = Frame(root)
f.pack(expand=1, fill=BOTH)
button = Button(f, width=25)
button["text"] = "Button"
button.bind("<Button>",die)
button.pack()

st = ScrolledText(f,background="white")
st.pack()

root.mainloop()

Very simple and straight forward but if I mouseclick in the text window
the program seg faults.  Can anyone tell me why?  As an aside, I cannot
use idle (a text editor) because it seg faults everytime I try to
initialize.

Eve


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

From credo2004 at fmail.co.uk  Mon Jan  5 16:47:45 2004
From: credo2004 at fmail.co.uk (credo)
Date: Mon Jan  5 16:47:54 2004
Subject: [Tutor] Newbie: First program - looking for feedback :)
Message-ID: <20040105214745.989CD44D7B@server1.messagingengine.com>

Hi Pythoneers,

Okay, ive been trying to teach myself python for a few weeks and i'm
making some slow progress, (not a natural coder here). This started
mainly
due to me switching from Windows -> GNU/Linux about a year ago. 

I find i am getting comfortable with GNU/Linux now, and it has recently
encouraged 
me to try my hand at programming; for those times when you wished you had
a 
little tool to do something :). 
The possibilty of helping the open source commnunity by contributing to
software 
development etc is also a plus, although a distant dream at this point.
;) 

My primary goal is to have some fun with this. I believe selecting Python
as my first
language was the right choice :)

With this in mind, and with some embarrassment, i post my first *real*
python program. 

Its a function to convert mp3 -> wav using the 'lame' encoder. I also
went beyond a 
simple 'for' loop to add some interaction with the user, purely as an
exercise.

--------------------------------------- code
-----------------------------------------

#! /usr/bin/env python

# mp32wav
# A *basic* function to convert mp3 to wav format.
# 28/12/03 - credo - credo2004@fmail.co.uk 

#####################################
# To-Do                             #
#####################################

# 1. Add some PROPER error handling.
# 2. Get filenames to print in order. (ie: 01 -> 10)
# 3. Allow option for target other than cwd.
# 4. Make function modular to allow use from other progs. 

import os
import sys
import os.path

wavext = '.wav'
mp3ext = '.mp3'

def mp32wav():
    
    # Get file list from current directory.    
    cwd = os.getcwd()
    list = os.listdir(cwd)
    os.system('clear')
   
    print
    print '============================='
    print 'MP3 to convert to WAV format:' 
    print '============================='
    print 


    # Sort the mp3 to convert and add them to a list for later use, also
    # keep tally of valid and non-valid files.
    good = 0
    bad = 0
    mp3 = []
    
    for eachfile in list:
        if eachfile.endswith(mp3ext):
            mp3.append(eachfile)
            good += 1
        else:
            pass
            bad += 1
    print
    print 'Mp3 files to convert = ',good
    print 'Non-mp3 files to be left alone = ',bad
    print
    
    choice = raw_input('\nConvert? (Y/n): ')
    choice = choice.lower()

    if (choice == 'y'):
        print
        print 'Converting...'
        print

        # Pass the mp3 files to the 'lame' encoder, extract filenames and
        # concatenate with constant to create output wav based on
        original 
        # filename. I think that makes sense ;)
        # Some very basic error handling here also.
        for eachfile in mp3:
            name = os.path.splitext(eachfile)
            result = os.system('lame --decode %s %s%s'  %
            (eachfile,name[0],wavext))
            if (result == 0):
                print
                print 'Converted %s -> %s%s' % (eachfile,name[0],wavext)
                print
            else:
                result = 1
    else:
        print
        sys.exit()
        
    # Had this problem myself, so added this as an afterthought. Need to
    clean
    # and add some proper error/exception handling.
    if (result == 1):
        print
        print "Error! - Can't convert: Please check folder/file
        permissions :)"
        print
        raw_input('Press any key to quit: ')
        print
    else:
        print 'Finished!!!!!!!!!!!!!!!!'   
        print
        raw_input('Press any key to quit: ')
        print
    
if __name__ == '__main__':
    mp32wav()
	
--------------------------------------- code
-----------------------------------------

I know, its not pretty and theres probably a 1001 ways to make it more
elegant and efficient
but i really just went into it with some basic knowledge of some standard
libraries and an idea
of how i wanted the program to flow. The little testing i have done
indicates it does work but 
i'm working on beautifying it. See the To-do comments for some of the
obvious that i noted down :)

Some general feedback on the code and use of python language would be
appreciated. I'm looking for
tips/tricks and anything that can help me become better at this. Some of
the above code already 
makes me cringe, but i thought it was worth posting my first draft incase
i'm making some big 
mistakes early on, then i can eliminate them now.

Thanks in advance for any comments...i can accept constructive criticism
:)

Best Regards

credo

-- 
http://www.fastmail.fm - Access all of your messages and folders
                          wherever you are

From alan.gauld at blueyonder.co.uk  Mon Jan  5 17:09:25 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Mon Jan  5 17:08:54 2004
Subject: [Tutor] Newbie: First program - looking for feedback :)
References: <20040105214745.989CD44D7B@server1.messagingengine.com>
Message-ID: <011501c3d3d8$94fbc330$6401a8c0@xp>

> With this in mind, and with some embarrassment, i post my first
*real*
> python program.

For a first program its fine. You obviously understand how
to write functions so you might want to consider breaking
it up into several smaller functions - ONe to deal with
the user input and get the list of files, another to process
the files, and another to do the reporting of the results.

This separation of concerns helps to build reusable functions
- for example the function that takes a filename, converts
it and reports success could be used from a GUI version
of the program. And a function which can ask the user to
provide a list of filenames could be used in several other,
similar tools.

Some specific comments:

>         for eachfile in mp3:
>             name = os.path.splitext(eachfile)
>             result = os.system('lame --decode %s %s%s'  %
>             (eachfile,name[0],wavext))
>             if (result == 0):
>                 print
>                 print 'Converted %s -> %s%s' %
(eachfile,name[0],wavext)
>                 print
>             else:
>                 result = 1

This last else isn't really needed because result will be set
by the system() call each time through the loop.

>     else:
>         print
>         sys.exit()
>
>     # Had this problem myself, so added this as an afterthought.
Need to
>     clean
>     # and add some proper error/exception handling.
>     if (result == 1):


And this then gets changed to

        if result != 0

Note you don't really need the parems round the test
- unlike in C.

> I know, its not pretty and theres probably a 1001 ways
> to make it more elegant and efficient

Probably, but it seems to work and for a first attempt it's OK.

Add the new features etc you mention and try "refactoring"
it into smaller functions and it should make a nice project.

One last thought - you might like to use triple quotes instead
of multiple print statements, but thats mostly a matter of
personal taste.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


From missive at hotmail.com  Mon Jan  5 17:20:42 2004
From: missive at hotmail.com (Lee Harr)
Date: Mon Jan  5 17:20:51 2004
Subject: [Tutor] Re: importing into fields
Message-ID: <BAY2-F7IXWb9DYccSN00004dd4f@hotmail.com>

>I'm trying to manipulate a string to seperate before entering each seperate 
>instance in >some fields on a software program, here's an example of the 
>script
>
>f=open ("book2.txt", "r")
>s=f.readline ()
>while s != "":
>  print s
>  l = string.split(s, ",",[11])
>


You use the string module here. If you want to do that, you will
have to put

import string

before that in the file. The alternative (and recommended) way
would be to use "string methods" which would look like ...

s.split(",")

I am also not sure about your string.split call ... You probably want
to look at the docs to be sure you are calling properly.  If you use

string.split(s, ",", 11)

that would split string s at commas returning at most 12 pieces.

>>>a='1, 2, 3, 4'
>>>import string
>>>string.split(a, ',', 2)
['1', ' 2', ' 3, 4']
>>>a.split(',', 2)
['1', ' 2', ' 3, 4']
>>>a.split(',')
['1', ' 2', ' 3', ' 4']

_________________________________________________________________
STOP MORE SPAM with the new MSN 8 and get 2 months FREE* 
http://join.msn.com/?page=features/junkmail


From anewby at mailbolt.com  Mon Jan  5 17:37:17 2004
From: anewby at mailbolt.com (Alex Newby)
Date: Mon Jan  5 17:37:24 2004
Subject: [Tutor] WebDAV filesystem access with Boa Constructor
In-Reply-To: <20040105191113.989D6E45C5@mail.messagingengine.com>
References: <20040105191113.989D6E45C5@mail.messagingengine.com>
Message-ID: <20040105223717.D9D027F8A4@server2.messagingengine.com>

Hi,

I am trying to connect with Boa Constructor to a subdomain, but get the
error message:

"...The requested URL // was not found on this server..."

And, more specifically (from Boa's event log):

10:58:29: xml.parsers.expat.ExpatError: syntax error: line 1, column
          49Traceback (mostrecent call last):
10:58:30: xml.parsers.expat.ExpatError: syntax error: line 1, column
          49 File "C:\Python23\Lib\site-
          packages\wxPython\tools\boa\Explorers\Explorer.py", line
          147, in OnOpen
10:58:31: lst = data.openList()
10:58:32: File "C:\Python23\Lib\site-
          packages\wxPython\tools\boa\Explorers\DAVExplorer.py", line
          180, in openList
10:58:33: l = XMLListBuilder(resp.body).lists
10:58:34: File "C:\Python23\Lib\site-
          packages\wxPython\tools\boa\Explorers\DAVExplorer.py", line 49,
          in __init__
10:58:35: self.status = parser.Parse(data[xmlStart:xmlEnd+1], 1)
10:58:36: xml.parsers.expat.ExpatError: syntax error: line 1, column 49

> I said, "Could you give me the absolute system path to try? I think Boa
> could be a little weak with this."

The friendly SysAdmin at Zettai said, "With http that would not have
anything to do with things. Boa would need to pass the VirtualHost
variable. You might want to make sure it can do HTTP 1.1 Good luck."

Does anyone know anything about this? I suppose the alternative, if this
doesn't work, would be to use Cadaver  under Cygwin, but it would really
make life easier if this could work through Boa.

BTW ~ Thanks to this list I found out about Stani's Python Editor.
Exactly what a would-be programmer like me needs. Lots of hand-holding:)
I have GVim with Cream on my system, but it just doesn't seem where its
at. Curious if anyone knows what Stani means by 'extensible with Boa'?
-----------------------
Regards,

Alex Newby 
http://alexnewby.com

From andrewm at object-craft.com.au  Mon Jan  5 17:47:28 2004
From: andrewm at object-craft.com.au (Andrew McNamara)
Date: Mon Jan  5 17:47:39 2004
Subject: [Tutor] O_EXLOCK ? 
In-Reply-To: Message from jb <jb@riseup.net> of "Sun,
	04 Jan 2004 03:44:17 BST."
	<20040104024416.GA10069@mubai.polvo.sakeos.net> 
References: <20040104024416.GA10069@mubai.polvo.sakeos.net> 
Message-ID: <20040105224728.A81303C041@coffee.object-craft.com.au>

>i'm with Python 2.3.3 on a openbsd.
>
>i'm looking everywhere (or at least in all the wrong places) and i can't find
>a O_EXLOCK as in open(2), grepped the sources, etc.  This seems especially 
>weird since fcntl doc says there's more about locking in os.open.
>
>can anyone tell me where is this O_EXLOCK ?  am i missing something ?

All the common O_ symbols are defined in the "os" module, but O_EXLOCK
is not standard (not part of the Single Unix spec [1]) - it's a BSD
extension. That's not to say it couldn't be added to "os" at a future
time, but that won't help you in the short term. There is, however, a
"posixfile" module that may do what you need.

 [1] http://www.opengroup.org/onlinepubs/007908799/xsh/open.html

-- 
Andrew McNamara, Senior Developer, Object Craft
http://www.object-craft.com.au/

From sigurd at 12move.de  Mon Jan  5 17:51:21 2004
From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=)
Date: Mon Jan  5 17:53:23 2004
Subject: [Tutor] Mailing Made Simple - Multiple Recipient Problem
In-Reply-To: <Law15-DAV37BZTW5k1E00001ff2@hotmail.com> (steegness@hotmail.com's
	message of "Mon, 5 Jan 2004 12:54:22 -0500")
References: <Law15-DAV37BZTW5k1E00001ff2@hotmail.com>
Message-ID: <m3oetiau7c.fsf@hamster.pflaesterer.de>

On  5 Jan 2004, Steegness <- steegness@hotmail.com wrote:

> It doesn't seem to send to multiple recipients well. When passed the info for
> its TO field, only the first recipient listed recieves an e-mail; all others
> are seemingly ignored.

This is a feature. Use Cc: for multiple recipients or BCc: (see RfC
2822). In the smtp dialog each recipient in To: or Cc should produce a
RCPT TO: command.  Coping with BCc is a bit tricky (there are different
srtategies; cf also RfC 2822).


   Karl
-- 
Please do *not* send copies of replies to me.
I read the list


From sigurd at 12move.de  Mon Jan  5 18:02:57 2004
From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=)
Date: Mon Jan  5 18:03:33 2004
Subject: [Tutor] downloading files
In-Reply-To: <20040101193141.40507.qmail@web20311.mail.yahoo.com> (Ron
	Nixon's message of "Thu, 1 Jan 2004 11:31:41 -0800 (PST)")
References: <20040101193141.40507.qmail@web20311.mail.yahoo.com>
Message-ID: <m3k746atok.fsf@hamster.pflaesterer.de>

On  1 Jan 2004, Ron Nixon <- nixonron@yahoo.com wrote:

> I'm fairly new at Python and I have a project where I need to scan a
> webpage for a list of names and then download any files associated
> with those names. Any utilites like that already exist out there that
> somone could point me to or give me some advice on how to do it?

Can you be a bit more verbose?

To find a webpage you can use urllib or urllib2; to parse the content
htmllib or HTMLParser; to fetch the content again urlib(2).

Be a bit more specific and it's easy to help.


   Karl
-- 
Please do *not* send copies of replies to me.
I read the list


From sigurd at 12move.de  Mon Jan  5 18:31:25 2004
From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=)
Date: Mon Jan  5 18:33:48 2004
Subject: [Tutor] importing into fields
In-Reply-To: <20040102233235.33591.qmail@web21203.mail.yahoo.com> (Chris
	Rosenboom's message of "Fri, 2 Jan 2004 15:32:35 -0800 (PST)")
References: <20040102233235.33591.qmail@web21203.mail.yahoo.com>
Message-ID: <m3fzeuat9t.fsf@hamster.pflaesterer.de>

On  3 Jan 2004, Chris Rosenboom <- boomer4467@yahoo.com wrote:

> I'm trying to manipulate a string to seperate before entering each seperate
> instance in some fields on a software program, here's an example of the script

> f=open ("book2.txt", "r")
> s=f.readline ()
> while s != "":
>   print s
>   l = string.split(s, ",",[11])

You never imported string; so you have the name error.
Furthermore the [11] is alist; but you need to give a integer as
argument here.

>   PlayIt.SetFieldContent ("SY012M1", "art-nr", l[0])
[...]
>   s=f.readline ()
> f.close ()

> this is the error returned:

> Traceback (innermost last):
>   File "<string>", line 5, in ?
> NameError: string

But there is no need to import string.


> I've also tried this in line 5

> l = (s, ",",[11])

> I get further with this I actually get the first part of the string in the
> first field like it should be but in the second field all i get is a comma and
> it freezes, Initially I've been trying to import this from a csv file and now
> I've been working with text files. I'm sure I just don't know how to
> manipulate the string and I'm having trouble finding descriptions and methods
> to use with a string object. Do you have any suggestions or anything that
> would be helpful? Thank You,


First there should be a lot of documentation coming with your Python
system.  Then a lot of docu can be read interactively. Eg. if you wanted
to know which methods strings have you just type:

>>> s = ""
>>> dir(s)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__str__', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'replace', 'rfind', 'rindex', 'rjust', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>> 

The first line created a string, the second line shows me all its
methods.  The same works for every object.  Also try help()

>>> help()

Welcome to Python 2.3!  This is the online help utility.

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://www.python.org/doc/tut/.

Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules.  To quit this help utility and
return to the interpreter, just type "quit".

To get a list of available modules, keywords, or topics, type "modules",
"keywords", or "topics".  Each module also comes with a one-line summary
of what it does; to list the modules whose summaries contain a given word
such as "spam", type "modules spam".

help> 


You can read a lot there.

But back to your problem.

I assume you have a relatively current version of Python so your code
can be written a bit simpler and IMO easier to read.

f=open ("book2.txt")
for line in f:
  print line
  L = line.split(",", 11)
  PlayIt.SetFieldContent ("SY012M1", "art-nr", L[0])
  PlayIt.PlayContent ("{CSB SY012M1|art-nr}{Enter}")
  PlayIt.SetFieldContent ("SY012ADM1", "001bez",  L[1])
  PlayIt.SetFieldContent ("SY012ADM1", "005agr",  L[2])
  PlayIt.SetFieldContent ("SY012ADM1", "006agr",  L[3])
  PlayIt.SetFieldContent ("SY012ADM1", "009kst",  L[4])
  PlayIt.SetFieldContent ("SY012EHM1", "005laeh", L[5])
  PlayIt.SetFieldContent ("SY012EHM1", "006lauf", L[6])
  PlayIt.SetFieldContent ("SY012EHM1", "011vkuf", L[7])
  PlayIt.SetFieldContent ("SY012SDM1", "012fest", L[8])
  PlayIt.SetFieldContent ("SY012PRM1", "001tpr",  L[9])
  PlayIt.SetFieldContent ("SY012PRM1", "002wpr",  L[10])
  PlayIt.SetFieldContent ("SY012PRM1", "003plpr", L[11])
  PlayIt.PlayContent ("{CSB SY012M1|art-nr}{F2}")

f.close()

(I replaced your l with L since IMO a single smallcaps l is hard to
distinguish from a 1.)



   Karl
-- 
Please do *not* send copies of replies to me.
I read the list


From littledanehren at yahoo.com  Mon Jan  5 19:06:47 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Mon Jan  5 19:06:51 2004
Subject: [Tutor] importing into fields
In-Reply-To: <m3fzeuat9t.fsf@hamster.pflaesterer.de>
Message-ID: <20040106000647.38101.qmail@web41805.mail.yahoo.com>

> But back to your problem.
> 
> I assume you have a relatively current version of
> Python so your code
> can be written a bit simpler and IMO easier to read.
> 
> f=open ("book2.txt")
> for line in f:
>   print line
>   L = line.split(",", 11)
>   PlayIt.SetFieldContent ("SY012M1", "art-nr", L[0])
>   PlayIt.PlayContent ("{CSB SY012M1|art-nr}{Enter}")
>   PlayIt.SetFieldContent ("SY012ADM1", "001bez", 
> L[1])
>   PlayIt.SetFieldContent ("SY012ADM1", "005agr", 
> L[2])
>   PlayIt.SetFieldContent ("SY012ADM1", "006agr", 
> L[3])
>   PlayIt.SetFieldContent ("SY012ADM1", "009kst", 
> L[4])
>   PlayIt.SetFieldContent ("SY012EHM1", "005laeh",
> L[5])
>   PlayIt.SetFieldContent ("SY012EHM1", "006lauf",
> L[6])
>   PlayIt.SetFieldContent ("SY012EHM1", "011vkuf",
> L[7])
>   PlayIt.SetFieldContent ("SY012SDM1", "012fest",
> L[8])
>   PlayIt.SetFieldContent ("SY012PRM1", "001tpr", 
> L[9])
>   PlayIt.SetFieldContent ("SY012PRM1", "002wpr", 
> L[10])
>   PlayIt.SetFieldContent ("SY012PRM1", "003plpr",
> L[11])
>   PlayIt.PlayContent ("{CSB SY012M1|art-nr}{F2}")
> 
> f.close()
> 
> (I replaced your l with L since IMO a single
> smallcaps l is hard to
> distinguish from a 1.)
> 
> 
> 
>    Karl

Are you sure that would have the same functionality?
His program stopped at any empty string, not just the
end of the file. I'm not sure if this was the desired
behavior, though.

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Find out what made the Top Yahoo! Searches of 2003
http://search.yahoo.com/top2003

From littledanehren at yahoo.com  Mon Jan  5 19:09:32 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Mon Jan  5 19:09:37 2004
Subject: [Tutor] importing into fields
In-Reply-To: <m3fzeuat9t.fsf@hamster.pflaesterer.de>
Message-ID: <20040106000932.40017.qmail@web41810.mail.yahoo.com>

> But back to your problem.
> 
> I assume you have a relatively current version of
> Python so your code
> can be written a bit simpler and IMO easier to read.
> 
> f=open ("book2.txt")
> for line in f:
>   print line
>   L = line.split(",", 11)
>   PlayIt.SetFieldContent ("SY012M1", "art-nr", L[0])
>   PlayIt.PlayContent ("{CSB SY012M1|art-nr}{Enter}")
>   PlayIt.SetFieldContent ("SY012ADM1", "001bez", 
> L[1])
>   PlayIt.SetFieldContent ("SY012ADM1", "005agr", 
> L[2])
>   PlayIt.SetFieldContent ("SY012ADM1", "006agr", 
> L[3])
>   PlayIt.SetFieldContent ("SY012ADM1", "009kst", 
> L[4])
>   PlayIt.SetFieldContent ("SY012EHM1", "005laeh",
> L[5])
>   PlayIt.SetFieldContent ("SY012EHM1", "006lauf",
> L[6])
>   PlayIt.SetFieldContent ("SY012EHM1", "011vkuf",
> L[7])
>   PlayIt.SetFieldContent ("SY012SDM1", "012fest",
> L[8])
>   PlayIt.SetFieldContent ("SY012PRM1", "001tpr", 
> L[9])
>   PlayIt.SetFieldContent ("SY012PRM1", "002wpr", 
> L[10])
>   PlayIt.SetFieldContent ("SY012PRM1", "003plpr",
> L[11])
>   PlayIt.PlayContent ("{CSB SY012M1|art-nr}{F2}")
> 
> f.close()
> 
> (I replaced your l with L since IMO a single
> smallcaps l is hard to
> distinguish from a 1.)
> 
> 
> 
>    Karl

Are you sure that would have the same functionality?
His program stopped at any empty line, not just the
end of the file. I'm not sure if this was the desired
behavior, though.

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Find out what made the Top Yahoo! Searches of 2003
http://search.yahoo.com/top2003

From sigurd at 12move.de  Mon Jan  5 19:27:04 2004
From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=)
Date: Mon Jan  5 19:31:02 2004
Subject: [Tutor] importing into fields
In-Reply-To: <20040106000647.38101.qmail@web41805.mail.yahoo.com> (Daniel
	Ehrenberg's message of "Mon, 5 Jan 2004 16:06:47 -0800 (PST)")
References: <20040106000647.38101.qmail@web41805.mail.yahoo.com>
Message-ID: <m37k05c488.fsf@hamster.pflaesterer.de>

On  6 Jan 2004, Daniel Ehrenberg <- littledanehren@yahoo.com wrote:

> Are you sure that would have the same functionality?
> His program stopped at any empty string, not just the
> end of the file. I'm not sure if this was the desired
> behavior, though.

Ithought he wanted to detect that way EOF.  But you're right.  If he
wanted the same behaviour he must add a test for an empty string and
break if it's true.


   Karl
-- 
Please do *not* send copies of replies to me.
I read the list


From littledanehren at yahoo.com  Mon Jan  5 20:24:00 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Mon Jan  5 20:24:05 2004
Subject: [Tutor] help leraning python
In-Reply-To: <D9CA008BEBE6D4118CFF00805FBE470D2225E9@MVINCT10>
Message-ID: <20040106012400.55393.qmail@web41811.mail.yahoo.com>

> I 'm learning by myself the Python's language,
> starting from an e-book
> called 'How to think like a computer scientist'
> traduced in french by Gerard
> Swinnen 
> Some exercises are difficult and without solution
> described in the e-book 
> Does somebody know where I can find the solution, or
> other examples with
> their comments, to support my learning lessons? 
> Thanks a lot

How to Think Like a Computer Scientist is one of the
harder tutorials. Some easier tutorials include
Learning to program and Non-Programmer's tutorial to
Python. Personally, I prefer the latter because the
former actually teaches Python, BASIC, and Tcl, but
it's really a matter of opinion. They are available at
http://www.honors.montana.edu/~jjc/easytut/easytut/
and http://www.freenetpages.co.uk/hp/alan.gauld/
respectively. If by traduced you mean translated
(traduce means to malign), I don't think you will be
able to find any tutorials other than How to Think
Like a Computer Scientist that have been translated
into French. Although Learning to Program has been
translated into six languages, French is not one of
them. If you're stuck with How to Think Like a
Computer Scientist for that reason, you can always ask
the people on this list for answers to excercises (or
if the other people on this list don't like that, you
can email me privately for the answer).

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Find out what made the Top Yahoo! Searches of 2003
http://search.yahoo.com/top2003

From jb at riseup.net  Mon Jan  5 22:48:01 2004
From: jb at riseup.net (jb)
Date: Mon Jan  5 22:53:07 2004
Subject: [Tutor] O_EXLOCK ?
In-Reply-To: <20040105224728.A81303C041@coffee.object-craft.com.au>
References: <20040104024416.GA10069@mubai.polvo.sakeos.net>
	<20040105224728.A81303C041@coffee.object-craft.com.au>
Message-ID: <20040106034801.GA9566@mubai.polvo.sakeos.net>

On Tue, Jan 06, 2004 at 09:47:28AM +1100, Andrew McNamara wrote:
> >i'm with Python 2.3.3 on a openbsd.
> >
> >i'm looking everywhere (or at least in all the wrong places) and i can't find
> >a O_EXLOCK as in open(2), grepped the sources, etc.  This seems especially 
> >weird since fcntl doc says there's more about locking in os.open.
> >
> >can anyone tell me where is this O_EXLOCK ?  am i missing something ?
> 
> All the common O_ symbols are defined in the "os" module, but O_EXLOCK
> is not standard (not part of the Single Unix spec [1]) - it's a BSD
> extension. That's not to say it couldn't be added to "os" at a future
> time, but that won't help you in the short term. There is, however, a
> "posixfile" module that may do what you need.
> 
>  [1] http://www.opengroup.org/onlinepubs/007908799/xsh/open.html
> 

hi,

It hurts that O_EXLOCK and O_SHLOCK are only BSD extensions.  Plan was to
use O_EXLOCK for concurrent pickling and unpickling and now i guess i'll enter
homegrown locking solutions madness.

thanks for your help and for pointing me to the standards.

later'
jb


From andrewm at object-craft.com.au  Tue Jan  6 00:18:34 2004
From: andrewm at object-craft.com.au (Andrew McNamara)
Date: Tue Jan  6 00:18:38 2004
Subject: [Tutor] O_EXLOCK ? 
In-Reply-To: Message from jb <jb@riseup.net> of "Tue,
	06 Jan 2004 04:48:01 BST."
	<20040106034801.GA9566@mubai.polvo.sakeos.net> 
References: <20040104024416.GA10069@mubai.polvo.sakeos.net>
	<20040105224728.A81303C041@coffee.object-craft.com.au>
	<20040106034801.GA9566@mubai.polvo.sakeos.net> 
Message-ID: <20040106051834.DF96F3C131@coffee.object-craft.com.au>

>> All the common O_ symbols are defined in the "os" module, but O_EXLOCK
>> is not standard (not part of the Single Unix spec [1]) - it's a BSD
>> extension. That's not to say it couldn't be added to "os" at a future
>> time, but that won't help you in the short term. There is, however, a
>> "posixfile" module that may do what you need.
>
>It hurts that O_EXLOCK and O_SHLOCK are only BSD extensions.  Plan was to
>use O_EXLOCK for concurrent pickling and unpickling and now i guess i'll
>enter homegrown locking solutions madness.

You can still use fcntl locking (as provided by posixfile) - no need to
invent something bodgy. It really doesn't matter that you have to open the
file first, provided you don't change it until you gain the lock.

Either use the locking provided by posixfile, or copy their implementation
(you'll see the arguments to the fcntl locking operations vary between
playforms).

-- 
Andrew McNamara, Senior Developer, Object Craft
http://www.object-craft.com.au/

From jb at riseup.net  Tue Jan  6 01:45:50 2004
From: jb at riseup.net (jb)
Date: Tue Jan  6 01:50:48 2004
Subject: [Tutor] O_EXLOCK ?
In-Reply-To: <20040106051834.DF96F3C131@coffee.object-craft.com.au>
References: <20040104024416.GA10069@mubai.polvo.sakeos.net>
	<20040105224728.A81303C041@coffee.object-craft.com.au>
	<20040106034801.GA9566@mubai.polvo.sakeos.net>
	<20040106051834.DF96F3C131@coffee.object-craft.com.au>
Message-ID: <20040106064550.GA22612@mubai.polvo.sakeos.net>

On Tue, Jan 06, 2004 at 04:18:34PM +1100, Andrew McNamara wrote:
> >> All the common O_ symbols are defined in the "os" module, but O_EXLOCK
> >> is not standard (not part of the Single Unix spec [1]) - it's a BSD
> >> extension. That's not to say it couldn't be added to "os" at a future
> >> time, but that won't help you in the short term. There is, however, a
> >> "posixfile" module that may do what you need.
> >
> >It hurts that O_EXLOCK and O_SHLOCK are only BSD extensions.  Plan was to
> >use O_EXLOCK for concurrent pickling and unpickling and now i guess i'll
> >enter homegrown locking solutions madness.
> 
> You can still use fcntl locking (as provided by posixfile) - no need to
> invent something bodgy. It really doesn't matter that you have to open the
> file first, provided you don't change it until you gain the lock.

agreed, but oops, i shoud have said that i found the situation problematic 
only at file creation time.  When a file already exists and contains pickled 
data there's no problem and fcntl locking permits that the file stays in a 
consistent state (for pickle).  

when a file is to be created and process A (wanting to dump a pickled object)
and B (wanting to read a pickled object) are competing, there's the possibility
that B gain the lock and start reading just after A has created the file - 
then pickle in B will raise an EOFError (or something).  I was concerned by
this.

but i can dump my object to a temporary file, and then link(2), this looks ok
for my needs.

thanks,
jb


From andrewm at object-craft.com.au  Tue Jan  6 02:28:10 2004
From: andrewm at object-craft.com.au (Andrew McNamara)
Date: Tue Jan  6 02:28:13 2004
Subject: [Tutor] O_EXLOCK ? 
In-Reply-To: Message from jb <jb@riseup.net> of "Tue,
	06 Jan 2004 07:45:50 BST."
	<20040106064550.GA22612@mubai.polvo.sakeos.net> 
References: <20040104024416.GA10069@mubai.polvo.sakeos.net>
	<20040105224728.A81303C041@coffee.object-craft.com.au>
	<20040106034801.GA9566@mubai.polvo.sakeos.net>
	<20040106051834.DF96F3C131@coffee.object-craft.com.au>
	<20040106064550.GA22612@mubai.polvo.sakeos.net> 
Message-ID: <20040106072810.E5A593C131@coffee.object-craft.com.au>

>agreed, but oops, i shoud have said that i found the situation problematic 
>only at file creation time.  When a file already exists and contains pickled 
>data there's no problem and fcntl locking permits that the file stays in a 
>consistent state (for pickle).  
>
>when a file is to be created and process A (wanting to dump a pickled object)
>and B (wanting to read a pickled object) are competing, there's the possibility
>that B gain the lock and start reading just after A has created the file - 
>then pickle in B will raise an EOFError (or something).  I was concerned by
>this.
>
>but i can dump my object to a temporary file, and then link(2), this looks ok
>for my needs.

Yep, under unix, that would be your best bet.

-- 
Andrew McNamara, Senior Developer, Object Craft
http://www.object-craft.com.au/

From steegness at hotmail.com  Tue Jan  6 11:34:09 2004
From: steegness at hotmail.com (Sean Steeg)
Date: Tue Jan  6 12:00:31 2004
Subject: [Tutor] Mailing Made Simple - Multiple Recipient Problem
Message-ID: <Law15-F90dfEm58zJZj00018ac7@hotmail.com>

OK then, just to make sure I grasp what's going on here then:

Where is the SMTP server getting its recipient information from?  That is to 
say, which is parsed to send the letter out to someone?  smtplib's send 
function calls for recipients in its argument, outside of any headers in the 
letter itself; I would think it'd be there where the recipients are found.

Let's say I want to switch this around to get multiple recipients.  I know I 
can adjust the headers easily enough, so that the multiples are CCs instead 
of TOs, but what should I do with that first argument for the smtplib.send() 
function?

Thanks,
Sean

-----------------
Message: 5
Date: Mon, 05 Jan 2004 23:51:21 +0100
From: sigurd@12move.de (Karl Pfl?sterer )
Subject: Re: [Tutor] Mailing Made Simple - Multiple Recipient Problem
To: tutor@python.org
Message-ID: <m3oetiau7c.fsf@hamster.pflaesterer.de>
Content-Type: text/plain; charset=us-ascii

On  5 Jan 2004, Steegness <- steegness@hotmail.com wrote:

>It doesn't seem to send to multiple recipients well. When passed the info 
>for
>its TO field, only the first recipient listed recieves an e-mail; all 
>others
>are seemingly ignored.

This is a feature. Use Cc: for multiple recipients or BCc: (see RfC
2822). In the smtp dialog each recipient in To: or Cc should produce a
RCPT TO: command.  Coping with BCc is a bit tricky (there are different
srtategies; cf also RfC 2822).


   Karl

_________________________________________________________________
Check your PC for viruses with the FREE McAfee online computer scan.  
http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963


From roypython at hotmail.com  Tue Jan  6 13:16:54 2004
From: roypython at hotmail.com (roy ollis)
Date: Tue Jan  6 13:17:00 2004
Subject: [Tutor] help leraning python
Message-ID: <BAY2-F14TEq9xwUJ0wF000066e4@hotmail.com>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20040106/f43c9f10/attachment.html
From sigurd at 12move.de  Tue Jan  6 14:36:34 2004
From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=)
Date: Tue Jan  6 14:39:16 2004
Subject: [Tutor] Mailing Made Simple - Multiple Recipient Problem
In-Reply-To: <Law15-F90dfEm58zJZj00018ac7@hotmail.com> (Sean Steeg's message
	of "Tue, 06 Jan 2004 11:34:09 -0500")
References: <Law15-F90dfEm58zJZj00018ac7@hotmail.com>
Message-ID: <m3hdz86fy9.fsf@hamster.pflaesterer.de>

On  6 Jan 2004, Sean Steeg <- steegness@hotmail.com wrote:

> OK then, just to make sure I grasp what's going on here then:

> Where is the SMTP server getting its recipient information from?  That
> is to say, which is parsed to send the letter out to someone?
> smtplib's send function calls for recipients in its argument, outside
> of any headers in the letter itself; I would think it'd be there where
> the recipients are found.

,----[ Python library docu ]
| `sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options])'
|      Send mail.  The required arguments are an RFC 822 from-address
|      string, a list of RFC 822 to-address strings, and a message string.
`----

So the to_addrs are a list of strings.  To send e-mail to multiple
recipients you could write:

In [1]: import smtplib

In [2]: server = smtplib.SMTP('127.0.0.1')

In [3]: msg = """
   ...: mFrom: me
   ...: mTo: some people 
   ...: m
   ...: mbody body body
   ...: m"""

In [4]: server.sendmail('me', ['admin', 'testeins'], msg)
Out[4]: {}

If I look in the log file of my smtp server I see (logfile is debug
level and all possible checking turned off):

ceb} < 220 SMTP-Server Classic Hamster Version 2.0 (Build 2.0.4.0) on wintendo.pflaesterer.de is ready.
ceb} > ehlo [127.0.0.1]
ceb} < 250-wintendo.pflaesterer.de
ceb} < 250-8BITMIME
ceb} < 250-AUTH DIGEST-MD5 CRAM-SHA1 CRAM-MD5 LOGIN
ceb} < 250-AUTH=DIGEST-MD5 CRAM-SHA1 CRAM-MD5 LOGIN
ceb} < 250 HELP
ceb} > mail FROM:<me>
ceb} < 250 OK
ceb} > rcpt TO:<admin>
ceb} < 250 OK
ceb} > rcpt TO:<testeins>
ceb} < 250 OK
ceb} > data
ceb} < 354 Start mail input; end with <CRLF>.<CRLF>
[...]
ceb} Mailrouter: Mail from <me> delivered to all recipients
ceb} < 250 OK

So for every entry in the list of recipients one RCPT TO is created.


> Let's say I want to switch this around to get multiple recipients.  I
> know I can adjust the headers easily enough, so that the multiples are
> CCs instead of TOs, but what should I do with that first argument for
> the smtplib.send() function?

Hope the above helps (I think you mean smtplib.sendmail()).

(please consider to stop top posting; it's hard to read).


   Karl
-- 
Please do *not* send copies of replies to me.
I read the list


From Christian.Wyglendowski at greenville.edu  Tue Jan  6 17:38:44 2004
From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski)
Date: Tue Jan  6 17:38:49 2004
Subject: [Tutor] Newbie: First program - looking for feedback :)
Message-ID: <CE1475C007B563499EDBF8CDA30AB45B0A3894@empex.greenville.edu>

> -----Original Message-----
> Hi Pythoneers,
> 
> Okay, ive been trying to teach myself python for a few weeks 
> and i'm making some slow progress, (not a natural coder 
> here). This started mainly due to me switching from Windows 
> -> GNU/Linux about a year ago. 

Cool.  Python is the first general purpose programming language that I
have learned as well.  I played with PHP on my web site and then moved
on to Python.  What a breath of fresh air that was!
 
> I find i am getting comfortable with GNU/Linux now, and it 
> has recently encouraged 
> me to try my hand at programming; for those times when you 
> wished you had a 
> little tool to do something :). 
> The possibilty of helping the open source commnunity by 
> contributing to software 
> development etc is also a plus, although a distant dream at 
> this point.
> ;) 

Good goals.  I have had the most fun with some of the little "tools"
that I have written for mine and others' benefit.  I hope to contribute
to the open source world someday as well.

> My primary goal is to have some fun with this. I believe 
> selecting Python as my first language was the right choice :)
> 
> With this in mind, and with some embarrassment, i post my 
> first *real* python program. 

Well, I don't have any specific stuff to say about your code (Alan had
some good thoughts that I don't need to rehash).  I would, however,
suggest that you revamp the program as a command line utility.  You
could really trim down the size of your program and it would be more
flexible (you could pass onlyone.mp3 or *.mp3 in a directory).

There's my thoughts.

Christian
http://www.dowski.com


From dyoo at hkn.eecs.berkeley.edu  Tue Jan  6 18:23:44 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue Jan  6 18:23:50 2004
Subject: [Tutor] Newbie: First program - looking for feedback :)
In-Reply-To: <CE1475C007B563499EDBF8CDA30AB45B0A3894@empex.greenville.edu>
Message-ID: <Pine.LNX.4.44.0401061516500.31167-100000@hkn.eecs.berkeley.edu>



On Tue, 6 Jan 2004, Christian Wyglendowski wrote:

> > I find i am getting comfortable with GNU/Linux now, and it has
> > recently encouraged me to try my hand at programming; for those times
> > when you wished you had a little tool to do something :).  The
> > possibilty of helping the open source commnunity by contributing to
> > software development etc is also a plus, although a distant dream at
> > this point. ;)
>
> Good goals.  I have had the most fun with some of the little "tools"
> that I have written for mine and others' benefit.  I hope to contribute
> to the open source world someday as well.


Hi Christian,



Yup.  *grin*  Here's an example of a tool that I wrote for myself just
today.  It's called 'flip':


###
"""flip: A small utility to reverse the columns from lines in standard
input.

Todo: add delimiter option using optparse.
"""

import fileinput

for line in fileinput.input():
    words = line.split()
    words.reverse()
    print "\t".join(words)
###


So say that I'm at a Unix command line, and I want to calculate md5sums:

###
-bash-2.05b$ md5sum flip
c957c64326962b9d7fa477ac00340751  flip
###



With 'flip', I can now reverse the order of the columns so that the
filename comes first:

###
-bash-2.05b$ md5sum flip
c957c64326962b9d7fa477ac00340751  flip
-bash-2.05b$ md5sum flip | flip
flip    c957c64326962b9d7fa477ac00340751
###


Python is a great tool for augmenting the command line.



Talk to you later!


From alan.gauld at blueyonder.co.uk  Tue Jan  6 18:25:52 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Tue Jan  6 18:25:55 2004
Subject: [Tutor] help leraning python
References: <20040106012400.55393.qmail@web41811.mail.yahoo.com>
Message-ID: <016301c3d4ac$6cfb0740$6401a8c0@xp>

> Python. Personally, I prefer the latter because the
> former actually teaches Python, BASIC, and Tcl, 

And I'm currently rewriting it to teach Python, VBScript 
and Javascript.

The message is the same, programming is about concepts 
not languages...

:-)

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld

From beyondthezero at earthlink.net  Tue Jan  6 23:55:06 2004
From: beyondthezero at earthlink.net (Peter Jakubowicz)
Date: Tue Jan  6 23:55:27 2004
Subject: [Tutor] Python vs. C
Message-ID: <5.2.1.1.0.20040106204618.00b3a8b0@earthlink.net>

Hi,

I was talking with a friend who works as a programmer, and I mentioned that 
I was interested in learning C because it was faster than Python. And he 
asked me why it was faster; and I said because it's compiled and Python's 
interpreted; but he pressed me and I couldn't really say why C's being 
compiled makes it faster. And my friend left me to wonder about this: why 
is it faster? Intuitively, it makes sense to me that a language like 
assembly would be faster because I believe you can manipulate the chipset 
or whatever directly. Is that why C is faster, too? I am wondering about 
this because my Python programs are getting bigger, and occasionally I 
wonder if I want to learn C too. Plus, I've gotten to like programming 
enough that I learning another language would be fun. Or maybe I should 
just work on making my Python code more efficient or whatever? Anyway, if 
anyone knows the specific details of why C is faster or can point me to 
somewhere I can read about it I'd appreciate it. Thanks,

Peter


From marilyn at deliberate.com  Wed Jan  7 02:16:25 2004
From: marilyn at deliberate.com (Marilyn Davis)
Date: Wed Jan  7 02:16:31 2004
Subject: [Tutor] Python vs. C
In-Reply-To: <5.2.1.1.0.20040106204618.00b3a8b0@earthlink.net>
Message-ID: <Pine.LNX.4.44.0401062307390.4486-100000@Kuna>

On Tue, 6 Jan 2004, Peter Jakubowicz wrote:

> Hi,
> 
> I was talking with a friend who works as a programmer, and I mentioned that 
> I was interested in learning C because it was faster than Python. And he 
> asked me why it was faster; and I said because it's compiled and Python's 
> interpreted; but he pressed me and I couldn't really say why C's being 
> compiled makes it faster. And my friend left me to wonder about this: why 
> is it faster? Intuitively, it makes sense to me that a language like 

Hi,

Besides being completely compiled and so quick to run, C does not have
dynamic typing -- which means that the programmer has to decide whether
each variable will be an integer, or a floating point number, or whatever.

Python does this automatically but there is runtime overhead involved
in figuring that out for each variable and so it runs more slowly.

Also, Python handles dynamic memory allocation automatically.  In C,
when you want some memory, the programmer has to ask for it explicitly 
while Python figures it all out at runtime -- making it slower.

These are the reasons I'm aware of.  C is harder for the programmer, but
faster at runtime.  It is a rewarding language too, my other favorite.

> assembly would be faster because I believe you can manipulate the chipset 

Well!  I have heard that sometimes C is faster than assembler because
the language invites more efficiency in the coding.

That's all I know.

Yes, learn C!  It's interesting and powerful.

Marilyn Davis

> or whatever directly. Is that why C is faster, too? I am wondering about 
> this because my Python programs are getting bigger, and occasionally I 
> wonder if I want to learn C too. Plus, I've gotten to like programming 
> enough that I learning another language would be fun. Or maybe I should 
> just work on making my Python code more efficient or whatever? Anyway, if 
> anyone knows the specific details of why C is faster or can point me to 
> somewhere I can read about it I'd appreciate it. Thanks,
> 
> Peter
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 



From Janssen at rz.uni-frankfurt.de  Wed Jan  7 02:49:37 2004
From: Janssen at rz.uni-frankfurt.de (Michael Janssen)
Date: Wed Jan  7 02:49:52 2004
Subject: [Tutor] Python vs. C
In-Reply-To: <5.2.1.1.0.20040106204618.00b3a8b0@earthlink.net>
References: <5.2.1.1.0.20040106204618.00b3a8b0@earthlink.net>
Message-ID: <Pine.A41.4.56.0401070804500.364690@hermes-22.rz.uni-frankfurt.de>

On Tue, 6 Jan 2004, Peter Jakubowicz wrote:

> Hi,
>
> I was talking with a friend who works as a programmer, and I mentioned that
> I was interested in learning C because it was faster than Python. And he
> asked me why it was faster; and I said because it's compiled and Python's
> interpreted; but he pressed me and I couldn't really say why C's being
> compiled makes it faster. And my friend left me to wonder about this: why
> is it faster? Intuitively, it makes sense to me that a language like
> assembly would be faster because I believe you can manipulate the chipset
> or whatever directly. Is that why C is faster, too? I am wondering about
> this because my Python programs are getting bigger, and occasionally I
> wonder if I want to learn C too. Plus, I've gotten to like programming
> enough that I learning another language would be fun. Or maybe I should
> just work on making my Python code more efficient or whatever? Anyway, if
> anyone knows the specific details of why C is faster or can point me to
> somewhere I can read about it I'd appreciate it. Thanks,

Hello Peter,


to begin with: learning yet another language is allways (well, often) a
good idea: even if the other language isn't faster, it will have it's
own strengths and own way of solving problems, which will help your mind
to view the programming world of another angle wich in turn will help to
abstract from "typicall language idioms" and see the problem in first
place. As Danny pointed out recently: do not apply this to "intercall"
or April Fool's languages like that ;-)


On the python vs C speed topic I want to bring in discussion, that's the
python interpreter has a looong startoff time (Yes, it's really bad: my
python "hello world" runs *twice* as long than a shell version (See
below for details). 10 times slower than GNU hello. Some might claim
that 40 ms in total arn't that long at all. But when your webserver shal
deliver a "hello world" multithousands times per minute it aches).
Remember: this is solely a matter of interpreter *startoff* time. That
means, running through a long programm doesn't do consume twice the
time, too. Not at all.


Another advantage of C is, that it gives you fine grained control about
memory consumption and datastructures: C hasn't got such strong buildin
"list" or "dict" but lets you define anything as strong and both best
suited for your needs. The flipside is, that you should implement it
good to gain increased performance. I can imaging that you would have a
very hard time competing with python list's sort method. list.sort is
(like many performance relevant parts) coded in C and for all I have
heard it's some of the best C code you can think of.


This lends to strategies for real-world performance enhancement: One
important rule is to do it only when needed. This means, first write
your programm good or nice or functional (perhaps all of these ;-) and
*then* look out for perfomance bottlenecks. Bottlenecks can be dissolved
by another algorithem (and writing python is fun enough to implement
some of them to choose the best) or - turn it over to C ("faine grained
control"). The good thing is, that python lets you embed C for only the
perfomance related parts.


My personal plan is to start learning C after I experienced severe
performance problems with an important one of my scripts. Furthermore my
plan is to identify only the bottleneck and learn how to embed enough C
to put it down. Then.


Michael


hello timings
"""
[root@linus root]# echo 'print "hello world"' > hello.py
[root@linus root]# time python hello.py
hello world

real    0m0.042s
user    0m0.010s
sys     0m0.040s
[root@linus root]# echo 'echo "hello world"' > hello.sh
[root@linus root]# time sh hello.sh
hello world

real    0m0.018s
user    0m0.010s
sys     0m0.000s
[root@linus root]# apt-get install hello
[snip installation]

[root@linus root]# time hello
Hello, world!

real    0m0.004s
user    0m0.000s
sys     0m0.000s
[root@linus root]#
"""

From dyoo at hkn.eecs.berkeley.edu  Wed Jan  7 13:56:08 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Jan  7 13:56:12 2004
Subject: [Tutor] Python vs. C
In-Reply-To: <Pine.LNX.4.44.0401062307390.4486-100000@Kuna>
Message-ID: <Pine.LNX.4.44.0401071038590.25317-100000@hkn.eecs.berkeley.edu>



> And my friend left me to wonder about this: why is it faster?

Hi Marilyn,


Python is doing a lot more for you then meets the eye.  A program like
this:

###
l = [0 * 4]
for i in range(20):
    l[i] = i
###



is obviously buggy, but at least Python will give a good error message:

###
Traceback (most recent call last):
  File "<stdin>", line 2, in ?
IndexError: list assignment index out of range
###


That is, on every list assignment, Python is actively checking to see if
the index is in the range of our list.  If it isn't, it throws an
exception.  This sort of bug can be caught gracefully at least, and at no
point has Python lost control: it is voluntarily exiting, with the full
knowledge that an IndexError has occurred.



C provides no such guarantees, and the following C program:

/***/
int main() {
    int l[4];
    int i;
    for (i = 0; i < 20; i++) {
        l[i] = i;
    }
    return 0;
}
/***/


does no "range checking", and will break terribly with a very ugly error
message:


###
[dyoo@tesuque dyoo]$ ./a.out
Segmentation fault (core dumped)
###


That error message that you're seeing there is not coming from our program
either.  Rather, it's coming from the operating system itself --- the OS
sees that the program is doing something hideous with memory, and kills
the program in self defense.  *grin*


So compilation is sort of a red herring here: Python is slower because
it's simply doing more for you.  If a Python program were compiled into
machine code, it would still be slow because it's doing more work at
runtime.


Not that this extra work is always a bad thing!  Many of the computer
"security flaws"  that you have been hearing in the news lately is
entirely due to C's hands-off approach to memory and range checking.  If
many of the programs that are currently in use had been written in a more
modern language, those sort of attacks would have been obsolete a long
time ago.  C sacrifies safety for speed.


Talk to you later!


From littledanehren at yahoo.com  Wed Jan  7 14:23:18 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Wed Jan  7 14:23:21 2004
Subject: [Tutor] Python vs. C
In-Reply-To: <Pine.LNX.4.44.0401071038590.25317-100000@hkn.eecs.berkeley.edu>
Message-ID: <20040107192318.30096.qmail@web41802.mail.yahoo.com>

> So compilation is sort of a red herring here: Python
> is slower because
> it's simply doing more for you.  If a Python program
> were compiled into
> machine code, it would still be slow because it's
> doing more work at
> runtime.

How could that be true if extentions like Pysco and
Pyrex help speed?

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes
http://hotjobs.sweepstakes.yahoo.com/signingbonus

From credo2004 at fmail.co.uk  Wed Jan  7 14:32:44 2004
From: credo2004 at fmail.co.uk (credo)
Date: Wed Jan  7 14:32:52 2004
Subject: [Tutor] Newbie: First program - looking for feedback :)
In-Reply-To: <011501c3d3d8$94fbc330$6401a8c0@xp>
References: <20040105214745.989CD44D7B@server1.messagingengine.com>
	<011501c3d3d8$94fbc330$6401a8c0@xp>
Message-ID: <20040107193244.01E15450A0@server1.messagingengine.com>


On Mon, 5 Jan 2004 22:09:25 -0000, "Alan Gauld"
<alan.gauld@blueyonder.co.uk> said:
> > With this in mind, and with some embarrassment, i post my first
> *real*
> > python program.
> 
> For a first program its fine. You obviously understand how
> to write functions so you might want to consider breaking
> it up into several smaller functions - ONe to deal with
> the user input and get the list of files, another to process
> the files, and another to do the reporting of the results.
> 
> This separation of concerns helps to build reusable functions
> - for example the function that takes a filename, converts
> it and reports success could be used from a GUI version
> of the program. And a function which can ask the user to
> provide a list of filenames could be used in several other,
> similar tools.
> 
> Some specific comments:
> 
> >         for eachfile in mp3:
> >             name = os.path.splitext(eachfile)
> >             result = os.system('lame --decode %s %s%s'  %
> >             (eachfile,name[0],wavext))
> >             if (result == 0):
> >                 print
> >                 print 'Converted %s -> %s%s' %
> (eachfile,name[0],wavext)
> >                 print
> >             else:
> >                 result = 1
> 
> This last else isn't really needed because result will be set
> by the system() call each time through the loop.
> 
> >     else:
> >         print
> >         sys.exit()
> >
> >     # Had this problem myself, so added this as an afterthought.
> Need to
> >     clean
> >     # and add some proper error/exception handling.
> >     if (result == 1):
> 
> 
> And this then gets changed to
> 
>         if result != 0
> 
> Note you don't really need the parems round the test
> - unlike in C.
> 
> > I know, its not pretty and theres probably a 1001 ways
> > to make it more elegant and efficient
> 
> Probably, but it seems to work and for a first attempt it's OK.
> 
> Add the new features etc you mention and try "refactoring"
> it into smaller functions and it should make a nice project.
> 
> One last thought - you might like to use triple quotes instead
> of multiple print statements, but thats mostly a matter of
> personal taste.
> 
> Alan G
> Author of the Learn to Program web tutor
> http://www.freenetpages.co.uk/hp/alan.gauld
> 

Hi Alan,

Thankyou for taking the time to look over my first effort. I'm pleased
that i seemed to have made a reasonable job of it :)

> This separation of concerns helps to build reusable functions
> - for example the function that takes a filename, converts
> it and reports success could be used from a GUI version
> of the program. And a function which can ask the user to
> provide a list of filenames could be used in several other,
> similar tools.

Interesting that you make this point about functions as i have started to
exactly that :) A little more refinement and testing and i shall unleash
it upon this mailing list for some more feedback. 
I hope you might find the time to give me some comments on my progress as
it is very much appreciated.

> >             else:
> >                 result = 1
> 
> This last else isn't really needed because result will be set
> by the system() call each time through the loop.
> 

Duh!, i see what you mean :)

> Note you don't really need the parems round the test
> - unlike in C.

I was aware of this and included them only for readabilty sake,
(suggested by a book or tutorial i read), however i personally dont find
that it hinders my comprehension of the code so i will try not to use
them in the future. 

> One last thought - you might like to use triple quotes instead
> of multiple print statements, but thats mostly a matter of
> personal taste.

Yep, i read about triple quotes and will use them when writing a
significant amount of text to the screen, however i find this situation:

def message():
    print ''' 
Hello to all members of the python tutor mailing list
new and old and thanx for helping a newbie pythoneer like me 
find some help, as coding is not natural to me :)
'''
.. where the text needs to be left most aligned, (despite the code
indentation), to be somewhat ugly. Especially when the text is embedded
within a nested 'if' statement etc.. 
I prefer to avoid triple quotes when dealing with just 1 or 2 lines to
preserve the indentation, otherwise i will use the triple quotes as
suggested.

I am trying to drop the habit of empty 'print' statements to achieve a
newline when i could easily embed a '\n' inside a print statement to
achieve the same. Again, its a tool i use to aid my readability of the
code. :)

Thanx again for your comments Alan and ive bookmarked your website for
further reading ;)

Best Regards

Credo

-- 
http://www.fastmail.fm - And now for something completely different


From gerrit at nl.linux.org  Wed Jan  7 14:32:40 2004
From: gerrit at nl.linux.org (Gerrit Holl)
Date: Wed Jan  7 14:33:44 2004
Subject: [Tutor] Python vs. C
In-Reply-To: <Pine.A41.4.56.0401070804500.364690@hermes-22.rz.uni-frankfurt.de>
References: <5.2.1.1.0.20040106204618.00b3a8b0@earthlink.net>
	<Pine.A41.4.56.0401070804500.364690@hermes-22.rz.uni-frankfurt.de>
Message-ID: <20040107193240.GA2344@nl.linux.org>

Michael Janssen wrote:
> Another advantage of C is, that it gives you fine grained control about
> memory consumption and datastructures: C hasn't got such strong buildin
> "list" or "dict" but lets you define anything as strong and both best
> suited for your needs. The flipside is, that you should implement it
> good to gain increased performance. I can imaging that you would have a
> very hard time competing with python list's sort method. list.sort is
> (like many performance relevant parts) coded in C and for all I have
> heard it's some of the best C code you can think of.

But there are a lot of C libraries. Aren't there so many C libraries
that one can essentially program higher-level by using a lot of
libraries? Or am I overlooking something?

Me, I know only Python as well, and the only language on my
'want-to-learn'-list is Ruby, so that's not a giant leap at all
(university will teach me Java next year).

> The good thing is, that python lets you embed C for only the
> perfomance related parts.

The bad thing is, that learning C only to be able te embed C in a Python
program seems a bit odd. There isn't a C-for-Python-programmers
tutorial, or is there?

> [root@linus root]# time hello
> Hello, world!
> 
> real    0m0.004s
> user    0m0.000s
> sys     0m0.000s

$ time echo hello
hello

real    0m0.000s
user    0m0.000s
sys     0m0.000s
$ timeit.py 'print "hello"'
(skip output)
1000 loops, best of 3: 196 usec per loop

heh heh :)

yours,
Gerrit.

-- 
135. If a man be taken prisoner in war and there be no sustenance in
his house and his wife go to another house and bear children; and if later
her husband return and come to his home: then this wife shall return to
her husband, but the children follow their father.
          -- 1780 BC, Hammurabi, Code of Law
-- 
PrePEP: Builtin path type
    http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html
Asperger's Syndrome - a personal approach:
	http://people.nl.linux.org/~gerrit/english/

From isrgish at fusemail.com  Wed Jan  7 14:51:36 2004
From: isrgish at fusemail.com (Isr Gish)
Date: Wed Jan  7 14:51:53 2004
Subject: [Tutor] Newbie: Help on comparing files
Message-ID: <E1AeJiR-0002sD-9R@fuse1.fusemail.net>

I looking to write a function to compare 2 files.  
What I want is it should take from first file a certain amount of text. (For example till it reaches 2 end of line marks).  Then it should search the "WHOLE" second file if its there.  If not found in second file, write to new file this text. If found then continue with taking next amount of text from first file.  After the file is finished, any text that's in second file that was not in first file. Should be written to a new file.

IOW, I want to know what's in first file and not in second file. And what's in second that's not in first.

I guess my main question is should I first use Regular Expression to split the files first. Or should I use string methods.

Put any ideas would be appreciated.

Thanks in advance.

---------------
Isr Gish


From credo2004 at fmail.co.uk  Wed Jan  7 14:52:44 2004
From: credo2004 at fmail.co.uk (credo)
Date: Wed Jan  7 14:52:51 2004
Subject: [Tutor] Newbie: First program - looking for feedback :)
In-Reply-To: <CE1475C007B563499EDBF8CDA30AB45B0A3894@empex.greenville.edu>
References: <CE1475C007B563499EDBF8CDA30AB45B0A3894@empex.greenville.edu>
Message-ID: <20040107195244.214223FE52@server1.messagingengine.com>


On Tue, 6 Jan 2004 16:38:44 -0600, "Christian Wyglendowski"
<Christian.Wyglendowski@greenville.edu> said:
> > -----Original Message-----
> > Hi Pythoneers,
> > 
> > Okay, ive been trying to teach myself python for a few weeks 
> > and i'm making some slow progress, (not a natural coder 
> > here). This started mainly due to me switching from Windows 
> > -> GNU/Linux about a year ago. 
> 
> Cool.  Python is the first general purpose programming language that I
> have learned as well.  I played with PHP on my web site and then moved
> on to Python.  What a breath of fresh air that was!

Hehe, i looked at PHP and dabbled with C/C++ before settling on Python as
it seemed to be easier to grasp and also powerful in many areas :)

> > I find i am getting comfortable with GNU/Linux now, and it 
> > has recently encouraged 
> > me to try my hand at programming; for those times when you 
> > wished you had a 
> > little tool to do something :). 
> > The possibilty of helping the open source commnunity by 
> > contributing to software 
> > development etc is also a plus, although a distant dream at 
> > this point.
> > ;) 
> 
> Good goals.  I have had the most fun with some of the little "tools"
> that I have written for mine and others' benefit.  I hope to contribute
> to the open source world someday as well.

I'm starting to find some reward in simple little tools, now that i seem
to be making some progress with the language. It seems a natural thing
for me to hopefully contribute something back to the open source
community and it pleases me to find others with the same intentions.
Perhaps we end up working on something together ;) - I have some way to
go still :p
 
> > My primary goal is to have some fun with this. I believe 
> > selecting Python as my first language was the right choice :)
> > 
> > With this in mind, and with some embarrassment, i post my 
> > first *real* python program. 
> 
> Well, I don't have any specific stuff to say about your code (Alan had
> some good thoughts that I don't need to rehash).  I would, however,
> suggest that you revamp the program as a command line utility.  You
> could really trim down the size of your program and it would be more
> flexible (you could pass onlyone.mp3 or *.mp3 in a directory).
> 
> There's my thoughts.
> 
> Christian
> http://www.dowski.com
>

Well, i have the command line at heart. I use Slackware and have fallen
in love with the Terminal after using primarily GUI in Mandrake 9.1
previously.
I did find the lack of the *.mp3 funcionality in the lame encoder to
decode/encode a batch of files surprising, although i may have missed
something in the man page.

Still it was a good excuse to try solving the problem myself and i am
really just flexing my understanding of the language at this point adding
functions etc to do cool stuff that is not really required save to use
different libraries to solve probs etc.

I have a larger project in mind that will benefit from my tinkering, but
thats in the future :)
Thanx for your comments and good luck with your own goals ;)

cheers

Credo

-- 
http://www.fastmail.fm - The way an email service should be

From gerrit at nl.linux.org  Wed Jan  7 15:02:27 2004
From: gerrit at nl.linux.org (Gerrit Holl)
Date: Wed Jan  7 15:03:22 2004
Subject: [Tutor] Newbie: Help on comparing files
In-Reply-To: <E1AeJiR-0002sD-9R@fuse1.fusemail.net>
References: <E1AeJiR-0002sD-9R@fuse1.fusemail.net>
Message-ID: <20040107200227.GA2576@nl.linux.org>

Isr Gish wrote:
> I looking to write a function to compare 2 files.  

You are looking for difflib:
http://www.python.org/doc/current/lib/module-difflib.html

Examples:
http://www.python.org/doc/current/lib/differ-examples.html

yours,
Gerrit.

-- 
132. If the "finger is pointed" at a man's wife about another man, but
she is not caught sleeping with the other man, she shall jump into the
river for her husband.
          -- 1780 BC, Hammurabi, Code of Law
-- 
PrePEP: Builtin path type
    http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html
Asperger's Syndrome - a personal approach:
	http://people.nl.linux.org/~gerrit/english/

From dyoo at hkn.eecs.berkeley.edu  Wed Jan  7 16:50:17 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Jan  7 16:50:33 2004
Subject: [Tutor] Python vs. C
In-Reply-To: <20040107192318.30096.qmail@web41802.mail.yahoo.com>
Message-ID: <Pine.LNX.4.44.0401071243410.25317-100000@hkn.eecs.berkeley.edu>



On Wed, 7 Jan 2004, Daniel Ehrenberg wrote:

> > So compilation is sort of a red herring here: Python is slower because
> > it's simply doing more for you.  If a Python program were compiled
> > into machine code, it would still be slow because it's doing more work
> > at runtime.
>
> How could that be true if extentions like Psyco and Pyrex help speed?



Hi Daniel,


For reference:


Pyrex is a language extension that allows the mixing of C and Python:

    http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/

Psyco is an extension that can optimize certain functions:

    http://psyco.sourceforge.net/



I have to admit that I'm not comfortably familiar with with either.  But
at least I can try talking about them!  *grin* And if I say something
wrong, at least I can be corrected and learn from my mistakes.


Pyrex does allow us to embed C stuff into Python, but at the expense of
safety.  That is, as soon as we start using Pyrex, all bets are off.
Here's a concrete example:

###
[dyoo@tesuque dyoo]$ cat test_pyrex.pyx
def test_pyrex():
    cdef int numbers[4]
    cdef int i
    i = 0
    while i < 20:
        numbers[i] = i
        i = i + 1
    i = 0
    while i < 20:
        print i
        i = i + 1
###


Again, as soon as we start using native C, we abandon strict
bounds-checks, and introduce the potential for mischief:

###
[dyoo@tesuque dyoo]$ python
Python 2.2.1 (#1, Sep  3 2002, 14:52:01)
[GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-112)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import test_pyrex
>>> test_pyrex.test_pyrex()
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Segmentation fault (core dumped)
###

So Pyrex does allow for increased speed, but that's mostly because it just
allows us to abandon the runtime checks that Python usually does.  People
who use Pyrex understand the sacrifice, and must simply be very very
careful when they write Pyrex code.



>From what I understand, Psyco optimizes away certain features of Python if
it can prove to itself that bad things aren't possible.  For example, if
it sees code like this:

###
for i in range(20):
    print i
###


Psyco can look at this code fragment, and assert to itself that 'i' here
can never be anything except an integer --- not only that, but that it's
going to always be an integer that won't overflow.  So rather than use a
full-fledged Python object, Psyco can instead transform this code so that
it uses native machine integers, something similar to:

/***/
int i;
for(i = 0; i < 20; i++) { ... }
/***/



But it does all this analysis at runtime, when it has enough information
to prove to itself that certain situations are true.  Here's another code
snippet that would confound this kind of optimization:

###
i = 2147483647
while 1:
    print i
    i += 1
###

Psyco better not try to optimize this by using standard hardware integers,
because we really do need full fledged Python integers to get correct
output.  Otherwise, when 'i' hits 2**31, it'll overflow and give radically
different results from the unoptimized Python code.


These sort of things are part of code analysis, and most compilers perform
code analysis statically, before the program is even run once.  Psyco, on
the other hand, does analysis at runtime, with the same end result of
getting the code to run faster.


But Python's features are still so rich that certain kinds of
optimizations are probably going to be difficult to implement.  One
particular place that's difficult is name resolution.  If we have a
function like:

###
def printSomething():
    print str(42)
###

It might seem obvious that this can be reduced to something like the C
code:

/***/
void printSomething() {
    printf("%d\n", 42);
}
/***/


Unfortunately, this optimization, too, isn't always correct.  There are
two things, in particular, that complicate matters.  What if sys.stdout is
reassigned, or what if str() has been redefined?  For it is perfectly
legal in Python to do things like:

###
sys.stdout = StringIO.StringIO()
str = 'Hello world, this is my string'
###


And because these things are allowed in Python, there's very little that
can be statically optimized out of printSomething().  Every time that
printSomething() is called Python has to make a runtime check to see what
'str' means.

What Psyco and other runtime analyzers can probably do, though, is make
two versions of printSomething(): one to handle the common case (if
sys.stdout and str are unmolested), and another to handle the general
case.  But our computer will still need to be some work to toggle between
the two cases.


Both Pyrex and Psyco allow us to improve the performance of our code, but
it doesn't invalidate the claim that Python's rich feature set forces the
system to do more work to support those dynamic features.


Hope this helps!


From alan.gauld at blueyonder.co.uk  Wed Jan  7 17:10:49 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Wed Jan  7 17:10:37 2004
Subject: [Tutor] Python vs. C
References: <5.2.1.1.0.20040106204618.00b3a8b0@earthlink.net>
	<Pine.A41.4.56.0401070804500.364690@hermes-22.rz.uni-frankfurt.de>
Message-ID: <01a601c3d56b$1beab750$6401a8c0@xp>

> > I was interested in learning C because it was faster than Python.
And he
> > asked me why it was faster; and I said because it's compiled and
Python's
> > interpreted; but he pressed me ....

Thats a very good friend to have! :-)

> > wonder if I want to learn C too. Plus, I've gotten to like
programming
> > enough that I learning another language would be fun.

Thats a good enough reason to learn a new language.

> > just work on making my Python code more efficient or whatever?

Thats the best first step. Understanding how to identify
the bottleneckks and how to remove them in Python will
almost always be more useful than reprogramming a very
inefficient design in C.

> anyone knows the specific details of why C is faster

First thing to realize is that C is not always faster!
Someone already pointed out that sorting a list in C will
usually require you to write your own sort code, and Pythons
sort routine is almost certainly faster than anything you
will come up with as a beginner. And its in C...

Similarly using regiular expressions can be very difficult
and slow in C since it depemds on the library you use and
many standard C regex libraries are less efficient than the
Python re module.

So it depends on what you are doing whether C will even be
any faster.

> On the python vs C speed topic I want to bring in discussion, that's
the
> python interpreter has a looong startoff time


Actually it doesn't, but the initial compilation of the
python code can take a while. Compare my figures for your
Hello World tests:

> [root@linus root]# echo 'print "hello world"' > hello.py
> [root@linus root]# time python hello.py
> hello world
>
> real    0m0.042s
> user    0m0.010s
> sys     0m0.040s


$ time python hello.py
hello world

real    0m0.696s
user    0m0.040s
sys     0m0.140s



$ time python -c 'print "hello world"'
hello world

real    0m0.144s
user    0m0.060s
sys     0m0.090s



$ time bash hello.sh
hello world

real    0m0.079s
user    0m0.030s
sys     0m0.040s


$ time hello
Hello world

real    0m0.027s
user    0m0.020s
sys     0m0.030s

Notice the second one which evaluates the command from the
command line is much faster. It seems that its the loading
of the file and subsequent compilation that takes the bulk
of the time.(No doubt a guru can explain the discrepancy
better). And of course sh is still faster...

And notice that the pure C version at the end is not
significantly different to the sh version... and that
real time is less than sys time!! :-)

The lesson of all this is that performance is a complex
topic dependant on very many factors. If a program has
networking or database elements in it then they are likely
to dominate performance more than the code. In fact in my
work I can't remember having to tune code to fix
performance problems at any time in the last 5 years, its
always been fixed by tweaking the network or the database.

But to return to the original point, learning new languages
is a good thing because it will teach you more about
programming in general. And that will make you a better
programmer in any language.


Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld



From dyoo at hkn.eecs.berkeley.edu  Wed Jan  7 17:17:03 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Jan  7 17:17:11 2004
Subject: [Tutor] Newbie: Help on comparing files
In-Reply-To: <E1AeJiR-0002sD-9R@fuse1.fusemail.net>
Message-ID: <Pine.LNX.4.44.0401071403120.25317-100000@hkn.eecs.berkeley.edu>



On Wed, 7 Jan 2004, Isr Gish wrote:

> I looking to write a function to compare 2 files.
>
> What I want is it should take from first file a certain amount of text.
> (For example till it reaches 2 end of line marks).  Then it should
> search the "WHOLE" second file if it's there.  If not found in second
> file, write to new file this text. If found then continue with taking
> next amount of text from first file.  After the file is finished, any
> text that's in second file that was not in first file. Should be written
> to a new file.


Hi Isr,


This sounds very much like a homework problem, Any help we can give on
this will be very vague by necessity.



Do you have some example test cases to see how such a thing might work?
What happens if your first file has something like:

###
a..b..c
###

and your second file has something like:

###
b..c..d
###

if we assume that '.' is the end of line mark.  What should your output
be?





Also, what happens if you have something like:

###
alphabet soup..
###

as the first file and

###
this is a bowl of alphabet soup..
###

as the second?  (Again, assuming that '.' is the end of line mark.)




Good luck to you.


From alan.gauld at blueyonder.co.uk  Wed Jan  7 17:18:47 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Wed Jan  7 17:18:35 2004
Subject: [Tutor] Python vs. C
References: <5.2.1.1.0.20040106204618.00b3a8b0@earthlink.net><Pine.A41.4.56.0401070804500.364690@hermes-22.rz.uni-frankfurt.de>
	<20040107193240.GA2344@nl.linux.org>
Message-ID: <01b901c3d56c$38f04300$6401a8c0@xp>

> But there are a lot of C libraries. Aren't there so many C libraries
> that one can essentially program higher-level by using a lot of
> libraries? Or am I overlooking something?

Yes but using in libraries in C is a lot less friendly
than doing a Python import. and because C has no real
namespace support (unlike C++) you often can't use two
libraries together because of name conflicts. And you
can spend a lot of time converting one data struvcture
to another if the libraries are not consistent - which
kills performance of course!

> Me, I know only Python as well, and the only language on my
> 'want-to-learn'-list is Ruby, so that's not a giant leap at all
> (university will teach me Java next year).

You'd be far better off learning Lisp or scheme IMHO. Ruby
is so close to Python that you are not likely to gain much
extra insight. Lisp OTOH will take you into myriad new
possibilities...

> > The good thing is, that python lets you embed C for only the
> > perfomance related parts.
>
> The bad thing is, that learning C only to be able te embed C in a
Python
> program seems a bit odd. There isn't a C-for-Python-programmers
> tutorial, or is there?

Nowadays that wouldn't be a bad idea at all. The huge
effort required to write even a moderate program in C
(compared to Python) means that only using C where there is a valid
reason would be pefectly sane.

When I started programming people were just about giving up
on assembler as a main language. My entire experience with
assembler programming is to implement routines that weren't
fast enough in Pascal or C (recognise a pattern here? :-).
And thats more than enough assembler to teach me all I want
to know about it. C is high level assembler for the 21st Century...

Alan G.


From piir at earthlink.net  Wed Jan  7 17:21:31 2004
From: piir at earthlink.net (Todd G. Gardner)
Date: Wed Jan  7 17:21:36 2004
Subject: [Tutor] How to eliminate the background command window?
Message-ID: <CAENJDPIMKAJINIKKHOCEEEJCCAA.piir@earthlink.net>

Hello,

I would like to know what I am not doing here.  Every progran I write in
Python on WXP shows a background command window unless I build a .exe using
py2exe with the -w option.

How can I get rid of the back ground command window?

Thanks,

Todd


From tim at johnsons-web.com  Wed Jan  7 17:44:23 2004
From: tim at johnsons-web.com (Tim Johnson)
Date: Wed Jan  7 17:42:14 2004
Subject: [Tutor] Python vs. C
In-Reply-To: <Pine.LNX.4.44.0401071038590.25317-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0401062307390.4486-100000@Kuna>
	<Pine.LNX.4.44.0401071038590.25317-100000@hkn.eecs.berkeley.edu>
Message-ID: <20040107224423.GG1452@johnsons-web.com>

> 
> C provides no such guarantees, and the following C program:
> 
> /***/
> int main() {
>     int l[4];
>     int i;
>     for (i = 0; i < 20; i++) {
>         l[i] = i;
>     }
>     return 0;
> }
> /***/
> 
> 
> does no "range checking", and will break terribly with a very ugly error
> message:
> 
> 
> ###
> [dyoo@tesuque dyoo]$ ./a.out
> Segmentation fault (core dumped)
> ###
> 
> 
> That error message that you're seeing there is not coming from our program
> either.  Rather, it's coming from the operating system itself --- the OS
> sees that the program is doing something hideous with memory, and kills
> the program in self defense.  *grin*
 I'm probably rephrasing what Danny and Alan have said, but with a
 different perspective:

 Python and most other "scripting"(interpreted) programming languages
 like perl, and rebol are written in C, to the best of my
 knowledge.

 As a long-time C programmer, I think of those people who develop
 scripting languages (Wall, Sassenrath, von Rossum et al) as some of
 the best C programmers in the world. 

 Knowing a bit about C can help one to understand what 'python' or
 any other C-based scripting language is doing. It is also helpful
 to know if the resource that you are using is being
 'imported'(originates in python code) or is 'native' (C code compiled
 into the binary).

 In terms of speed, it is arguable that C is faster - but good python
 could out-perform bad C code. Suppose one were using a badly
 implemented binary tree in C as opposed to python's well-designed
 dictionary? Whats more, there are times in which 'speed' isn't as
 important as maintainability and sheer coding time. 

 Here's two examples: 
 1)At one time, I used to do a lot of desktop programming, using
 text-cell or pixel-based graphics and direct video-memory access.
 Using C with assembler modules handling the video access and string
 handling bottlenecks far out-performed python terms of
 the user's viewpoint.

 2)But now, I do a lot of web programming. For me to update some code
 running on a remote unix or windows server from my linux server, using
 C, I would have to transfer all code changes to the server, and compile
 it there. (Given that I had the permissions). Whereas in a scripting
 language, I should just have to transfer my code changes and let the
 interpreter take care of it.

 And: where bandwidth is a large factor, speed tends to get
 obfuscated by the bandwidth......
-- 
Tim Johnson <tim@johnsons-web.com>
      http://www.alaska-internet-solutions.com

From david at graniteweb.com  Wed Jan  7 17:35:58 2004
From: david at graniteweb.com (David Rock)
Date: Wed Jan  7 17:43:07 2004
Subject: [Tutor] How to eliminate the background command window?
In-Reply-To: <CAENJDPIMKAJINIKKHOCEEEJCCAA.piir@earthlink.net>
References: <CAENJDPIMKAJINIKKHOCEEEJCCAA.piir@earthlink.net>
Message-ID: <20040107223558.GA3327@wdfs.graniteweb.com>

* Todd G. Gardner <piir@earthlink.net> [2004-01-07 17:21]:
> Hello,
> 
> I would like to know what I am not doing here.  Every progran I write in
> Python on WXP shows a background command window unless I build a .exe using
> py2exe with the -w option.
> 
> How can I get rid of the back ground command window?

I believe you can accomplish this by naming your pythin script with a
.pyw extention to tell the system it is a "Windows Python" script rather
than a "DOS Python" script.

-- 
David Rock
david@graniteweb.com
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20040107/1495219d/attachment.bin
From littledanehren at yahoo.com  Wed Jan  7 17:59:05 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Wed Jan  7 17:59:10 2004
Subject: [Tutor] Python vs. C
In-Reply-To: <5.2.1.1.0.20040106204618.00b3a8b0@earthlink.net>
Message-ID: <20040107225905.81483.qmail@web41811.mail.yahoo.com>

> Hi,
> 
> I was talking with a friend who works as a
> programmer, and I mentioned that 
> I was interested in learning C because it was faster
> than Python. And he 
> asked me why it was faster; and I said because it's
> compiled and Python's 
> interpreted; but he pressed me and I couldn't really
> say why C's being 
> compiled makes it faster. And my friend left me to
> wonder about this: why 
> is it faster? Intuitively, it makes sense to me that
> a language like 
> assembly would be faster because I believe you can
> manipulate the chipset 
> or whatever directly. Is that why C is faster, too?

Yes. In general, lower-level languages are faster.
Although programs like Psyco are trying to break that
(and have already suceeded in making python as fast as
C for simple arithmetic calculations), I don't think
it'll happen anytime soon. However, you can usually
find extentions for Python written in C that increase
the speed of your program without having to resort to
rewriting your program, such as Numeric, a high-speed
list processing library. These programs are very
heavily optimized so they can rival or beat naive
implimentations for involving list processing made by
beginner programmers in C, not to mention that you
don't have to reimpliment everything. If you're not
doing calculation-intensive tasks like manipulating
large lists, you generally can get off writing things
in Python.

> I am wondering about 
> this because my Python programs are getting bigger,
> and occasionally I 
> wonder if I want to learn C too. Plus, I've gotten
> to like programming 
> enough that I learning another language would be
> fun. Or maybe I should 
> just work on making my Python code more efficient or
> whatever? Anyway, if 
> anyone knows the specific details of why C is faster
> or can point me to 
> somewhere I can read about it I'd appreciate it.
> Thanks,
> 
> Peter

There are many large Python programs and most of them
don't have to resort to writing things in C, unless
it's something where speed really matters (like Zope).
Unless you're writing a large database and webserver,
you probably don't need C.

Daniel Ehrenberg 

__________________________________
Do you Yahoo!?
Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes
http://hotjobs.sweepstakes.yahoo.com/signingbonus

From clickron at webtv.net  Wed Jan  7 18:41:15 2004
From: clickron at webtv.net (Ron A)
Date: Wed Jan  7 18:41:20 2004
Subject: [Tutor] for loop
Message-ID: <20515-3FFC991B-2807@storefull-3197.bay.webtv.net>

I'm experimenting and would like 'yes' to be printed only if 5 is not in
the list, but I want to look in each list. This prints out two yeses.
How do I get it to print just one 'yes'?

x = [[1,2,3],[2,4,6],[8,4,5,6],[9,8,7]]

for num in x:
    if 5 in num:
        break
    else:
        print 'yes'    


From pythontutor at venix.com  Wed Jan  7 19:02:26 2004
From: pythontutor at venix.com (Lloyd Kvam)
Date: Wed Jan  7 19:02:28 2004
Subject: [Tutor] for loop
In-Reply-To: <20515-3FFC991B-2807@storefull-3197.bay.webtv.net>
References: <20515-3FFC991B-2807@storefull-3197.bay.webtv.net>
Message-ID: <3FFC9E12.3020108@venix.com>

Ron A wrote:

> I'm experimenting and would like 'yes' to be printed only if 5 is not in
> the list, but I want to look in each list. This prints out two yeses.
> How do I get it to print just one 'yes'?
> 
> x = [[1,2,3],[2,4,6],[8,4,5,6],[9,8,7]]
> 
> for num in x:
>     if 5 in num:
>         break
>     else:
>         print 'yes'    
> 
This code prints yes until it finds a num list that contains 5.

To stop printing yes after the first time, simply break after printing
yes.  However, this is equivalent to simply checking the first element
of x.  You no longer need the loop.  So now the equivalent code is:

if 5 not in x[0]:
	print "yes"

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582


From godoy at ieee.org  Wed Jan  7 04:48:12 2004
From: godoy at ieee.org (Jorge Godoy)
Date: Wed Jan  7 19:05:10 2004
Subject: [Tutor] Python vs. C
In-Reply-To: <Pine.A41.4.56.0401070804500.364690@hermes-22.rz.uni-frankfurt.de>
References: <5.2.1.1.0.20040106204618.00b3a8b0@earthlink.net>
	<Pine.A41.4.56.0401070804500.364690@hermes-22.rz.uni-frankfurt.de>
Message-ID: <200401070748.30910.godoy@ieee.org>

On Wednesday 07 January 2004 05:49, Michael Janssen (Michael Janssen 
<Janssen@rz.uni-frankfurt.de>) wrote:

> On the python vs C speed topic I want to bring in discussion,
> that's the python interpreter has a looong startoff time (Yes, it's
> really bad: my python "hello world" runs *twice* as long than a
> shell version (See below for details). 10 times slower than GNU
> hello. Some might claim that 40 ms in total arn't that long at all.
> But when your webserver shal deliver a "hello world" multithousands
> times per minute it aches). Remember: this is solely a matter of
> interpreter *startoff* time. That means, running through a long
> programm doesn't do consume twice the time, too. Not at all.

When running in a webserver one would like to benefit from other 
things such as mod_python, Zope, etc. The same happens for Perl (and 
you know it's widely used on web) where mod_perl keeps a running 
interpreter so that it eliminates the startup overhead (actually it 
does more things, but this is the point you brought up). 

There's also Medusa, for servers in general and not specifically 
webservers (although you can use it to write one...). 


Be seeing you,
-- 
Godoy.     <godoy@ieee.org>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: signature
Url : http://mail.python.org/pipermail/tutor/attachments/20040107/cb0311fe/attachment-0001.bin
From gcampanelli at ciudad.com.ar  Wed Jan  7 18:49:52 2004
From: gcampanelli at ciudad.com.ar (Gustavo Campanelli)
Date: Wed Jan  7 19:05:16 2004
Subject: [Tutor] for loop
In-Reply-To: <20515-3FFC991B-2807@storefull-3197.bay.webtv.net>
References: <20515-3FFC991B-2807@storefull-3197.bay.webtv.net>
Message-ID: <3FFC9B20.1060107@ciudad.com.ar>

Ron A wrote:

>I'm experimenting and would like 'yes' to be printed only if 5 is not in
>the list, but I want to look in each list. This prints out two yeses.
>How do I get it to print just one 'yes'?
>
>x = [[1,2,3],[2,4,6],[8,4,5,6],[9,8,7]]
>
>for num in x:
>    if 5 in num:
>        break
>    else:
>        print 'yes'    
>
>  
>
This code goes to the first list, checks if 5 is there, and as it's not, 
prints a yes (when there is no 5 there), then enters the second, sees 
it's not there and prints another yes, goes to the third and as 5 is in 
there breaks and doesn't do anything more. The code does, in other 
words, exactly what you told it to do, but not what you intended. This 
should do the trick, you had the if evaluating things the oposite way as 
you intended :)

x = [[1,2,3],[2,4,6],[8,4,5,6],[9,8,7]]
for num in x:
    if 5 in num:
        print 'yes'
        break

Gedece, still a python newbie

From hec.villafuerte at telgua.com.gt  Wed Jan  7 21:29:06 2004
From: hec.villafuerte at telgua.com.gt (=?ISO-8859-1?Q?=22H=E9ctor_Villafuerte_D=2E=22?=)
Date: Wed Jan  7 19:27:19 2004
Subject: [Tutor] Converting to PDF
Message-ID: <3FFCC072.5010406@telgua.com.gt>

Hi all,
I'm trying to generate PDFs with this little script:

-----SCRIPT-------------------------
import fileinput, os, Image

def get_calls(dir, file):
    im = Image.open(dir + file)
    im.save(dir + '_' + file, 'PDF')

if __name__ == '__main__':
    dir = 'c:\\tmp\\scan\\'
    for x in os.listdir(dir):
        if x.split('.')[1] == 'jpg':
            print x
            get_calls(dir, x)
-----------------------------------

But get this error:
-----ERROR-------------------------
Traceback (most recent call last):
  File "e:\src\python\convert_jpeg.py", line 22, in ?
    get_calls(dir, x)
  File "e:\src\python\convert_jpeg.py", line 6, in get_calls
    im.save(dir + '_' + file, 'PDF')
  File "C:\Python23\Lib\site-packages\PIL\Image.py", line 1145, in save
    SAVE[string.upper(format)](self, fp, filename)
  File "C:\Python23\Lib\site-packages\PIL\PdfImagePlugin.py", line 120, 
in _save
    raise ValueError, "unsupported PDF filter"
ValueError: unsupported PDF filter
-----------------------------------

Any ideas or suggestions of how to generate PDF from JPEG?
Thanks in advance.
Hector


From dyoo at hkn.eecs.berkeley.edu  Wed Jan  7 20:40:00 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Jan  7 20:40:09 2004
Subject: [Tutor] Converting to PDF
In-Reply-To: <3FFCC072.5010406@telgua.com.gt>
Message-ID: <Pine.LNX.4.44.0401071720340.15436-100000@hkn.eecs.berkeley.edu>



On Wed, 7 Jan 2004, [ISO-8859-1] "H=E9ctor Villafuerte D." wrote:

> Hi all,
> I'm trying to generate PDFs with this little script:
>
> -----SCRIPT-------------------------
> import fileinput, os, Image
>
> def get_calls(dir, file):
>     im =3D Image.open(dir + file)
>     im.save(dir + '_' + file, 'PDF')
>
> if __name__ =3D=3D '__main__':
>     dir =3D 'c:\\tmp\\scan\\'
>     for x in os.listdir(dir):
>         if x.split('.')[1] =3D=3D 'jpg':
>             print x
>             get_calls(dir, x)


Hi Hector,


I looked into the PdfImagePlugin.py source from version 1.1.4 of the
Python Imaging Library,

    http://www.pythonware.com/products/pil/


And you appear to have run into a bug in PIL!  The code in question in
PIL/PdfImagePlugin.py is:

###
    if filter =3D=3D "/ASCIIHexDecode":
        ImageFile._save(im, op, [("hex", (0,0)+im.size, 0, None)])
    elif filter =3D=3D "/DCTDecode":
        ImageFile._save(im, op, [("jpeg", (0,0)+im.size, 0, im.mode)])
    elif filter =3D=3D "/FlateDecode":
        ImageFile._save(im, op, [("zip", (0,0)+im.size, 0, im.mode)])
    elif filter =3D=3D "/RunLengthDecode":
        ImageFile._save(im, op, [("packbits", (0,0)+im.size, 0, im.mode)])
    else:
        raise ValueError, "unsupported PDF filter"
###


That block is within the _safe() function in PdfImagePlugin.py.  But
there's only one block of code that assigns to this 'filter' variable:

###
    if im.mode =3D=3D "1":
        filter =3D "/ASCIIHexDecode"
        config =3D "/DeviceGray", "/ImageB", 1
    elif im.mode =3D=3D "L":
        filter =3D "/DctDecode"
        # params =3D "<< /Predictor 15 /Columns %d >>" % (width-2)
        config =3D "/DeviceGray", "/ImageB", 8
    elif im.mode =3D=3D "P":
        filter =3D "/ASCIIHexDecode"
        config =3D "/Indexed", "/ImageI", 8
    elif im.mode =3D=3D "RGB":
        filter =3D "/DCTDecode"
        config =3D "/DeviceRGB", "/ImageC", 8
    elif im.mode =3D=3D "CMYK":
        filter =3D "/DCTDecode"
        config =3D "/DeviceRGB", "/ImageC", 8
    else:
        raise ValueError, "illegal mode"
###


'filter' here has three possible values:

    ['/ASCIIHexDecode',
     '/DctDecode',
     '/DCTDecode']


Notice the case difference here between '/DctDecode' and '/DCTDecode'.
Python is case sensitive.  This is a bad sign.  *grin*


The block that we're running into problems with, the one that throws the
exception, checks for:

    ["/ASCIIHexDecode",
     "/DCTDecode",
     "/FlateDecode",
     "/RunLengthDecode"]


It doesn't handle "/DctDecode"!  Furthermore, there's no way 'filter' can
be '/RunLengthDecode', so there's some dead code here too.

There's definitely a bug here.  Send a holler out to the Python Imaging
Library folks.  *grin*

    http://mail.python.org/mailman/listinfo/image-sig

and get them to fix it so no one else runs into this.



In the meantime, my best guess right now to fix the bug is to modify
PdfImagePlugin.py and switch over the '/DctDecode' string to '/DCTDecode'
and see if that clears up the problem.  Unfortunately, I can't test this
hypothesis without a sample JPEG image.





By the way: you may want use os.path.join() to join together the directory
name with the file name.  The code in get_calls():

> def get_calls(dir, file):
>     im =3D Image.open(dir + file)
>     im.save(dir + '_' + file, 'PDF')

may not get the correct name of the directory, since the path separator
might be missing.

I can see that you have hardcoded the path separator embedded in the 'dir'
directory name within your main program, but if you are using get_calls()
from another program, then there's no guarantee that the directory name
ends with the path separator character.



Hope this helps!


From isrgish at fusemail.com  Wed Jan  7 21:40:39 2004
From: isrgish at fusemail.com (Isr Gish)
Date: Wed Jan  7 21:40:52 2004
Subject: [Tutor] Newbie: Help on comparing files
Message-ID: <E1AeQ6G-0001EH-Cg@fuse1.fusemail.net>

Thanks for the prompt replys.
(I'm on Windows.)
                	     See  below	  |
           	  			 \/
-----Original Message-----
   >From: "Danny Yoo"<dyoo@hkn.eecs.berkeley.edu>
   >Sent: 1/7/04 5:17:03 PM
   >Subject: Re: [Tutor] Newbie: Help on comparing files
   >
   >
   >
   >###
   >a..b..c
   >###
   >
   >and your second file has something like:
   >
   >###
   >b..c..d
   >###
   >
   >if we assume that '.' is the end of line mark.  What should your output
   >be?
   >


I would want "a.." to be left from the first file. "b.." & "c.."(because all files end with 2 end of lines) to matched from both files.  And "d to be left from second file.



   >Also, what happens if you have something like:
   >
   >###
   >alphabet soup..
   >###
   >
   >as the first file and
   >
   >###
   >this is a bowl of alphabet soup..
   >###
   >
   >as the second?  (Again, assuming that '.' is the end of line mark.)
   >
   >
This shold not match at all. For I want to only match full strings.

I have 2 exports of the registry (from Widows CE). I woulld like to see the differences beetween the 2. What key/va ues both have, and what is in one and not in the other. Etc.
Whope its clearer now what I want. 

-------
Isr Gish


From isrgish at fusemail.com  Wed Jan  7 21:40:35 2004
From: isrgish at fusemail.com (Isr Gish)
Date: Wed Jan  7 21:41:00 2004
Subject: [Tutor] Newbie: Help on comparing files
Message-ID: <E1AeQ6C-0001EH-Fj@fuse1.fusemail.net>

   >From: "Gerrit Holl"<gerrit@nl.linux.org>
   >Sent: 1/7/04 3:02:27 PM
   >To: "Isr Gish"<isrgish@fusemail.com>
   >Cc: "tutor@python.org"<tutor@python.org>
   >Subject: Re: [Tutor] Newbie: Help on comparing files
   >
   >Isr Gish wrote:
   >> I looking to write a function to compare 2 files.  
   >
   >You are looking for difflib:
   >http://www.python.org/doc/current/lib/module-difflib.html
   >
   >Examples:
   >http://www.python.org/doc/current/lib/differ-examples.html
Thanks for the reply.

What I need it to have an output to a file with exact differences what was in first file not in second, in second file not in first.
It doesn't seem to me that difflib does that, but I may be mistaken please correct me if I am.


From littledanehren at yahoo.com  Wed Jan  7 22:01:24 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Wed Jan  7 22:01:29 2004
Subject: [Tutor] for loop
In-Reply-To: <3FFC9E12.3020108@venix.com>
Message-ID: <20040108030124.32581.qmail@web41807.mail.yahoo.com>

Lloyd Kvam wrote:
> Ron A wrote:
> 
> > I'm experimenting and would like 'yes' to be
> printed only if 5 is not in
> > the list, but I want to look in each list. This
> prints out two yeses.
> > How do I get it to print just one 'yes'?
> > 
> > x = [[1,2,3],[2,4,6],[8,4,5,6],[9,8,7]]
> > 
> > for num in x:
> >     if 5 in num:
> >         break
> >     else:
> >         print 'yes'    
> > 
> This code prints yes until it finds a num list that
> contains 5.
> 
> To stop printing yes after the first time, simply
> break after printing
> yes.  However, this is equivalent to simply checking
> the first element
> of x.  You no longer need the loop.  So now the
> equivalent code is:
> 
> if 5 not in x[0]:
> 	print "yes"
> 
> -- 
> Lloyd Kvam

Are you sure that's what he intended to do? Your code
checks only the first list in x, but I think he wanted
to check them all. I would impliment it like this
instead:

x = [[1,2,3],[2,4,6],[8,4,5,6],[9,8,7]]
contains5 = False

for num in x:
    if 5 in x:
        contains5 = True
        break

if contains5: print 'yes'

You still need to loop through x to access each list.

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes
http://hotjobs.sweepstakes.yahoo.com/signingbonus

From fleming.j at comcast.net  Wed Jan  7 22:09:13 2004
From: fleming.j at comcast.net (john fleming)
Date: Wed Jan  7 22:07:21 2004
Subject: [Tutor] for loop
Message-ID: <3FFCC9D9.60005@comcast.net>

This is Guatavos solution to Ron's loop:

x = [[1,2,3],[2,4,6],[8,4,5,6],[9,8,7]]
for num in x:
   if 5 in num:
       print 'yes'
       break
This is Loyds solution:
if 5 not in x[0]:
    print "yes"
This was mine:
x = [[1,2,3],[2,4,6],[8,4,5,6],[9,8,7]]

for num in x:
    if 5 not in num:
        print 'yes'   

What is the advantage to using break as in gustavo's code?



From dyoo at hkn.eecs.berkeley.edu  Wed Jan  7 23:36:28 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Jan  7 23:36:33 2004
Subject: [Tutor] Newbie: Help on comparing files
In-Reply-To: <E1AeQ6G-0001EH-Cg@fuse1.fusemail.net>
Message-ID: <Pine.LNX.4.44.0401072027001.29018-100000@hkn.eecs.berkeley.edu>



On Wed, 7 Jan 2004, Isr Gish wrote:

> I have 2 exports of the registry (from Widows CE). I woulld like to see
> the differences beetween the 2. What key/va ues both have, and what is
> in one and not in the other. Etc. Whope its clearer now what I want.

Hi Isr,

Ok, sounds good.  Sounds like you may want regular expressions then, and
split against two "end-of-line" characters.  Here's an example of split():

###
>>> 'helloworldthisisatestoh'.split('o')
['hell', 'w', 'rldthisisatest', 'h']
###


For more information: A.M. Kuchling has written a nice HOWTO on Regular
expressions that should help explain them:

    http://www.amk.ca/python/howto/regex/


You can probably use regexes to break your files into text chunks.  After
that, your problem is pretty much done.  *grin*


> 2. What key/va ues both have, and what is in one and not in the other.

Ah!  If you want to check for set membership very quickly, you may want to
look into the 'sets' module:

    http://python.org/doc/lib/module-sets.html

which provide a very fast way to do membership tests.  If you ever find
yourself seeing if one thing is in a collection of other things, 'sets' is
probably a good thing to know about.


Good luck to you!


From philip at pacer.co.za  Thu Jan  8 01:13:08 2004
From: philip at pacer.co.za (philip gilchrist)
Date: Thu Jan  8 01:13:11 2004
Subject: [Tutor] for loop
Message-ID: <598B5E93DCDC614C9C1FE22406A0F5BE3660@pacer-server.pacer.local>


Hi Ron

Your question seems to have confused everyone, as you ask it to print
out yes only if 5 is not in the list and then you say that you only want
1 yes. It seems to me that the output that you want would either be
three yeses or none at all??
regards
 
Philip Gilchrist
Pacer Computers
Cell 0824589733

-----Original Message-----
From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On
Behalf Of Ron A
Sent: 08 January 2004 01:46 AM
To: tutor@python.org
Subject: [Tutor] for loop

I'm experimenting and would like 'yes' to be printed only if 5 is not in
the list, but I want to look in each list. This prints out two yeses.
How do I get it to print just one 'yes'?

x = [[1,2,3],[2,4,6],[8,4,5,6],[9,8,7]]

for num in x:
    if 5 in num:
        break
    else:
        print 'yes'    


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





From isrgish at fusemail.com  Thu Jan  8 01:13:15 2004
From: isrgish at fusemail.com (Isr Gish)
Date: Thu Jan  8 01:13:31 2004
Subject: [Tutor] Newbie: Help on comparing files
Message-ID: <E1AeTQ0-000PAP-UH@fuse1.fusemail.net>

Danny Yoo wrote:   
>Subject: Re: [Tutor] Newbie: Help on comparing files
     >
   >
   >On Wed, 7 Jan 2004, Isr Gish wrote:
   >
   >> I have 2 exports of the registry (from Widows CE). I would like to see
   >> the differences between the 2. What key/values both have, and what is
   >> in one and not in the other. Etc. Hope its clearer now what I want.
   >
   >Hi Isr,
   >
   >Ok, sounds good.  Sounds like you may want regular expressions then, and
   >split against two "end-of-line" characters.  Here's an example of split():
   >
   >###
   >>>> 'helloworldthisisatestoh'.split('o')
   >['hell', 'w', 'rldthisisatest', 'h']
   >###
  
Hi Danny,

I just want to make clear what your saying.
That I'm rather off using Regular Expressions to divide the files. Rather then slicing a string from one file and searching if its in the other...

------
Isr Gish


From tbrown at occamnetworks.com  Thu Jan  8 01:21:22 2004
From: tbrown at occamnetworks.com (Trent Brown)
Date: Thu Jan  8 01:21:58 2004
Subject: [Tutor] p2exe and icons
Message-ID: <3FFCF6E2.6020901@occamnetworks.com>

Seems that my version of py2exe will does not support the --icon flag 
(that or I'm doing something very wrong that I just don't see). Running 
it with the --icon flag returns an unknown option flag, and help does 
not list it as a supported option.

any help appreciated!

thx
trent


C:\Data\Python\Compile\Demo1a>python setup.py py2exe --icon
usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
   or: setup.py --help [cmd1 cmd2 ...]
   or: setup.py --help-commands
   or: setup.py cmd --help

error: option --icon not recognized

C:\Data\Python\Compile\Demo1a>python setup.py py2exe -help
Global options:
  --verbose (-v)  run verbosely (default)
  --quiet (-q)    run quietly (turns verbosity off)
  --dry-run (-n)  don't actually do anything
  --help (-h)     show detailed help message

Options for 'py2exe' command:
  --optimize (-O)    optimization level: -O1 for "python -O", -O2 for 
"python
                     -OO", and -O0 to disable [default: -O0]
  --dist-dir (-d)    directory to put final built distributions in 
(default is
                     dist)
  --excludes (-e)    comma-separated list of modules to exclude
  --ignores          comma-separated list of modules to ignore if they 
are not
                     found
  --includes (-i)    comma-separated list of modules to include
  --packages (-p)    comma-separated list of packages to include
  --compressed (-c)  create a compressed zipfile

usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
   or: setup.py --help [cmd1 cmd2 ...]
   or: setup.py --help-commands
   or: setup.py cmd --help


C:\Data\Python\Compile\Demo1a>python setup.py py2exe -help
Global options:
  --verbose (-v)  run verbosely (default)
  --quiet (-q)    run quietly (turns verbosity off)
  --dry-run (-n)  don't actually do anything
  --help (-h)     show detailed help message

Options for 'py2exe' command:
  --optimize (-O)    optimization level: -O1 for "python -O", -O2 for 
"python
                     -OO", and -O0 to disable [default: -O0]
  --dist-dir (-d)    directory to put final built distributions in 
(default is
                     dist)
  --excludes (-e)    comma-separated list of modules to exclude
  --ignores          comma-separated list of modules to ignore if they 
are not
                     found
  --includes (-i)    comma-separated list of modules to include
  --packages (-p)    comma-separated list of packages to include
  --compressed (-c)  create a compressed zipfile

usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
   or: setup.py --help [cmd1 cmd2 ...]
   or: setup.py --help-commands
   or: setup.py cmd --help



From Harm_Kirchhoff at mail.digital.co.jp  Thu Jan  8 01:46:53 2004
From: Harm_Kirchhoff at mail.digital.co.jp (Harm_Kirchhoff@mail.digital.co.jp)
Date: Thu Jan  8 01:47:01 2004
Subject: [Tutor] Looking for Module with Financial Functions
Message-ID: <OF5C56F258.21C52C2F-ON49256E15.002408A7-49256E15.0025161A@jp.schneider-electric.com>

Does anyone know, if there is a module of financial functions available in 
python ?
I looked on the internet, but could not find any.

From carroll at tjc.com  Thu Jan  8 02:03:35 2004
From: carroll at tjc.com (Terry Carroll)
Date: Thu Jan  8 02:03:40 2004
Subject: [Tutor] Looking for Module with Financial Functions
In-Reply-To: <OF5C56F258.21C52C2F-ON49256E15.002408A7-49256E15.0025161A@jp.schneider-electric.com>
Message-ID: <Pine.LNX.4.44.0401072302230.7640-100000@violet.rahul.net>

On Thu, 8 Jan 2004 Harm_Kirchhoff@mail.digital.co.jp wrote:

> Does anyone know, if there is a module of financial functions available
> in python ? I looked on the internet, but could not find any.

<http://www.advogato.com/proj/py-fi/> is a page for pyfi, "a module that 
provides financial functions for the Python language," but it sends you to 
<http://metro.yak.net/pyfi.html>, which seems to be down, at least at the 
moment.

-- 
Terry Carroll
Santa Clara, CA
carroll@tjc.com 


From alan.gauld at blueyonder.co.uk  Thu Jan  8 02:26:35 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Thu Jan  8 02:26:17 2004
Subject: [Tutor] How to eliminate the background command window?
References: <CAENJDPIMKAJINIKKHOCEEEJCCAA.piir@earthlink.net>
Message-ID: <01f001c3d5b8$bf58c330$6401a8c0@xp>

> I would like to know what I am not doing here.  Every progran I
write in
> Python on WXP shows a background command window unless I build a
.exe using
> py2exe with the -w option.
>
> How can I get rid of the back ground command window?

remame the top level script from .py to .pyw.

Or just use pythonw to launch the script instead of python.

Alan g.


From alan.gauld at blueyonder.co.uk  Thu Jan  8 02:41:49 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Thu Jan  8 02:41:31 2004
Subject: [Tutor] for loop
References: <20040108030124.32581.qmail@web41807.mail.yahoo.com>
Message-ID: <022401c3d5ba$e02a5590$6401a8c0@xp>

> Are you sure that's what he intended to do? Your code
> checks only the first list in x, but I think he wanted
> to check them all. I would impliment it like this
> instead:

I couldn't quite work out what the original req was.
But here are another 2 options:

> x = [[1,2,3],[2,4,6],[8,4,5,6],[9,8,7]]
> contains5 = False
> 
> for num in x:
>     if 5 in x:
>         contains5 = True
>         break
> 
> if contains5: print 'yes'

# needs python 2.3, lower versions substitute 1 for True
x = [[1,2,3],[2,4,6],[8,4,5,6],[9,8,7]]
if True in [ 5 in L for L in x]:
   print 'Yes'

Or if you prefer:

# you don't need fthe len() call but I think it 
# makes the intent clearer
x = [[1,2,3],[2,4,6],[8,4,5,6],[9,8,7]]
if len(filter(lambda L:5 in L, x)) > 0:
   print 'Yes'

Alan G.


From python at comber.cix.co.uk  Thu Jan  8 08:59:13 2004
From: python at comber.cix.co.uk (Eddie Comber)
Date: Thu Jan  8 09:03:58 2004
Subject: [Tutor] Dialog box under windows
Message-ID: <BEEOLJNPLOPIONOMGLAAKECECKAA.python@comber.cix.co.uk>

Would anyone have a working piece of code that can open a simple dialog bow
in Windows?

I have a background Python app running and I just want to inform the user
when particular events occur.

It would be ideal if the box showed a few lines of information and an #'OK'
button.

I have the Mark Hammond's win32all stuff but while the function calls are
there, the stuff like the windows API constants that are needed for e.g. the
style of the box etc.

Ta,
Eddie Comber


From hec.villafuerte at telgua.com.gt  Thu Jan  8 11:39:01 2004
From: hec.villafuerte at telgua.com.gt (=?UTF-8?B?IkjDqWN0b3IgVmlsbGFmdWVydGUgRC4i?=)
Date: Thu Jan  8 09:37:16 2004
Subject: [Tutor] Converting to PDF
In-Reply-To: <Pine.LNX.4.44.0401071720340.15436-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0401071720340.15436-100000@hkn.eecs.berkeley.edu>
Message-ID: <3FFD87A5.8020706@telgua.com.gt>

Hi all!
Danny was so right! This is a bug in PIL.
I changed '/DctDecode' and '/DCTDecode' in PdfImagePlugin.py
and it worked just fine!
Thanks Danny and all you Python people.
Hector


Danny Yoo wrote:

>
>On Wed, 7 Jan 2004, [ISO-8859-1] "H?ctor Villafuerte D." wrote:
>
>
>>Hi all,
>>I'm trying to generate PDFs with this little script:
>>
>>-----SCRIPT-------------------------
>>import fileinput, os, Image
>>
>>def get_calls(dir, file):
>>    im = Image.open(dir + file)
>>    im.save(dir + '_' + file, 'PDF')
>>
>>if __name__ == '__main__':
>>    dir = 'c:\\tmp\\scan\\'
>>    for x in os.listdir(dir):
>>        if x.split('.')[1] == 'jpg':
>>            print x
>>            get_calls(dir, x)
>>
>
>
>Hi Hector,
>
>
>I looked into the PdfImagePlugin.py source from version 1.1.4 of the
>Python Imaging Library,
>
>    http://www.pythonware.com/products/pil/
>
>
>And you appear to have run into a bug in PIL!  The code in question in
>PIL/PdfImagePlugin.py is:
>
>###
>    if filter == "/ASCIIHexDecode":
>        ImageFile._save(im, op, [("hex", (0,0)+im.size, 0, None)])
>    elif filter == "/DCTDecode":
>        ImageFile._save(im, op, [("jpeg", (0,0)+im.size, 0, im.mode)])
>    elif filter == "/FlateDecode":
>        ImageFile._save(im, op, [("zip", (0,0)+im.size, 0, im.mode)])
>    elif filter == "/RunLengthDecode":
>        ImageFile._save(im, op, [("packbits", (0,0)+im.size, 0, im.mode)])
>    else:
>        raise ValueError, "unsupported PDF filter"
>###
>
>
>That block is within the _safe() function in PdfImagePlugin.py.  But
>there's only one block of code that assigns to this 'filter' variable:
>
>###
>    if im.mode == "1":
>        filter = "/ASCIIHexDecode"
>        config = "/DeviceGray", "/ImageB", 1
>    elif im.mode == "L":
>        filter = "/DctDecode"
>        # params = "<< /Predictor 15 /Columns %d >>" % (width-2)
>        config = "/DeviceGray", "/ImageB", 8
>    elif im.mode == "P":
>        filter = "/ASCIIHexDecode"
>        config = "/Indexed", "/ImageI", 8
>    elif im.mode == "RGB":
>        filter = "/DCTDecode"
>        config = "/DeviceRGB", "/ImageC", 8
>    elif im.mode == "CMYK":
>        filter = "/DCTDecode"
>        config = "/DeviceRGB", "/ImageC", 8
>    else:
>        raise ValueError, "illegal mode"
>###
>
>
>'filter' here has three possible values:
>
>    ['/ASCIIHexDecode',
>     '/DctDecode',
>     '/DCTDecode']
>
>
>Notice the case difference here between '/DctDecode' and '/DCTDecode'.
>Python is case sensitive.  This is a bad sign.  *grin*
>
>
>The block that we're running into problems with, the one that throws the
>exception, checks for:
>
>    ["/ASCIIHexDecode",
>     "/DCTDecode",
>     "/FlateDecode",
>     "/RunLengthDecode"]
>
>
>It doesn't handle "/DctDecode"!  Furthermore, there's no way 'filter' can
>be '/RunLengthDecode', so there's some dead code here too.
>
>There's definitely a bug here.  Send a holler out to the Python Imaging
>Library folks.  *grin*
>
>    http://mail.python.org/mailman/listinfo/image-sig
>
>and get them to fix it so no one else runs into this.
>
>
>
>In the meantime, my best guess right now to fix the bug is to modify
>PdfImagePlugin.py and switch over the '/DctDecode' string to '/DCTDecode'
>and see if that clears up the problem.  Unfortunately, I can't test this
>hypothesis without a sample JPEG image.
>
>
>
>
>
>By the way: you may want use os.path.join() to join together the directory
>name with the file name.  The code in get_calls():
>
>
>>def get_calls(dir, file):
>>    im = Image.open(dir + file)
>>    im.save(dir + '_' + file, 'PDF')
>>
>
>may not get the correct name of the directory, since the path separator
>might be missing.
>
>I can see that you have hardcoded the path separator embedded in the 'dir'
>directory name within your main program, but if you are using get_calls()
>from another program, then there's no guarantee that the directory name
>ends with the path separator character.
>
>
>
>Hope this helps!
>
>
>
>



From rick at niof.net  Thu Jan  8 10:34:54 2004
From: rick at niof.net (Rick Pasotto)
Date: Thu Jan  8 10:32:27 2004
Subject: [Tutor] Dialog box under windows
In-Reply-To: <BEEOLJNPLOPIONOMGLAAKECECKAA.python@comber.cix.co.uk>
References: <BEEOLJNPLOPIONOMGLAAKECECKAA.python@comber.cix.co.uk>
Message-ID: <20040108153453.GS22796@niof.net>

On Thu, Jan 08, 2004 at 01:59:13PM -0000, Eddie Comber wrote:
> Would anyone have a working piece of code that can open a simple
> dialog bow in Windows?
> 
> I have a background Python app running and I just want to inform the
> user when particular events occur.
> 
> It would be ideal if the box showed a few lines of information and an
> #'OK' button.

import tkMessageBox
tkMessageBox.showinfo(title='window title',
	message='put your message text here')

> I have the Mark Hammond's win32all stuff but while the function calls
> are there, the stuff like the windows API constants that are needed
> for e.g. the style of the box etc.

tkMessageBox contains:

def showinfo(title=None, message=None, **options):
    "Show an info message"
    return _show(title, message, INFO, OK, **options)

def showwarning(title=None, message=None, **options):
    "Show a warning message"
    return _show(title, message, WARNING, OK, **options)

def showerror(title=None, message=None, **options):
    "Show an error message"
    return _show(title, message, ERROR, OK, **options)

def askquestion(title=None, message=None, **options):
    "Ask a question"
    return _show(title, message, QUESTION, YESNO, **options)

def askokcancel(title=None, message=None, **options):
    "Ask if operation should proceed; return true if the answer is ok"
    s = _show(title, message, QUESTION, OKCANCEL, **options)
    return s == OK

def askyesno(title=None, message=None, **options):
    "Ask a question; return true if the answer is yes"
    s = _show(title, message, QUESTION, YESNO, **options)
    return s == YES

def askretrycancel(title=None, message=None, **options):
    "Ask if operation should be retried; return true if the answer is yes"
    s = _show(title, message, WARNING, RETRYCANCEL, **options)
    return s == RETRY

-- 
"Politics has always been the institutionalized and established way
 in which some men have exercised the power to live off the output
 of other men." -- Karl Hess
    Rick Pasotto    rick@niof.net    http://www.niof.net

From pythontutor at venix.com  Thu Jan  8 11:14:35 2004
From: pythontutor at venix.com (Lloyd Kvam)
Date: Thu Jan  8 11:14:39 2004
Subject: [Tutor] for loop
In-Reply-To: <20040108030124.32581.qmail@web41807.mail.yahoo.com>
References: <20040108030124.32581.qmail@web41807.mail.yahoo.com>
Message-ID: <3FFD81EB.1040202@venix.com>

The intent of the programmer may have been to print yes if there
was any group with no 5.  For that intent the break was placed with
the wrong conditional branch.

This is a minimal change to fix it.
 >>>x = [[1,2,3],[2,4,6],[8,4,5,6],[9,8,7]]
 >>>
 >>>for num in x:
 >>>    if 5 in num:
	   pass
 >>>    else:
 >>>        print 'yes'
 >>>        break

I got hung up reading the original code.  The code has two features:
	1. yes implies there is a group with NO 5 (and Ron only wants one yes)
	2. we stop looking once we encounter a group with a 5

Combining those ideas, we no longer need the loop.  If the first group
contains a 5 we stop looking (#2).  If the first group does not contain
a five, print yes satisfying #1.



Daniel Ehrenberg wrote:

> Lloyd Kvam wrote:
> 
>>Ron A wrote:
>>
>>
>>>I'm experimenting and would like 'yes' to be
>>
>>printed only if 5 is not in
>>
>>>the list, but I want to look in each list. This
>>
>>prints out two yeses.
>>
>>>How do I get it to print just one 'yes'?
>>>
>>>x = [[1,2,3],[2,4,6],[8,4,5,6],[9,8,7]]
>>>
>>>for num in x:
>>>    if 5 in num:
>>>        break
>>>    else:
>>>        print 'yes'    
>>>
>>
>>This code prints yes until it finds a num list that
>>contains 5.
>>
>>To stop printing yes after the first time, simply
>>break after printing
>>yes.  However, this is equivalent to simply checking
>>the first element
>>of x.  You no longer need the loop.  So now the
>>equivalent code is:
>>
>>if 5 not in x[0]:
>>	print "yes"
>>
>>-- 
>>Lloyd Kvam
> 
> 
> Are you sure that's what he intended to do? Your code
> checks only the first list in x, but I think he wanted
> to check them all. I would impliment it like this
> instead:
> 
> x = [[1,2,3],[2,4,6],[8,4,5,6],[9,8,7]]
> contains5 = False
> 
> for num in x:
>     if 5 in x:
>         contains5 = True
>         break
> 
> if contains5: print 'yes'
> 
> You still need to loop through x to access each list.
> 
> Daniel Ehrenberg
> 
> __________________________________
> Do you Yahoo!?
> Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes
> http://hotjobs.sweepstakes.yahoo.com/signingbonus
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582


From rick at niof.net  Thu Jan  8 11:24:42 2004
From: rick at niof.net (Rick Pasotto)
Date: Thu Jan  8 11:23:16 2004
Subject: [Tutor] Dialog box under windows
In-Reply-To: <BEEOLJNPLOPIONOMGLAAMECGCKAA.comber@cix.co.uk>
References: <20040108153453.GS22796@niof.net>
	<BEEOLJNPLOPIONOMGLAAMECGCKAA.comber@cix.co.uk>
Message-ID: <20040108162442.GT22796@niof.net>

On Thu, Jan 08, 2004 at 03:46:03PM -0000, Edward Comber wrote:
> Thanks very much for that, I'll get stuck into it. At the moment it
> opens a Tk main app screen that can't be closed but I'll persist.

Not if you already have a main window open. It's not meant to be used
standalone but as part of an application.

-- 
"The suppression of unnecessary offices, of useless establishments and
 expenses, enabled us to discontinue our internal taxes.   These
 covering our land with officers and opening our doors to their
 intrusions, had already begun that process of domiciliary vexation
 which once entered is scarcely to be restrained from reaching,
 successively, every article of property and produce."
		-- Thomas Jefferson
    Rick Pasotto    rick@niof.net    http://www.niof.net

From m.evanetich at att.net  Thu Jan  8 12:43:04 2004
From: m.evanetich at att.net (m.evanetich@att.net)
Date: Thu Jan  8 12:43:10 2004
Subject: [Tutor] Dialog box under windows
Message-ID: <010820041743.27026.6f0a@att.net>

> 
> On Thu, Jan 08, 2004 at 03:46:03PM -0000, Edward Comber wrote:
> > Thanks very much for that, I'll get stuck into it. At the moment it
> > opens a Tk main app screen that can't be closed but I'll persist.
> 
> Not if you already have a main window open. It's not meant to be used
> standalone but as part of an application.
> 
I dealt with this, thanks to suggestions on this list by writing my own 
little modeule that calls these TK dialogs and withdraws the top level main 
app.  Since I use these things in scripts, that seems to work pretty well.
Here is an example:

import Tkinter
import tkMessageBox
def InfoBox(Title=None, Message=None):

    root =Tkinter.Tk()
    root.withdraw()     # Prevent spurious root window from showing
    message = tkMessageBox.showinfo(title=Title, message=Message)
    root.destroy()
    return message

--
Best wishes,
mark

From dyoo at hkn.eecs.berkeley.edu  Thu Jan  8 12:54:40 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Jan  8 12:54:48 2004
Subject: [Tutor] p2exe and icons
In-Reply-To: <3FFCF6E2.6020901@occamnetworks.com>
Message-ID: <Pine.LNX.4.44.0401080953320.24932-100000@hkn.eecs.berkeley.edu>



On Wed, 7 Jan 2004, Trent Brown wrote:

> Seems that my version of py2exe will does not support the --icon flag
> (that or I'm doing something very wrong that I just don't see). Running
> it with the --icon flag returns an unknown option flag, and help does
> not list it as a supported option.

Hi Trent,

According to the documentation at:

    http://py2exe.sourceforge.net/

the '--icon' option only works under Windows NT/2000/XP.  What release of
Windows are you running?


Talk to you later!


From dyoo at hkn.eecs.berkeley.edu  Thu Jan  8 13:06:33 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Jan  8 13:06:40 2004
Subject: [Tutor] Newbie: Help on comparing files
In-Reply-To: <E1AeTQ0-000PAP-UH@fuse1.fusemail.net>
Message-ID: <Pine.LNX.4.44.0401080954480.24932-100000@hkn.eecs.berkeley.edu>



On Thu, 8 Jan 2004, Isr Gish wrote:

>    >> I have 2 exports of the registry (from Widows CE). I would like to
>    >> see
>    >> the differences between the 2. What key/values both have, and what is
>    >> in one and not in the other. Etc. Hope its clearer now what I want.
>    >
>    >Ok, sounds good.  Sounds like you may want regular expressions then,
>    >and split against two "end-of-line" characters.  Here's an example
>    >of split():
>    >
>    >###
>    >>>> 'helloworldthisisatestoh'.split('o')
>    >['hell', 'w', 'rldthisisatest', 'h']
>    >###
>
> I just want to make clear what your saying. That I'm rather off using
> Regular Expressions to divide the files. Rather then slicing a string
> from one file and searching if its in the other...


Hi Isr,


You're going to have to try it out.  *grin*


Again, this is much too close to a homework assignment for my own comfort;
I don't think any of us can say much more about this without seeing what
you have done so far.


If you're still stuck, simplify the problem and try working on that
variation.  Your experience with a simpler problem should help you with
the original problem.

Here's one possible simplification: assume for the moment that there's
only one chunk of text in the first file.  With that restriction, can you
solve the problem?  How would you check to see if that single chunk exists
in the second file?


Good luck to you!


From tbrown at occamnetworks.com  Thu Jan  8 13:10:22 2004
From: tbrown at occamnetworks.com (Trent Brown)
Date: Thu Jan  8 13:11:26 2004
Subject: [Tutor] p2exe and icons
In-Reply-To: <Pine.LNX.4.44.0401080953320.24932-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0401080953320.24932-100000@hkn.eecs.berkeley.edu>
Message-ID: <3FFD9D0E.7090301@occamnetworks.com>

Hello Danny,

thanks for replying. I'm actually running 2000 which is perplexing (I 
had the same thought also)

thanks
again
trent

Danny Yoo wrote:

>On Wed, 7 Jan 2004, Trent Brown wrote:
>
>  
>
>>Seems that my version of py2exe will does not support the --icon flag
>>(that or I'm doing something very wrong that I just don't see). Running
>>it with the --icon flag returns an unknown option flag, and help does
>>not list it as a supported option.
>>    
>>
>
>Hi Trent,
>
>According to the documentation at:
>
>    http://py2exe.sourceforge.net/
>
>the '--icon' option only works under Windows NT/2000/XP.  What release of
>Windows are you running?
>
>
>Talk to you later!
>  
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20040108/bd706e45/attachment.html
From cspears2002 at yahoo.com  Thu Jan  8 15:22:52 2004
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Thu Jan  8 15:23:00 2004
Subject: [Tutor] absolute locations
Message-ID: <20040108202252.2303.qmail@web12401.mail.yahoo.com>

Grrr!

I'm trying to open up a file with the following
absloute path in Windows 2000:

C:\Documents and Settings\Christstopher Spears\My
Documents\python\unit4.txt

So I enter the following in IDLE:

>>> import os
>>> fileName = os.path.join("c:", "Documents and
Settings", "Christopher Spears", "My Documents",
"python", "unit4.txt")
>>> fileobject = open(fileName, 'r')

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in -toplevel-
    fileobject = open(fileName, 'r')
IOError: [Errno 2] No such file or directory:
'c:Documents and Settings\\Christopher Spears\\My
Documents\\python\\unit4.txt'

I know unit4.txt is there, but I can't seem to
convince python of that!  What is up with \\ anyway?

=====
"I'm the last person to pretend that I'm a radio.  I'd rather go out and be a color television set."
-David Bowie

"Who dares wins"
-British military motto

"Far more creativity, today, goes into the marketing of products than into the products themselves..."
-"Pattern Recognition" by William Gibson

From hall at nhn.ou.edu  Thu Jan  8 15:32:41 2004
From: hall at nhn.ou.edu (Isaac Hall)
Date: Thu Jan  8 15:32:51 2004
Subject: [Tutor] memory leaks
Message-ID: <Pine.LNX.4.44.0401081432190.1016-100000@ouhep1.nhn.ou.edu>


Hi folks,

I was wondering if any of you might know what kinds of tools are available 
for checking large python programs for memory leaks.  I have a program 
that seems to have developed one recently, and it is so large that I am 
having difficulty tracking it down.  thanks in advance.

Ike Hall

-- 




From birdiepage at ciudad.com.ar  Thu Jan  8 15:22:47 2004
From: birdiepage at ciudad.com.ar (Gustavo Campanelli)
Date: Thu Jan  8 15:33:36 2004
Subject: [Tutor] absolute locations
In-Reply-To: <20040108202252.2303.qmail@web12401.mail.yahoo.com>
References: <20040108202252.2303.qmail@web12401.mail.yahoo.com>
Message-ID: <3FFDBC17.8080102@ciudad.com.ar>

Christopher Spears wrote:

>Grrr!
>
>I'm trying to open up a file with the following
>absloute path in Windows 2000:
>
>C:\Documents and Settings\Christstopher Spears\My
>Documents\python\unit4.txt
>
>So I enter the following in IDLE:
>
>  
>
>>>>import os
>>>>fileName = os.path.join("c:", "Documents and
>>>>        
>>>>
>Settings", "Christopher Spears", "My Documents",
>"python", "unit4.txt")
>  
>
>>>>fileobject = open(fileName, 'r')
>>>>        
>>>>
>
>Traceback (most recent call last):
>  File "<pyshell#2>", line 1, in -toplevel-
>    fileobject = open(fileName, 'r')
>IOError: [Errno 2] No such file or directory:
>'c:Documents and Settings\\Christopher Spears\\My
>Documents\\python\\unit4.txt'
>
>I know unit4.txt is there, but I can't seem to
>convince python of that!  What is up with \\ anyway?
>
>=====
>"I'm the last person to pretend that I'm a radio.  I'd rather go out and be a color television set."
>-David Bowie
>
>"Who dares wins"
>-British military motto
>
>"Far more creativity, today, goes into the marketing of products than into the products themselves..."
>-"Pattern Recognition" by William Gibson
>

I don't have experience with Python relating to the OS module, but I'll 
suggest two possible failures here.
1) you are trying to get data from another user without reading 
permissions (not likely but possible)
2) and I'm preety sure this is it, you are trying to reach C:\Documents 
and Settings\Christstopher Spears\My Documents\python\unit4.txt, wich is 
an absolute path, but your Python is trying to locate 'c:Documents and 
Settings\\Christopher Spears\\My Documents\\python\\unit4.txt', which 
lacks the \ right after the c: thus making itself a relative path.

Gedece, still a Python newbie

From alan.gauld at blueyonder.co.uk  Thu Jan  8 16:03:36 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Thu Jan  8 16:28:35 2004
Subject: [Tutor] Dialog box under windows
References: <BEEOLJNPLOPIONOMGLAAKECECKAA.python@comber.cix.co.uk>
Message-ID: <025b01c3d62a$e1f73170$6401a8c0@xp>

Take a look at the GUI page of my tutor. It shows the use 
of all the standard Dialogs in Tkinter. You can call those 
very easily indeed.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


From op73418 at mail.telepac.pt  Thu Jan  8 16:45:40 2004
From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=)
Date: Thu Jan  8 16:43:21 2004
Subject: [Tutor] absolute locations
In-Reply-To: <20040108202252.2303.qmail@web12401.mail.yahoo.com>
References: <20040108202252.2303.qmail@web12401.mail.yahoo.com>
Message-ID: <tijrvvka24b4vndcrk5l76con3pvrt0kup@4ax.com>

Em Thu, 8 Jan 2004 12:22:52 -0800 (PST), Christopher Spears
<cspears2002@yahoo.com> atirou este peixe aos pinguins:

>Grrr!
>
>I'm trying to open up a file with the following
>absloute path in Windows 2000:
>
>C:\Documents and Settings\Christstopher Spears\My
>Documents\python\unit4.txt
>
>So I enter the following in IDLE:
>
>>>> import os
>>>> fileName = os.path.join("c:", "Documents and
>Settings", "Christopher Spears", "My Documents",
>"python", "unit4.txt")
>>>> fileobject = open(fileName, 'r')
>
>Traceback (most recent call last):
>  File "<pyshell#2>", line 1, in -toplevel-
>    fileobject = open(fileName, 'r')
>IOError: [Errno 2] No such file or directory:
>'c:Documents and Settings\\Christopher Spears\\My
>Documents\\python\\unit4.txt'
>

The answer is right there in the traceback. 

Look at the *right* way to do it:

>>> fileName = os.path.join("c:\\Documents and Settings", "Christopher Spears", "My Documents", "python", "unit4.txt")
>>> fileName
'c:\\Documents and Settings\\Christopher Spears\\My
Documents\\python\\unit4.txt'
>>> 

Do you notice the difference?

>I know unit4.txt is there, but I can't seem to
>convince python of that!  What is up with \\ anyway?

The character \ is special, it's the escape character. For example

"\n"

means new line, e.g.

>>> print "A sentence and a newline\n"
A sentence and a newline

>>> 

This means that if you want Python to interpret \ literally you have
to use some scheme - hence the doubling \\.

Hope it helps,
G. Rodrigues

From bwinton at latte.ca  Thu Jan  8 17:34:53 2004
From: bwinton at latte.ca (Blake Winton)
Date: Thu Jan  8 17:35:02 2004
Subject: [Tutor] absolute locations
In-Reply-To: <tijrvvka24b4vndcrk5l76con3pvrt0kup@4ax.com>
Message-ID: <005001c3d637$a290a680$6401a8c0@phantomfiber.com>

> >>>> fileName = os.path.join("c:", "Documents and
> >Settings", "Christopher Spears", "My Documents",
> >"python", "unit4.txt")
> 
> Look at the *right* way to do it:
> 
> >>> fileName = os.path.join("c:\\Documents and Settings", 
> "Christopher Spears", "My Documents", "python", "unit4.txt")

Well, that's a way that works, but I, for one, am not
completely convinced that the first way shouldn't work.
Why should someone be forced to type the first "\\",
especially since that might change on a per-os basis?

Later,
Blake.


From littledanehren at yahoo.com  Thu Jan  8 18:43:54 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Thu Jan  8 18:44:04 2004
Subject: [Tutor] absolute locations
In-Reply-To: <005001c3d637$a290a680$6401a8c0@phantomfiber.com>
Message-ID: <20040108234354.99592.qmail@web41801.mail.yahoo.com>

> Well, that's a way that works, but I, for one, am
> not
> completely convinced that the first way shouldn't
> work.
> Why should someone be forced to type the first "\\",
> especially since that might change on a per-os
> basis?
> 
> Later,
> Blake.

If you're refering to the C drive, it's not going to
be at all cross-platform at all, considering that
practically all modern OS's except for Windows use an
everything-is-a-file paradigm. The only way to be
truely cross-platform is to use relative paths or some
library that does different things for different
platforms manually.

Python lets you use unix-style paths on all platforms
anyway, so you don't really need to use os.path.join
at all.

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes
http://hotjobs.sweepstakes.yahoo.com/signingbonus

From littledanehren at yahoo.com  Thu Jan  8 18:49:41 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Thu Jan  8 18:49:45 2004
Subject: [Tutor] absolute locations
In-Reply-To: <tijrvvka24b4vndcrk5l76con3pvrt0kup@4ax.com>
Message-ID: <20040108234941.53864.qmail@web41810.mail.yahoo.com>

> This means that if you want Python to interpret \
> literally you have
> to use some scheme - hence the doubling \\.
> 
> Hope it helps,
> G. Rodrigues

This can be annoying if you do it alot, so to skip all
of the escape codes and have \ interpreted as \, you
can prefix the string with the letter r. Example:

>>> print 'C:\\new' #annoying, but correct
C:\new
>>> print 'C:\new' #wrong
C:
ew
>>> print r'C:\new' #right and not annoying

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes
http://hotjobs.sweepstakes.yahoo.com/signingbonus

From ralobao at click21.com.br  Thu Jan  8 19:13:29 2004
From: ralobao at click21.com.br (Ruivaldo Neto)
Date: Thu Jan  8 19:52:19 2004
Subject: [Tutor] absolute locations
In-Reply-To: <20040108202252.2303.qmail@web12401.mail.yahoo.com>
References: <20040108202252.2303.qmail@web12401.mail.yahoo.com>
Message-ID: <200401082213.29875.ralobao@click21.com.br>

Did you try:
file_adress = 'C:\Documents and Settings\Christstopher Spears\My Documents 
python\unit4.txt'
fileobject = open(file_adress,'r')
?

Good luck :)

Em Qui 08 Jan 2004 18:22, Christopher Spears escreveu:
> Grrr!
>
> I'm trying to open up a file with the following
> absloute path in Windows 2000:
>
> C:\Documents and Settings\Christstopher Spears\My
> Documents\python\unit4.txt
>
> So I enter the following in IDLE:
> >>> import os
> >>> fileName = os.path.join("c:", "Documents and
>
> Settings", "Christopher Spears", "My Documents",
> "python", "unit4.txt")
>
> >>> fileobject = open(fileName, 'r')
>
> Traceback (most recent call last):
>   File "<pyshell#2>", line 1, in -toplevel-
>     fileobject = open(fileName, 'r')
> IOError: [Errno 2] No such file or directory:
> 'c:Documents and Settings\\Christopher Spears\\My
> Documents\\python\\unit4.txt'
>
> I know unit4.txt is there, but I can't seem to
> convince python of that!  What is up with \\ anyway?
>
> =====
> "I'm the last person to pretend that I'm a radio.  I'd rather go out and be
> a color television set." -David Bowie
>
> "Who dares wins"
> -British military motto
>
> "Far more creativity, today, goes into the marketing of products than into
> the products themselves..." -"Pattern Recognition" by William Gibson
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
RS: Ruivaldo Neto


From isrgish at fusemail.com  Thu Jan  8 21:38:45 2004
From: isrgish at fusemail.com (Isr Gish)
Date: Thu Jan  8 21:38:48 2004
Subject: [Tutor] Time - Less then a second
Message-ID: <E1AemXh-000Ov2-0a@fuse1.fusemail.net>

I'm looking to be able to get time in less then seconds.
I have looked in the time module and seen the time.clock() and time.time() functions. But on my machine (Pocket PC running Python Ver. 2.3.2) it doesn't return anything less than seconds. And they both return the same thing, (the full time since ??? In seconds).

If someone can please point me in the right direction it would be greatly appreciated.

(I have used ticks() previously in PocketC for the Windows CE platform. I have never programmed in any other language before besides PocketC) 

---------------
Isr Gish


From exnihilo at myrealbox.com  Thu Jan  8 22:02:12 2004
From: exnihilo at myrealbox.com (exnihilo@myrealbox.com)
Date: Thu Jan  8 22:02:22 2004
Subject: [Tutor] Time - Less then a second
In-Reply-To: <E1AemXh-000Ov2-0a@fuse1.fusemail.net>
References: <E1AemXh-000Ov2-0a@fuse1.fusemail.net>
Message-ID: <3FFE19B4.4030401@myrealbox.com>

Isr Gish wrote:
> I'm looking to be able to get time in less then seconds.
> I have looked in the time module and seen the time.clock() and time.time() functions. But on my machine (Pocket PC running Python Ver. 2.3.2) it doesn't return anything less than seconds. And they both return the same thing, (the full time since ??? In seconds).
> 
> If someone can please point me in the right direction it would be greatly appreciated.
> 
> (I have used ticks() previously in PocketC for the Windows CE platform. I have never programmed in any other language before besides PocketC) 
> 
> ---------------
> Isr Gish

hi Isr,

The following little snippet illustrates how time.clock() works. I've 
never used time.time() before though.

 >>> import random, time
 >>> def timeSort(l):
	start = time.clock()
	l.sort()
	print "Sort Time:", (time.clock() - start) * 1000, "milliseconds"

	
 >>> randList = [random.random() for i in range(100000)]
 >>> timeSort(randList)
Sort Time: 190.0 milliseconds
 >>> # you don't want to print that huge

time.clock() returns a time in seconds as a floating point number (see 
help(time.clock)) to as much precision as the system provides, so I 
think that should satisfy your requirement (if you want milliseconds, 
just multiply by 1000 as I did in the example).

Hope that helps...



From exnihilo at myrealbox.com  Thu Jan  8 22:36:53 2004
From: exnihilo at myrealbox.com (exnihilo@myrealbox.com)
Date: Thu Jan  8 22:37:01 2004
Subject: [Tutor] Time - Less then a second
In-Reply-To: <E1AemXh-000Ov2-0a@fuse1.fusemail.net>
References: <E1AemXh-000Ov2-0a@fuse1.fusemail.net>
Message-ID: <3FFE21D5.3010505@myrealbox.com>

Isr Gish wrote:
> I'm looking to be able to get time in less then seconds.
> I have looked in the time module and seen the time.clock() and time.time() functions. But on my machine (Pocket PC running Python Ver. 2.3.2) it doesn't return anything less than seconds. And they both return the same thing, (the full time since ??? In seconds).
> 
> If someone can please point me in the right direction it would be greatly appreciated.
> 
> (I have used ticks() previously in PocketC for the Windows CE platform. I have never programmed in any other language before besides PocketC) 
> 
> ---------------
> Isr Gish

hello again,

After playing around a bit, I'm now thoroughly confused.

 >>> help(time.clock)
Help on built-in function clock:

clock(...)
     clock() -> floating point number

     Return the CPU time or real time since the start of the process or 
since
     the first call to clock().  This has as much precision as the system
     records.


This indicates that the float will be as precise as the system records, 
yet time.time() seems to give me much greater precision:


 >>> def timeSort(l):
	start = time.time()
	l.sort()
	print "Sort Time:", (time.time() - start) * 1000, "milliseconds"

	
 >>> def clockSort(l):
	start = time.clock()
	l.sort()
	print "Sort Time:", (time.clock() - start) * 1000,"milliseconds"

	
 >>> tList = [random.random() for i in range(100000)]
 >>> cList = [random.random() for i in range(100000)]
 >>> timeSort(tList)
Sort Time: 184.044003487 milliseconds
 >>> clockSort(cList)
Sort Time: 200.0 milliseconds

And a second time:
 >>> tList = [random.random() for i in range(100000)]
 >>> cList = [random.random() for i in range(100000)]
 >>> timeSort(tList)
Sort Time: 207.070946693 milliseconds
 >>> clockSort(cList)
Sort Time: 180.0 milliseconds


Time certainly looks more precise than clock to me.

Okay, I checked the docs, as I should have done originally 
(http://python.org/doc/current/lib/module-time.html):

clock(   )

On Unix, return the current processor time as a floating point number 
expressed in seconds. The precision, and in fact the very definition of 
the meaning of ``processor time'', depends on that of the C function of 
the same name, but in any case, this is the function to use for 
benchmarkingPython or timing algorithms.

On Windows, this function returns wall-clock seconds elapsed since the 
first call to this function, as a floating point number, based on the 
Win32 function QueryPerformanceCounter(). The resolution is typically 
better than one microsecond.

time(  	)
     Return the time as a floating point number expressed in seconds 
since the epoch, in UTC. Note that even though the time is always 
returned as a floating point number, not all systems provide time with a 
better precision than 1 second. While this function normally returns 
non-decreasing values, it can return a lower value than a previous call 
if the system clock has been set back between the two calls.

Hmmm, perhaps more experienced hands can explain the results of my tests.


From alan.gauld at blueyonder.co.uk  Fri Jan  9 02:59:59 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Fri Jan  9 02:59:23 2004
Subject: [Tutor] absolute locations
References: <005001c3d637$a290a680$6401a8c0@phantomfiber.com>
Message-ID: <02a501c3d686$941016f0$6401a8c0@xp>

> > >>> fileName = os.path.join("c:\\Documents and Settings", 
> > "Christopher Spears", "My Documents", "python", "unit4.txt")
> 
> Well, that's a way that works, but I, for one, am not
> completely convinced that the first way shouldn't work.
> Why should someone be forced to type the first "\\",
> especially since that might change on a per-os basis?

Because C:Documets....

is a perfectly valid path(*) and if join() always put a \\ after 
the drive letter you would not be able to create a relative path 
on another disk!

If you want the path to be absolute you need to make it so.


(*)For those not accustomed to DOS and its peculiarities, 
the OS stores the current location *per disk*, thus:

C:> cd WINDOWS\SYSTEM32
C:\WINDOWS\SYSTEM32> D:
D:> dir C:
....contents of WINDOWS\SYSTEM32 directory....
....

So although I am now in the root of D:, Windows knows that 
my last C: location was C:\WINDOWS\SYSTEM32 and when I ask 
for a dir listing thats the directory it tells me about.
And if I change back to the C: drive thats where it puts me.

D:> C:
C:\WINDOWS\SYSTEM32> CD D:\TEMP
C:\WINDOWS\SYSTEM32> D:
D:\TEMP>

Similarly if I CD on the D drive while located on C it does 
not move me into D: it simply changes the current D position, 
so that when I next move to D I move into the new position, 
not to root.

Thats why a relative path can begin with the drive letter!

Alan G.

From Michael.Dunn at mpi.nl  Fri Jan  9 05:33:08 2004
From: Michael.Dunn at mpi.nl (Michael Dunn)
Date: Fri Jan  9 05:33:16 2004
Subject: [Tutor] running an interactive program from a script
Message-ID: <Pine.GSO.4.55.0401091130230.2751@sun02.mpi.nl>

Hi Pythoneers,

I am working with an excellent series of (non-Python) programs for doing
cladistics called PHYLIP. For historical reasons these are run
interactively, with the user selecting settings to toggle from a prompt.
The little script below simulates the user experience of this:

###
#!/usr/bin/env python
# sample.py

prompt = """Settings:
 (F)loats: %(float)s
 Is (D)uck: %(duck)s
Enter F or D to change a setting, Q to quit
> """
settings = {'float':'Yes', 'duck':'No'}
toggle = {'Yes':'Maybe','Maybe':'No','No':'Yes'}
selection = ''

while selection.upper() != 'Q':
    selection = raw_input((prompt % settings))
    if selection.upper() == 'F':
        settings['float'] = toggle[settings['float']]
    if selection.upper() == 'D':
        settings['duck'] = toggle[settings['duck']]

print 'Settings are:', settings
###

The real PHYLIP programs will also  accept a text command file with
newline-delineated keystroke entries, e.g. from the command line it's
possible to run:
  sample.py < commands.txt > output
where commands.txt could contain something like:
"""
D
D
F
""".

This is obviously a pain for scripting -- you have to know how many
keystrokes necessary to toggle a value in advance, and if the options
change between versions you are lost. In the real PHYLIP programs there
are sometimes also some other messages you have to deal with (asking for
the names of input and output files etc -- all with quite regular
formats). I've been in contact with the author of the program, and it's
apparently too difficult/too much work to implement a change to the more
familiar command line style.

So my question: Is it possible to run a program like my sample.py using
a python script as a wrapper? I'd want to parse the prompt message after
each bit of input (prob. using a regex) and to carry on toggling things
until the values match the ones I had stored in a settings file. I think
I can handle the logic for toggling values and so forth, but I can't
work out how (or if it's possible)  to get python to interactively
'drive' another program. I know it would be a horrible hack -- I should
of course learn C and then fix the original programs -- but it's never
going to happen and the hack would solve my problems nicely. I've been
experimenting with the popen2 module, but I can't make it work. Is this
the right track? Any suggestions?

Thanks, Michael

From missive at hotmail.com  Fri Jan  9 07:22:18 2004
From: missive at hotmail.com (Lee Harr)
Date: Fri Jan  9 07:22:24 2004
Subject: [Tutor] Re: running an interactive program from a script
Message-ID: <BAY2-F105QVUyOyVe5r00004308@hotmail.com>

>I can handle the logic for toggling values and so forth, but I can't
>work out how (or if it's possible)  to get python to interactively
>'drive' another program. I know it would be a horrible hack -- I should
>of course learn C and then fix the original programs -- but it's never
>going to happen and the hack would solve my problems nicely. I've been
>experimenting with the popen2 module, but I can't make it work. Is this
>the right track? Any suggestions?


I expect that will work, or there is also a python expect module ... :o)

http://pexpect.sourceforge.net/

I have used that recently and much prefer it to the tcl expect, but mostly
just because I am much more familiar with python than tcl.

_________________________________________________________________
Protect your PC - get McAfee.com VirusScan Online 
http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963


From lbray_103 at yahoo.com  Fri Jan  9 10:23:43 2004
From: lbray_103 at yahoo.com (Monroe Compton)
Date: Fri Jan  9 10:23:52 2004
Subject: [Tutor] Profiling in Python
Message-ID: <20040109152343.87533.qmail@web60806.mail.yahoo.com>

I'm just wondering what is "profiling" and how do you do it in Python.  Any help is welcome.  Thanks in advance.
     rayshaun103


---------------------------------
Do you Yahoo!?
Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20040109/be237d11/attachment.html
From Christian.Wyglendowski at greenville.edu  Fri Jan  9 10:49:28 2004
From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski)
Date: Fri Jan  9 10:49:31 2004
Subject: [Tutor] Nine Language Performance Round-up: Benchmarking Math &
	File I/O
Message-ID: <CE1475C007B563499EDBF8CDA30AB45B0A3899@empex.greenville.edu>

I suppose that some of you might have looked at the article mentioned in
the subject line.  For those who haven't, the reviewer pits Python,
Python/Psycho, the .NET languages and Java against each other in math
and file I/O operations.  Here is a link to the article:
http://www.osnews.com/story.php?news_id=5602


In the mathematical operations benchmarks, Python does not fair so well
against the other languages.  I know that these sort of ops aren't
Python's strong suit, but I was interested to see if there was anyway to
speed up the stock Python performance in this test.  I only messed with
the integer math function. 

Here is a link to the python code used in the benchmark:
http://www.ocf.berkeley.edu/~cowell/research/benchmark/code/Benchmark.py

Here is my change to it:

def intArithmeticNew(intMax):

    startTime = time.clock()

    i = 1
    intResult = 1
    while i < intMax:
        intResult = intResult - i
        
        intResult = intResult + i
        
        intResult = intResult * i
        
        intResult = intResult / I
        ###########
        i = i + 4 # instead of doing an assignment for each operation,
we now simply do one assignment for all four
        ###########
    stopTime = time.clock()
    elapsedTime = (stopTime - startTime) * 1000 # convert from secs to
millisecs.
    print "Int arithmetic elapsed time:", elapsedTime, "ms with intMax
of", intMax
    print " i:", i
    print " intResult:", intResult
    return elapsedTime

Here are the results on my system running the origial code and my
modified code:
>>> Benchmark.intArithmetic(1000000000)
Int arithmetic elapsed time: 293486.648163 ms with intMax of 1000000000
 i: 1000000001
 intResult: 1
293486.64816338394
>>> Benchmark.intArithmeticNew(1000000000)
Int arithmetic elapsed time: 207132.665464 ms with intMax of 1000000000
 i: 1000000001
 intResult: 1
207132.66546446539

My change yielded close to a 30% speed increase.  I got the idea to
reduce the amount of assignments from a comment on the article.  What
other methods could be used to speed this up?

Christian
http://www.dowski.com

From magnus at thinkware.se  Fri Jan  9 12:56:59 2004
From: magnus at thinkware.se (Magnus Lycka)
Date: Fri Jan  9 12:57:06 2004
Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gQ29udmVydGluZyB0byBQREY=?=
Message-ID: <think001_3ffeeadfc57c4@webmail.thinkware.se>

> Danny was so right! This is a bug in PIL.
> I changed '/DctDecode' and '/DCTDecode' in PdfImagePlugin.py
> and it worked just fine!
> Thanks Danny and all you Python people.

Good. Don't forget to be a "good citizen" and report
the bug to the image-sig, or Fredrik Lundh or where
ever it's supposed to be reported.

-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se

From project5 at redrival.net  Fri Jan  9 13:11:21 2004
From: project5 at redrival.net (Andrei)
Date: Fri Jan  9 13:14:16 2004
Subject: [Tutor] Re: Python vs. C
References: <5.2.1.1.0.20040106204618.00b3a8b0@earthlink.net>
Message-ID: <1dcg3o1j1uwaw.1evlbnm8uzxvp.dlg@40tude.net>

Peter Jakubowicz wrote on Tue, 06 Jan 2004 20:55:06 -0800:

> this because my Python programs are getting bigger, and occasionally I 
> wonder if I want to learn C too. Plus, I've gotten to like programming 

Coming from Delphi, I thought I wanted to learn something lower-level and
more widespread. After doing a C tutorial, I ended up with Python which is
higher level and less widespread than Delphi (I think) - and stuck with it
:). Turns out I was actually looking for a language which is more
productive than Delphi and C is virtually contraproductive from my POV (my
taste doesn't include writing device drivers and OS kernels, so I'm OK
without C). BTW, a tiny little bit of C did stick around in my head and at
one point it proved to be handy, when I compiled GnuPlot on Windows and had
to modify a line of code or so :).

> enough that I learning another language would be fun. Or maybe I should 

Give it a go. If you don't like it, it won't cost you a lot, just a few
hours (or days) of wasted time. I see you're on Windows, so you can get a
very nice free IDE for C called Dev-C++ (look on Sourceforge). I'd also be
tempted to recommend Delphi (it's fast like C and low-level compared to
Python - it has static typing, machine-code compilation, pointers, OOP,
everything; Object Pascal doesn't *force* you to go extremely low level
like C does, but you can if you want to; OP is less hairy than C/C++ and
Delphi has extremely comfortable GUI development), but the free versions of
it are nowadays rather hard to find. Oh, and using Python for Delphi you
can use both at once! 
But either way, it's rather annoying if you're using such a low-level
language and you can't simply write MyList.sort() or MyDict['MyKey'].

> just work on making my Python code more efficient or whatever? Anyway, if 

Do you *need* the speed? If so, that's probably your best bet :).

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.


From vicki.stanfield at ROCHE.COM  Fri Jan  9 13:25:06 2004
From: vicki.stanfield at ROCHE.COM (Stanfield, Vicki {D167~Indianapolis})
Date: Fri Jan  9 13:27:01 2004
Subject: [Tutor] Re: Python vs. C
Message-ID: <CA3458C84C976E45B6372A6C14724C9F355EBE@ridmsem02.nala.roche.com>


Peter Jakubowicz wrote on Tue, 06 Jan 2004 20:55:06 -0800:

> this because my Python programs are getting bigger, and occasionally I
> wonder if I want to learn C too. Plus, I've gotten to like programming


I always advocate learning C. If nothing else, it teaches you how memory
management is accomplished which languages which manage memory for you
like Python do not teach. I recommend learning C, doing lots of mallocs
and the like to get the feel for them, doing a lot of pointer stuff for
the same reason, and then abandoning C for Python. If you ever need to
use C, you will have that experience, and MORE IMPORTANTLY, you will
understand the drawbacks and benefits of these features of C well enough
to know when they will be useful. If you have the time, experiment with
C.

--vicki 

From magnus at thinkware.se  Fri Jan  9 13:29:42 2004
From: magnus at thinkware.se (Magnus Lycka)
Date: Fri Jan  9 13:29:47 2004
Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gTmluZSBMYW5ndWFnZSBQZXJmb3JtYW5jZSBSb3VuZC11cDogQmVuY2htYXJraW5nIE1hdGggJiBGaWxlIEkvTw==?=
Message-ID: <think001_3ffeedcbe8467@webmail.thinkware.se>

> My change yielded close to a 30% speed increase.  I got the idea to
> reduce the amount of assignments from a comment on the article.  What
> other methods could be used to speed this up?

First of all, benchmarks of anything else but programs that
actually perform a time critical function that *you* really
need are rarely relevant. For instance, the graph in the
article shows Java as being much slower than the other
languages (except Python). But it's a sum of different
benchmarks designed and weighed arbitrarily by the author. 
If your application doesn't need trigonometry, but behaves
as the benchmark otherwise (very unlikely), java 1.4 is 
almost as fast as Visual C++, and beats everything else.

For 64 integer operations, Python converts to using slow
unlimited length integers if you use a 32 bit environment. 
Use a 64 bit OS and Python compiled to support that, and 
you'll see a big difference. (Does MS support any of those
platforms yet? Python certainly supports a few.)

Or see what happens if you need to use more than 64 bit
integers, maybe 128 bit integers. (Do the other languages 
support that at all?)

Another option could be to try pyrex. For "real" mathematical
applications, numerical python will often give you a big
advantage, but these benchmarks don't really reflect what
any real application would do.

The thing is, that many of the things you can write up in
for instance Python with Numerical Python in half an hour
would be so time consuming to write in C++, VB or C# that
no benchmark designer would ever try to do that. Instead,
they decide to do a test that is easier to perform, even if
it isn't very meaningful.


-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se

From magnus at thinkware.se  Fri Jan  9 14:02:05 2004
From: magnus at thinkware.se (Magnus Lycka)
Date: Fri Jan  9 14:02:12 2004
Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gUHJvZmlsaW5nIGluIFB5dGhvbg==?=
Message-ID: <think001_3ffef494e3667@webmail.thinkware.se>

> I'm just wondering what is "profiling" and how do you do it in Python.  Any help is welcome.  Thanks in advance.

Profiling is the process of determining how much
time is spent in different parts of your program
while it's running.

It is a very important part improving runtime
performance and understanding of the code.

It's very difficult to know where the bottlenecks
in code occur, and if 80% of the runtime is spent
in one particular routine, it's not possible to
improve performance more than 25% however much you
improve the rest of the program. You must improve
*this* routine (or call it less often).

Besides seeing the time spent in different parts of
the code, seeing how many times various routines are
called might be an important eye opener for the
programmer. It will often make you understand that
you aren't doing things the right way, or that the
usage pattern is different than you thought.

An example (not very meaningful) session could look
like this:

>>> import profile
>>> import calendar
>>> profile.run("calendar.calendar(2004)")
         149 function calls in 0.358 CPU seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.012    0.012 <string>:1(?)
       12    0.001    0.000    0.001    0.000 calendar.py:105(monthcalendar)
       62    0.002    0.000    0.002    0.000 calendar.py:124(week)
        1    0.000    0.000    0.002    0.002 calendar.py:135(weekheader)
       27    0.000    0.000    0.000    0.000 calendar.py:169(format3cstring)
        1    0.002    0.002    0.012    0.012 calendar.py:178(calendar)
       12    0.004    0.000    0.004    0.000 calendar.py:34(__getitem__)
        7    0.002    0.000    0.002    0.000 calendar.py:47(__getitem__)
        1    0.000    0.000    0.000    0.000 calendar.py:80(isleap)
       12    0.000    0.000    0.000    0.000 calendar.py:91(weekday)
       12    0.000    0.000    0.000    0.000 calendar.py:96(monthrange)
        1    0.347    0.347    0.358    0.358 profile:0(calendar.calendar(2004))
        0    0.000             0.000          profile:0(profiler)


For more info look here:
http://www.python.org/doc/current/lib/profile-instant.html

There are actually two profilers now. The old one (profile)
is written in Python. The new one (hotshot) is written in
C, and it's (as one might expect) much faster, i.e. it doesn't
slow down program execution nearly as much. On the other hand
it collects much more data, so the analysis takes longer. (At
least reading in the profiling data. In the typical case, you
would not analyze righth away like above, but rather store the
measurement results in a file, and analyze that after the
program run. I sometimes set a command line switch in python
programs, and ask users to start the program in profiling
mode and do whatever they feel is too slow if they have
complained about performance. Then I ask them to send me the
generated profiling file, and I can analyze why their runs
go slowly. I often lack enough data to run into trouble, or
I might not use the program in exactly the same way, which
might give me a very different execution time.)

For an example of using hotshot, see
http://www.python.org/doc/current/lib/hotshot-example.html

-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se

From dyoo at hkn.eecs.berkeley.edu  Fri Jan  9 14:02:27 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri Jan  9 14:02:32 2004
Subject: [Tutor] Re: Python vs. C  [learning C?]
In-Reply-To: <CA3458C84C976E45B6372A6C14724C9F355EBE@ridmsem02.nala.roche.com>
Message-ID: <Pine.LNX.4.44.0401091047050.14414-100000@hkn.eecs.berkeley.edu>



On Fri, 9 Jan 2004, Stanfield, Vicki {D167~Indianapolis} wrote:

> Peter Jakubowicz wrote on Tue, 06 Jan 2004 20:55:06 -0800:
>
> > this because my Python programs are getting bigger, and occasionally I
> > wonder if I want to learn C too. Plus, I've gotten to like programming
>
> I always advocate learning C. If nothing else, it teaches you how memory
> management is accomplished which languages which manage memory for you
> like Python do not teach. I recommend learning C, doing lots of mallocs
> and the like to get the feel for them, doing a lot of pointer stuff for
> the same reason, and then abandoning C for Python.

Hi Vicki,

I wouldn't totally abandon C.  It does come in handy every once in a
while.  I know I wrote a lot of stuff about how C is unsafe --- but
despite that, it's still a valuable language to learn.  If anything, it
helps one to appreciate how amazingly precise and simple our computers
are, and how vaguely fuzzy we humans are. *grin*



Peter, if you want to learn more about C, you really will want to look at
Kernighan and Richie's classic book, "The C Programming Language".

    http://cm.bell-labs.com/cm/cs/cbook/

That book is a classic in the best sense of the word.  I have no qualms
recommending this to any programmer who wants to learn C... and even those
who don't plan to program in C should consider browsing through it at
least once.  The tutorial presentation they give in the book is excellent,
and the content is all solid stuff.

Best of all, the book is nice and thin.


Good luck to you!


From dyoo at hkn.eecs.berkeley.edu  Fri Jan  9 14:16:53 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri Jan  9 14:17:04 2004
Subject: [Tutor] memory leaks
In-Reply-To: <Pine.LNX.4.44.0401081432190.1016-100000@ouhep1.nhn.ou.edu>
Message-ID: <Pine.LNX.4.44.0401091105130.14414-100000@hkn.eecs.berkeley.edu>



On Thu, 8 Jan 2004, Isaac Hall wrote:

> I was wondering if any of you might know what kinds of tools are
> available for checking large python programs for memory leaks.  I have a
> program that seems to have developed one recently, and it is so large
> that I am having difficulty tracking it down.  thanks in advance.

Hi Issac,

Jeremy Hilton wrote a small article summarizing techniques one can use for
looking at leaks:

    http://www.python.org/~jeremy/weblog/030410.html


Python 2.3 has a tool called 'combinerefs.py' in the Tools/Scripts
directory of the Python source distribution. That tool dumps out all
'live' objects, as well as their reference counts, at the end of a
program's execution --- it may help you track down exactly what is staying
alive.

I'm not sure if many of us have had experience with combinerefs.py though;
has anyone played with it before?



Good luck!


From vicki at thepenguin.org  Fri Jan  9 14:09:37 2004
From: vicki at thepenguin.org (Vicki Stanfield)
Date: Fri Jan  9 14:17:09 2004
Subject: [Tutor] Re: Python vs. C  [learning C?]
In-Reply-To: <Pine.LNX.4.44.0401091047050.14414-100000@hkn.eecs.berkeley.edu>
References: <CA3458C84C976E45B6372A6C14724C9F355EBE@ridmsem02.nala.roche.com> 
	<Pine.LNX.4.44.0401091047050.14414-100000@hkn.eecs.berkeley.edu>
Message-ID: <32625.206.53.226.235.1073675377.squirrel@www.thepenguin.org>

>
>
> On Fri, 9 Jan 2004, Stanfield, Vicki {D167~Indianapolis} wrote:
>
>> Peter Jakubowicz wrote on Tue, 06 Jan 2004 20:55:06 -0800:
>>
>> > this because my Python programs are getting bigger, and occasionally I
>> > wonder if I want to learn C too. Plus, I've gotten to like programming
>>
>> I always advocate learning C. If nothing else, it teaches you how memory
>> management is accomplished which languages which manage memory for you
>> like Python do not teach. I recommend learning C, doing lots of mallocs
>> and the like to get the feel for them, doing a lot of pointer stuff for
>> the same reason, and then abandoning C for Python.
>
> Hi Vicki,
>
> I wouldn't totally abandon C.  It does come in handy every once in a
> while.  I know I wrote a lot of stuff about how C is unsafe --- but
> despite that, it's still a valuable language to learn.  If anything, it
> helps one to appreciate how amazingly precise and simple our computers
> are, and how vaguely fuzzy we humans are. *grin*

Yes, I didn't write that well. I do a lot of C vocationally but less
avocationally. My point was, as you said, that C is a very valuable
jumping off point. I am really disappointed with teaching someone the easy
way first. I hated it when many schools stopped teaching programming in a
UNIX environment in favor of the "everything is in the compiler" method. I
think it is invaluable to get on a command line and type out your C
compile statements complete with including Libs and headers. After you
know that stuff, sure, use a compiler where it is largely obfuscated
behind a pretty gui. But know what the compiler is doing and where it
expects the lib and header files to be! I recommend C on a Linux box as a
first step to learning programming.

--vicki

From dyoo at hkn.eecs.berkeley.edu  Fri Jan  9 14:21:20 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri Jan  9 14:21:26 2004
Subject: [Tutor] p2exe and icons
In-Reply-To: <3FFD9D0E.7090301@occamnetworks.com>
Message-ID: <Pine.LNX.4.44.0401091116590.14414-100000@hkn.eecs.berkeley.edu>



On Thu, 8 Jan 2004, Trent Brown wrote:

> thanks for replying. I'm actually running 2000 which is perplexing (I
> had the same thought also)

Hi Trent,


Hmmm.... I have to admit that I'm stumped then.  I'm not quite sure what
to suggest next.


I think it's time you talk with the pygame folks!  *grin*

    http://pygame.org/info.shtml#maillist

They can probably suggest other things to check for.  Make sure to tell
them what version of Pygame you're running, so that the folks there can
try duplicating the problem.


Good luck to you!


From dyoo at hkn.eecs.berkeley.edu  Fri Jan  9 14:28:43 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri Jan  9 14:28:48 2004
Subject: [Tutor] p2exe and icons
In-Reply-To: <Pine.LNX.4.44.0401091116590.14414-100000@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.44.0401091123390.14414-100000@hkn.eecs.berkeley.edu>



On Fri, 9 Jan 2004, Danny Yoo wrote:

>
>
> On Thu, 8 Jan 2004, Trent Brown wrote:
>
> > thanks for replying. I'm actually running 2000 which is perplexing (I
> > had the same thought also)
>
> Hi Trent,
>
>
> Hmmm.... I have to admit that I'm stumped then.  I'm not quite sure what
> to suggest next.
>
>
> I think it's time you talk with the pygame folks!  *grin*


Hi Trent,

Oh my gosh, I screwed that up big time.  I mean py2exe, not pygame.  I'm
having a bad day today.


I just noticed that in the original call to py2exe, the --icon option is
missing an argument:


###
C:\Data\Python\Compile\Demo1a>python setup.py py2exe --icon
usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
   or: setup.py --help [cmd1 cmd2 ...]
   or: setup.py --help-commands
   or: setup.py cmd --help

error: option --icon not recognized
###



Do you get an error if you do:

    C:\Data\Python\Compile\Demo1a>python setup.py py2exe --icon icon.ico

from the command line?  Also, what version of py2exe are you running?



Again, my apologies.  I need to get my morning coffee.


From comber at cix.co.uk  Thu Jan  8 10:46:03 2004
From: comber at cix.co.uk (Edward Comber)
Date: Fri Jan  9 14:31:06 2004
Subject: [Tutor] Dialog box under windows
In-Reply-To: <20040108153453.GS22796@niof.net>
Message-ID: <BEEOLJNPLOPIONOMGLAAMECGCKAA.comber@cix.co.uk>

Thanks very much for that, I'll get stuck into it. At the moment it opens a
Tk main app screen that can't be closed but I'll persist.

Thanks for your help.

Eddie.

-----Original Message-----
From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On
Behalf Of Rick Pasotto
Sent: 08 January 2004 15:35
To: tutor@python.org
Subject: Re: [Tutor] Dialog box under windows


On Thu, Jan 08, 2004 at 01:59:13PM -0000, Eddie Comber wrote:
> Would anyone have a working piece of code that can open a simple
> dialog bow in Windows?
>
> I have a background Python app running and I just want to inform the
> user when particular events occur.
>
> It would be ideal if the box showed a few lines of information and an
> #'OK' button.

import tkMessageBox
tkMessageBox.showinfo(title='window title',
	message='put your message text here')

> I have the Mark Hammond's win32all stuff but while the function calls
> are there, the stuff like the windows API constants that are needed
> for e.g. the style of the box etc.

tkMessageBox contains:

def showinfo(title=None, message=None, **options):
    "Show an info message"
    return _show(title, message, INFO, OK, **options)

def showwarning(title=None, message=None, **options):
    "Show a warning message"
    return _show(title, message, WARNING, OK, **options)

def showerror(title=None, message=None, **options):
    "Show an error message"
    return _show(title, message, ERROR, OK, **options)

def askquestion(title=None, message=None, **options):
    "Ask a question"
    return _show(title, message, QUESTION, YESNO, **options)

def askokcancel(title=None, message=None, **options):
    "Ask if operation should proceed; return true if the answer is ok"
    s = _show(title, message, QUESTION, OKCANCEL, **options)
    return s == OK

def askyesno(title=None, message=None, **options):
    "Ask a question; return true if the answer is yes"
    s = _show(title, message, QUESTION, YESNO, **options)
    return s == YES

def askretrycancel(title=None, message=None, **options):
    "Ask if operation should be retried; return true if the answer is yes"
    s = _show(title, message, WARNING, RETRYCANCEL, **options)
    return s == RETRY

--
"Politics has always been the institutionalized and established way
 in which some men have exercised the power to live off the output
 of other men." -- Karl Hess
    Rick Pasotto    rick@niof.net    http://www.niof.net

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


From comber at cix.co.uk  Fri Jan  9 03:18:48 2004
From: comber at cix.co.uk (Edward Comber)
Date: Fri Jan  9 14:31:10 2004
Subject: [Tutor] Dialog box under windows
In-Reply-To: <010820041743.27026.6f0a@att.net>
Message-ID: <BEEOLJNPLOPIONOMGLAAIECMCKAA.comber@cix.co.uk>

Spot on, thanks very much.
Eddie.

-----Original Message-----
From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On
Behalf Of m.evanetich@att.net
Sent: 08 January 2004 17:43
To: tutor@python.org
Subject: Re: [Tutor] Dialog box under windows


>
> On Thu, Jan 08, 2004 at 03:46:03PM -0000, Edward Comber wrote:
> > Thanks very much for that, I'll get stuck into it. At the moment it
> > opens a Tk main app screen that can't be closed but I'll persist.
>
> Not if you already have a main window open. It's not meant to be used
> standalone but as part of an application.
>
I dealt with this, thanks to suggestions on this list by writing my own
little modeule that calls these TK dialogs and withdraws the top level main
app.  Since I use these things in scripts, that seems to work pretty well.
Here is an example:

import Tkinter
import tkMessageBox
def InfoBox(Title=None, Message=None):

    root =Tkinter.Tk()
    root.withdraw()     # Prevent spurious root window from showing
    message = tkMessageBox.showinfo(title=Title, message=Message)
    root.destroy()
    return message

--
Best wishes,
mark

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


From graumann at caltech.edu  Wed Jan  7 22:46:13 2004
From: graumann at caltech.edu (Johannes Graumann)
Date: Fri Jan  9 14:31:42 2004
Subject: [Tutor] re.match enigma
Message-ID: <20040107194613.17c370e0.graumann@caltech.edu>

Hello,

Wrote this snippet:

for counter in range(0,len(ms2_data[spectrum]['spectrum'])):
	try:
		re.match(r"^[\d\.]+",spectrum_data)
	except: 
		spectrum_data = \LINEBREAK
string.join(ms2_data[spectrum]['spectrum'][counter],'|')			else:	
		spectrum_data = \LINEBREAK
string.join([spectrum_data,string.join(ms2_data[spectrum]['spectrum'][c
ounter],'|')],'#')

Which is supposed to give me a data string, where members of a pair
(which originally come from a group) are separated by '|' and subsequent
pairs are delimited by '#'.

This does what I want UNLESS the 'spectrum_data' variable is emptied to 
spectrum_data =''
somewhere further on in the 'for counter' loop. In this case no except
occurs, even though 'spectrum_data' does neither start with a digit (\d)
nor with a comma - it's empty!

What am I doing?

Confused, Joh


From firephreek at earthlink.net  Fri Jan  9 14:22:41 2004
From: firephreek at earthlink.net (firephreek)
Date: Fri Jan  9 14:31:46 2004
Subject: [Tutor] quicker .strip?
Message-ID: <005701c3d6e5$f3e98c50$6f01010a@Rachel>

Hey, I'm brand spanking new to python, but I'm loving it.  I've begun
writing my first program that will run as a temperature
monitor/recorder.  I'm keeping track of unit IP's in a mysql database,
and I've written a function to pull them out, problem is when I retrieve
my 'list' of IP's from the databse, I get the info as a list, with each
IP surrounded by ( and "  i.e. (("10.1.1.205"),("10.1.1.206"))  and I'm
using strip() several times to get rid of the excess so that I can
re-use the IP address when gathering my data.  Here's the code, I hope
this all makes sense.  
 
## Setup MySQL connection:
conn=MySQLdb.connect(host=SQLHOST, user=SQLUSER, db=SQLDATA
passwd=SQLPASS)    
cursor=conn.cursor()    ## Setup MySQL cursor
cursor.execute("SELECT * FROM ip")  ## My list of IP address where my
devices are located
ip=cursor.fetchall()
## At this point ip looks like this: (("10.1.1.205"),("10.1.1.206"))
for x in range(len(ip)):  
        alpha=IP_strip(str(ip[x])) 
        config=getConfig(alpha)  ##Custom function that uses httplib to
get a page from my device over the network.

def IP_strip(ip):
    alpha=string.strip(ip, ")")
    alpha=string.strip(alpha, "(")
    alpha=string.strip(alpha, ",")
    alpha=string.strip(alpha,"'")
    return alpha
 
I'm wondering if there's any functions/methods that will strip the info
in fewer lines.  Or if there's another way of retrieving my information
so that I won't have to strip it.
 
-Stryder
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20040109/77bec88b/attachment.html
From isrgish at fusemail.com  Fri Jan  9 14:41:39 2004
From: isrgish at fusemail.com (Isr Gish)
Date: Fri Jan  9 14:41:46 2004
Subject: [Tutor] Time - Less then a second
Message-ID: <E1Af2Vj-000KE0-IC@fuse1.fusemail.net>

Thanks for the response.

exnihilo@myrealbox.com wrote:  
   >The following little snippet illustrates how time.clock() works. I've 
   >never used time.time() before though.
   >
   > >>> import random, time
   > >>> def timeSort(l):
   >	start = time.clock()
   >	l.sort()
   >	print "Sort Time:", (time.clock() - start) * 1000, "milliseconds"
  >	
   > >>> randList = [random.random() for i in range(100000)]
   > >>> timeSort(randList)
   >Sort Time: 190.0 milliseconds

My problem is that on my CE device I only get seconds, nothing less. TheforeI'm looking for an alternative.

-------
Isr Gish


From missive at hotmail.com  Fri Jan  9 14:57:53 2004
From: missive at hotmail.com (Lee Harr)
Date: Fri Jan  9 14:57:57 2004
Subject: [Tutor] Re: re.match enigma
Message-ID: <BAY2-F137fnp3eEHJtf00044d58@hotmail.com>

for counter in range(0, len(ms2_data[spectrum]['spectrum'])):
    try:
        re.match(r"^[\d\.]+", spectrum_data)
    except:
        spectrum_data = string.join(
                           ms2_data[spectrum]['spectrum'][counter], '|')
    else:
        spectrum_data = string.join(
                                        [spectrum_data, string.join(
                 ms2_data[spectrum]['spectrum'][counter], '|')], '#')



Your function came through pretty garbled.  Above is how I
interpreted it...

A few things:

Try catching only the exception you believe you will throw, instead
of any possible exception ... you never know if you might have some
other error in there (even just a simple syntax error)

It might be clearer if you save the pieces you want to join in to
temporary variables. That way you can print them out as you go
also to see what exactly is happening.

Are you doing this just so you don't have to initialize spectrum_data?
This whole construction seems strange to me ... especially how you
do not save or use the return value from the re.match()

_________________________________________________________________
Protect your PC - get McAfee.com VirusScan Online 
http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963


From project5 at redrival.net  Fri Jan  9 15:05:58 2004
From: project5 at redrival.net (Andrei)
Date: Fri Jan  9 15:08:52 2004
Subject: [Tutor] Re: quicker .strip?
References: <005701c3d6e5$f3e98c50$6f01010a@Rachel>
Message-ID: <18hxxajoduwv$.dnt5fas83a1g.dlg@40tude.net>

firephreek wrote on Fri, 9 Jan 2004 12:22:41 -0700:

> Hey, I'm brand spanking new to python, but I'm loving it.  I've begun
> writing my first program that will run as a temperature
> monitor/recorder.  I'm keeping track of unit IP's in a mysql database,
> and I've written a function to pull them out, problem is when I retrieve
> my 'list' of IP's from the databse, I get the info as a list, with each
> IP surrounded by ( and "  i.e. (("10.1.1.205"),("10.1.1.206"))  and I'm
> using strip() several times to get rid of the excess so that I can
> re-use the IP address when gathering my data.  Here's the code, I hope
> this all makes sense.  

I'm not sure I understand it correctly. Is ip a string? If it doesn't, my
reply won't make sense :).

Now that string looks just like Python code, doesn't it? If you just eval()
such a structure, it should automatically be turned into a tuple of tuples
in one line of code.

> I'm wondering if there's any functions/methods that will strip the info

The other solution is to use split() to split at '"),("' - this will split
all but the first and last IP in the resulting list. Then strip the leading
'(("' of the first IP and the trailing '"))' in the last IP of the
resulting list. It's a few extra lines of code.

> in fewer lines.  Or if there's another way of retrieving my information

I don't know more about this, but the options above should be enough even
if there is no smarter way of getting the data.

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.


From speno at isc.upenn.edu  Fri Jan  9 15:13:54 2004
From: speno at isc.upenn.edu (John P Speno)
Date: Fri Jan  9 15:14:04 2004
Subject: [Tutor] quicker .strip?
In-Reply-To: <005701c3d6e5$f3e98c50$6f01010a@Rachel>
References: <005701c3d6e5$f3e98c50$6f01010a@Rachel>
Message-ID: <20040109201354.GA6199@isc.upenn.edu>

On Fri, Jan 09, 2004 at 12:22:41PM -0700, firephreek wrote:
> ip=cursor.fetchall()
> ## At this point ip looks like this: (("10.1.1.205"),("10.1.1.206"))
> for x in range(len(ip)):  
>         alpha=IP_strip(str(ip[x])) 
>         config=getConfig(alpha)  ##Custom function that uses httplib to
>  
> I'm wondering if there's any functions/methods that will strip the info
> in fewer lines.  Or if there's another way of retrieving my information
> so that I won't have to strip it.

MySQLdb is returning to you a tuple of tuples, not a string. Try something
like this:

ips = cursor.fetchall()
for ip in ips:
   print ip 

Does that help?

From pythontutor at venix.com  Fri Jan  9 15:17:48 2004
From: pythontutor at venix.com (Lloyd Kvam)
Date: Fri Jan  9 15:18:16 2004
Subject: [Tutor] quicker .strip?
In-Reply-To: <005701c3d6e5$f3e98c50$6f01010a@Rachel>
References: <005701c3d6e5$f3e98c50$6f01010a@Rachel>
Message-ID: <3FFF0C6C.7070309@venix.com>

fetchall returns a list of lists (well tuples, but you understand).
Effectively it's a matrix.  Your data looks a little funny because
each row is a single element.

I'd suggest:

ip = cursor.fetchall()
for x in ip:	# row by row
	for alpha in x:	# column by column
		config=getConfig(alpha)  ##Custom function that uses httplib to

There's no need to convert the row to a string and remove the characters
introduced by the conversion.  The IP address is already there as a string.

A cute coding trick for this case:

ip_list = zip(*cursor.fetchall())[0]
for ip in ip_list:
	config =getConfig(ip)

While we usually think of zip as peeling of list members in parallel it is
actually a matrix transpose function.  This converts the fetchall results
from a list of rows to a list of columns.  Your ip addresses are the first
(zeroth) column.

HTH

firephreek wrote:

> Hey, I'm brand spanking new to python, but I'm loving it.  I've begun 
> writing my first program that will run as a temperature 
> monitor/recorder.  I'm keeping track of unit IP's in a mysql database, 
> and I've written a function to pull them out, problem is when I retrieve 
> my 'list' of IP's from the databse, I get the info as a list, with each 
> IP surrounded by ( and "  i.e. (("10.1.1.205"),("10.1.1.206"))  and I'm 
> using strip() several times to get rid of the excess so that I can 
> re-use the IP address when gathering my data.  Here's the code, I hope 
> this all makes sense. 
>  
> ## Setup MySQL connection:
> conn=MySQLdb.connect(host=SQLHOST, user=SQLUSER, db=SQLDATA 
> passwd=SQLPASS)    
> cursor=conn.cursor()    ## Setup MySQL cursor
> cursor.execute("SELECT * FROM ip")  ## My list of IP address where my 
> devices are located
> ip=cursor.fetchall()
> ## At this point ip looks like this: (("10.1.1.205"),("10.1.1.206"))
> for x in range(len(ip)): 
>         alpha=IP_strip(str(ip[x])) 
>         config=getConfig(alpha)  ##Custom function that uses httplib to 
> get a page from my device over the network.
> def IP_strip(ip):
>     alpha=string.strip(ip, ")")
>     alpha=string.strip(alpha, "(")
>     alpha=string.strip(alpha, ",")
>     alpha=string.strip(alpha,"'")
>     return alpha
>  
> I'm wondering if there's any functions/methods that will strip the info 
> in fewer lines.  Or if there's another way of retrieving my information 
> so that I won't have to strip it.
>  
> -Stryder
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582


From missive at hotmail.com  Fri Jan  9 15:47:36 2004
From: missive at hotmail.com (Lee Harr)
Date: Fri Jan  9 15:47:52 2004
Subject: [Tutor] Re: quicker .strip?
Message-ID: <BAY2-F53n4TaSMWu1UM0001ff21@hotmail.com>

>I get the info as a list, with each
>IP surrounded by ( and "  i.e. (("10.1.1.205"),("10.1.1.206"))  and I'm
>using strip() several times to get rid of the excess so that I can
>re-use the IP address when gathering my data.


Not sure what you mean, exactly.
If I put what you wrote in to python, i get ...

>>>a=(("10.1.1.205"),("10.1.1.206"))
>>>a
('10.1.1.205', '10.1.1.206')


Are they strings?  like ...

ips = ['("10.1.1.205")', '("10.1.1.206")']
?

In that case, I would probably do something like ...

>>>stripped = [ip[2:-2] for ip in ips]
>>>stripped
['10.1.1.205', '10.1.1.206']

_________________________________________________________________
Help STOP SPAM with the new MSN 8 and get 2 months FREE*  
http://join.msn.com/?page=features/junkmail


From pythontutor at venix.com  Fri Jan  9 15:59:01 2004
From: pythontutor at venix.com (Lloyd Kvam)
Date: Fri Jan  9 15:59:31 2004
Subject: [Tutor] Nine Language Performance Round-up: Benchmarking Math
	&	File I/O
In-Reply-To: <CE1475C007B563499EDBF8CDA30AB45B0A3899@empex.greenville.edu>
References: <CE1475C007B563499EDBF8CDA30AB45B0A3899@empex.greenville.edu>
Message-ID: <3FFF1615.9050407@venix.com>

Your change "breaks" the benchmark because now i increments by 4.  The
skipped values are not used, unlike in the "benchmark".

Unfortunately, the benchmark is simply stress testing pythons garbage
collection capability, not python's arithmetic capabilities.

Christian Wyglendowski wrote:

> I suppose that some of you might have looked at the article mentioned in
> the subject line.  For those who haven't, the reviewer pits Python,
> Python/Psycho, the .NET languages and Java against each other in math
> and file I/O operations.  Here is a link to the article:
> http://www.osnews.com/story.php?news_id=5602
> 
> 
> In the mathematical operations benchmarks, Python does not fair so well
> against the other languages.  I know that these sort of ops aren't
> Python's strong suit, but I was interested to see if there was anyway to
> speed up the stock Python performance in this test.  I only messed with
> the integer math function. 
> 
> Here is a link to the python code used in the benchmark:
> http://www.ocf.berkeley.edu/~cowell/research/benchmark/code/Benchmark.py
> 
> Here is my change to it:
> 
> def intArithmeticNew(intMax):
> 
>     startTime = time.clock()
> 
>     i = 1
>     intResult = 1
>     while i < intMax:
>         intResult = intResult - i
>         
>         intResult = intResult + i
>         
>         intResult = intResult * i
>         
>         intResult = intResult / I
>         ###########
>         i = i + 4 # instead of doing an assignment for each operation,
> we now simply do one assignment for all four
>         ###########
>     stopTime = time.clock()
>     elapsedTime = (stopTime - startTime) * 1000 # convert from secs to
> millisecs.
>     print "Int arithmetic elapsed time:", elapsedTime, "ms with intMax
> of", intMax
>     print " i:", i
>     print " intResult:", intResult
>     return elapsedTime
> 
> Here are the results on my system running the origial code and my
> modified code:
> 
>>>>Benchmark.intArithmetic(1000000000)
> 
> Int arithmetic elapsed time: 293486.648163 ms with intMax of 1000000000
>  i: 1000000001
>  intResult: 1
> 293486.64816338394
> 
>>>>Benchmark.intArithmeticNew(1000000000)
> 
> Int arithmetic elapsed time: 207132.665464 ms with intMax of 1000000000
>  i: 1000000001
>  intResult: 1
> 207132.66546446539
> 
> My change yielded close to a 30% speed increase.  I got the idea to
> reduce the amount of assignments from a comment on the article.  What
> other methods could be used to speed this up?
> 
> Christian
> http://www.dowski.com
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582


From alan.gauld at blueyonder.co.uk  Fri Jan  9 16:23:51 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Fri Jan  9 16:23:21 2004
Subject: [Tutor] absolute locations
References: <002101c3d6d2$8dafa2c0$6401a8c0@phantomfiber.com>
Message-ID: <005b01c3d6f6$e10e3750$6401a8c0@xp>

Hi BLake,

> > If you want the path to be absolute you need to make it so.
> > Thats why a relative path can begin with the drive letter!
> 
> Ah, but that's not what your example showed.  D:\TEMP is an
> absolute path.  (It starts with a \ after the drive letter.)

Sure, But the significant part of that bit of the example 
was that I was setting the current location on the D drive 
while I was located on the C Drive - to show that DOS/Windows 
keeps track of current folder independently for each drive.

> I just tried "cd c:windows" followed by "cd c:system32", and
> it worked, so relative paths can begin with a drive letter,

Yes, because there is a separate current folder on each drive.
So if you are on the C: drive you can do

CD Windows
CD System32
DEL FOO.TXT

But to do the same if you were on the D drive you would need 
to do:

CD C:WIindows
CD C:System32
DEL C:foo.txt

But the important point here is that you did not need to change 
drive back to C: to change the realative path.

> back to my FreeBSD box, where there's only one filesystem,
> and everything makes sense.  ;)

The bit that doesn't make sense is having each drive be the 
root of its own filesystem, but once you've decided to do 
that the multiple path model is actually very good.

> Anyways, that was exactly the convincing explanation I needed.

Glad to help :-)

Alan g.

From Christian.Wyglendowski at greenville.edu  Fri Jan  9 16:56:42 2004
From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski)
Date: Fri Jan  9 16:57:06 2004
Subject: [Tutor] Nine Language Performance Round-up: Benchmarking Math &
	File I/O
Message-ID: <CE1475C007B563499EDBF8CDA30AB45B0A389A@empex.greenville.edu>

> -----Original Message-----
> 
> > My change yielded close to a 30% speed increase.  I got the idea to 
> > reduce the amount of assignments from a comment on the 
> article.  What 
> > other methods could be used to speed this up?
> 
> First of all, benchmarks of anything else but programs that 
> actually perform a time critical function that *you* really 
> need are rarely relevant. 

Agreed.  I was just trying to experiment to see what could be done to
speed it up a bit.  But from what Lloyd pointed out, I cheated anyhow.
Oh well.  Thanks for the info about numeric and pyrex.  I'll have to
check those out.

Christian
http://www.dowski.com

From lumbricus at gmx.net  Fri Jan  9 17:03:22 2004
From: lumbricus at gmx.net (=?ISO-8859-1?Q?=22J=F6rg_W=F6lke=22?=)
Date: Fri Jan  9 17:03:36 2004
Subject: [Tutor] re.match enigma
References: <20040107194613.17c370e0.graumann@caltech.edu>
Message-ID: <25341.1073685802@www48.gmx.net>

Hallo!

> 	try:
> 		re.match(r"^[\d\.]+",spectrum_data)
> 	except: 
> 		spectrum_data = \LINEBREAK

[ snip ]

> somewhere further on in the 'for counter' loop. In this case no except
> occurs, even though 'spectrum_data' does neither start with a digit (\d)
> nor with a comma - it's empty!

A not matching regular expression is no exception, is ?t?
 
> What am I doing?
> 
> Confused, Joh

HTH und Gruss, J"o!


-- 
"Wir k?nnen alles sehen, was sich bewegt 
und wir k?nnen alles zerst?ren, was wir sehen."
         -- Richard Perle

+++ GMX - die erste Adresse f?r Mail, Message, More +++
Neu: Preissenkung f?r MMS und FreeMMS! http://www.gmx.net



From pythontutor at venix.com  Fri Jan  9 17:30:11 2004
From: pythontutor at venix.com (Lloyd Kvam)
Date: Fri Jan  9 17:30:31 2004
Subject: [Tutor] quicker .strip?
In-Reply-To: <008201c3d6fb$148f0b00$6f01010a@Rachel>
References: <008201c3d6fb$148f0b00$6f01010a@Rachel>
Message-ID: <3FFF2B73.4060502@venix.com>

Stryder wrote:

> Wow, completely surprised by the quick reply, thanks all!
> 
(snipped)
> Why the * with zip though?  It seems to be necessary to achieve the
> formatting I want, but I didn't notice any direct reference to it in the
> python23 doc.
> 
> -Stryder

zip is written to get multiple arguments, each of which is a sequence, e.g.:
	zip( (1,2,3), (4,5,6), (7,8,9) )

fetchall would return the above data like so:
	( (1,2,3), (4,5,6), (7,8,9) )
embedded in a tuple.

Python as some alternative syntax for passing parameters to functions.  If
you have a tuple that contains the positional arguments for a function, passing
the tuple with a preceding * causes the contents of the tuple to be mapped into
the positional args.

Similarly a dictionary passed with ** preceding it will map its contents to the
keyword parameters of a function.

These conventions allow you to easily program cases where the arguments for
functions originate in less conventional ways - such as you've just encountered
with fetchall and zip.

> 
> -----Original Message-----
> From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On
> Behalf Of Lloyd Kvam
> Sent: Friday, January 09, 2004 1:18 PM
> To: firephreek
> Cc: tutor@python.org
> Subject: Re: [Tutor] quicker .strip?
> 
> 
> fetchall returns a list of lists (well tuples, but you understand).
> Effectively it's a matrix.  Your data looks a little funny because each
> row is a single element.
> 
> I'd suggest:
> 
> ip = cursor.fetchall()
> for x in ip:	# row by row
> 	for alpha in x:	# column by column
> 		config=getConfig(alpha)  ##Custom function that uses
> httplib to
> 
> There's no need to convert the row to a string and remove the characters
> introduced by the conversion.  The IP address is already there as a
> string.
> 
> A cute coding trick for this case:
> 
> ip_list = zip(*cursor.fetchall())[0]
> for ip in ip_list:
> 	config =getConfig(ip)
> 
> While we usually think of zip as peeling of list members in parallel it
> is actually a matrix transpose function.  This converts the fetchall
> results from a list of rows to a list of columns.  Your ip addresses are
> the first
> (zeroth) column.
> 
> HTH
> 
> 
> Lloyd Kvam
> Venix Corp.
> 1 Court Street, Suite 378
> Lebanon, NH 03766-1358
> 
> voice:	603-653-8139
> fax:	801-459-9582
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582


From choncho101 at radio.fm  Fri Jan  9 19:34:46 2004
From: choncho101 at radio.fm (antonio salgado)
Date: Fri Jan  9 19:34:56 2004
Subject: [Tutor] IDLE question
Message-ID: <20040110003446.1015E393C@sitemail.everyone.net>

Hi there to all. I;m new to programming and new to Python, a friend of mine recommended me to start to learn whit this.
I want to know if when writting an instruction and get an error message the IDLE gets you to "another sentence" starting with the ">>>" you have to write everything all over again or if you can keep going whit the things you were doing?
I was copying the "Animals" script to start.
thanks for your time and understanding. I can't get any info on that, so I ask you all.
thank you again
P.S. any tips on self learning?

_____________________________________________________________
Why Pay $35 for a .COM, .NET or .ORG Web Address? iDotz.Net offers Cool Domains @ Great Prices! Starting @ $8.75 Go: http://www.idotz.net

From birdiepage at ciudad.com.ar  Fri Jan  9 20:37:06 2004
From: birdiepage at ciudad.com.ar (Gustavo Campanelli)
Date: Fri Jan  9 20:47:41 2004
Subject: [Tutor] IDLE question
In-Reply-To: <20040110003446.1015E393C@sitemail.everyone.net>
References: <20040110003446.1015E393C@sitemail.everyone.net>
Message-ID: <3FFF5742.8030304@ciudad.com.ar>

antonio salgado wrote:

>Hi there to all. I;m new to programming and new to Python, a friend of mine recommended me to start to learn whit this.
>I want to know if when writting an instruction and get an error message the IDLE gets you to "another sentence" starting with the ">>>" you have to write everything all over again or if you can keep going whit the things you were doing?
>I was copying the "Animals" script to start.
>thanks for your time and understanding. I can't get any info on that, so I ask you all.
>thank you again
>P.S. any tips on self learning?
>

Instead of using a comand line interpreter to test a full script and 
then play a little with the code to get a better hang of it, you should 
make a new empty text file with .py extension (this goes a little 
different for Linux people, who need a first line in that file to tell 
Bash what to use to execute the code, as with any Linux script) and type 
your script there. After that, double click on it and it executes. You 
can even use IDLE, PythonWin, or any other IDE/Editor to have sintax 
highlighting, object methods dictionaries, and a lot of little extras, 
but the simple notepad that comes with windows is enough to do it. The 
advantages of this is that you have the code for reusing without 
retyping, and can copy and paste code in websites, mailing lists and 
other python programs with almost no effort at all.

Gedece, still a python newbie

From credo2004 at fmail.co.uk  Sat Jan 10 04:47:25 2004
From: credo2004 at fmail.co.uk (credo)
Date: Sat Jan 10 04:47:31 2004
Subject: [Tutor] IDLE question
In-Reply-To: <3FFF5742.8030304@ciudad.com.ar>
References: <20040110003446.1015E393C@sitemail.everyone.net>
	<3FFF5742.8030304@ciudad.com.ar>
Message-ID: <20040110094725.922614576E@server1.messagingengine.com>


On Fri, 09 Jan 2004 22:37:06 -0300, "Gustavo Campanelli"
<birdiepage@ciudad.com.ar> said:
> antonio salgado wrote:
> 
> >Hi there to all. I;m new to programming and new to Python, a friend of mine recommended me to start to learn whit this.
> >I want to know if when writting an instruction and get an error message the IDLE gets you to "another sentence" starting with the ">>>" you have to write everything all over again or if you can keep going whit the things you were doing?
> >I was copying the "Animals" script to start.
> >thanks for your time and understanding. I can't get any info on that, so I ask you all.
> >thank you again
> >P.S. any tips on self learning?
> >
 
> this goes a little 
> different for Linux people, who need a first line in that file to tell 
> Bash what to use to execute the code, as with any Linux script

For linux people just add:

#! /usr/bin/env python

to the top of your python script (myprogram.py) and remember to chmod to
make the script executable
(chmod 744 myprogram.py)

then simply type the command at the shell and it'll run. 

Alternatively you could simply run the script without all that by typing
this at the shell: 
python myprogram.py

If youre gonna use IDLE. Its easier to goto File -> New. Type your
program out on that page, and save. Then to run simply goto Run -> Run
Module. This should cause the interpreter to jump up and run your prog :)

The interpreter is a great tool for trying out code fragments to see if
they function, once they do, then you can add them to your actual script.
For a while i didn't really understand the concept, (still a newbie
myself), but am learning to appreciate it now ;) Its not much use for
writing an entire program in though :D

If you do hit an error in the idle interpreter, in my experience, it
seems to hold any constants/variable values that you have created just
fine, so you may only need to redo the last bit of code. For example:

>>> 
>>> a = 1
>>> b = 2
>>> c = 3
>>> 
>>> print d

Traceback (most recent call last):
  File "<pyshell#6>", line 1, in -toplevel-
    print d
NameError: name 'd' is not defined
>>> print a,b,c
1 2 3
>>> 

As you can see, the values i defined for a,b,c were held despite the
error and i was able to continue just fine. :)

Hope some of the above helps and congrats on becoming a pythoneer :)

Credo







-- 
http://www.fastmail.fm - mmm... Fastmail...

From alan.gauld at blueyonder.co.uk  Sat Jan 10 16:26:20 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Sat Jan 10 16:25:18 2004
Subject: [Tutor] IDLE question
References: <20040110003446.1015E393C@sitemail.everyone.net>
Message-ID: <008f01c3d7c0$63c76350$6401a8c0@xp>


> Hi there to all. I;m new to programming and new to Python, 
> a friend of mine recommended me to start to learn whit this.

He (or she) is quite right! :-)

> I want to know if when writting an instruction and get an 
> error message the IDLE gets you to "another sentence" starting 
> with the ">>>" you have to write everything all over again 
> or if you can keep going whit the things you were doing?

It depends. In principle you will have all of the variables 
you have created still in place. And you can just retype the 
bit that failed, however in practice it can sometimes be hard 
to know whats still around. You can find out by just printing 
the values from the >>> prompt.

> I was copying the "Animals" script to start.

Sorry I don't know what you mean? Where is this animals 
script?

>  P.S. any tips on self learning?

First go through Danny Yoo's IDLE tutorial - found from the 
IDLE subsection of the Python website

Then go to the intro page for non programmers and pick one 
of the tutorials there. If you want to learn about 
programming per se then pick either How To Think Like a 
Computer Scientist, or my tutor. If you just want a fast 
track way to learn Python programming pick Josh Caglieri's(sp??) 
tutor. (There are a few more now and I can't comment on the others.)

Now try to write a program of your own, maybe one of the 
excercises on the Useless Python web site...

Once you have completed one of those move onto the official 
tutor that comes with Python, it will fill in the gaps left 
out by the beginers tutorials.

Now you should be ready to try something serious :-)

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld

From carroll at tjc.com  Sat Jan 10 17:11:30 2004
From: carroll at tjc.com (Terry Carroll)
Date: Sat Jan 10 17:11:35 2004
Subject: [Tutor] IDLE question
In-Reply-To: <008f01c3d7c0$63c76350$6401a8c0@xp>
Message-ID: <Pine.LNX.4.44.0401101410170.22140-100000@violet.rahul.net>

On Sat, 10 Jan 2004, Alan Gauld wrote:

> First go through Danny Yoo's IDLE tutorial - found from the 
> IDLE subsection of the Python website


Because the IDLE subsection is non-trivial to find from the front page or 
documentation pages on www.python.org, here's that URL:

http://www.python.org/idle/

-- 
Terry Carroll
Santa Clara, CA
carroll@tjc.com 


From cspears2002 at yahoo.com  Sun Jan 11 01:39:57 2004
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Sun Jan 11 01:40:02 2004
Subject: [Tutor] padding frames
Message-ID: <20040111063957.40234.qmail@web12405.mail.yahoo.com>

I'm trying to figure out way to use Python to pad
frames.  The name of the frames follow the this format
DSCN-2.JPG.  What would be the best strategy to use
Python to convert DSCN-2.JPG to DSCN-0002.JPG?

=====
"I'm the last person to pretend that I'm a radio.  I'd rather go out and be a color television set."
-David Bowie

"Who dares wins"
-British military motto

"Far more creativity, today, goes into the marketing of products than into the products themselves..."
-"Pattern Recognition" by William Gibson

From dyoo at hkn.eecs.berkeley.edu  Sun Jan 11 02:00:09 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun Jan 11 02:00:14 2004
Subject: [Tutor] padding frames
In-Reply-To: <20040111063957.40234.qmail@web12405.mail.yahoo.com>
Message-ID: <Pine.LNX.4.44.0401102255090.11405-100000@hkn.eecs.berkeley.edu>



On Sat, 10 Jan 2004, Christopher Spears wrote:

> I'm trying to figure out way to use Python to pad frames.  The name of
> the frames follow the this format DSCN-2.JPG.  What would be the best
> strategy to use Python to convert DSCN-2.JPG to DSCN-0002.JPG?

Hi Christopher,


There's a padding method in strings called 'zfill':

###
>>> '42'.zfill(4)
'0042'
###

So using zfill() on the numeric portion of each of your filenames should
do the trick.  Doing zfill() directly on filenames like:

###
>>> 'dsnc-2.jpg'.zfill(4)
'dsnc-2.jpg'
###

won't work.  But if we can somehow extract the numeric portion, then we
should be in business:

###
>>> 'dsnc-' + '2'.zfill(4) + '.jpg'
'dsnc-0002.jpg'
###


If you have more questions on this, please feel free to ask.  Good luck!


From cspears2002 at yahoo.com  Sun Jan 11 12:09:47 2004
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Sun Jan 11 12:09:51 2004
Subject: [Tutor] padding frames
Message-ID: <20040111170947.57594.qmail@web12403.mail.yahoo.com>

Hmmm...

zfill is a great tool, but how would I go about
isolating the part of file's name (DSCN-2.JPG) that I
would need?  My first idea is to somehow get the files
(or their names anyway) into a list as strings:

x = ['DSCN-2.JPG', 'DSCN-11.jpg', 'DSCN-101.JPG',
'DSCN-2302.JPG']

Then somehow strip off the parts I don't need and run
zfill on the numbers:

>>>'DSCN-' + x[0][5].zfill(4) + '.JPG'

Problem 1:
How do I go about putting the files into a list?  Do I
even need to put the files into a list?  After all, I
just want to change their names.  Do the files need to
be opened?

Problem 2:
How do I isolate the portion of the file name that I
need?

Any thoughts, strategies?

=====
"I'm the last person to pretend that I'm a radio.  I'd rather go out and be a color television set."
-David Bowie

"Who dares wins"
-British military motto

"Far more creativity, today, goes into the marketing of products than into the products themselves..."
-"Pattern Recognition" by William Gibson

From guillermo.fernandez at epfl.ch  Sun Jan 11 12:16:14 2004
From: guillermo.fernandez at epfl.ch (Guillermo Fernandez Castellanos)
Date: Sun Jan 11 12:16:22 2004
Subject: [Tutor] Memory problem
Message-ID: <400184DE.1040402@epfl.ch>

Hi,

First of all, happy year to all :-)

I'm playing with a database. I've done a user interface to this database 
that do several queries and print the results. The problem is that, this 
database being important (several hundred of thousands entries), each 
time I do a query the use of RAM increases very substancially (several 
dozens, sometimes a few undreds of Mb). I do something like:
dbresult=cursor.execute(query)

I was wondering if there is a way of making that memory 'free' 
afterwards. I mean to say to python somehow 'I don't need dbresult 
anymore, so you can forget it and give me back the memory'. I've tried 
the gc module, but it does not seem to answer my needs as it works with 
the number of objects refered, and not with the memory they use.

Thanks,

Guille


From david at graniteweb.com  Sun Jan 11 12:52:26 2004
From: david at graniteweb.com (David Rock)
Date: Sun Jan 11 13:00:05 2004
Subject: [Tutor] padding frames
In-Reply-To: <20040111170947.57594.qmail@web12403.mail.yahoo.com>
References: <20040111170947.57594.qmail@web12403.mail.yahoo.com>
Message-ID: <20040111175226.GA2126@wdfs.graniteweb.com>

* Christopher Spears <cspears2002@yahoo.com> [2004-01-11 09:09]:
> Problem 1:
> How do I go about putting the files into a list?  Do I
> even need to put the files into a list?  After all, I
> just want to change their names.  Do the files need to
> be opened?

You will want them in a list so you can iterate over that list and make
changes as necessary. The files do not need to be opened to change their
names. Look into some of the modules under os, like listdir, rename,
etc.

http://www.python.org/doc/current/lib/os-file-dir.html

> Problem 2:
> How do I isolate the portion of the file name that I
> need?

You could use the re module which will allow you to match a specific
pattern and split up the filename and store different pieces to be
recalled later.

http://www.python.org/doc/current/lib/node109.html


-- 
David Rock
david@graniteweb.com
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20040111/bd75cc17/attachment.bin
From littledanehren at yahoo.com  Sun Jan 11 14:29:47 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Sun Jan 11 14:29:52 2004
Subject: [Tutor] padding frames
In-Reply-To: <20040111170947.57594.qmail@web12403.mail.yahoo.com>
Message-ID: <20040111192947.66952.qmail@web41812.mail.yahoo.com>

Christopher Spears wrote:
> Hmmm...
> 
> zfill is a great tool, but how would I go about
> isolating the part of file's name (DSCN-2.JPG) that
> I
> would need?  My first idea is to somehow get the
> files
> (or their names anyway) into a list as strings:
> 
> x = ['DSCN-2.JPG', 'DSCN-11.jpg', 'DSCN-101.JPG',
> 'DSCN-2302.JPG']
> 
> Then somehow strip off the parts I don't need and
> run
> zfill on the numbers:
> 
> >>>'DSCN-' + x[0][5].zfill(4) + '.JPG'

If you wanted to let that work for all of them, you
should probably do:

>>> 'DSCN-' + x[0][5:-4].zfill(4) + '.JPG'

Is that what you wanted?

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes
http://hotjobs.sweepstakes.yahoo.com/signingbonus

From littledanehren at yahoo.com  Sun Jan 11 15:19:27 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Sun Jan 11 15:19:32 2004
Subject: [Tutor] Nine Language Performance Round-up: Benchmarking Math &
	File I/O
In-Reply-To: <CE1475C007B563499EDBF8CDA30AB45B0A3899@empex.greenville.edu>
Message-ID: <20040111201927.96969.qmail@web41810.mail.yahoo.com>

Christian Wyglendowski wrote:
> I suppose that some of you might have looked at the
> article mentioned in
> the subject line.  For those who haven't, the
> reviewer pits Python,
> Python/Psycho, the .NET languages and Java against
> each other in math
> and file I/O operations.  Here is a link to the
> article:
> http://www.osnews.com/story.php?news_id=5602
> 
> 
> In the mathematical operations benchmarks, Python
> does not fair so well
> against the other languages.  I know that these sort
> of ops aren't
> Python's strong suit, but I was interested to see if
> there was anyway to
> speed up the stock Python performance in this test. 
> I only messed with
> the integer math function. 
> 
> Here is a link to the python code used in the
> benchmark:
>
http://www.ocf.berkeley.edu/~cowell/research/benchmark/code/Benchmark.py
> 
> Here is my change to it:
> 
> def intArithmeticNew(intMax):
> 
>     startTime = time.clock()
> 
>     i = 1
>     intResult = 1
>     while i < intMax:
>         intResult = intResult - i
>         
>         intResult = intResult + i
>         
>         intResult = intResult * i
>         
>         intResult = intResult / I
>         ###########
>         i = i + 4 # instead of doing an assignment
> for each operation,
> we now simply do one assignment for all four
>         ###########
>     stopTime = time.clock()
>     elapsedTime = (stopTime - startTime) * 1000 #
> convert from secs to
> millisecs.
>     print "Int arithmetic elapsed time:",
> elapsedTime, "ms with intMax
> of", intMax
>     print " i:", i
>     print " intResult:", intResult
>     return elapsedTime
> 
> Here are the results on my system running the
> origial code and my
> modified code:
> >>> Benchmark.intArithmetic(1000000000)
> Int arithmetic elapsed time: 293486.648163 ms with
> intMax of 1000000000
>  i: 1000000001
>  intResult: 1
> 293486.64816338394
> >>> Benchmark.intArithmeticNew(1000000000)
> Int arithmetic elapsed time: 207132.665464 ms with
> intMax of 1000000000
>  i: 1000000001
>  intResult: 1
> 207132.66546446539
> 
> My change yielded close to a 30% speed increase.  I
> got the idea to
> reduce the amount of assignments from a comment on
> the article.  What
> other methods could be used to speed this up?
> 
> Christian
> http://www.dowski.com

Are you sure that does the same calculation? I would
have done it more like this to optimize it (this is
just the loop):

for i in range(1, intMax, step=4):
    intResult = ((((
        intResult - i)
        + (i+1))
        * (i+2))
        / (i+3))

Getting rid of temporary variables and using range()
should make for a speedup, but I haven't tested it.

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes
http://hotjobs.sweepstakes.yahoo.com/signingbonus

From cspears2002 at yahoo.com  Sun Jan 11 17:28:31 2004
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Sun Jan 11 17:28:36 2004
Subject: [Tutor] unpacking
Message-ID: <20040111222831.24443.qmail@web12402.mail.yahoo.com>

What is unpacking?

-Chris

=====
"I'm the last person to pretend that I'm a radio.  I'd rather go out and be a color television set."
-David Bowie

"Who dares wins"
-British military motto

"Far more creativity, today, goes into the marketing of products than into the products themselves..."
-"Pattern Recognition" by William Gibson

From hcohen2 at comcast.net  Sun Jan 11 18:19:46 2004
From: hcohen2 at comcast.net (hcohen2)
Date: Sun Jan 11 18:21:32 2004
Subject: [Tutor] Memory problem
In-Reply-To: <400184DE.1040402@epfl.ch>
References: <400184DE.1040402@epfl.ch>
Message-ID: <4001DA12.8090806@comcast.net>

Guillermo Fernandez Castellanos wrote:

> Hi,
>
> First of all, happy year to all :-)
>
> I'm playing with a database. I've done a user interface to this 
> database that do several queries and print the results. The problem is 
> that, this database being important (several hundred of thousands 
> entries), each time I do a query the use of RAM increases very 
> substancially (several dozens, sometimes a few undreds of Mb). I do 
> something like:
> dbresult=cursor.execute(query)
>
> I was wondering if there is a way of making that memory 'free' 
> afterwards. I mean to say to python somehow 'I don't need dbresult 
> anymore, so you can forget it and give me back the memory'. I've tried 
> the gc module, but it does not seem to answer my needs as it works 
> with the number of objects refered, and not with the memory they use.
>
> Thanks,
>
> Guille
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
Guille,

Could you just allow the process to die?  If you have an open connection 
awaiting the appearance of a query - it might be better to have a new 
instance of the process where the return of the result allows the code 
to terminate.

Probably jumping to conclusions.   If the term cursor is significant it 
sounds as if previous results still reside within the cursor, but only 
reporting the last data set.  {A cursor is a special database temporary 
table with ordered data set.  A standard sql table in principle is an 
unordered array of data that is retrieved via its relationship to keys 
(indexes).]

Perhaps you could outline your code showing where "dbresult = 
cursor.execute(query) resides and those much more skilled with python 
than I will clarify the issues.

Herschel


From littledanehren at yahoo.com  Sun Jan 11 21:55:25 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Sun Jan 11 21:55:30 2004
Subject: [Tutor] unpacking
In-Reply-To: <20040111222831.24443.qmail@web12402.mail.yahoo.com>
Message-ID: <20040112025525.81071.qmail@web41806.mail.yahoo.com>

Christopher Spears wrote:
> What is unpacking?
> 
> -Chris

Tuple packing and unpacking is a simple but powerful
mechanism that python uses for multiple assignment,
creation of tuples, and seperation of the elements of
a list or tuple. You can't really understand unpacking
until you understand packing. To pack a tuple, simply
place commas between different things. This will
automatically form a tuple. The comma has somewhat low
precidence, so you will sometimes need to put parens
around it. Tuples can be treated like lists for the
most part, except they are immutable. Here are some
examples using tuples:

>>> 1, 2
(1, 2)
>>> x = 1, 2
>>> x
(1, 2)
>>> x = (1, 2, 3, 4), 5, 6, 7
>>> x
((1, 2, 3, 4), 5, 6, 7)
>>> x[1]
5
>>> x[0]
(1, 2, 3, 4)
>>> x[0][2]
3

Taking a tuple apart is just as easy as making it.
Although you could go through the process like the
following:

>>> x = 1, 2
>>> x0 = x[0]
>>> x1 = x[1]

it is much easier to do this:

>>> x = 1, 2
>>> x0, x1 = x

When things are seperated by commas on the left side
of the =, Python interprets it that you want to take
each element of the tuple and store it in those
variables. This is called unpacking.

When you use multiple assignment, as in the following:

>>> x, y = 1, 2
>>> x
1
>>> y
2

Python is actually constructing 1, 2 into a tuple and
then unpacking it onto x and y.

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes
http://hotjobs.sweepstakes.yahoo.com/signingbonus

From littledanehren at yahoo.com  Sun Jan 11 22:09:13 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Sun Jan 11 22:09:18 2004
Subject: [Tutor] Memory problem
In-Reply-To: <400184DE.1040402@epfl.ch>
Message-ID: <20040112030913.6709.qmail@web41807.mail.yahoo.com>

Guillermo Fernandez Castellanos wrote:
> Hi,
> 
> First of all, happy year to all :-)
> 
> I'm playing with a database. I've done a user
> interface to this database 
> that do several queries and print the results. The
> problem is that, this 
> database being important (several hundred of
> thousands entries), each 
> time I do a query the use of RAM increases very
> substancially (several 
> dozens, sometimes a few undreds of Mb). I do
> something like:
> dbresult=cursor.execute(query)
> 
> I was wondering if there is a way of making that
> memory 'free' 
> afterwards. I mean to say to python somehow 'I don't
> need dbresult 
> anymore, so you can forget it and give me back the
> memory'. I've tried 
> the gc module, but it does not seem to answer my
> needs as it works with 
> the number of objects refered, and not with the
> memory they use.
> 
> Thanks,
> 
> Guille

have you tried del dbresult? The del keyword is rarely
used since Python has such good memory management, but
it still has its uses. Another way is to just
overwrite dbresult, implicitly deleting what was there
before. If you're already doing one of these, I don't
know what the problem is.

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes
http://hotjobs.sweepstakes.yahoo.com/signingbonus

From cspears2002 at yahoo.com  Sun Jan 11 23:42:29 2004
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Sun Jan 11 23:42:33 2004
Subject: [Tutor] listdir
Message-ID: <20040112044229.17929.qmail@web12408.mail.yahoo.com>

I was trying to use listdir to look into the contents
of a file on my Win2K system.  According to the online
docs, I should be able to do this, but instead, I get
the following error message:

>>> import os
>>> listdir('C:\Documents and Settings\Christstopher
Spears\My Documents\python')

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in -toplevel-
    listdir('C:\Documents and Settings\Christstopher
Spears\My Documents\python')
NameError: name 'listdir' is not defined

What does this mean?  I have the same problem when I
try to rename a file.


=====
"I'm the last person to pretend that I'm a radio.  I'd rather go out and be a color television set."
-David Bowie

"Who dares wins"
-British military motto

"Far more creativity, today, goes into the marketing of products than into the products themselves..."
-"Pattern Recognition" by William Gibson

From peterabrown at froggy.com.au  Mon Jan 12 00:17:07 2004
From: peterabrown at froggy.com.au (Peter Brown)
Date: Mon Jan 12 00:17:18 2004
Subject: [Tutor] listdir
In-Reply-To: <20040112044229.17929.qmail@web12408.mail.yahoo.com>
References: <20040112044229.17929.qmail@web12408.mail.yahoo.com>
Message-ID: <6.0.0.22.0.20040112160124.02cf7880@mail.froggy.com.au>

See below

At 20:42 11/01/04 -0800, you wrote:
>I was trying to use listdir to look into the contents
>of a file on my Win2K system.  According to the online
>docs, I should be able to do this, but instead, I get
>the following error message:
>
> >>> import os
> >>> listdir('C:\Documents and Settings\Christstopher
>Spears\My Documents\python')
>
>Traceback (most recent call last):
>   File "<pyshell#1>", line 1, in -toplevel-
>     listdir('C:\Documents and Settings\Christstopher
>Spears\My Documents\python')
>NameError: name 'listdir' is not defined
>
>What does this mean?  I have the same problem when I
>try to rename a file.
>
>
>=====
>"I'm the last person to pretend that I'm a radio.  I'd rather go out and 
>be a color television set."
>-David Bowie
>
>"Who dares wins"
>-British military motto
>
>"Far more creativity, today, goes into the marketing of products than into 
>the products themselves..."
>-"Pattern Recognition" by William Gibson
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor



Chris,

You haven't fully qualified name.

if you use
 >>>import os
you have to fully qualify the function
 >>> a= os.listdir('e:/voip')
 >>> a
['04-iad.pdf']

or use
 >>>from os import listdir
 >>>a=listdir('e:/voip')
 >>> a
['04-iad.pdf']

If more than one file in directory naturally you get more file names in list

Peter



From Michael.Dunn at mpi.nl  Mon Jan 12 04:04:37 2004
From: Michael.Dunn at mpi.nl (Michael Dunn)
Date: Mon Jan 12 04:04:52 2004
Subject: [Tutor] re: running an interactive program from a script
Message-ID: <Pine.GSO.4.55.0401121000450.23208@sun02.mpi.nl>

Thanks Lee for the pointer to the pexpect module, it was exactly what I
needed. There are notes in the faq on the pexpect webpage about why a
simple pipe wouldn't work for the sort of thing I need.

Anyway, I've written a test program and it works. I'd appreciate anybody's
comments (specific or general -- Python is my first computer language,
barring a bit of fiddling with BASIC on a Vic20 at the dawn of time).

This is the parent program using pexpect (the child program is copied
below). Run the parent and it will run the child itself (should be named
sample.py):

###
#!/usr/bin/env python
# parent.py

import re
import pexpect

def main():
    child = pexpect.spawn('python sample.py')
    while 1:
        index = child.expect(['> ', pexpect.EOF])
        if index == 0:
            print child.before.strip()
            s = select_switch(child.before)
            child.sendline(s)
        else:
            print child.before
            #print child.after
            break

def select_switch(s):
    r = re.search(r'\(F\)loats: ([a-zA-Z]+).*\(D\)uck: ([a-zA-Z]+)', s, re.DOTALL)
    values = r.groups()
    current = {'float':values[0], 'duck':values[1]}
    if current['float'] != target['float']:
        return 'f'
    elif current['duck'] != target['duck']:
        return 'd'
    else:
        return 'q'


target = {'float':'Maybe', 'duck':'Maybe'}
# these values could come from command line switches or a configuration file

main()
###

This is the sample of the kind of interactive program I want to automate
(copied from my initial query):

###
#!/usr/bin/env python
# sample.py
# the parent assumes this script is called 'sample.py' and is in the
# same directory

prompt = """Settings:
 (F)loats: %(float)s
 Is (D)uck: %(duck)s
Enter F or D to change a setting, Q to quit
> """
settings = {'float':'Yes', 'duck':'No'}
toggle = {'Yes':'Maybe','Maybe':'No','No':'Yes'}
selection = ''

while selection.upper() != 'Q':
    selection = raw_input((prompt % settings))
    if selection.upper() == 'F':
        settings['float'] = toggle[settings['float']]
    if selection.upper() == 'D':
        settings['duck'] = toggle[settings['duck']]

print 'Settings are:', settings
###

I'm currently working on doing a similar thing with one of the programs in
the PHYLIP package. There are a few additional problems -- changing one
option in PHYLIP will occasionally cause other options to be added or
removed, and selecting some options calls forth additional questions. The
worst problem is that there's no standard prompt character used, so it's
hard to decide what to get child.expect(???) to look for.

--Michael

From hameedkhaan at yahoo.com  Mon Jan 12 12:06:45 2004
From: hameedkhaan at yahoo.com (Hameed Khan)
Date: Mon Jan 12 12:06:52 2004
Subject: [Tutor] Sequence Comparison
Message-ID: <20040112170645.31347.qmail@web61103.mail.yahoo.com>

Hi,
  i was reading the Sequence comparison section of
python documentation. but i really didnot understand
from it. if anyne of you can explain it to me then it
will be very kind of you. the below is the examples
with the questions i have in mind.

>>> (1, 2, 3)              < (1, 2, 4)
True
# Q.1 why it returns True when 1 is not lower then 1
and 2 is not lower then 2. only 3 is lower then 4

>>> [1, 2, 3]              < [1, 2, 4]
True
# the above question (Q.1) similarly apllies to this
comparison result too


>>> 'ABC' < 'C' < 'Pascal' < 'Python'
True
# Q.2 what is the procedure of comparison in different
size of sequences because 'ABC' is greater then 'C' in
size and 'Pascal' is greater then 'C' but equal to
'Python' in size

>>> (1, 2, 3, 4)           < (1, 2, 4)
True
# the above 2 question (Q.1 and Q.2) applies to this
comparison because this tuples have different sizes

>>> (1, 2)                 < (1, 2, -1)
True
# i totally didnot understand it

>>> (1, 2, 3)             == (1.0, 2.0, 3.0)
True
# i understand it a little bit that the elements of
second tuple converted to the type of elements of
first tuple and then compared but what if we compare
(1,"string",3) == (1.0,2.0,3.0)

>>> (1, 2, ('aa', 'ab'))   < (1, 2, ('abc', 'a'), 4)
True
# may be i will understand it if someone explains me
the above comparisons

Hameed khan

__________________________________
Do you Yahoo!?
Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes
http://hotjobs.sweepstakes.yahoo.com/signingbonus

From dyoo at hkn.eecs.berkeley.edu  Mon Jan 12 13:18:42 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon Jan 12 13:18:52 2004
Subject: [Tutor] Memory problem
In-Reply-To: <4001DA12.8090806@comcast.net>
Message-ID: <Pine.LNX.4.44.0401121015340.2683-100000@hkn.eecs.berkeley.edu>



> > I'm playing with a database. I've done a user interface to this
> > database that do several queries and print the results. The problem is
> > that, this database being important (several hundred of thousands
> > entries), each time I do a query the use of RAM increases very
> > substancially (several dozens, sometimes a few undreds of Mb). I do
> > something like:
>
> > dbresult=cursor.execute(query)


Hi Guillermo,

Are you doing anything else, like storing the results of the result set in
a container?  Do you do things like 'fetchall()' or 'fetchrow()' anywhere?

Also, what database interface are you using?  MySQLdb?



> > I was wondering if there is a way of making that memory 'free'
> > afterwards. I mean to say to python somehow 'I don't need dbresult
> > anymore, so you can forget it and give me back the memory'.

That dbresult should contain a simple integer.  For SELECT statements, it
should simply be the number of values returned. I don't think the issue is
dbresult itself, but some other use of the 'cursor'.  I think we need to
see more code before we're able to diagnose this.


Talk to you later!


From dyoo at hkn.eecs.berkeley.edu  Mon Jan 12 13:41:01 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon Jan 12 13:41:11 2004
Subject: [Tutor] Sequence Comparison
In-Reply-To: <20040112170645.31347.qmail@web61103.mail.yahoo.com>
Message-ID: <Pine.LNX.4.44.0401121019450.2683-100000@hkn.eecs.berkeley.edu>



On Mon, 12 Jan 2004, Hameed Khan wrote:

> i was reading the Sequence comparison section of python documentation.
> but i really did not understand from it. if anyne of you can explain it
> to me then it will be very kind of you. the below is the examples with
> the questions i have in mind.
>
> >>> (1, 2, 3)              < (1, 2, 4)
> True
> # Q.1 why it returns True when 1 is not lower then 1
> and 2 is not lower then 2. only 3 is lower then 4
                             ^^^^^^^^^^^^^^^^^^^^^^

Hi Hameed,

That's exactly right.  *grin* Python is doing a lexicographical
"dictionary" based sort.


You should have already seen this kind of sort before, in a regular
English dictionary.  Say that we have two words, like "abc" and "abd".
If those were real words, which one would come first in a dictionary?
And why?

A more concrete example: think about the words "account" and "accountant".
Which one would come first in a dictionary, and why?

The tuples above are being sorted for the same reason.






> >>> (1, 2, 3, 4)           < (1, 2, 4)
> True
> # the above 2 question (Q.1 and Q.2) applies to this
> comparison because this tuples have different sizes


Imagine that the system has two arrows pointed to the first components of
each item:

(1, 2, 3, 4)    (1, 2, 4)
 ^               ^
 A               B


Let's call them Arrow A and Arrow B.  If Arrows A and B are pointed to the
same thing, they'll move to the right one place:


(1, 2, 3, 4)    (1, 2, 4)
    ^               ^
    A               B


Again, they point to the same thing.  Let's move Arrows A and B again:



(1, 2, 3, 4)    (1, 2, 4)
       ^               ^
       A               B


3 is less than 4, so (1, 2, 3, 4) is less than (1, 2, 4).


Does this make sense so far?









> >>> (1, 2)                 < (1, 2, -1)
> True


Let's use the arrow notation again:

   (1, 2)          (1, 2, -1)
    ^               ^
    A               B

Equal.  Move the arrows to the right one:


   (1, 2)          (1, 2, -1)
       ^               ^
       A               B

Equal again.  Let's move the arrows to the right again:

   (1, 2)          (1, 2, -1)
          ^                ^
          A                B



Arrow A has fallen off!  In this case, (1, 2) is less than (1, 2, -1)
because its arrow has fallen off first.





> # i understand it a little bit that the elements of second tuple
> converted to the type of elements of first tuple and then compared but
> what if we compare
>
> (1,"string",3) == (1.0,2.0,3.0)


Good question.  The equality (==) comparison between a string and a number
is always False, according to the Python language spec.  According to:

    http://www.python.org/doc/current/ref/comparisons.html

"""The operators <, >, ==, >=, <=, and != compare the values of two
objects. The objects need not have the same type. If both are numbers,
they are converted to a common type. Otherwise, objects of different types
always compare unequal, and are ordered consistently but arbitrarily."""


So we will get a False value off:

   "string" == 2.0

And that's what forces:

    (1, "string", 3) == (1.0, 2.0, 3.0)

to evaluate to False.




Please feel free to ask more questions.  Hope this helps!


From Stryder at Frenchfriedhell.com  Fri Jan  9 16:53:54 2004
From: Stryder at Frenchfriedhell.com (Stryder)
Date: Mon Jan 12 13:48:08 2004
Subject: [Tutor] quicker .strip?
In-Reply-To: <3FFF0C6C.7070309@venix.com>
Message-ID: <008201c3d6fb$148f0b00$6f01010a@Rachel>

Wow, completely surprised by the quick reply, thanks all!

A tuple of tuples?  I that makes so much more sense.  I was using the
str() func because I thought it was some sort of formatting issue with
MySQLdb.  

Why the * with zip though?  It seems to be necessary to achieve the
formatting I want, but I didn't notice any direct reference to it in the
python23 doc.

-Stryder

-----Original Message-----
From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On
Behalf Of Lloyd Kvam
Sent: Friday, January 09, 2004 1:18 PM
To: firephreek
Cc: tutor@python.org
Subject: Re: [Tutor] quicker .strip?


fetchall returns a list of lists (well tuples, but you understand).
Effectively it's a matrix.  Your data looks a little funny because each
row is a single element.

I'd suggest:

ip = cursor.fetchall()
for x in ip:	# row by row
	for alpha in x:	# column by column
		config=getConfig(alpha)  ##Custom function that uses
httplib to

There's no need to convert the row to a string and remove the characters
introduced by the conversion.  The IP address is already there as a
string.

A cute coding trick for this case:

ip_list = zip(*cursor.fetchall())[0]
for ip in ip_list:
	config =getConfig(ip)

While we usually think of zip as peeling of list members in parallel it
is actually a matrix transpose function.  This converts the fetchall
results from a list of rows to a list of columns.  Your ip addresses are
the first
(zeroth) column.

HTH


Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582


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


From jumesh at icreon.com  Sat Jan 10 01:54:23 2004
From: jumesh at icreon.com (Umesh C Joshi)
Date: Mon Jan 12 13:48:12 2004
Subject: [Tutor] Why should I use Python??
Message-ID: <ADEILMLEIDNBMPPANPCKGEMICEAA.jumesh@icreon.com>

Hi,

I am reading the mailing list from last one month. I found lot of
subscribers are starter. I am doing internet programming from last 5 years.
I have a good experience using PHP. Whenever I got a mail from this list a
question arises in my mind. Do I need to learn python. Where It could be
more profitable in my career.

1. is python a better language to use in web development than  PHP?
2. Apart form web programming, where do I use  python and HOW?

I am really interested to explore python more.

rgds
Umesh C Joshi
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20040110/584483ce/attachment.html
From carroll at tjc.com  Mon Jan 12 14:16:08 2004
From: carroll at tjc.com (Terry Carroll)
Date: Mon Jan 12 14:16:19 2004
Subject: [Tutor] Sequence Comparison
In-Reply-To: <20040112170645.31347.qmail@web61103.mail.yahoo.com>
Message-ID: <Pine.LNX.4.44.0401121055490.22140-100000@violet.rahul.net>

On Mon, 12 Jan 2004, Hameed Khan wrote:

> >>> (1, 2, 3)              < (1, 2, 4)
> True
> # Q.1 why it returns True when 1 is not lower then 1
> and 2 is not lower then 2. only 3 is lower then 4

Because the *sequence* is lower.

Put it another way: is (1,2,3) *equal* to ((1,2,4)?  Obviously not.  So it 
has to be either less than or greater than.  Less than is the one that 
makes sense.

> >>> 'ABC' < 'C' < 'Pascal' < 'Python'
> True
> # Q.2 what is the procedure of comparison in different
> size of sequences because 'ABC' is greater then 'C' in
> size and 'Pascal' is greater then 'C' but equal to
> 'Python' in size

This construct is kind of confusing, and I would never use it; I would 
draw the lines at three comparators for a simple range check.

But this is basically saying
 "ABC" < "C" is true; and
 "C" < "Pascal" is true; and
 "Pascal" < "Python" is also true.

You don't really have to worry about different lengths here, because the 
difference shows up within the shortest length of each comparison (i.e. 
"ABC" < "C" is essentially just checking "A" <"C"; "C" < "Pascal" is 
essentially just checking "C"<"P", etc.).

It would be worth worrying anoy if you were comparing, say "aoto" and 
"automatic":

>>> "auto"<"automatic"
True

In such a case, the shorter string is less.

This is pretty much what you'd expect if you went to look something up in 
the index of a textbook, right?  "ABC" would sort before "C";" "Pascal" 
would sort before "Python": "auto" would sort before "automatic".

> >>> (1, 2, 3, 4)           < (1, 2, 4)
> True
> # the above 2 question (Q.1 and Q.2) applies to this
> comparison because this tuples have different sizes

Right; the same rule as above applies; Python just compares up to the 
first differentce; and 1, 2, 3... is less than 1, 2, 4...

What probably throws you here is either a) you're thinking of (1,2,3,4) 
and (1,2,4)
as though they're integers 1234 and 124, in which case you'd expect 1234 
to be greater than 124; but they're not integers, so it doesn't work to 
think of them like that.  

Or maybe, b) it bothers you that tuple (1,2,3,4)  is longer ("bigger," if
you will) than (1,2,4), and intuitively looks "greater than" to you.
The thing here is that you're mentally comparing, not the tuples 
themselves, but their lengths.  If you explicitly check the lengths, 
comparing them *is* consistent with that approache:

>>> len((1,2,3,4)) < len((1,2,4))
False

If this is where you're coming from, try separating in your mind the value 
of the tuple itself from the value of the tuple's length -- think of the 
length as an attribue ot the tuple.


> >>> (1, 2)                 < (1, 2, -1)
> True
> # i totally didnot understand it

That's a good thing to be confused about.  It looks like Python's rule is 
that the shorter of two tuples, where the two tuples are equal up to the 
shortest of the two tuples, is the lesser of the two.  That works 
intuitively if the rest of the tuple is positive, but not in cases like 
this where it's negative.

I guess the approach here is to hark back to the "what order would you 
expect in a book index" idea.  Personally, I don't like this feature, and 
think it should sort the opposite way.


> >>> (1, 2, 3)             == (1.0, 2.0, 3.0)
> True
> # i understand it a little bit that the elements of
> second tuple converted to the type of elements of
> first tuple and then compared but what if we compare
> (1,"string",3) == (1.0,2.0,3.0)

That's false, because (I think), it's converting the 2.0 in the second 
tuple to the string "2.0".  Someone who knows more of this want to 
comment?

> >>> (1, 2, ('aa', 'ab'))   < (1, 2, ('abc', 'a'), 4)
> True
> # may be i will understand it if someone explains me
> the above comparisons

Well, there's a tie comparing the tuples up through the elements 1 and 2.  
So the tie breaker is comparing the third elements: ('aa', 'ab') in the 
first tuple and ('abc', 'a') in the second.  The tie is broken with the 
very first subelement comparison: comparing 'aa' to 'abc':

 'aa' < 'abc', so therefore:
 ('aa', 'ab') < ('abc', 'a'), so therefore:
 (1, 2, ('aa', 'ab') [, ...] ) < (1, 2, ('abc', 'a') [, ...]),
   so therefore:
 (1, 2, ('aa', 'ab'))   < (1, 2, ('abc', 'a'), 4)

Does this help?

-- 
Terry Carroll
Santa Clara, CA
carroll@tjc.com 


From piir at earthlink.net  Mon Jan 12 14:18:57 2004
From: piir at earthlink.net (Todd G. Gardner)
Date: Mon Jan 12 14:19:17 2004
Subject: [Tutor] Do tuples replace structures?
Message-ID: <CAENJDPIMKAJINIKKHOCAEHDCCAA.piir@earthlink.net>

Hello all,

Do tuples allow one to form data structures like those formed by structures
in 'c' or are there better ways to form structures in python?

Thanks,

Todd


From carroll at tjc.com  Mon Jan 12 14:36:40 2004
From: carroll at tjc.com (Terry Carroll)
Date: Mon Jan 12 14:36:44 2004
Subject: [Tutor] Do tuples replace structures?
In-Reply-To: <CAENJDPIMKAJINIKKHOCAEHDCCAA.piir@earthlink.net>
Message-ID: <Pine.LNX.4.44.0401121125211.22140-100000@violet.rahul.net>

On Mon, 12 Jan 2004, Todd G. Gardner wrote:

> Do tuples allow one to form data structures like those formed by structures
> in 'c' or are there better ways to form structures in python?

You can do structures in tuples (although lists are probably a better way, 
being mutable).  If you do that, you have to remember what element number 
corresponds to what data, e.g.:

 record = ["Jim", "Smith", 22, 130]

It's up to you to remember that record[0] is first name, record[1] is last 
name, etc.

A dictionary makes this a little easier:

 record = {
   "fname":"Jim",
   "lname":"Smith",
   "age":22,
   "weight":130
   }

Then you can refer to, for example, record["age"] and pull out the age.

I prefer to use classes, though for just about anything where I need a 
structure:

>>> class person:
...   def __init__(self,fname,lname,age,height):
...     self.fname = fname
...     self.lname = lname
...     self.age = age
...     self.height = height
...
>>> record = person("Jim", "Smith", 22, 130)
>>> record.fname
'Jim'

-- 
Terry Carroll
Santa Clara, CA
carroll@tjc.com 


From barnabydscott at yahoo.com  Mon Jan 12 15:06:21 2004
From: barnabydscott at yahoo.com (Barnaby Scott)
Date: Mon Jan 12 15:06:28 2004
Subject: [Tutor] Reviewing scripts
Message-ID: <20040112200621.30866.qmail@web41413.mail.yahoo.com>

Is there a place for people to ask for others'
opinions of Python scripts they have written? Is
*this* that place?

I am asking because I have been working on one for
some time now, and think it is as good as I can get
it, but am still painfully aware of how much of a
beginner I am and how much still I have to learn. A
good critique of it would be very helpful, but I don't
want to come here and bore everyone with it in case
there is a better forum for this function (it is also
quite long!) Any suggestions?


__________________________________
Do you Yahoo!?
Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes
http://hotjobs.sweepstakes.yahoo.com/signingbonus

From littledanehren at yahoo.com  Mon Jan 12 15:36:43 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Mon Jan 12 15:36:49 2004
Subject: [Tutor] Why should I use Python??
In-Reply-To: <ADEILMLEIDNBMPPANPCKGEMICEAA.jumesh@icreon.com>
Message-ID: <20040112203643.14170.qmail@web41806.mail.yahoo.com>

Umesh C Joshi wrote:
> Hi,
> 
> I am reading the mailing list from last one month. I
> found lot of
> subscribers are starter. I am doing internet
> programming from last 5 years.
> I have a good experience using PHP. Whenever I got a
> mail from this list a
> question arises in my mind. Do I need to learn
> python. Where It could be
> more profitable in my career.
> 
> 1. is python a better language to use in web
> development than  PHP?

I'm not exactly sure what you mean by 'better'. For
simple but slightly dynamic websites, or if speed is a
big requirement, PHP might be better. But if you want
to make something that's complex, extendable, and
reusable, you're probably better off with Python.
That's mainly because Python doesn't rely on HTML
embedding and web development, making it much more
flexible, but slightly more difficult for simple
things. Although these are mostly opinions, Python
also has many advantages in its syntax and
functionality, such as:

-no curly brackets
-no variable prefixes
-better-integrated object orientation
-functional features including list comprehensions
-docstrings
-no need to put <? around programs ?> if they're not
embedded
-etc.

If you just try Python, you'll probably see many more
advantages since I don't know much PHP.

For web development in Python, most people use Zope,
which has its own templating language called DTML.
DTML can be used similarly to HTML embedding in PHP,
but most of the coding is seperated out in DTML.

> 2. Apart form web programming, where do I use 
> python and HOW?
> 
> I am really interested to explore python more.
> 
> rgds
> Umesh C Joshi

Python can be used for anything. It is usually used
for standalone scripts, though. On Unix/Linux, simply
put the following at the beginning of a script to make
it run Python:
#!/usr/bin/env python
You do something similar on MacOSX, but all of the
path names are weird. On Windows, this will just be
interpreted as a comment. On all platforms with a GUI,
file associations can be used to make it so if you
double click on a Python script (ending in .py or
.pyw), it will automatically run it using Python.

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes
http://hotjobs.sweepstakes.yahoo.com/signingbonus

From littledanehren at yahoo.com  Mon Jan 12 16:10:27 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Mon Jan 12 16:10:33 2004
Subject: [Tutor] Reviewing scripts
In-Reply-To: <20040112200621.30866.qmail@web41413.mail.yahoo.com>
Message-ID: <20040112211027.24917.qmail@web41808.mail.yahoo.com>

Barnaby Scott wrote:
> Is there a place for people to ask for others'
> opinions of Python scripts they have written? Is
> *this* that place?
> 
> I am asking because I have been working on one for
> some time now, and think it is as good as I can get
> it, but am still painfully aware of how much of a
> beginner I am and how much still I have to learn. A
> good critique of it would be very helpful, but I
> don't
> want to come here and bore everyone with it in case
> there is a better forum for this function (it is
> also
> quite long!) Any suggestions?

This can be used for short code snippets or you can
link to a place where you have a medium-length script.
But we don't want everyone sending in their code here
to be reviewed because then we'd be swamped, and your
idea for a code review website sounded useful, so I
made one at
http://zope.org/Members/LittleDan/CodeReview . You can
post your code there, if you want.

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes
http://hotjobs.sweepstakes.yahoo.com/signingbonus

From alan.gauld at blueyonder.co.uk  Mon Jan 12 18:55:35 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Mon Jan 12 18:55:00 2004
Subject: [Tutor] Why should I use Python??
References: <ADEILMLEIDNBMPPANPCKGEMICEAA.jumesh@icreon.com>
Message-ID: <005501c3d967$925b9440$6401a8c0@xp>

> I am reading the mailing list from last one month. I found lot of
> subscribers are starter.

That's because it's a list for beginners!
If you want a more in-depth discussion visit the comp.lang.python
usenet group.

> I am doing internet programming from last 5 years.
> I have a good experience using PHP. ....Do  I need to learn python.

If PHP works for you then no. If there is a problem you can't solve,
or would like to solve faster, or maybe more maintainably(?) then
look to see if Python would help.

> Where It could be more profitable in my career.

Anywhere where Python is used rather than PHP...

> 1. is python a better language to use in web development than  PHP?

No, not better just diffrent. It does some things better than PHP
but PHP has its own advantages, and PHP is better "tuned" to web
work whereas Python is intended for general programming.

> 2. Apart form web programming, where do I use  python and HOW?

Pretty much most things. Avoid high performamce games and device
drivers and operating systems. But for most user level programming
Python does fine.

> I am really interested to explore python more.

The easiest way is to dive in. You should have no problem running
through the offoicial tutorial in a day or so at most. Then just
write some programs. If you like it great, if not you've learned
a new language with some new features. That can only help your
PHP work too.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


From alan.gauld at blueyonder.co.uk  Mon Jan 12 18:57:10 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Mon Jan 12 18:56:35 2004
Subject: [Tutor] Do tuples replace structures?
References: <CAENJDPIMKAJINIKKHOCAEHDCCAA.piir@earthlink.net>
Message-ID: <005a01c3d967$cb31e710$6401a8c0@xp>

> Do tuples allow one to form data structures like those formed by
structures
> in 'c' or are there better ways to form structures in python?

Quick n dirty structures yes, but for general use a class is
usually a better bet. Take a look at the last page of the Raw
Materials
topic in my tutor for an example of using a class to hold an "address"
structure (in the yellow box)

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


From isrgish at fusemail.com  Mon Jan 12 23:16:51 2004
From: isrgish at fusemail.com (Isr Gish)
Date: Mon Jan 12 23:16:55 2004
Subject: [Tutor] Newbie: Help on comparing files
Message-ID: <E1AgFyn-0005Y8-1P@fuse1.fusemail.net>

This is the code I wrote to compare the files.

def compare(oldfilepth, newfilepth, sep):
	seplen = len(sep)
	olddata = getfiledata(oldfilepth)
	newdata = getfiledata(newfilepth)
	fw = file('\\Temp\\Code Breaker\\only in old.txt', 'w')

	index = 1
	while index != -1:
		index = olddata.find(sep)
		if index != -1:
			srchstr = olddata[:index]
			olddata = olddata[index + seplen:]
		else:
			srchstr = olddata
		srchlen = len(srchstr)
		fnd_indx = newdata.find(srchstr)
		if fnd_indx != -1:   #Substring was found
			newdata = newdata[:fnd_indx] + newdata[fnd_indx + srchlen + seplen:]
		else:   #The substring wasn't found
			fw.write(srchstr + sep)
	fw.close()
	fw = file('\\temp\\code breaker\\only in new.txt', 'w')
	fw.write(newdata)
	fw.close()

def getfiledata(filepth):
	fr = file(filepth)
	data = fr.read()
	fr.close()
	return data

This is the basic code. (it still needs a few enhancements).
What I want to know is, if there is a quicker way. For example if I would first split the whole file into list if the find  would be quicker.
Any other pointers about my code, would also be greatly appreciated.

Best Wishes
Isr Gish


From piir at earthlink.net  Mon Jan 12 23:38:16 2004
From: piir at earthlink.net (Todd G. Gardner)
Date: Mon Jan 12 23:38:54 2004
Subject: [Tutor] graphing and data acquisition
Message-ID: <CAENJDPIMKAJINIKKHOCAEHJCCAA.piir@earthlink.net>

Hello everyone,

On Windows XP/2000 :(...

I have written a basic data acquisition and graphing routine building on
several things so that maybe some day I can use python at work.  It seems to
work really well when I run it in the Boa Constructor enviroment.  It also
works if I run it directly as a .py and .pyw file.  It seems to lock when
it runs in the IDLE enviroment.

Any ideas as to whay are the differences between these enviroments?

Thanks,

Todd
--
PS. This depends on the libraries:
ctypes
wxPyPlot
	wxPython
and
Numeric


From Harm_Kirchhoff at mail.digital.co.jp  Tue Jan 13 01:55:36 2004
From: Harm_Kirchhoff at mail.digital.co.jp (Harm_Kirchhoff@mail.digital.co.jp)
Date: Tue Jan 13 01:55:43 2004
Subject: [Tutor] Module with Financial Functions
Message-ID: <OF73B78ED1.E33EA5EA-ON49256E1A.0024E1AC-49256E1A.0025E1EC@jp.schneider-electric.com>

A while ago I posted a message asking for a module with financial 
functions (compounded interest, annuities, IRR analysis, Depreciation 
tables).

I followed up the one feedback I got and it seems that there is not 
comprehensive module.

I am writing such a module now and I wonder, what would be the 
preferred/best/easiest place to make it available to others ?

 
 


From philip at pacer.co.za  Tue Jan 13 03:38:32 2004
From: philip at pacer.co.za (philip gilchrist)
Date: Tue Jan 13 03:38:28 2004
Subject: [Tutor] graphics
Message-ID: <598B5E93DCDC614C9C1FE22406A0F5BE3678@pacer-server.pacer.local>

Hi 

 

I am trying to use the graphics module from livewires, and can't get any
timing working. It seems to me that the timing from the main program and
the graphics are separate.

 

 

from livewires import *

print 'opening the graphics window'

begin_graphics()

move(100,200)

box(50,200,100,350)

circle( 75,275,20,filled=1)

circle(75,230,20,filled=0)

circle(75,310,20,filled=0)

time.sleep(3)

circle( 75,275,20,filled=0)

circle(75,230,20,filled=1)

circle(75,310,20,filled=0)

   

circle( 75,275,20,filled=0)

circle(75,230,20,filled=0)

circle(75,310,20,filled=1)

 

end_graphics()

 

I was hoping to simulate a traffic light (obviously I will include
colors later) but this times the three seconds and then draws the
graphic.

 

Any pointers??

 

Regards,

 

Philip

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20040113/16acaebc/attachment.html
From alan.gauld at blueyonder.co.uk  Tue Jan 13 03:54:59 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Tue Jan 13 03:54:16 2004
Subject: [Tutor] padding frames
References: <20040111170947.57594.qmail@web12403.mail.yahoo.com>
Message-ID: <008e01c3d9b2$ec8bd920$6401a8c0@xp>

> x = ['DSCN-2.JPG', 'DSCN-11.jpg', 'DSCN-101.JPG',
> 'DSCN-2302.JPG']
> 
> Problem 1:
> How do I go about putting the files into a list?  

Try the glob module.

> even need to put the files into a list?  After all, I
> just want to change their names.  Do the files need to
> be opened?

No, just use the names.

> Problem 2:
> How do I isolate the portion of the file name that I
> need?

Try using the split() method of strings. split by '-' 
to get the N.JPG bit then split that by '.' to get the 
N by itself.

zfill N then join the three bits together again.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld

From alan.gauld at blueyonder.co.uk  Tue Jan 13 04:00:13 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Tue Jan 13 03:59:29 2004
Subject: [Tutor] Memory problem
References: <400184DE.1040402@epfl.ch>
Message-ID: <009301c3d9b3$a7e10060$6401a8c0@xp>

> time I do a query the use of RAM increases very substancially
(several
> dozens, sometimes a few undreds of Mb). I do something like:
> dbresult=cursor.execute(query)
>
> I was wondering if there is a way of making that memory 'free'

I assume you tried the simple del() function to mark it for gc?

The other approach is to use less memory in the first place.
Its very unusual to actually need all of the entries in the
datbase at once, so you can tell the cursor to only fetch
the firt N - say 1000. By fetching in batches of 1000 at
a time you should find the memory demands are less. How you
do that will probably depend on your database SQL dialect.

But I don't know how you use the data, maybe you do need all
the records at one go...

Alan G.


From alan.gauld at blueyonder.co.uk  Tue Jan 13 04:05:23 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Tue Jan 13 04:04:44 2004
Subject: [Tutor] listdir
References: <20040112044229.17929.qmail@web12408.mail.yahoo.com>
Message-ID: <00af01c3d9b4$60d15ca0$6401a8c0@xp>

> >>> import os

This makes the name 'os' available to Python.

> >>> listdir('C:\Documents and Settings\Christstopher
> Spears\My Documents\python')
> NameError: name 'listdir' is not defined

But Python does not know the names of anything inside os.
To use a function within os you must prefix the function name 
with os, thus:

>>> os.listdir(....)

The "Simple Sequences" and "Modules and Functions" topics 
in my tutorial address this issue in more depth.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld

From hrz at geodata.soton.ac.uk  Tue Jan 13 04:57:51 2004
From: hrz at geodata.soton.ac.uk (Homme Zwaagstra)
Date: Tue Jan 13 04:58:10 2004
Subject: [Tutor] Why should I use Python??
In-Reply-To: <E1Ag8nw-0000Nb-Lz@mail.python.org> from
	"tutor-request@python.org" at Jan 12, 2004 03:36:56 PM
Message-ID: <200401130957.i0D9vpF28060@betsy.geodata.soton.ac.uk>

> For web development in Python, most people use Zope,
> which has its own templating language called DTML.
> DTML can be used similarly to HTML embedding in PHP,
> but most of the coding is seperated out in DTML.

If you're able to deploy your websites using the Apache webserver I
recommend looking at mod_python (http://www.modpython.org) in addition
to Zope. Mod_python integrates Python with Apache resulting in a very
powerful web development environment. The project is under active
development and the next version (currently in beta) will support
Cookies, Sessions and HTML embedded python (so you can use the <% %>
paradigm if you want!).  All of this will make migrating from PHP much
easier.

If you don't have Apache then there's always the Python CGI module
(http://www.python.org/doc/current/lib/module-cgi.html) or a toolkit
such as Albatross (http://www.object-craft.com.au/projects/albatross).

I agree with Daniel that for simple applications PHP is the way to
go. Having programmed extensively in PHP, however, I've found that PHP
4 starts to get unwieldy for large projects. Python scales much
better, is easier to extend using C or C++ (check out Boost.Python at
http://www.boost.org/libs/python/doc/index.html) and, being a more
general purpose language than PHP, is a better 'glue' between
different system components. All IMHO. PHPs scalability issue,
however, may be addressed with the upcoming release of PHP 5 with it's
refined object orientation and exception handling. 

Good Luck!

Homme

From Janssen at rz.uni-frankfurt.de  Tue Jan 13 05:25:03 2004
From: Janssen at rz.uni-frankfurt.de (Michael Janssen)
Date: Tue Jan 13 05:25:18 2004
Subject: [Tutor] Sequence Comparison
In-Reply-To: <20040112170645.31347.qmail@web61103.mail.yahoo.com>
References: <20040112170645.31347.qmail@web61103.mail.yahoo.com>
Message-ID: <Pine.A41.4.56.0401131038160.475516@hermes-22.rz.uni-frankfurt.de>

On Mon, 12 Jan 2004, Hameed Khan wrote:

> >>> (1, 2, 3)              < (1, 2, 4)
> True
> # Q.1 why it returns True when 1 is not lower then 1
> and 2 is not lower then 2. only 3 is lower then 4

python doesn't use the tuples directly for comparing but the elements
inside both tuples (same for lists).

python compares each element from left to right until it founds a pair
of element, where the condition (<) is true:
1 < 1 ---> python find's: not true therefore:
2 < 2 ---> not true, next try
3 < 4 ---> true. Overall condition is true

> >>> [1, 2, 3]              < [1, 2, 4]
> True
> # the above question (Q.1) similarly apllies to this
> comparison result too

yes.

> >>> 'ABC' < 'C' < 'Pascal' < 'Python'
> True
> # Q.2 what is the procedure of comparison in different
> size of sequences because 'ABC' is greater then 'C' in
> size and 'Pascal' is greater then 'C' but equal to
> 'Python' in size

it's not string-length what get compared here: Python compares - as
Danny stated - the lexicographic weight of *each element*. 'ABC' is
smaller than 'C' because 'A' is smaller than 'C'.

> >>> (1, 2, 3, 4)           < (1, 2, 4)
> True
> # the above 2 question (Q.1 and Q.2) applies to this
> comparison because this tuples have different sizes

yes. To make it completly clear: after python found a pair of elements
which compares "smaller then" it doesn't look any further.

> >>> (1, 2)                 < (1, 2, -1)
> True
> # i totally didnot understand it

-1 from the second tuple is compared against None (because first tuple
runs out of elements). None is allways smaller than anything.

> >>> (1, 2, 3)             == (1.0, 2.0, 3.0)
> True
> # i understand it a little bit that the elements of
> second tuple converted to the type of elements of
> first tuple and then compared but what if we compare
> (1,"string",3) == (1.0,2.0,3.0)

python doesn't need to compare elements of the same type. It's completly
sane to compare integers with floats or strings. When you compare
integers with floats, each are compared by it's numerically value.
Strings allways compare greater than integers or floats.

Note: the rules for comparisions between different types (eg. strings
allways greater than integers; tuples allways greater then lists)
shouldn't be used in if-conditions. Normally, it indicates a bug when
you compare different types within a if clauses. But it's fine to sort a
list of arbitrary types by type and maybe print it out.


> >>> (1, 2, ('aa', 'ab'))   < (1, 2, ('abc', 'a'), 4)
> True
> # may be i will understand it if someone explains me
> the above comparisons

you very likly will :-) Nevertheless I describe what python does: since
to tuples are to be compared, python compares them element by element.
First two elements compares equal. Third elements are both tuple and
therefore compared elem by elem. 'aa' and 'abc' are both strings and
compared char by char. second 'a' of 'aa' compares smaller than 'b' of
'abc'


some other cases:

>>> [1,2,3] < (1,2,3)
True
---> python regards lists smaller than tuples

>>> (0,) > 99         # (0,) is a single element tuple
True
---> tuples are allways greater than integers

As you see, comparisions between different types are tricky. Better not
use them in conditions.



Michael

From darnold02 at sprynet.com  Tue Jan 13 07:00:11 2004
From: darnold02 at sprynet.com (don arnold)
Date: Tue Jan 13 07:00:33 2004
Subject: [Tutor] graphing and data acquisition
References: <CAENJDPIMKAJINIKKHOCAEHJCCAA.piir@earthlink.net>
Message-ID: <0b2401c3d9cc$d3d233b0$6310ba3f@don2uvsu54fwiq>

----- Original Message -----
From: "Todd G. Gardner" <piir@earthlink.net>
To: "Tutor@Python. Org" <tutor@python.org>
Sent: Monday, January 12, 2004 10:38 PM
Subject: [Tutor] graphing and data acquisition


> Hello everyone,
>
> On Windows XP/2000 :(...
>
> I have written a basic data acquisition and graphing routine building on
> several things so that maybe some day I can use python at work.  It seems
to
> work really well when I run it in the Boa Constructor enviroment.  It also
> works if I run it directly as a .py and .pyw file.  It seems to lock when
> it runs in the IDLE enviroment.
>
> Any ideas as to whay are the differences between these enviroments?
>

Which version of Python are you using? Prior to 2.3, both IDLE and your
program would run in a single thread. As a result, IDLE's Tkinter-based
event loop would often (always?) clash with your script's event-processing
loop, bring evertyhing to a screeching halt. The version of IDLE that ships
with Python 2.3  executes your script in its own thread, avoiding this
problem.

> Thanks,
>
> Todd
> --
> PS. This depends on the libraries:
> ctypes
> wxPyPlot
> wxPython
> and
> Numeric

HTH,
Don


From piir at earthlink.net  Tue Jan 13 07:18:07 2004
From: piir at earthlink.net (Todd G. Gardner)
Date: Tue Jan 13 07:18:24 2004
Subject: [Tutor] graphing and data acquisition
In-Reply-To: <0b2401c3d9cc$d3d233b0$6310ba3f@don2uvsu54fwiq>
Message-ID: <CAENJDPIMKAJINIKKHOCMEHLCCAA.piir@earthlink.net>

Don,

I was running Python 2.2.

It works on 2.3.

Thanks!

Todd

-----Original Message-----
From: don arnold [mailto:darnold02@sprynet.com]
Sent: Tuesday, January 13, 2004 7:00 AM
To: Todd G. Gardner; Tutor@Python. Org
Subject: Re: [Tutor] graphing and data acquisition


----- Original Message -----
From: "Todd G. Gardner" <piir@earthlink.net>
To: "Tutor@Python. Org" <tutor@python.org>
Sent: Monday, January 12, 2004 10:38 PM
Subject: [Tutor] graphing and data acquisition


> Hello everyone,
>
> On Windows XP/2000 :(...
>
> I have written a basic data acquisition and graphing routine building on
> several things so that maybe some day I can use python at work.  It seems
to
> work really well when I run it in the Boa Constructor enviroment.  It also
> works if I run it directly as a .py and .pyw file.  It seems to lock when
> it runs in the IDLE enviroment.
>
> Any ideas as to whay are the differences between these enviroments?
>

Which version of Python are you using? Prior to 2.3, both IDLE and your
program would run in a single thread. As a result, IDLE's Tkinter-based
event loop would often (always?) clash with your script's event-processing
loop, bring evertyhing to a screeching halt. The version of IDLE that ships
with Python 2.3  executes your script in its own thread, avoiding this
problem.

> Thanks,
>
> Todd
> --
> PS. This depends on the libraries:
> ctypes
> wxPyPlot
> wxPython
> and
> Numeric

HTH,
Don


From alistair.mcgowan at ucl.ac.uk  Tue Jan 13 09:42:32 2004
From: alistair.mcgowan at ucl.ac.uk (Alistair McGowan)
Date: Tue Jan 13 09:44:35 2004
Subject: [Tutor] Cloning lists to avoid alteration of original list
Message-ID: <p05200f0cbc29b4408405@[128.40.44.13]>

Dear All,
		I am having problems with cloning a list in such a 
way that it alters one list but not the other. The list for the new 
area should have "4"

I have tried the standard procedure of taking a slice of the list, 
renaming it and operatiing on that, but to no avail. One issue that 
may make a difference is that I am taking a slice of a longer list, 
rather than the complete list.

Here is the section of code, which is a class. I have tried cloning 
the two lists outside of the class, as well as within the class, but 
the program always carries out the changes to both lists. I apologize 
for the length of the extact. If further information is needed, 
please let me know.
	Thanks in advance,
			Al

class mergeTaxa: # geodispersal of taxon lists from colliding areas
	def __init__(self,m,y,clone1,clone2):
		self.mergetaxa=[] #empty list
		self.mergetaxa.append (name)#id of new merged area
		one = clone1
		two = clone2
		print "one", one
		print "two", two
		temp = []# an empty list for listing taxa for comparison
		for e in range (0, len(one)):# starts to loop over 
list 1 and writes to merged list
			x = one[e] #extracts info for each taxon in area
			a = one[e][0]#gets the id #
			if one [e][2]==0: #checks if taxon is alive
				one[e][3]= 4
				print clone1
				self.mergetaxa.append(x)
				temp.append(a)
			else:
				pass
		for j in range (0, len(two)):# starts loop over other list
			p=two[j]
			f = two[j][0]
			if two[j][2]==0:
				z = temp.count(f)# checks if taxon 
occurs in other area list
				if z ==0: #  if not add to new area list
					two[j][3]=4
					self.mergetaxa.append(p)
				else:
					pass
			else:
				pass
		merge = self.mergetaxa
		print "merged", merge
		print clone1
		print clone2
		tbya.append(merge)#writes out to main taxon by area matrix
-- 
Alistair J. McGowan
Department of Earth Sciences,
University College, London,
London

WC1E 6BT

Phone: TBA
Fax: +44 (0)20 7387 1612

"Hope is a duty from which paleontologists are exempt."
				David Quammen

"Empty causes. You've got yours and I've got mine"
				Greg Graffin
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20040113/d1d8f18b/attachment.html
From jboone01 at bcuc.ac.uk  Tue Jan 13 10:40:12 2004
From: jboone01 at bcuc.ac.uk (Jim Boone)
Date: Tue Jan 13 10:40:47 2004
Subject: [Tutor] Why should I use Python??
In-Reply-To: <ADEILMLEIDNBMPPANPCKGEMICEAA.jumesh@icreon.com>
References: <ADEILMLEIDNBMPPANPCKGEMICEAA.jumesh@icreon.com>
Message-ID: <4004115C.8040305@bcuc.ac.uk>

Umesh C Joshi wrote:

> Hi,
>  
> I am reading the mailing list from last one month. I found lot of 
> subscribers are starter. I am doing internet programming from last 5 
> years. I have a good experience using PHP. Whenever I got a mail from 
> this list a question arises in my mind. Do I need to learn python. 
> Where It could be more profitable in my career.
>  
> 1. is python a better language to use in web development than  PHP?
> 2. Apart form web programming, where do I use  python and HOW?
>  
> I am really interested to explore python more.


I wrote a command line app to take a csv file of users and crank out an 
ldif with all the relevant context and grouping info to import users 
into novells nds, its 200 lines of fast portable code that replaces a 
slow labour intensive database query system.  Dunno how useful it is for 
web stuff, but if you want to knock a little program for reg-ex stuff 
its great!

>  
> rgds
> Umesh C Joshi
>
>------------------------------------------------------------------------
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
>  
>


-- 
Jim Boone
--------------------------------------------
Buckinghamshire Chilterns University College
R&D Manager - Information and Communication Technologies
Tel: 01494 522141 ext 3569

The myth that Bill Gates has appeared like a knight in shining armor to lead all customers out of a mire of technological chaos neatly ignores the fact that it was he who, by peddling second-rate technology, led them into it in the first place, and continues to do so today.

~Douglas Adams~



From speno at isc.upenn.edu  Tue Jan 13 11:05:02 2004
From: speno at isc.upenn.edu (John P Speno)
Date: Tue Jan 13 11:05:06 2004
Subject: [Tutor] Memory problem
In-Reply-To: <009301c3d9b3$a7e10060$6401a8c0@xp>
References: <400184DE.1040402@epfl.ch> <009301c3d9b3$a7e10060$6401a8c0@xp>
Message-ID: <20040113160502.GA11580@isc.upenn.edu>

On Tue, Jan 13, 2004 at 09:00:13AM -0000, Alan Gauld wrote:
> > time I do a query the use of RAM increases very substancially
> (several
> > dozens, sometimes a few undreds of Mb). I do something like:
> > dbresult=cursor.execute(query)
> >
> > I was wondering if there is a way of making that memory 'free'
> 
> I assume you tried the simple del() function to mark it for gc?

Wether or not this actually frees up memory will depend on what OS the
program runs on. On some unix systems, once the memory has been allocated
to a process, the kernel might not try to reclaim it. Either use less
memory to start, or have the process kill itself.

You might be able to use use code like this to check your processes memory
size:

import resource
mem_used = resource.getrusage(resource.RUSAGE_SELF)[2]

Take care.

From guillermo.fernandez at epfl.ch  Tue Jan 13 12:18:48 2004
From: guillermo.fernandez at epfl.ch (Guillermo Fernandez Castellanos)
Date: Tue Jan 13 12:18:54 2004
Subject: [Tutor] memory problem (II part)
Message-ID: <40042878.2000300@epfl.ch>

Hi,

Thanks for the replies.

I tried the del statement, but does not seem to work for me. Maybe due 
to the high number of functions and variables, I was not able to 
identify rigth the variable to del. When one function is called and 
returns, it's the memory used by it's variables make free?

I ahve been a little confusing in the extract of code I gived. I use 
SQlite as database, and PySqlite for interfacing. I send a link to the 
(actual) code. it may be a little bit confusing and big:
http://diwww.epfl.ch/~cfernand/begotutor.tar.gz

The code is supposed to go through logs of the wireless network of my 
university, parse them and store the parsed results in a database. Then 
this database will be queried interactivelly  (with a command line 
interface) to get different information and statistics.

A little explanation of the code:
bego.py               : Command line interface. Simply interfaces the 
functions of begohandler to the cmd module to create commands.
begohandler.py  : interface to all functions bego is supposed to do 
(simple ones as opening and closing DBs, or more complicated ones like 
retrieving from the logs all the sessions of given macs)
files.py               : interface for opening and closing files. I'll 
delete it soon...
mac.py                : identifies MAC addresses and vendors
statemachine.py : identifies sessions for MAC addresses or APs
syslogdb.py        : interface to create, fill and retrieve information 
from the database. I use fetchall() here.
syslogparse.py   : the parse of the log files is done here

The problematic code is then probably shared among several files. When I 
start my program and do a 'macsessions' command (that will identify all 
sessions of a command) it will launch the do_macsessions function of 
begohandler, that will launch the macsessions function of statemachine.
This function will call get_macsessions that will query the database 
through the function machistory, both in statemachine,   that will call 
execute function in the syslogdb module to interface with the database. 
Complicated way, but I wanted a lot of modularity. it's quite clear when 
you catch the logic...

The main idea is that variables that take lot's of place exist all over 
the code. I tried to delete some of them, when they are not returned, 
but memory does not get lower.
Could this memory be occupied by the SQLite database itself?
Could the weakref be of any help here?
Comments about the code or logic are of course wellcome. I'm a begginer 
in programming design.

Thanks again,

Guille


From hec.villafuerte at telgua.com.gt  Tue Jan 13 14:40:57 2004
From: hec.villafuerte at telgua.com.gt (=?ISO-8859-1?Q?=22H=E9ctor_Villafuerte_D=2E=22?=)
Date: Tue Jan 13 12:39:05 2004
Subject: [Tutor] Avoiding MySQLdb Warnings
Message-ID: <400449C9.6020400@telgua.com.gt>

Hi all,
I'm using this piece of code to connect to a MySQL database:
loc_db = MySQLdb.connect(host = "localhost", user = "villaf", passwd = 
"hvillaf", db = "traffic", \
                         cursorclass=MySQLdb.BaseCursor)

But it raises the following exception:
AttributeError: 'module' object has no attribute 'BaseCursor'

I'm trying to use the BaseCursor, because it doesn't raises warnings 
from MySQL.
Any ideas ?
Thanks in advance,
Hector


From dyoo at hkn.eecs.berkeley.edu  Tue Jan 13 14:29:19 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue Jan 13 14:29:25 2004
Subject: [Tutor] Avoiding MySQLdb Warnings
In-Reply-To: <400449C9.6020400@telgua.com.gt>
Message-ID: <Pine.LNX.4.44.0401131126460.16500-100000@hkn.eecs.berkeley.edu>



On Tue, 13 Jan 2004, [ISO-8859-1] "H=E9ctor Villafuerte D." wrote:

> Hi all,
> I'm using this piece of code to connect to a MySQL database:
> loc_db =3D MySQLdb.connect(host =3D "localhost", user =3D "villaf", passw=
d =3D
> "hvillaf", db =3D "traffic", \
>                          cursorclass=3DMySQLdb.BaseCursor)
>
> But it raises the following exception:
> AttributeError: 'module' object has no attribute 'BaseCursor'
>
> I'm trying to use the BaseCursor, because it doesn't raises warnings
> from MySQL.


Hi Hector,


Ah!  Try:

###
loc_db =3D MySQLdb.connect(host =3D "localhost", user =3D "villaf",
                         passwd =3D "hvillaf",
                         db =3D "traffic",
                         cursorclass=3DMySQLdb.cursors.BaseCursor)
###

All of MySQLdb's specialized cursor classes should live in
MySQLdb.cursors.  You may need to do a:

###
import MySQLdb.cursors
###

at the head of your script.



Good luck to you!


From dyoo at hkn.eecs.berkeley.edu  Tue Jan 13 14:33:49 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue Jan 13 14:33:58 2004
Subject: [Tutor] graphics
In-Reply-To: <598B5E93DCDC614C9C1FE22406A0F5BE3678@pacer-server.pacer.local>
Message-ID: <Pine.LNX.4.44.0401131129590.16500-100000@hkn.eecs.berkeley.edu>



On Tue, 13 Jan 2004, philip gilchrist wrote:

> I am trying to use the graphics module from livewires, and can't get any
> timing working. It seems to me that the timing from the main program and
> the graphics are separate.


Hi Philip,


(I feel like I've answered this question several times already... *grin*)

If you're using the livewires package, use livewires's version of sleep().
So instead of:


    time.sleep(3)

just say:

    sleep(3)


The function you're using now, time.sleep(), actually conflicts with the
graphical subsystem in Livewires.


If you have the time, please email the Livewires folks and request that
they emphasize the time.sleep()-vs-livewires.sleep() issue in their
documentation.


Good luck to you!


From carroll at tjc.com  Tue Jan 13 16:09:53 2004
From: carroll at tjc.com (Terry Carroll)
Date: Tue Jan 13 16:09:59 2004
Subject: [Tutor] Newbie: Help on comparing files
In-Reply-To: <E1AgFyn-0005Y8-1P@fuse1.fusemail.net>
Message-ID: <Pine.LNX.4.44.0401131307380.26758-100000@violet.rahul.net>

On Mon, 12 Jan 2004, Isr Gish wrote:

> This is the code I wrote to compare the files.

Isr;  I haven't tried running your code, but did you look into the difflib
module to see if it did what you needed?

-- 
Terry Carroll
Santa Clara, CA
carroll@tjc.com 


From dyoo at hkn.eecs.berkeley.edu  Tue Jan 13 17:04:22 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue Jan 13 17:04:29 2004
Subject: [Tutor] Newbie: Help on comparing files
In-Reply-To: <Pine.LNX.4.44.0401131307380.26758-100000@violet.rahul.net>
Message-ID: <Pine.LNX.4.44.0401131352120.3098-100000@hkn.eecs.berkeley.edu>



On Tue, 13 Jan 2004, Terry Carroll wrote:

> On Mon, 12 Jan 2004, Isr Gish wrote:
>
> > This is the code I wrote to compare the files.
>
> Isr;  I haven't tried running your code, but did you look into the
> difflib module to see if it did what you needed?


Hi Terry,

difflib won't work for Isr's problem, because difflib takes the order of
elements into account.



As a concrete example:

###
>>> s1 = '''
... a
... b
... c
... '''
>>> s2 = '''
... b
... a
... c
... '''
>>> import difflib
>>> diff = difflib.ndiff(s1, s2)
>>> print ''.join(diff)
+
+ b
  a
- b-
  c
###


According to Isr's problem statement, we shouldn't get any output, because
all the elements in 's1' exist in 's2'.  So we can discount using
'difflib'.



However, there's still a module in the Standard Library that should be
very appropriate to Isr's question: the 'sets' module:

    http://www.python.org/doc/lib/module-sets.html


###
>>> from sets import Set
>>> t1 = 'a b c d'
>>> t2 = 'c b d e'
>>> s1 = Set(t1.split())
>>> s2 = Set(t2.split())
>>> s1
Set(['a', 'c', 'b', 'd'])
>>> s2
Set(['c', 'b', 'e', 'd'])
>>> s1 - s2
Set(['a'])
>>> s2 - s1
Set(['e'])
###



Hope this clears up the situation!


From missive at hotmail.com  Tue Jan 13 17:55:34 2004
From: missive at hotmail.com (Lee Harr)
Date: Tue Jan 13 17:55:40 2004
Subject: [Tutor] Re: Module with Financial Functions
Message-ID: <BAY2-F91s17fWHAHFMc0001c4fa@hotmail.com>

>A while ago I posted a message asking for a module with financial
>functions (compounded interest, annuities, IRR analysis, Depreciation
>tables).
>
>I followed up the one feedback I got and it seems that there is not
>comprehensive module.
>
>I am writing such a module now and I wonder, what would be the
>preferred/best/easiest place to make it available to others ?


"The Vaults of Parnassus"

http://www.vex.net/parnassus/

_________________________________________________________________
Add photos to your e-mail with MSN 8. Get 2 months FREE*. 
http://join.msn.com/?page=features/featuredemail


From alan.gauld at blueyonder.co.uk  Tue Jan 13 18:00:44 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Tue Jan 13 17:59:52 2004
Subject: [Tutor] Memory problem
References: <400184DE.1040402@epfl.ch> <009301c3d9b3$a7e10060$6401a8c0@xp>
	<20040113160502.GA11580@isc.upenn.edu>
Message-ID: <004a01c3da29$13803730$6401a8c0@xp>

> > I assume you tried the simple del() function to mark it for gc?
>
> Wether or not this actually frees up memory will depend on what OS
the
> program runs on. On some unix systems, once the memory has been
allocated
> to a process, the kernel might not try to reclaim it.

This is true but regular use of del() ensures that memory growth is
limited to the minimum needed.

However the best solution is to not grab all the memory at once.
Think of the days when mainframe computers had 4 Kilobytes of RAM,
and they processed the US national census with them? They used
techniques which processed the minimum data set in RAM at a time
and wrote intermediate results to backing store. We may need to
try the same kind of trick here (but using more than 4K of course!).

Alan G.


From alan.gauld at blueyonder.co.uk  Tue Jan 13 18:02:51 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Tue Jan 13 18:01:59 2004
Subject: [Tutor] Cloning lists to avoid alteration of original list
References: <p05200f0cbc29b4408405@[128.40.44.13]>
Message-ID: <005201c3da29$5f210660$6401a8c0@xp>

Sorry the formatting on that is so messed up I can't read it.

I do notice a lot of

else: pass

lines though. They are doing nothing but occupying screen space,
you might as well lose them. One advantage of Python's indentation
based syntax is that dangling else problems don't arise. The
disadbvantage is that bad indentation makes the code unreadable!

Alan G.



----- Original Message ----- 
From: "Alistair McGowan" <alistair.mcgowan@ucl.ac.uk>
To: <tutor@python.org>
Sent: Tuesday, January 13, 2004 2:42 PM
Subject: [Tutor] Cloning lists to avoid alteration of original list


> Dear All,
> I am having problems with cloning a list in such a
> way that it alters one list but not the other. The list for the new
> area should have "4"
>
> I have tried the standard procedure of taking a slice of the list,
> renaming it and operatiing on that, but to no avail. One issue that
> may make a difference is that I am taking a slice of a longer list,
> rather than the complete list.
>
> Here is the section of code, which is a class. I have tried cloning
> the two lists outside of the class, as well as within the class, but
> the program always carries out the changes to both lists. I
apologize
> for the length of the extact. If further information is needed,
> please let me know.
> Thanks in advance,
> Al
>
> class mergeTaxa: # geodispersal of taxon lists from colliding areas
> def __init__(self,m,y,clone1,clone2):
> self.mergetaxa=[] #empty list
> self.mergetaxa.append (name)#id of new merged area
> one = clone1
> two = clone2
> print "one", one
> print "two", two
> temp = []# an empty list for listing taxa for comparison
> for e in range (0, len(one)):# starts to loop over
> list 1 and writes to merged list
> x = one[e] #extracts info for each taxon in area
> a = one[e][0]#gets the id #
> if one [e][2]==0: #checks if taxon is alive
> one[e][3]= 4
> print clone1
> self.mergetaxa.append(x)
> temp.append(a)
> else:
> pass
> for j in range (0, len(two)):# starts loop over other list
> p=two[j]
> f = two[j][0]
> if two[j][2]==0:
> z = temp.count(f)# checks if taxon
> occurs in other area list
> if z ==0: #  if not add to new area list
> two[j][3]=4
> self.mergetaxa.append(p)
> else:
> pass
> else:
> pass
> merge = self.mergetaxa
> print "merged", merge
> print clone1
> print clone2
> tbya.append(merge)#writes out to main taxon by area matrix
> -- 
> Alistair J. McGowan
> Department of Earth Sciences,
> University College, London,
> London
>
> WC1E 6BT
>
> Phone: TBA
> Fax: +44 (0)20 7387 1612
>
> "Hope is a duty from which paleontologists are exempt."
> David Quammen
>
> "Empty causes. You've got yours and I've got mine"
> Greg Graffin
>


From michael at themontagnes.com  Tue Jan 13 18:51:19 2004
From: michael at themontagnes.com (Michael Montagne)
Date: Tue Jan 13 18:51:26 2004
Subject: [Tutor] Windows User Groups
Message-ID: <20040113235119.GA2077@themontagnes.com>

I need to be able to get all the Security groups that a particular
user is a member of.  This is on windows 2000.  :(.


-- 
Michael Montagne
michael@themontagnes.com
http://www.themontagnes.com

From littledanehren at yahoo.com  Tue Jan 13 19:49:41 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Tue Jan 13 19:49:44 2004
Subject: [Tutor] Windows User Groups
In-Reply-To: <20040113235119.GA2077@themontagnes.com>
Message-ID: <20040114004941.92180.qmail@web41804.mail.yahoo.com>

Michael Montagne wrote:
> I need to be able to get all the Security groups
> that a particular
> user is a member of.  This is on windows 2000.  :(.

There's builtin stuff for this on Unix in the os
module, but for Windows, you'll probably need to use
the win32all extension. Although you'll probably get a
better answer from someone else, for questions that
are like this (not often encountered and specific to
Windows), try the Python-win32 group. The information
for the list is at
http://mail.python.org/mailman/listinfo/python-win32 .

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes
http://hotjobs.sweepstakes.yahoo.com/signingbonus

From dyoo at hkn.eecs.berkeley.edu  Tue Jan 13 19:54:27 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue Jan 13 19:54:37 2004
Subject: [Tutor] Cloning lists to avoid alteration of original list 
	[example of refactoring]
In-Reply-To: <p05200f0cbc29b4408405@[128.40.44.13]>
Message-ID: <Pine.LNX.4.44.0401131135050.16500-100000@hkn.eecs.berkeley.edu>



On Tue, 13 Jan 2004, Alistair McGowan wrote:

> class mergeTaxa: # geodispersal of taxon lists from colliding areas
> 	def __init__(self,m,y,clone1,clone2):
> 		self.mergetaxa=[] #empty list
> 		self.mergetaxa.append (name)#id of new merged area
> 		one = clone1
> 		two = clone2

[code cut]



Hi Alistair,


The code is a little long; it's a little hard for me to figure out what's
happening.  Near the bottom of this message, let's talk about how to
refactor parts of it --- that may help us make the intent of the code more
clear.



Let's take a look at the parameters that the initializer takes in:

> 	def __init__(self,m,y,clone1,clone2):

What is 'm', 'y', 'clone1', and 'clone2'?  Those parameters need to be
documented, especially because the names 'm' and 'y' aren't really that
descriptive.



Also, it looks like you're depending on some global variables.  For
example, the reference to 'name' in:

> 		self.mergetaxa.append (name)#id of new merged area

appears to depend on a 'name' variable that's outside the class
definition.  Is this what you mean?




> 		one = clone1
> 		two = clone2

Ok, I think we've found a problem here.  The names 'one' and 'two' are now
aliases for the lists.  'one' and 'two' are not copies.  To demonstrate:

###
>>> mylist1 = range(10)
>>> mylist2 = mylist1
>>> mylist1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> mylist2
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> mylist1.pop()
9
>>> mylist1
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> mylist2
[0, 1, 2, 3, 4, 5, 6, 7, 8]
###

This issue may be causing problems the your code.


If we want to copy a list, we need to state that explicitely:

###
>>> from copy import copy
>>> mylist1 = range(10)
>>> mylist2 = copy(mylist1)
>>> mylist1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> mylist2
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> mylist1.pop()
9
>>> mylist1
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> mylist2
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
###





By the way, I want to concentrate on one of the inner loops in the
initializer:

> 		for e in range (0, len(one)):
> 			x = one[e] #extracts info for each taxon in area
> 			a = one[e][0]#gets the id #
> 			if one [e][2]==0: #checks if taxon is alive
> 				one[e][3]= 4
> 				print clone1
> 				self.mergetaxa.append(x)
> 				temp.append(a)
> 			else:
> 				pass

>From the code, I am now guessing that clone1 and clone2 are lists of
taxons.  It also looks like each taxon itself is a list --- the code is
using a list as an ad-hoc data structure.


Let's define a few accessor helper functions to make the loop above easier
to read:

###
def get_taxon_id(taxon):
    return taxon[0]

def is_taxon_alive(taxon):
    return taxon[2] == 0
###


The advantage of using these "accessors" is that it helps to document the
code.  Now the loop can be written as:

###
		for e in range (0, len(one)):
			x = one[e] #extracts info for each taxon in area
			a = get_taxon_id(one[e])
			if is_taxon_alive(one[e]):
				one[e][3]= 4
				print clone1
				self.mergetaxa.append(x)
				temp.append(a)
			else:
				pass
###




Another improvement: we can also iterate across lists directly.  That is,
instead of:

    for e in range(len(one)):
        element = one[e]
        ...

we can more directly iterate on the elements themselves:

    for element in one:
        ...


With these changes, the inner loop can be rewritten as:

###
for taxon in clone1:
    if is_taxon_alive(taxon):
        taxon[4] = 4                 ## What is this doing?
        self.mergetaxa.append(taxon)
        temp.append(get_taxon_id(taxon))
###


And we can summarize the effect of this loop as this: self.mergetaxa
contains all of the alive taxons.  'temp' contains all of those alive
taxon's ids --- it might be good to rename 'temp' to something that
describes those ids.



Anway, let's give this process a name --- let's call it
'collect_alive_taxons()':

###
def collect_alive_taxons(taxons):
    """Given a list of taxons, returns a list of the alive taxons, as well
       as their ids."""
    alive_taxons = []
    alive_taxon_ids = []
    for taxon in taxons:
        if is_taxon_alive(taxon):
            taxon[4] = 4                 ## What is this doing?  What is
                                         ## the fourth field?
            alive_taxons.append(taxon)
            alive_taxon_ids.append(get_taxon_id(taxon))
    return (alive_taxons, alive_taxon_ids)
###


Or something like this... *grin* The important thing is to give a good
name to this process.



If we've refactored the inner loop as a separate function or method, the
program might look something like this:

###

class mergeTaxa: # geodispersal of taxon lists from colliding areas
    def __init__(self, m, y, clone1, clone2):
        self.mergetaxa=[] #empty list
        self.mergetaxa.append (name)#id of new merged area
        alive_taxon_ids = self.collect_alive_taxons_in_mergetaxa(clone1)
        ### ... [second loop and the remainder of the initializer follows
        ###      this]


    def collect_alive_taxons_in_mergetaxa(self, taxons):
        """Given a list of taxons, adds the alive taxons to
           self.mergetaxa.  Returns a list of the alive taxon ids."""
        alive_taxon_ids = []
        for taxon in taxons:
           if is_taxon_alive(taxon):
               taxon[4] = 4                    ## ??
               self.mergetaxa.append(taxon)
               alive_taxon_ids.append(get_taxon_id(taxon))
        return alive_taxon_ids


def get_taxon_id(taxon):
    """Gets the taxon id out of a taxon record."""
    return taxon[0]


def is_taxon_alive(taxon):
    """Returns true if the taxon is alive."""
    return taxon[2] == 0
###


The initializer still needs work.  But I hope this shows that this process
of "refactoring" can improve the design of the code.



I hope this helps!


From littledanehren at yahoo.com  Tue Jan 13 20:25:23 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Tue Jan 13 20:25:29 2004
Subject: [Tutor] Cloning lists to avoid alteration of original list
In-Reply-To: <p05200f0cbc29b4408405@[128.40.44.13]>
Message-ID: <20040114012523.77245.qmail@web41808.mail.yahoo.com>

Dear All,
> 		I am having problems with cloning a list in such a
> 
> way that it alters one list but not the other. The
> list for the new 
> area should have "4"
> 
> I have tried the standard procedure of taking a
> slice of the list, 
> renaming it and operatiing on that, but to no avail.
> One issue that 
> may make a difference is that I am taking a slice of
> a longer list, 
> rather than the complete list.
> 
> Here is the section of code, which is a class. I
> have tried cloning 
> the two lists outside of the class, as well as
> within the class, but 
> the program always carries out the changes to both
> lists. I apologize 
> for the length of the extact. If further information
> is needed, 
> please let me know.
> 	Thanks in advance,
> 			Al

Try cloning the list using deepcopy. Here's an
example:

>>> from copy import deepcopy
>>> x = range(3)
>>> x
[0, 1, 2]
>>> y = x #just links it
>>> x.append(3)
>>> x
[0, 1, 2, 3]
>>> y
[0, 1, 2, 3]
>>> z = deepcopy(x)
>>> z
[0, 1, 2, 3]
>>> x.append(4)
>>> x
[0, 1, 2, 3, 4]
>>> y
[0, 1, 2, 3, 4]
>>> z
[0, 1, 2, 3]

If you could follow that, deepcopy copies the list but
it is not still linked.

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes
http://hotjobs.sweepstakes.yahoo.com/signingbonus

From piir at earthlink.net  Tue Jan 13 22:10:56 2004
From: piir at earthlink.net (Todd G. Gardner)
Date: Tue Jan 13 22:11:11 2004
Subject: [Tutor] Starting a basic RS232 application?
Message-ID: <CAENJDPIMKAJINIKKHOCMEIDCCAA.piir@earthlink.net>

Hello all,

I would appreciate your experience in determining the best way to learn how
to write a basic serial (RS232) software package.

I will need to do serial communication between one Windows pc and a custom
device around Feb. 2nd.  I currently do not have this device nor can I find
out the protocol to talk to this device until Feb. 2nd.

In asking myself, what is the best way to learn how to write a simple RS232
communication software I was thinking of using pyserial and writing a
laplink type of software.  I was thinking that this would teach me how to
write serial communication software in python23 to simply transfer data
between two local Windows pcs.

Any suggestions would be greatly appreciated!

Thank you,

Todd


From isrgish at fusemail.com  Tue Jan 13 23:52:54 2004
From: isrgish at fusemail.com (Isr Gish)
Date: Tue Jan 13 23:52:58 2004
Subject: [Tutor] Newbie: Help on comparing files
Message-ID: <E1Agd14-000HdG-EC@fuse1.fusemail.net>

Thanks Danny, I'll try this.

-----Original Message-----
   >From: "Danny Yoo"<dyoo@hkn.eecs.berkeley.edu>
   >Sent: 1/13/04 5:04:22 PM
   >To: "Terry Carroll"<carroll@tjc.com>
   >Cc: "tutor@python.org"<tutor@python.org>
   >Subject: Re: [Tutor] Newbie: Help on comparing files
     >
   >
   >On Tue, 13 Jan 2004, Terry Carroll wrote:
   >
   >> On Mon, 12 Jan 2004, Isr Gish wrote:
   >>
   >> > This is the code I wrote to compare the files.
   >>
   >> Isr;  I haven't tried running your code, but did you look into the
   >> difflib module to see if it did what you needed?
   >
   >
   >Hi Terry,
   >
   >difflib won't work for Isr's problem, because difflib takes the order of
   >elements into account.
   >
   >
   >
   >As a concrete example:
   >
   >###
   >>>> s1 = '''
   >... a
   >... b
   >... c
   >... '''
   >>>> s2 = '''
   >... b
   >... a
   >... c
   >... '''
   >>>> import difflib
   >>>> diff = difflib.ndiff(s1, s2)
   >>>> print ''.join(diff)
   >+
   >+ b
   >  a
   >- b-
   >  c
   >###
   >
   >
   >According to Isr's problem statement, we shouldn't get any output, because
   >all the elements in 's1' exist in 's2'.  So we can discount using
   >'difflib'.
   >
   >
   >
   >However, there's still a module in the Standard Library that should be
   >very appropriate to Isr's question: the 'sets' module:
   >
   >    http://www.python.org/doc/lib/module-sets.html
   >
   >
   >###
   >>>> from sets import Set
   >>>> t1 = 'a b c d'
   >>>> t2 = 'c b d e'
   >>>> s1 = Set(t1.split())
   >>>> s2 = Set(t2.split())
   >>>> s1
   >Set(['a', 'c', 'b', 'd'])
   >>>> s2
   >Set(['c', 'b', 'e', 'd'])
   >>>> s1 - s2
   >Set(['a'])
   >>>> s2 - s1
   >Set(['e'])
   >###
   >
   >
   >
   >Hope this clears up the situation!
   >


Thanks to all,
Isr


From hal at dtor.com  Wed Jan 14 00:35:02 2004
From: hal at dtor.com (Hal Wine)
Date: Wed Jan 14 00:37:29 2004
Subject: [Tutor] debugging approach for shimmed classes
Message-ID: <4004D506.9000102@dtor.com>

[I heard about this list at the Bay Piggies meeting, so I'm a first time 
poster.]

I just slogged through a painful debugging session, and would love to 
learn of a better way to do it.

I was trying out newsbot (on jabberstudio.org) to talk to a jabber 
server I run. The difference is I run an SSL only server. So I had to 
make some mods to newsbot to do to make it work on https.

However, it kept failing, reporting no SSL Support. I could connect with 
seemingly identical code to an https server on the same host. Finally, 
through use of print statements - I figured out that a sub module of 
newsbot used Timothy O'Malley's timeoutsocket.py to shim python's 
socket.socket method. That module has been incorporated into python 2.3, 
so there was a name space collision.

So, basically two questions:

1. What would be a better method than random print statements to find a 
problem cause by a shim installed elsewhere?

2. How should one write code to use a shim module only if it's not 
already part of python? I.e. how best do I modify the newsbot code to 
not use the shim under python 2.3 or later.

Thanks,
--Hal


From credo2004 at fmail.co.uk  Wed Jan 14 03:06:59 2004
From: credo2004 at fmail.co.uk (credo)
Date: Wed Jan 14 03:07:03 2004
Subject: [Tutor] Starting a basic RS232 application?
In-Reply-To: <CAENJDPIMKAJINIKKHOCMEIDCCAA.piir@earthlink.net>
References: <CAENJDPIMKAJINIKKHOCMEIDCCAA.piir@earthlink.net>
Message-ID: <20040114080659.1E66F46531@server1.messagingengine.com>


On Tue, 13 Jan 2004 22:10:56 -0500, "Todd G. Gardner"
<piir@earthlink.net> said:
> Hello all,
> 
> I would appreciate your experience in determining the best way to learn
> how
> to write a basic serial (RS232) software package.
> 
> I will need to do serial communication between one Windows pc and a
> custom
> device around Feb. 2nd.  I currently do not have this device nor can I
> find
> out the protocol to talk to this device until Feb. 2nd.
> 
> In asking myself, what is the best way to learn how to write a simple
> RS232
> communication software I was thinking of using pyserial and writing a
> laplink type of software.  I was thinking that this would teach me how to
> write serial communication software in python23 to simply transfer data
> between two local Windows pcs.
> 
> Any suggestions would be greatly appreciated!
> 
> Thank you,
> 
> Todd
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

I'm also interested in this. If someone could lend there experience :)

Thanx in advance

Credo

-- 
http://www.fastmail.fm - IMAP accessible web-mail

From SWidney at LasVegasNevada.GOV  Wed Jan 14 11:02:49 2004
From: SWidney at LasVegasNevada.GOV (Scott Widney)
Date: Wed Jan 14 11:05:44 2004
Subject: [Tutor] RE: Windows User Groups
Message-ID: <0E5508EBA1620743B409A2B8365DE16F0E6CF65C@sovereign.ci.las-vegas.nv.us>

Date: Tue, 13 Jan 2004 15:51:19 -0800
From: Michael Montagne <michael@themontagnes.com>
Subject: [Tutor] Windows User Groups
To: tutor@python.org
Message-ID: <20040113235119.GA2077@themontagnes.com>
Content-Type: text/plain; charset=us-ascii

I need to be able to get all the Security groups that a particular
user is a member of.  This is on windows 2000.  :(.


-- 
In brief, with the win32all package installed, import win32net then call
win32net.NetUserGetGroups('PDCname','username'). You'll get a list of tuples
whose first elements are the names of the groups.


Scott

From dyoo at hkn.eecs.berkeley.edu  Wed Jan 14 14:20:32 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Jan 14 14:20:43 2004
Subject: [Tutor] Memory problem
In-Reply-To: <004a01c3da29$13803730$6401a8c0@xp>
Message-ID: <Pine.LNX.4.44.0401141050250.804-100000@hkn.eecs.berkeley.edu>



On Tue, 13 Jan 2004, Alan Gauld wrote:

> > > I assume you tried the simple del() function to mark it for gc?
> >
> > Wether or not this actually frees up memory will depend on what OS the
> > program runs on. On some unix systems, once the memory has been
> > allocated to a process, the kernel might not try to reclaim it.
>
> This is true but regular use of del() ensures that memory growth is
> limited to the minimum needed.

Hi Alan,


We better clarify the role of del() here: del does not tell the system to
mark memory for garbage collection!  Rather, it removes a name binding,
and in effect decrements the reference count of an object.


Concrete example:

###
>>> numbers = range(10)
>>> digits = numbers
>>> numbers
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> digits
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
###

Here, we've constructed one object --- a range of 10 numbers --- and bound
it to the name 'numbers'.  We've also bound that same object to the name
'digits'.



Ok, now let's do a del().

###
>>> del(digits)
###

It's important to see that all that del() does is drop the 'digits' name.

###
>>> digits
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'digits' is not defined
###



But the list that we've created is still accessible through our 'numbers'
name:

###
>>> numbers
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
###


The C implementation of Python uses a reference count scheme to manage
memory: when the number of names that refer to an object drops to zero,
then Python knows its safe to reclaim that memory.


(I'm not quite telling the truth: Python does have a hybrid system that
can handle recursive structures, so it's resistant to the kind of problems
that would confound a simple reference count system.)



Python programmers rarely use del() explicitly on variable names, because
names automatically drop out anyway whenever a local function exits.  If
we have something like:

###
>>> def foo():
...     bar = range(10**6)
...
>>> while 1:
...     foo()
...
###

then this code spins the computer's wheels, but at least it does not
exhaust memory.  'bar' goes out of scope when foo() exits, and then that
range of numbers gets collected since its reference count drops to zero.


The only place I've really seen del() used is when we drop out key/value
pairs from a dictionary:

###
>>> d = {1: 'one', 2: 'two', 3: 'three'}
>>> del d[2]
>>> d
{1: 'one', 3: 'three'}
###


But that's about it.  del() probably won't fix a leak problem.  Any
"leaking"  that's occurring in pure Python code should be the result of
either using global variables, or somehow accumulating a lot of values in
a container and passing that container around.  We really do need to see
code, and trace the flow of variables around --- from there, we can
probably pick out where the leak is occurring.



Hope this helps!


From dyoo at hkn.eecs.berkeley.edu  Wed Jan 14 14:30:58 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Jan 14 14:31:06 2004
Subject: [Tutor] memory problem (II part)
In-Reply-To: <40042878.2000300@epfl.ch>
Message-ID: <Pine.LNX.4.44.0401141121300.804-100000@hkn.eecs.berkeley.edu>



On Tue, 13 Jan 2004, Guillermo Fernandez Castellanos wrote:

> The main idea is that variables that take lot's of place exist all over
> the code. I tried to delete some of them, when they are not returned,
> but memory does not get lower.

Hi Guillermo,

Just checking up on this: when does memory usage shoot up?  Do you know if
it's when you're querying the database?  If so, then we can concentrate on
how the database is being queried.




> Could this memory be occupied by the SQLite database itself?

It's a possibility, though I wouldn't assume this quite yet.  I can't take
a look at the code yet (I'm still at work!  *grin*), but when I get home,
I'll see if I can catch something in the code.  Thanks for posting your
code up.



(Personal experience: I did run into a real leaking bug in MySQLdb about
two years ago,

http://sourceforge.net/tracker/index.php?func=detail&aid=536624&group_id=22307&atid=374932

So leaking can happen in C extensions if the C extension is buggy.  But
still, such things are really darn rare.  Let's just make sure your code
is fine before we start hacking at SQLite... *grin*)



Talk to you later!


From zmerch at 30below.com  Wed Jan 14 14:41:02 2004
From: zmerch at 30below.com (Roger Merchberger)
Date: Wed Jan 14 14:36:54 2004
Subject: [Tutor] Starting a basic RS232 application?
In-Reply-To: <20040114080659.1E66F46531@server1.messagingengine.com>
References: <CAENJDPIMKAJINIKKHOCMEIDCCAA.piir@earthlink.net>
	<CAENJDPIMKAJINIKKHOCMEIDCCAA.piir@earthlink.net>
Message-ID: <5.1.0.14.2.20040114143507.00adeb68@mail.30below.com>

Rumor has it that credo may have mentioned these words:

>On Tue, 13 Jan 2004 22:10:56 -0500, "Todd G. Gardner"
><piir@earthlink.net> said:

>[snippety]

> > In asking myself, what is the best way to learn how to write a simple
> > RS232
> > communication software I was thinking of using pyserial and writing a
> > laplink type of software.  I was thinking that this would teach me how to
> > write serial communication software in python23 to simply transfer data
> > between two local Windows pcs.

[snippety]

>I'm also interested in this. If someone could lend there experience :)

<MODE='AOL'>
Mee Tooo!
</MODE>

I'm interested in this for 2 reasons:
1) I'd like to get into learning to program some Atmel microcontrollers I 
have, and
2) being able to communicate with my 'oldie but goodie' Tandy Model 200 
laptop - eventually making a Winders and/or Linux floppy drive emulator 
(the floppy drive worked at 19200 thru the serial port...)

Thanks,
Roger "Merch" Merchberger

--
Roger "Merch" Merchberger   | "Profile, don't speculate."
sysadmin, Iceberg Computers |     Daniel J. Bernstein
zmerch@30below.com          |


From alan.gauld at blueyonder.co.uk  Wed Jan 14 14:57:22 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Wed Jan 14 14:56:14 2004
Subject: [Tutor] Memory problem
References: <Pine.LNX.4.44.0401141050250.804-100000@hkn.eecs.berkeley.edu>
Message-ID: <000401c3dad8$9fdce1b0$6401a8c0@xp>

> > > > I assume you tried the simple del() function to mark it for
gc?
> > >
> We better clarify the role of del() here: del does not tell the
system to
> mark memory for garbage collection!  Rather, it removes a name
binding,
> and in effect decrements the reference count of an object.

Thats true of course but the fewer names left hanging around the
more likely te garbage collector kicks in.

> But the list that we've created is still accessible through our
'numbers'
> name:
> ###
> >>> numbers
> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
> ###

Indeed so you need to be careful if making multiple references
to the same object. Its the opposite of C where you can delete
an object thats referred to by multiple pointers and strange
things happen if you subsequently try to access the deleted
object.

> The only place I've really seen del() used is when we drop out
key/value
> pairs from a dictionary:

Or indeed any list object where we collect data, which is
what seemed to be happening in the OP. If we store data
in a list (or dictionary) for later processing, and fail
to del() the item after processing we effectively get a
Python memory leak. This it is important to remove items
from lists when we are finished with them. This is the one
place where Python puts responsibility for "memory
management" onto the programmer. Of course once the list
itself goes out of scope the items contained therein will
too, but if the list is global that won't be till the
end of the program...

> But that's about it.  del() probably won't fix a leak problem.

NO, but it helps where dynamically created data is stored
in a list.

> either using global variables, or somehow accumulating a lot of
values in
> a container and passing that container around.

Nope, just storing stuff in a container and forgetting
to del them promptly has the same effect. The container
just keeps on growing.

Alan G.


From isrgish at fusemail.com  Wed Jan 14 15:01:28 2004
From: isrgish at fusemail.com (Isr Gish)
Date: Wed Jan 14 15:01:32 2004
Subject: [Tutor] Newbie: Help on comparing files
Message-ID: <E1AgrCT-000G99-D7@fuse1.fusemail.net>


Danny Yoo wrote:

   >However, there's still a module in the Standard Library that should be
   >very appropriate to Isr's question: the 'sets' module:
   >
   >    http://www.python.org/doc/lib/module-sets.html
   >
   >
   >###
   >>>> from sets import Set
   >>>> t1 = 'a b c d'
   >>>> t2 = 'c b d e'
   >>>> s1 = Set(t1.split())
   >>>> s2 = Set(t2.split())
   >>>> s1
   >Set(['a', 'c', 'b', 'd'])
   >>>> s2
   >Set(['c', 'b', 'e', 'd'])
   >>>> s1 - s2
   >Set(['a'])
   >>>> s2 - s1
   >Set(['e'])
   >###
   >
I tried it and it works great. But its not good for what I want. Because I want the return should be in the same order its in the file.
IOW if the first element of file1 is not in file2, then I want it to be the first thing in the output file. And sets don't keep it in the same order that they where before.

Thanks Again
Isr


From magnus at thinkware.se  Wed Jan 14 15:59:18 2004
From: magnus at thinkware.se (Magnus Lycka)
Date: Wed Jan 14 16:24:50 2004
Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gU2VxdWVuY2UgQ29tcGFyaXNvbg==?=
Message-ID: <think001_4005a7429166d@webmail.thinkware.se>

>   i was reading the Sequence comparison section of
> python documentation. but i really didnot understand
> from it. if anyne of you can explain it to me then it
> will be very kind of you. the below is the examples
> with the questions i have in mind.

If you think of < as a tool for sorting, I think
things will fall into place. In a sorted list, an
item X will always come before another item Y, if
X < Y. Ok?

The concept of "less than" and the "<" symbol is of
mathematical origin, and in that context only numbers
are compared, but in programming we have broadened the 
concept a bit.
 
> >>> (1, 2, 3)              < (1, 2, 4)
> True
> # Q.1 why it returns True when 1 is not lower then 1
> and 2 is not lower then 2. only 3 is lower then 4

Would section 1.2.3 come before section 1.2.4 in a
manual? I think so...

It's reasonable to think of (1,2,4) in a similar way
that you think of 123 or "ABC". I.e. the first element
is of greater importance than the following, and only
if the first elements are equal do you compare the rest.

Imagine that the < was only defined for simple values
and you would use a function less_than(a,b) instead of
a < b for compound values. Then you could write it a
bit like like this:

def less_than(a, b):
    # Compare first element in sequence.
    if a[0] < b[0]:
        # First element is less
        return True
    elif a[0] == b[0]:
        # Starts equal, compare the rest
        return less_than(a[1:], b[1:])
    else:
        # First element is greater
        return False

The obvious problem with the code above is that it doesn't
handle empty sequences, so it won't work in real life. (But
who cares, we don't need it anyway! :)

> >>> 'ABC' < 'C' < 'Pascal' < 'Python'
> True
> # Q.2 what is the procedure of comparison in different
> size of sequences because 'ABC' is greater then 'C' in
> size and 'Pascal' is greater then 'C' but equal to
> 'Python' in size

Forget about size. Think about how these would be sorted
in an alphabetical list. You wouldn't put C before ABC in
an alphabetical index, would you?

> >>> (1, 2, 3, 4)           < (1, 2, 4)
> True
> # the above 2 question (Q.1 and Q.2) applies to this
> comparison because this tuples have different sizes

Would section 1.2.3.4 come before 1.2.4 in a book?
 
> >>> (1, 2)                 < (1, 2, -1)
> True
> # i totally didnot understand it

Anything is more than nothing... Why is that difficult
to understand.
 
> >>> (1, 2, 3)             == (1.0, 2.0, 3.0)
> True
> # i understand it a little bit that the elements of
> second tuple converted to the type of elements of
> first tuple and then compared but what if we compare
> (1,"string",3) == (1.0,2.0,3.0)

How objects of different types compare to each other is
rather arbitrary. You can't really say what is "right"
in this case, but there is a point in making sure that
python behaves in a consistent way. You should always be
able to sort a python list and get a consistent result.
Sorting depends on comparision.

See also:
http://www.python.org/doc/current/ref/comparisons.html

"The operators <, >, ==, >=, <=, and != compare the values 
of two objects. The objects need not have the same type. If 
both are numbers, they are converted to a common type. 
Otherwise, objects of different types always compare unequal, 
and are ordered consistently but arbitrarily. "
 
> >>> (1, 2, ('aa', 'ab'))   < (1, 2, ('abc', 'a'), 4)
> True
> # may be i will understand it if someone explains me
> the above comparisons
> 
> Hameed khan



-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se

From magnus at thinkware.se  Wed Jan 14 16:25:23 2004
From: magnus at thinkware.se (Magnus Lycka)
Date: Wed Jan 14 16:25:31 2004
Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gU2VxdWVuY2UgQ29tcGFyaXNvbg==?=
Message-ID: <think001_4005adb23f7a4@webmail.thinkware.se>

Michael Janssen wrote:
> python compares each element from left to right until it founds a pair
> of element, where the condition (<) is true:
> 1 < 1 ---> python find's: not true therefore:
> 2 < 2 ---> not true, next try
> 3 < 4 ---> true. Overall condition is true

Wrong. Python only goes to the next element in a sequence
as long as all the previous element pairs compared equal.

If > is true for a pair, False is returned at once.

No element is less than any element, so it looks like
this...roughly.

(lhs = left hand side, you guess what rhs is)

def less_than(lhs, rhs):
    # Is lhs a sequence? (i.e. it has a length)
    if hasattr(lhs, '__len__'):
        # Are they both sequences?
        if hasattr(rhs, '__len__'):
            # Yes they are!
            # Either empty?
            if len(rhs) == 0:
                # lhs is either equal or greater
                return False
            elif len(lhs) == 0:
                # Nothing is less than something
                return True
            else:
                # Both are non-empty
                # Compare first elements
                if lhs[0] < rhs[0]:
                    return True
                elif lhs[0] == rhs[0]:
                    return less_than(lhs[1:], rhs[1:])
                else:
                    return False
        else:
            # Only lhs is a sequence. Make the arbitrary decision
            # that a sequence is always greater than a non-sequence
            return False
    else:
        # lhs is no sequence. Is rhs a sequence?
        if hasattr(rhs, '__len__'):
            # As we just said, sequence is greater...
            return True
        else:
            # Neither is a sequence, assume that we understand < here.
            return lhs < rhs

In real life, there are other non-obvious non-sequences, such as classes,
modules, files and mappings etc.

-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se

From magnus at thinkware.se  Wed Jan 14 16:44:02 2004
From: magnus at thinkware.se (Magnus Lycka)
Date: Wed Jan 14 16:44:09 2004
Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gU3RhcnRpbmcgYSBiYXNpYyBSUzIzMiBhcHBsaWNhdGlvbj8=?=
Message-ID: <think001_4005b4e578498@webmail.thinkware.se>

Todd G. Gardner wrote:
> I would appreciate your experience in determining the best way to learn how
> to write a basic serial (RS232) software package.

Have you tried using the example code in the pyserial 
library? (See http://pyserial.sourceforge.net/)

Perhaps you should start by establishing a very
rudimentary serial communication between 2 PCs
just using a cable between them and using a
simple serial terminal emulator program: The kind
of program you run if you would use your PC as
a dumb terminal. I thought the hyperterminal would
do, but it seems it expected to find a modem on my
machine at least. I guess something like TeraTerm
<http://hp.vector.co.jp/authors/VA002416/teraterm.html>
will do. If you can type something on one computer,
and see it on the other, you have at least established
a connection, and you know that the cable work etc.

Then you can try to write something on one PC and replace
the terminal in that end with that. Maybe just a little
program that echoes all its input, or maybe converts
lower case to upper case etc. Perhaps something that
emulates the device you expect to get.

Once you have written a program that can interact with
a manual terminal session in one end, you can start
writing code for the other end as well...

Good luck!

-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se

From isrgish at fusemail.com  Wed Jan 14 20:33:36 2004
From: isrgish at fusemail.com (Isr Gish)
Date: Wed Jan 14 20:33:33 2004
Subject: [Tutor] Sequence Comparison
Message-ID: <E1AgwNr-000LqT-Tj@fuse1.fusemail.net>

Magnus Lycka wrote: 

   >> >>> (1, 2)                 < (1, 2, -1)
   >> True
   >> # i totally didnot understand it
   >
   >Anything is more than nothing... Why is that difficult
   >to understand.
  
I would rather think that -1 which is less then 0 whould be less then nothing.



Isr Gish


From littledanehren at yahoo.com  Wed Jan 14 21:17:09 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Wed Jan 14 21:17:14 2004
Subject: [Tutor] Reviewing scripts
In-Reply-To: <20040115010031.16123.qmail@web41405.mail.yahoo.com>
Message-ID: <20040115021709.52105.qmail@web41813.mail.yahoo.com>

Barnaby Scott wrote:
> THanks for your reply. I'm sure it's just me, but I
> can't make out how to post a link on your site. I
> have
> therefore enclosed the script in case you are
> willing
> to put it there. If not - apologies for sending you
> all this garbage!
> 
> Thanks again

Just write something in CamelCase (eg PissiPissi) on
any page. I put up your program and made some changes
to it at http://zope.org/Members/LittleDan/PissiPissi
. Most of the error were really minor or just
stylistic (but there are coding conventions that
should be followed), although I may be missing
something. Could other people review the code?

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes
http://hotjobs.sweepstakes.yahoo.com/signingbonus

From rantek at pacific.net.sg  Thu Jan 15 02:58:25 2004
From: rantek at pacific.net.sg (William Rance)
Date: Thu Jan 15 03:02:04 2004
Subject: [Tutor] Re: RS232 Serial Application
References: <E1Agx4V-0006Kj-1o@mail.python.org>
Message-ID: <002101c3db3d$5b539c40$c26b18d2@pcmaster>

As Python is compiled in C, surely why not write the communications part in
C and use Python as a Front End script
Bill Rance


From carroll at tjc.com  Thu Jan 15 03:06:37 2004
From: carroll at tjc.com (Terry Carroll)
Date: Thu Jan 15 03:06:47 2004
Subject: [Tutor] Question on the "object" object
Message-ID: <Pine.LNX.4.44.0401142349400.26758-100000@violet.rahul.net>

in response to Todd's question in the thread "Do tuples replace 
structures?", I ended up saying:

> I prefer to use classes, though for just about anything where I need a
> structure:
>
> >>> class person:
> ...   def __init__(self,fname,lname,age,height):
> ...     self.fname = fname
> ...     self.lname = lname
> ...     self.age = age
> ...     self.height = height
> ...
> >>> record = person("Jim", "Smith", 22, 130)
> >>> record.fname
> 'Jim'

This got me wondering; how minimalist can you get in a class definition 
and still be able to access arbitrarily-named attributes?  Some toying 
around to figure that out has gotten me into something I don't understand, 
and would like to.

Now, none of the following three objects raise an Attribute error as a
result of assigning to foo.bar, a previously unreferenced attribute:

>>> #old-style class
... class c1:
...     pass
...
>>> o1=c1()
>>> o1.a="test"
>>> print "o1", o1.a
o1 test

>>> #new-style class
... class c2(object):
...     pass
...
>>> o2=c2()
>>> o2.a="test"
>>> print "o2", o2.a
o2 test

>>> #new-style class, calling object's __init__
... class c3(object):
...     def __init__(self):
...         object.__init__(self)
...
>>> o3=c3()
>>> o3.a="test"
>>> print "o3", o3.a
o3 test

Okay, so if we can do this with an instance of an object from a class that 
inherits from the "object" object, why can't we do the same with an 
instance of the "object" object itself?  (I tried several times to phrase 
that both clearly and accurately, and I'm not sure I got there; the 
example should be clearer.):

>>> #using object directly, instead of a class inherited from it
... o4=object()
>>> o4.a="test"
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'object' object has no attribute 'a'


In sum, why does:

 x=object()
 x.a

raise an AttributeError, when

 x=c()
 x.a

Does note, where c is nothing more than a flat-out, no-frills subclass of 
object?



From dyoo at hkn.eecs.berkeley.edu  Thu Jan 15 03:35:14 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Jan 15 03:35:20 2004
Subject: [Tutor] Sequence Comparison  [prefixes come first!]
In-Reply-To: <E1AgwNr-000LqT-Tj@fuse1.fusemail.net>
Message-ID: <Pine.LNX.4.44.0401142347480.32576-100000@hkn.eecs.berkeley.edu>



On Wed, 14 Jan 2004, Isr Gish wrote:

> Magnus Lycka wrote:
>
>    >> >>> (1, 2)                 < (1, 2, -1)
>    >> True
>    >> # i totally didnot understand it
>    >
>    >Anything is more than nothing... Why is that difficult
>    >to understand.
>
>   I would rather think that -1 which is less then 0 whould be less then
> nothing.

Hi Isr,


Unfortunately, this reason doesn't generalize well if that third component
is positive.  It's also true that (1, 2) < (1, 2, 42).


Lexicographic ordering should be a very familiar concept.  English
dictionaries follow the same method of ordering words.

If you're on a Unix system, here's a brute-force way to see some examples:

###
words = [w.strip() for w in open('/usr/share/dict/words')]
words.sort()
i = 0
while i < len(words):
    for j in range(i+1, len(words)):
        if words[j].startswith(words[i]):
            print words[i], words[j]
        else:
            break
    i = i + 1
###

I know there must be a smarter way to do this, but I'm lazy, and it's
late... *grin*


Here's a selection of what the program picks out:

    aft    afterburner
    thin thingumbob
    woo    wooden
    wrist  wristband
    yore   yoretime

In all these cases, the left word is a 'prefix' of the right word.  In
summary: prefixes come first.  *grin*


Because of our experience looking up words in a dictionary, we know that
'aft' comes before 'afterburner'.  It's not something arbitrary, but a
systematic way that we use to sort our words.

If this makes sense, then it's just a matter of crossing our eyes a little
to see that

     (1, 2) < (1, 2, -1)

is the same thing, just in a different domain.  Instead of comparing
"letter-by-letter", we're comparing element by element.


Hope this helps!


From rmangaliag at slu.edu.ph  Thu Jan 15 04:52:21 2004
From: rmangaliag at slu.edu.ph (ali)
Date: Thu Jan 15 04:39:32 2004
Subject: [Tutor] different results: why?
Message-ID: <1074160341.400662d5f2ebd@mbox>


why are the results of these codes different?

###### 1 ######

if True==[1,2,3]:
    print "test"

###### 2 ######

if [1,2,3]:
    print "test"

thanks...

ali

----------------------------------------------------------------
This message was sent using IMP, the Internet Messaging Program.

From rmangaliag at slu.edu.ph  Thu Jan 15 05:07:03 2004
From: rmangaliag at slu.edu.ph (ali)
Date: Thu Jan 15 05:02:01 2004
Subject: [Tutor] results: why different?
Message-ID: <004001c3db4f$6380f180$da19a8c0@slu.edu.ph>


why are the results of these codes different?

###### 1 ######

if True==[1,2,3]:
    print "test"

###### 2 ######

if [1,2,3]:
    print "test"

thanks...

ali



From op73418 at mail.telepac.pt  Thu Jan 15 06:54:19 2004
From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=)
Date: Thu Jan 15 06:52:13 2004
Subject: [Tutor] Sequence Comparison
In-Reply-To: <E1AgwNr-000LqT-Tj@fuse1.fusemail.net>
References: <E1AgwNr-000LqT-Tj@fuse1.fusemail.net>
Message-ID: <jnvc009jdb4sj1tmuisgncugnqfabfa35g@4ax.com>

Em Wed, 14 Jan 2004 20:33:36 -0500, "Isr Gish" <isrgish@fusemail.com>
atirou este peixe aos pinguins:

>Magnus Lycka wrote: 
>
>   >> >>> (1, 2)                 < (1, 2, -1)
>   >> True
>   >> # i totally didnot understand it
>   >
>   >Anything is more than nothing... Why is that difficult
>   >to understand.
>  
>I would rather think that -1 which is less then 0 whould be less then nothing.
>

But 0 is not nothing. It's better than nothing.

The better analogy is an empty bag and no bag at all. You can still
put your head inside an empty bag and choke to death.

Best,
G. Rodrigues

From godoy at ieee.org  Thu Jan 15 06:55:52 2004
From: godoy at ieee.org (Jorge Godoy)
Date: Thu Jan 15 06:56:13 2004
Subject: [Tutor] "Big Letters".
Message-ID: <200401150955.54279.godoy@ieee.org>

Hi,


Does anyone know of a Python module that can generate big letters as 
those seen on POS for text mode? It seems that curses can't generate 
them by itself... 


TIA,
-- 
Godoy.     <godoy@ieee.org>

From op73418 at mail.telepac.pt  Thu Jan 15 07:04:09 2004
From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=)
Date: Thu Jan 15 07:02:12 2004
Subject: [Tutor] results: why different?
In-Reply-To: <004001c3db4f$6380f180$da19a8c0@slu.edu.ph>
References: <004001c3db4f$6380f180$da19a8c0@slu.edu.ph>
Message-ID: <v60d009gp63pp3man5soi6e9h5vc13h6jl@4ax.com>

Em Thu, 15 Jan 2004 18:07:03 +0800, "ali" <rmangaliag@slu.edu.ph>
atirou este peixe aos pinguins:

>
>why are the results of these codes different?
>
>###### 1 ######
>
>if True==[1,2,3]:
>    print "test"
>
>###### 2 ######
>
>if [1,2,3]:
>    print "test"
>
>thanks...
>

Let me give you an hint: replace [1, 2, 3] by some other object and do
the same experiment. For example, let us try with "some string"

>>> if True == "some string":
... 	print "Test"
... 	
>>> if "some string":
... 	print "Test"
... 	
Test
>>> 

The same thing happens.

Can you see why?

I'll get back to you,
G. Rodrigues

From littledanehren at yahoo.com  Thu Jan 15 09:03:46 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Thu Jan 15 09:03:50 2004
Subject: [Tutor] results: why different?
In-Reply-To: <004001c3db4f$6380f180$da19a8c0@slu.edu.ph>
Message-ID: <20040115140346.77015.qmail@web41813.mail.yahoo.com>

ali wrote:
> 
> why are the results of these codes different?
> 
> ###### 1 ######
> 
> if True==[1,2,3]:
>     print "test"
> 
> ###### 2 ######
> 
> if [1,2,3]:
>     print "test"
> 
> thanks...
> 
> ali

Think of the if keyword like it's converting its
arguments into a boolean and *then* testing to see if
they equal True. == doesn't do this. Obviously, [1, 2,
3] is not the same thing as True, but converted to a
boolean, [1, 2, 3] is true. Here are some examples to
show this more clearly:

>>> bool([1, 2, 3])
True
>>> [1, 2, 3] == True
False
>>> bool([1, 2, 3]) == True
True
>>> if [1, 2, 3]: print 'yes'
yes
>>> if bool([1, 2, 3]): print 'yes'
yes
>>> if [1, 2, 3] == True: print 'yes'
>>> if bool([1, 2, 3]) == True: print 'yes'
yes

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes
http://hotjobs.sweepstakes.yahoo.com/signingbonus

From michael at themontagnes.com  Thu Jan 15 09:47:33 2004
From: michael at themontagnes.com (Michael Montagne)
Date: Thu Jan 15 09:47:39 2004
Subject: [Tutor] Dialog box under windows
In-Reply-To: <025b01c3d62a$e1f73170$6401a8c0@xp>
References: <BEEOLJNPLOPIONOMGLAAKECECKAA.python@comber.cix.co.uk>
	<025b01c3d62a$e1f73170$6401a8c0@xp>
Message-ID: <20040115144733.GA7834@themontagnes.com>

What if you wanted your message box to remain on the screen for only a
few seconds and then vanish?



>On 01/08/04, Alan Gauld busted out the keyboard and typed:

> Take a look at the GUI page of my tutor. It shows the use 
> of all the standard Dialogs in Tkinter. You can call those 
> very easily indeed.
> 
> Alan G
> Author of the Learn to Program web tutor
> http://www.freenetpages.co.uk/hp/alan.gauld
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
Michael Montagne
michael@themontagnes.com
http://www.themontagnes.com

From michael at themontagnes.com  Thu Jan 15 10:42:56 2004
From: michael at themontagnes.com (Michael Montagne)
Date: Thu Jan 15 10:43:01 2004
Subject: [Tutor] function location and importing modules
Message-ID: <20040115154256.GA8015@themontagnes.com>

I.
I have a simple login script that I am trying to simplify more by
putting some code into functions.  I'm finding that the functions can
only be called if they are placed BEFORE the call in the script.  Is
this really true?  Is there a different way to do it?  It is just that
it is more aesthetically pleasing to have the main function code
first.

II.
What is the proper way to be able to import custom modules.  This is
for my login script mentioned previously and python is not installed
on the server, just the workstations.  The script must live on the
server and I'd like to keep the support modules on yet another server.
Is it just a question of modifying PYTHONPATH on the fly each time the
script is run?  


-- 
Michael Montagne
michael@themontagnes.com
http://www.themontagnes.com

From littledanehren at yahoo.com  Thu Jan 15 10:52:03 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Thu Jan 15 10:52:08 2004
Subject: [Tutor] Question on the "object" object
In-Reply-To: <Pine.LNX.4.44.0401142349400.26758-100000@violet.rahul.net>
Message-ID: <20040115155203.24987.qmail@web41803.mail.yahoo.com>

Terry Carroll wrote:
> in response to Todd's question in the thread "Do
> tuples replace 
> structures?", I ended up saying:
> 
> > I prefer to use classes, though for just about
> anything where I need a
> > structure:
> >
> > >>> class person:
> > ...   def __init__(self,fname,lname,age,height):
> > ...     self.fname = fname
> > ...     self.lname = lname
> > ...     self.age = age
> > ...     self.height = height
> > ...
> > >>> record = person("Jim", "Smith", 22, 130)
> > >>> record.fname
> > 'Jim'
> 
> This got me wondering; how minimalist can you get in
> a class definition 
> and still be able to access arbitrarily-named
> attributes?  Some toying 
> around to figure that out has gotten me into
> something I don't understand, 
> and would like to.
> 
> Now, none of the following three objects raise an
> Attribute error as a
> result of assigning to foo.bar, a previously
> unreferenced attribute:
> 
> >>> #old-style class
> ... class c1:
> ...     pass
> ...
> >>> o1=c1()
> >>> o1.a="test"
> >>> print "o1", o1.a
> o1 test
> 
> >>> #new-style class
> ... class c2(object):
> ...     pass
> ...
> >>> o2=c2()
> >>> o2.a="test"
> >>> print "o2", o2.a
> o2 test
> 
> >>> #new-style class, calling object's __init__
> ... class c3(object):
> ...     def __init__(self):
> ...         object.__init__(self)
> ...
> >>> o3=c3()
> >>> o3.a="test"
> >>> print "o3", o3.a
> o3 test
> 
> Okay, so if we can do this with an instance of an
> object from a class that 
> inherits from the "object" object, why can't we do
> the same with an 
> instance of the "object" object itself?  (I tried
> several times to phrase 
> that both clearly and accurately, and I'm not sure I
> got there; the 
> example should be clearer.):
> 
> >>> #using object directly, instead of a class
> inherited from it
> ... o4=object()
> >>> o4.a="test"
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> AttributeError: 'object' object has no attribute 'a'
> 
> 
> In sum, why does:
> 
>  x=object()
>  x.a
> 
> raise an AttributeError, when
> 
>  x=c()
>  x.a
> 
> Does note, where c is nothing more than a flat-out,
> no-frills subclass of 
> object?

Object is a type, like int, not a class. Annoyingly,
you can't change anything about these, but they can be
converted into classes quite easily. Here's a small
function and usage examples that can make any builtin
mutable (as long as it's subclassable):
>>> import __builtin__
>>> def mutate(things):
...     for thing in things:
...         class temp(thing): pass
...         setattr(__builtin__, thing.__name__, temp)
...     
>>> mutate([int]) #make ints mutable
>>> x = int(0) #explicitly created
>>> x
0
>>> x.a = 5
>>> x.a
5
>>> y = 0
>>> y.a = 5 #should have been explicitly created int
Traceback (most recent call last):
  File "<input>", line 1, in ?
AttributeError: 'int' object has no attribute 'a'

What you're really trying to do is make this
prototype-oriented. Although it is possible to do that
in Python, it was not really made for that purpose and
so it doesn't work well. Python doesn't have good
anonymous functions (lambdas only evaluate something,
they can't have statements or flow control), so if you
want to use prototypes more, you might want to try a
language with perl-style object orientation (such as
Lua, Javascript, Nasal, etc), one that's completely
prototype-oriented (such as Io or Newtonscript), or a
overly-pure object oriented language (such as Ruby or
Smalltalk), which seem to inadvertantly support
prototype-orientation. I've looked at these, since
prototype-orientation seems more flexible, they turn
out to be less either flexible for everything else or
too minimalistic.

In my opinion, the best solution to the original
problem of datastructures would be best solved using
dictionaries, because that's what they were intended
for and they work well for that.

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes
http://hotjobs.sweepstakes.yahoo.com/signingbonus

From littledanehren at yahoo.com  Thu Jan 15 11:20:22 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Thu Jan 15 11:21:03 2004
Subject: [Tutor] function location and importing modules
In-Reply-To: <20040115154256.GA8015@themontagnes.com>
Message-ID: <20040115162022.6739.qmail@web41804.mail.yahoo.com>

> I.
> I have a simple login script that I am trying to
> simplify more by
> putting some code into functions.  I'm finding that
> the functions can
> only be called if they are placed BEFORE the call in
> the script.  Is
> this really true?  Is there a different way to do
> it?  It is just that
> it is more aesthetically pleasing to have the main
> function code
> first.

You can have functions or classes refer to things that
don't exist yet, and as long as you don't actually
execute the function until those variables are
initialized, it's ok.

The reason for Python initializing functions when they
are created has to do with its dynamic nature.
Consider the following code:

def hi():
    print 'hi'
hi()
def greeting():
    print 'hello, how are you'
hi = greeting
hi()

That's perfectly legal python code, and it would print
what is expected:

hi
hello, how are you

> 
> II.
> What is the proper way to be able to import custom
> modules.  This is
> for my login script mentioned previously and python
> is not installed
> on the server, just the workstations.  The script
> must live on the
> server and I'd like to keep the support modules on
> yet another server.
> Is it just a question of modifying PYTHONPATH on the
> fly each time the
> script is run?

Unless you need to run the script in a namespace, you
can use execfile(filename) to run a file. If you need
a namespace, you should modify sys.path (not
PYTHONPATH) by appending the directory that the custom
module is in. sys.path is more cross-platform and much
easier to manipulate than PYTHONPATH because it's in a
list.

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes
http://hotjobs.sweepstakes.yahoo.com/signingbonus

From abli at freemail.hu  Thu Jan 15 12:27:28 2004
From: abli at freemail.hu (Abel Daniel)
Date: Thu Jan 15 12:27:28 2004
Subject: [Tutor] Re: "Big Letters".
In-Reply-To: <200401150955.54279.godoy@ieee.org> (Jorge Godoy's message of
	"Thu, 15 Jan 2004 09:55:52 -0200")
References: <200401150955.54279.godoy@ieee.org>
Message-ID: <E1AhBHE-0000FH-00@hooloovoo>

Jorge Godoy writes:
> Does anyone know of a Python module that can generate big letters as 
> those seen on POS for text mode? It seems that curses can't generate 
> them by itself... 

Although not a python module, figlet (http://www.figlet.org/) is a nice program
which generates texts like these. You could open a pipe to it and write to
it's stdin and read from it's stdout.

-- 
Abel Daniel

From piir at earthlink.net  Thu Jan 15 12:36:04 2004
From: piir at earthlink.net (Todd G. Gardner)
Date: Thu Jan 15 12:36:15 2004
Subject: [Tutor] Starting a USB application on Windows and python23?
Message-ID: <CAENJDPIMKAJINIKKHOCOEJGCCAA.piir@earthlink.net>

Hello everyone,

Any suggestions as to where to look to find out how to start an app using
USB?  I was thinking that maybe I could use a USB to communicate to a
generic USB device like I can with pyserial but I am not sure.

Thanks for any pointers,

Todd


From joelrodrigues at ifrance.com  Thu Jan 15 13:38:59 2004
From: joelrodrigues at ifrance.com (Joel Rodrigues)
Date: Thu Jan 15 13:59:45 2004
Subject: [Tutor] dict(a, b) does not preserve sort order
Message-ID: <1507BA68-478A-11D8-A874-0005024EF27F@ifrance.com>

Am I wrong to be a just a wee bit annoyed about this ? :

 >>> a
('1', '2', '3')
 >>> b
('x', 'y', 'z')
 >>> zip(a,b)
[('1', 'x'), ('2', 'y'), ('3', 'z')]
 >>> dict(zip(a,b))
{'1': 'x', '3': 'z', '2': 'y'}


What I expect is :
{'1': 'x', '2': 'y', '3': 'z'}

- Joel

_____________________________________________________________________
Envie de discuter en "live" avec vos amis ? Télécharger MSN Messenger
http://www.ifrance.com/_reloc/m la 1ère messagerie instantanée de France


From alan.gauld at blueyonder.co.uk  Thu Jan 15 14:03:45 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Thu Jan 15 14:03:21 2004
Subject: [Tutor] different results: why?
References: <1074160341.400662d5f2ebd@mbox>
Message-ID: <006e01c3db9a$4cdc2c10$6401a8c0@xp>

> why are the results of these codes different?
> 
> ###### 1 ######
> 
> if True==[1,2,3]:
>     print "test"
> 
> ###### 2 ######
> 
> if [1,2,3]:
>     print "test"

Coz a boolean value is not a list - they are not equal.
If you convert the list to a boolean (which happens 
implicitly in the second case) it works:

> if True==bool([1,2,3]):
>     print "test"


Alan G.

From clay at shirky.com  Thu Jan 15 14:15:29 2004
From: clay at shirky.com (Clay Shirky)
Date: Thu Jan 15 14:15:37 2004
Subject: [Tutor] Different md5 values for files under Unix and Python?
Message-ID: <BC2C5101.151AA%clay@shirky.com>

So I'm hashing some files, and I get different outputs for

os.popen("md5 filename") and hash.update("filename"); digest=hash.digest()

and I can't figure out what I'm doing wrong. The two md5's should produce
the same hash, right?

Test below

#!/usr/bin/env python

# Import
import sys, os
import md5
hash = md5.md5()

# Unix way
unix_md5 = os.popen("md5 -r book.txt")

# Python way
hash.update("book.txt")   # hash the file
digest = hash.hexdigest() # hex digest

# Print comparison
print digest, "book.txt"
for value in unix_md5:
    print value
#-----

which outputs

543117d4fc8b2ac471a88a1baa1f2b59 book.txt
6a2b6248246f2ec5682688c63c477f1e book.txt

Puzzled.

-clay


From david at graniteweb.com  Thu Jan 15 14:14:49 2004
From: david at graniteweb.com (David Rock)
Date: Thu Jan 15 14:23:00 2004
Subject: [Tutor] dict(a, b) does not preserve sort order
In-Reply-To: <1507BA68-478A-11D8-A874-0005024EF27F@ifrance.com>
References: <1507BA68-478A-11D8-A874-0005024EF27F@ifrance.com>
Message-ID: <20040115191449.GA22709@wdfs.graniteweb.com>

* Joel Rodrigues <joelrodrigues@ifrance.com> [2004-01-16 00:08]:
> Am I wrong to be a just a wee bit annoyed about this ? :
> 
> >>> a
> ('1', '2', '3')
> >>> b
> ('x', 'y', 'z')
> >>> zip(a,b)
> [('1', 'x'), ('2', 'y'), ('3', 'z')]
> >>> dict(zip(a,b))
> {'1': 'x', '3': 'z', '2': 'y'}
> 
> 
> What I expect is :
> {'1': 'x', '2': 'y', '3': 'z'}

Yes, you are ;-)

Dictonaries are not sorted lists. The information is based on key:value
relationships that have nothing to do with the order they exist in the
dictionary. To access the value for a given key, simply ask for it:

>>> d = dict(zip(a,b))
>>> d[1]
x
>>> d[2]
y
>>> d[3]
z

-- 
David Rock
david@graniteweb.com
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20040115/c5fb2bde/attachment.bin
From bwinton at latte.ca  Thu Jan 15 14:27:29 2004
From: bwinton at latte.ca (Blake Winton)
Date: Thu Jan 15 14:27:36 2004
Subject: [Tutor] Different md5 values for files under Unix and Python?
In-Reply-To: <BC2C5101.151AA%clay@shirky.com>
Message-ID: <003501c3db9d$9dca38d0$6401a8c0@phantomfiber.com>

(Oops, I just sent this to Clay, whereas it probably should
 have gone to the whole list...)

> So I'm hashing some files, and I get different outputs for
> 
> os.popen("md5 filename") and hash.update("filename"); 
> digest=hash.digest()
> 
> which outputs
> 
> 543117d4fc8b2ac471a88a1baa1f2b59 book.txt
> 6a2b6248246f2ec5682688c63c477f1e book.txt
> 
> Puzzled.

Well, would it help if I showed you this:

-bash-2.05b$ md5 -r -s "book.txt"
543117d4fc8b2ac471a88a1baa1f2b59 "book.txt"

-bash-2.05b$ md5 -r "book.txt"
md5: book.txt: No such file or directory

-bash-2.05b$ python
Python 2.2.2 (#1, Mar 22 2003, 15:26:17)
[GCC 2.95.4 20020320 [FreeBSD]] on freebsd4
Type "help", "copyright", "credits" or "license" for more information.
>>> import md5
>>> hash = md5.md5()
>>> hash.update( "book.txt" )
>>> hash.hexdigest()
'543117d4fc8b2ac471a88a1baa1f2b59'

Later,
Blake.


From carroll at tjc.com  Thu Jan 15 15:02:25 2004
From: carroll at tjc.com (Terry Carroll)
Date: Thu Jan 15 15:02:55 2004
Subject: [Tutor] dict(a, b) does not preserve sort order
In-Reply-To: <1507BA68-478A-11D8-A874-0005024EF27F@ifrance.com>
Message-ID: <Pine.LNX.4.44.0401151153590.26758-100000@violet.rahul.net>

On Fri, 16 Jan 2004, Joel Rodrigues wrote:

> Am I wrong to be a just a wee bit annoyed about this ? :

Yes.
 
>  >>> a
> ('1', '2', '3')
>  >>> b
> ('x', 'y', 'z')
>  >>> zip(a,b)
> [('1', 'x'), ('2', 'y'), ('3', 'z')]

The above are lucky flukes.  You *cannot* depend on the keys of a 
dictionary being in sorted order.

>  >>> dict(zip(a,b))
> {'1': 'x', '3': 'z', '2': 'y'}
> 
> 
> What I expect is :
> {'1': 'x', '2': 'y', '3': 'z'}

If you need to process a dictionary in sorted-key order, use something 
along these lines:

>>> d=dict(zip(a,b))
>>> k=d.keys()
>>> k
['1', '3', '2']
>>> k.sort()
>>> k
['1', '2', '3']
>>> for foo in k:
...  print d[foo]
...
x
y
z
>>>



From jeffq16 at yahoo.com  Thu Jan 15 15:12:08 2004
From: jeffq16 at yahoo.com (j j)
Date: Thu Jan 15 15:12:15 2004
Subject: [Tutor] dict(a, b) does not preserve sort order
In-Reply-To: <Pine.LNX.4.44.0401151153590.26758-100000@violet.rahul.net>
Message-ID: <20040115201209.34288.qmail@web9805.mail.yahoo.com>

please remove me from teh list, i forgot how to do that.

Terry Carroll <carroll@tjc.com> wrote:On Fri, 16 Jan 2004, Joel Rodrigues wrote:

> Am I wrong to be a just a wee bit annoyed about this ? :

Yes.

> >>> a
> ('1', '2', '3')
> >>> b
> ('x', 'y', 'z')
> >>> zip(a,b)
> [('1', 'x'), ('2', 'y'), ('3', 'z')]

The above are lucky flukes. You *cannot* depend on the keys of a 
dictionary being in sorted order.

> >>> dict(zip(a,b))
> {'1': 'x', '3': 'z', '2': 'y'}
> 
> 
> What I expect is :
> {'1': 'x', '2': 'y', '3': 'z'}

If you need to process a dictionary in sorted-key order, use something 
along these lines:

>>> d=dict(zip(a,b))
>>> k=d.keys()
>>> k
['1', '3', '2']
>>> k.sort()
>>> k
['1', '2', '3']
>>> for foo in k:
... print d[foo]
...
x
y
z
>>>



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


---------------------------------
Do you Yahoo!?
Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20040115/e37b5879/attachment.html
From rob at jam.rr.com  Thu Jan 15 15:23:07 2004
From: rob at jam.rr.com (Rob Andrews)
Date: Thu Jan 15 15:20:06 2004
Subject: [Tutor] dict(a, b) does not preserve sort order
In-Reply-To: <20040115201209.34288.qmail@web9805.mail.yahoo.com>
References: <20040115201209.34288.qmail@web9805.mail.yahoo.com>
Message-ID: <4006F6AB.3080802@jam.rr.com>

At the bottom of each message is the URL you need to visit to remove 
yourself. See the quoted URL blow.

regards,
Rob

j j wrote:
> please remove me from teh list, i forgot how to do that.
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor


From rob at jam.rr.com  Thu Jan 15 15:23:19 2004
From: rob at jam.rr.com (Rob Andrews)
Date: Thu Jan 15 15:20:13 2004
Subject: [Tutor] dict(a, b) does not preserve sort order
In-Reply-To: <20040115201209.34288.qmail@web9805.mail.yahoo.com>
References: <20040115201209.34288.qmail@web9805.mail.yahoo.com>
Message-ID: <4006F6B7.2070009@jam.rr.com>

At the bottom of each message is the URL you need to visit to remove 
yourself. See the quoted URL below.

regards,
Rob

j j wrote:
> please remove me from teh list, i forgot how to do that.
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor


From dyoo at hkn.eecs.berkeley.edu  Thu Jan 15 15:22:24 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Jan 15 15:22:35 2004
Subject: [Tutor] Re: "Big Letters".
In-Reply-To: <E1AhBHE-0000FH-00@hooloovoo>
Message-ID: <Pine.LNX.4.44.0401151018280.21650-100000@hkn.eecs.berkeley.edu>



On Thu, 15 Jan 2004, Abel Daniel wrote:

> Jorge Godoy writes:
> > Does anyone know of a Python module that can generate big letters as
> > those seen on POS for text mode? It seems that curses can't generate
> > them by itself...
>
> Although not a python module, figlet (http://www.figlet.org/) is a nice
> program which generates texts like these. You could open a pipe to it
> and write to it's stdin and read from it's stdout.


On a tangent note, has anyone seen:

    http://online-judge.uva.es/portal/modules/acmproblemset/

yet?  I'm starting to read through the book "Programming Challenges: The
Programming Contest Training Manual", and it looks like a great source of
practice problems!


Jorge's question touches on one of the contest challenges, an LCD number
displayer problem:

    http://online-judge.uva.es/problemset/v7/706.html

*grin* Anyone want to try their hand at this?


Talk to you later!


*** spoiler space below ***














*** spoilers ahead ***



Here's my crack at the LCD problem:

###
"""An LCD displayer.

Danny Yoo (dyoo@hkn.eecs.berkeley.edu)

A solution for:

    http://online-judge.uva.es/problemset/v7/706.html
"""

from sys import stdout

def main():
    while 1:
        line = raw_input()
        if not line: break
        size, digits = line.split()
        if (size, digits) == ('0', '0'):
            break
        draw_digits(digits, int(size))


"""
An LCD digit is composed of 7 components:


  0
 1 2
  3
 4 5
  6

So we keep a map between digits and the LCD pattern to generate that
digit.
"""
LCD_DATA = { '0': (1, 1, 1, 0, 1, 1, 1),  ## zero
             '1': (0, 0, 1, 0, 0, 1, 0),  ## one
             '2': (1, 0, 1, 1, 1, 0, 1),  ## two
             '3': (1, 0, 1, 1, 0, 1, 1),  ## three
             '4': (0, 1, 1, 1, 0, 1, 0),  ## four
             '5': (1, 1, 0, 1, 0, 1, 1),  ## five
             '6': (1, 1, 0, 1, 1, 1, 1),  ## six
             '7': (1, 0, 1, 0, 0, 1, 0),  ## seven
             '8': (1, 1, 1, 1, 1, 1, 1),  ## eight
             '9': (1, 1, 1, 1, 0, 1, 1),  ## nine
             }

def draw_digits(digits, size):
    draw_horizontals(digits, size, 0)
    for i in range(size):
        draw_verticals(digits, size, 1, 2)
    draw_horizontals(digits, size, 3)
    for i in range(size):
        draw_verticals(digits, size, 4, 5)
    draw_horizontals(digits, size, 6)


def draw_horizontals(digits, size, component):
    for d in digits:
        space()
        if LCD_DATA[d][component] == 1:
            dash(size)
        else:
            space(size)
        space()

        space() ## one space between each digit
    newline()



def draw_verticals(digits, size, component1, component2):
    for d in digits:
        if LCD_DATA[d][component1] == 1:
            bar()
        else:
            space()
        space(size)
        if LCD_DATA[d][component2] == 1:
            bar()
        else:
            space()

        space() ## one space between each digit
    newline()




def dash(size):
    """Write out a dash."""
    stdout.write("-" * size)

def bar():
    """Write out a bar."""
    stdout.write("|")

def space(size = 1):
    """Write out a space."""
    stdout.write(" " * size)

def newline():
    """Write out a newline."""
    stdout.write("\n")



if __name__ == '__main__':
    main()
###


From zmerch at 30below.com  Thu Jan 15 16:07:57 2004
From: zmerch at 30below.com (Roger Merchberger)
Date: Thu Jan 15 16:04:02 2004
Subject: [Tutor] "Big Letters".
In-Reply-To: <Pine.LNX.4.44.0401151018280.21650-100000@hkn.eecs.berkeley .edu>
References: <E1AhBHE-0000FH-00@hooloovoo>
Message-ID: <5.1.0.14.2.20040115160015.00aded38@mail.30below.com>

Rumor has it that Danny Yoo may have mentioned these words:
>[snippety]

>On a tangent note, has anyone seen:
>
>     http://online-judge.uva.es/portal/modules/acmproblemset/

Interesting... Saw a few "fun" proggies that might be good for benchmarking 
stuff... ;-)

>Jorge's question touches on one of the contest challenges, an LCD number
>displayer problem:
>
>     http://online-judge.uva.es/problemset/v7/706.html
>
>*grin* Anyone want to try their hand at this?

[snippety]

>An LCD digit is composed of 7 components:
>
>   0
>  1 2
>   3
>  4 5
>   6

I'm not going to spoil it by quoting the entire proggie, but you might be 
able to use this proggie more useful for other things if you numbered the 
segment sequence like this:

[[ This is from "ancient" memory - it may not be 100% accurate ]]

  f
a e
  g
b d
  c  h[dp]

as that's the sequence (again, IIRC...) that 7-segment LEDs used (such as 
the TIL311 used on the Heathkit 3400 Motorola 680x based microprocessor 
trainer, which used 6 LEDs for it's visual output) you could use this as a 
basis for a microprocessor trainer emulator... ;-)

[[ yea, I added the dp -- decimal points are very handy on calculators... 
;-) ]]

Anywho, I have to go play with the pyserial package, so I won't have a 
chance to tinker with that proggie for a while... ;-)

Laterz,
Roger "Merch" Merchberger

--
Roger "Merch" Merchberger   ---   sysadmin, Iceberg Computers
zmerch@30below.com

Hi! I am a .signature virus.  Copy me into your .signature to join in!


From alan.gauld at blueyonder.co.uk  Thu Jan 15 16:31:44 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Thu Jan 15 16:31:19 2004
Subject: [Tutor] Starting a USB application on Windows and python23?
References: <CAENJDPIMKAJINIKKHOCOEJGCCAA.piir@earthlink.net>
Message-ID: <009601c3dbae$f9603490$6401a8c0@xp>

> Any suggestions as to where to look to find out how to start an app
using
> USB?  I was thinking that maybe I could use a USB to communicate to
a
> generic USB device like I can with pyserial but I am not sure.

I'm interested in this too. I have for a few weeks now been thinking
that it might be interesting to write a USB adapter for Python
- partly as a way to learn about USB and also to try writing
a C extension. If none exists I might look more seriously at it.

If one does exist maybe I'll try Firewire instead! :-)

Alan G.


From hcohen2 at comcast.net  Thu Jan 15 16:37:06 2004
From: hcohen2 at comcast.net (hcohen2)
Date: Thu Jan 15 16:38:49 2004
Subject: [Tutor] How to find pythons: exceptions.py file
Message-ID: <40070802.4080301@comcast.net>

Did this:

 usr]$ find -name 'exceptions*' -print
find: ./share/doc/printer-filters-1.0/EpsonEPL_L_Series/epl_docs: 
Permission denied
./lib/perl5/5.8.0/exceptions.pl

well found the perl file - does python ver. 2.2.2 have such a file?  
Obviously exceptions are active as I have seen so often when I type the 
wrong code in or on testing my scripts!

TIA



From dyoo at hkn.eecs.berkeley.edu  Thu Jan 15 17:00:19 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Jan 15 17:00:35 2004
Subject: [Tutor] How to find pythons: exceptions.py file
In-Reply-To: <40070802.4080301@comcast.net>
Message-ID: <Pine.LNX.4.44.0401151352130.31272-100000@hkn.eecs.berkeley.edu>



On Thu, 15 Jan 2004, hcohen2 wrote:

> Did this:
>
>  usr]$ find -name 'exceptions*' -print
> find: ./share/doc/printer-filters-1.0/EpsonEPL_L_Series/epl_docs:
> Permission denied
> ./lib/perl5/5.8.0/exceptions.pl
>
> well found the perl file - does python ver. 2.2.2 have such a file?
> Obviously exceptions are active as I have seen so often when I type the
> wrong code in or on testing my scripts!

Hello!


Some modules are statically compiled into the Python runtime.  The
'exceptions' module,

    http://www.python.org/doc/lib/module-exceptions.html


is one of them, so it doesn't correspond to a particular Python source
file:

###
>>> import exceptions
>>> exceptions.__file__
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'module' object has no attribute '__file__'
###

So for the 'exceptions' module, there's really no Python file that we can
point to.



However, the majority of the Standard Library is coded in Python:

###
>>> import difflib
>>> difflib.__file__
'/home/dyoo/local/Python-2.2.1/lib/python2.2/difflib.pyc'
>>> import copy
>>> copy.__file__
'/home/dyoo/local/Python-2.2.1/lib/python2.2/copy.pyc'
###

and from this, we can find that the Standard Library lives within
Python-2.2.1/lib/python2.2.  A more systematic way to find the Standard
Library uses the distutils:


###
"""Quick program to print the directory where the Standard Library
lives."""

import distutils.sysconfig
print distutils.sysconfig.get_python_lib(standard_lib=1)
###



Hope this helps!


From barnabydscott at yahoo.com  Thu Jan 15 17:20:21 2004
From: barnabydscott at yahoo.com (Barnaby Scott)
Date: Thu Jan 15 17:20:31 2004
Subject: [Tutor] Reviewing scripts & main statements in function
In-Reply-To: <20040115021709.52105.qmail@web41813.mail.yahoo.com>
Message-ID: <20040115222021.83828.qmail@web41402.mail.yahoo.com>

Thanks very much for that. I was interested to see
your comments, and am as pleased to receive stylistic
help as much as any other kind.

Can I ask one other question, which may have wider
relevance for others?:

You (or another contributor) put the main statement
block into a function and then called it with the line

if __name__ == '__main__': main()

I have seen this before - is it universally good
practice? What about scripts that were only ever
intended to be run standalone?

It also makes me think - if this is good practice,
should you always be prepared for someone to import
your script as a module, and maybe even subclass some
of my objects etc? If they did, they would get a rude
shock, as the classes are not very 'self-contained'.
For example they make reference to each other and to
global variables in the module. Should classes always
have every piece of data they will need passed to them
at the creation of an instance, or in other ways make
themselves 'available' more universally?

Thanks again - I really do appreciate all these
opportunites to learn more.



>I put up your program and made some
> changes
> to it at
> http://zope.org/Members/LittleDan/PissiPissi
> . Most of the error were really minor or just
> stylistic (but there are coding conventions that
> should be followed), although I may be missing
> something. Could other people review the code?
> 
> Daniel Ehrenberg
> 
> __________________________________
> Do you Yahoo!?
> Yahoo! Hotjobs: Enter the "Signing Bonus"
> Sweepstakes
> http://hotjobs.sweepstakes.yahoo.com/signingbonus
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor


__________________________________
Do you Yahoo!?
Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes
http://hotjobs.sweepstakes.yahoo.com/signingbonus

From littledanehren at yahoo.com  Thu Jan 15 17:33:32 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Thu Jan 15 17:33:37 2004
Subject: [Tutor] Reviewing scripts & main statements in function
In-Reply-To: <20040115222021.83828.qmail@web41402.mail.yahoo.com>
Message-ID: <20040115223332.29182.qmail@web41808.mail.yahoo.com>

Barnaby Scott wrote:
> Thanks very much for that. I was interested to see
> your comments, and am as pleased to receive
> stylistic
> help as much as any other kind.
> 
> Can I ask one other question, which may have wider
> relevance for others?:
> 
> You (or another contributor) put the main statement
> block into a function and then called it with the
> line
> 
> if __name__ == '__main__': main()
> 
> I have seen this before - is it universally good
> practice? What about scripts that were only ever
> intended to be run standalone?

Yes, this is considered universally good practice.
Even if this was originally only intended to be run
standalone, there is still a chance that someone will
want to reuse it without having to copy some of the
source code into a new file by using it as a module.
Your code was very well-structured and reusable, apart
from that one thing that I had to put in a function.
> 
> It also makes me think - if this is good practice,
> should you always be prepared for someone to import
> your script as a module, and maybe even subclass
> some
> of my objects etc? If they did, they would get a
> rude
> shock, as the classes are not very 'self-contained'.
> For example they make reference to each other and to
> global variables in the module. Should classes
> always
> have every piece of data they will need passed to
> them
> at the creation of an instance, or in other ways
> make
> themselves 'available' more universally?
> 
As long as the classes are not coppied and pasted into
another file, it will work fine. There is no real
reason to demand that everything be self-contained in
Python (although other languages have restrictions
which make it like that).

> Thanks again - I really do appreciate all these
> opportunites to learn more.

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes
http://hotjobs.sweepstakes.yahoo.com/signingbonus

From carroll at tjc.com  Thu Jan 15 17:41:59 2004
From: carroll at tjc.com (Terry Carroll)
Date: Thu Jan 15 17:42:04 2004
Subject: [Tutor] Question on the "object" object
In-Reply-To: <20040115155203.24987.qmail@web41803.mail.yahoo.com>
Message-ID: <Pine.LNX.4.44.0401151428380.26758-100000@violet.rahul.net>

On Thu, 15 Jan 2004, Daniel Ehrenberg wrote:

> Terry Carroll wrote:
> > In sum, why does:
> > 
> >  x=object()
> >  x.a
> > 
> > raise an AttributeError, when
> > 
> >  x=c()
> >  x.a
> > 
> > [does not], where c is nothing more than a flat-out,
> > no-frills subclass of object?
> 
> Object is a type, like int, not a class. 

Ah, that's interesting.  I didn't have that distinction, so now I'm going 
to have to think about it.  It never occurred to me that the thing that 
was capable being subclassed was anything other than a class.

> What you're really trying to do is make this
> prototype-oriented.... so if you
> want to use prototypes more, you might want to try a
> language with perl-style object orientation....

No, not really.  I don't have any particular use in mind.  I'm just always 
trying to get a better handle on Python and increase my understanding of 
it.

> In my opinion, the best solution to the original
> problem of datastructures would be best solved using
> dictionaries, because that's what they were intended
> for and they work well for that.

I especially like dictionaries where the keys are arbitrary; say, for 
example, you were going to count the letters in a line of text; you'd have 
one dict entry for each letter encountered, with the value being the 
count.  I have a module for accessing the Chinese Unicode characters 
where each character is represented by a dictionary having attributes 
like the Mandarin pronunciation, GB and or BigFive representation, 
English definition, etc, all keyed by the names of those attributes.

Where the data being represented is more like an entity with multiple
attributes (name, age, address, etc.), where all the attributes are 
more-or-less expected to exist, I like using objects.  But that might be 
from my old-timer background, being a 1981 CS graduate, where structures 
were pretty comfortable data structures.


From isrgish at fusemail.com  Thu Jan 15 20:27:25 2004
From: isrgish at fusemail.com (Isr Gish)
Date: Thu Jan 15 20:27:22 2004
Subject: [Tutor] different results: why?
Message-ID: <E1AhIlN-000BzD-2C@fuse1.fusemail.net>



"ali"<rmangaliag@slu.edu.ph> wrote:

"tutor@python.org"<tutor@python.org>
   >Subject: [Tutor] different results: why?
   >
   >
   >why are the results of these codes different?
   >
   >###### 1 ######
   >
   >if True==[1,2,3]:
   >    print "test"
   >
   >###### 2 ######
   >
   >if [1,2,3]:
   >    print "test"
   >
True is only equal to 1, nothing else.

But [1,2,3] is True, because every none empty list evaluates to True.
Thefore if [1,2,3]: evaluates to to True so it prints "test".

Isr



From rmangaliag at slu.edu.ph  Thu Jan 15 22:36:32 2004
From: rmangaliag at slu.edu.ph (ali)
Date: Thu Jan 15 22:31:06 2004
Subject: [Tutor] results: why different?
References: <20040115140346.77015.qmail@web41813.mail.yahoo.com>
Message-ID: <001c01c3dbe1$f04e6560$da19a8c0@slu.edu.ph>

thanks people... very clear...



----- Original Message ----- 
From: Daniel Ehrenberg <littledanehren@yahoo.com>
To: pytutor <tutor@python.org>
Sent: Thursday, January 15, 2004 10:03 PM
Subject: Re: [Tutor] results: why different?


> ali wrote:
> > 
> > why are the results of these codes different?
> > 
> > ###### 1 ######
> > 
> > if True==[1,2,3]:
> >     print "test"
> > 
> > ###### 2 ######
> > 
> > if [1,2,3]:
> >     print "test"
> > 
> > thanks...
> > 
> > ali
> 
> Think of the if keyword like it's converting its
> arguments into a boolean and *then* testing to see if
> they equal True. == doesn't do this. Obviously, [1, 2,
> 3] is not the same thing as True, but converted to a
> boolean, [1, 2, 3] is true. Here are some examples to
> show this more clearly:
> 
> >>> bool([1, 2, 3])
> True
> >>> [1, 2, 3] == True
> False
> >>> bool([1, 2, 3]) == True
> True
> >>> if [1, 2, 3]: print 'yes'
> yes
> >>> if bool([1, 2, 3]): print 'yes'
> yes
> >>> if [1, 2, 3] == True: print 'yes'
> >>> if bool([1, 2, 3]) == True: print 'yes'
> yes
> 
> Daniel Ehrenberg
> 
> __________________________________
> Do you Yahoo!?
> Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes
> http://hotjobs.sweepstakes.yahoo.com/signingbonus
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor


From isrgish at fusemail.com  Fri Jan 16 00:11:03 2004
From: isrgish at fusemail.com (Isr Gish)
Date: Fri Jan 16 00:10:58 2004
Subject: [Tutor] Sequence Comparison
Message-ID: <E1AhMFl-000O5a-4h@fuse1.fusemail.net>


-----Original Message-----
   >From: "Gon?alo Rodrigues"<op73418@mail.telepac.pt>
   >Sent: 1/15/04 6:54:19 AM
   >To: "tutor@python.org"<tutor@python.org>
   >Subject: Re: [Tutor] Sequence Comparison
   >
   >Em Wed, 14 Jan 2004 20:33:36 -0500, "Isr Gish" <isrgish@fusemail.com>
   >atirou este peixe aos pinguins:
   >
   >>Magnus Lycka wrote: 
   >>
   >>   >> >>> (1, 2)                 < (1, 2, -1)
   >>   >> True
   >>   >> # i totally didnot understand it
   >>   >
   >>   >Anything is more than nothing... Why is that difficult
   >>   >to understand.
   >>  
   >>I would rather think that -1 which is less then 0 whould be less then nothing.
   >>
   >
   >But 0 is not nothing. It's better than nothing.
   >
   >The better analogy is an empty bag and no bag at all. You can still
   >put your head inside an empty bag and choke to death.
   >
Thanks now I think I understand this.
IOW 0 is counted as a number, while None is not even a number.

Isr Gish


From guillermo.fernandez at epfl.ch  Fri Jan 16 06:14:56 2004
From: guillermo.fernandez at epfl.ch (Guillermo Fernandez Castellanos)
Date: Fri Jan 16 06:15:02 2004
Subject: [Tutor] memory problem (II part)
In-Reply-To: <Pine.LNX.4.44.0401141121300.804-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0401141121300.804-100000@hkn.eecs.berkeley.edu>
Message-ID: <4007C7B0.4070609@epfl.ch>

Hi,

Sorry for the late reply.

>Just checking up on this: when does memory usage shoot up?  Do you know if
>it's when you're querying the database?  If so, then we can concentrate on
>how the database is being queried.
>  
>
I made further tests with a machine (Linux) with much more RAM that mine 
(Windows) at home (1024 oposie to 256 :-)
I realized that the RAM exploses when I start query. If there is a query 
with little results (only some of the fields of the database), I'll have 
a short increment. If it's a query with larger results (all the fields 
of the table), it will go to a maximum of RAM use, and stabilize there, 
even if I do further queries.
If I close the database without closing the program, and prior of 
opening another database, the RAM gets lower again.
This seems to point the problem to the syslogdb module.
I start the database like this:

    global database
    global cursor
    database=db.connect(databasename)
    cursor=database.cursor()

Could the problem come from the cursor or database variable?

Thanks a lot!

Guille



From rick at niof.net  Fri Jan 16 06:40:00 2004
From: rick at niof.net (Rick Pasotto)
Date: Fri Jan 16 06:36:28 2004
Subject: [Tutor] memory problem (II part)
In-Reply-To: <4007C7B0.4070609@epfl.ch>
References: <Pine.LNX.4.44.0401141121300.804-100000@hkn.eecs.berkeley.edu>
	<4007C7B0.4070609@epfl.ch>
Message-ID: <20040116114000.GF11003@niof.net>

On Fri, Jan 16, 2004 at 12:14:56PM +0100, Guillermo Fernandez Castellanos wrote:
> 
> Could the problem come from the cursor or database variable?

Have you tried cursor.close() after you've finished processing the
returned data?

-- 
"Aided by a little sophistry on the words 'general welfare', [they
 claim] a right to do not only the acts to effect that which are
 specifically enumerated and permitted, but whatsoever they shall think
 or pretend will be for the general welfare."
		-- Thomas Jefferson 1825 to W. Giles
    Rick Pasotto    rick@niof.net    http://www.niof.net

From python-list at frenchfriedhell.com  Fri Jan 16 10:41:55 2004
From: python-list at frenchfriedhell.com (Stryder)
Date: Fri Jan 16 10:45:28 2004
Subject: [Tutor] Threads and loops
Message-ID: <004b01c3dc47$4698beb0$6f01010a@Rachel>



I'm starting to work with threads, but I'm a little confused.  I think I
understand the concepts, but not the controls. Why doesn't something like
this work:

#############
import threading

def counter(x):
    while tEvent.isSet():
        x+=1
        print x

def tStart():
    tEvent.set()
    if counterThread.isAlive():
        counterThread.join()
    else:
        counterThread.start()

def tStop():
    tEvent.clear()
  
counterThread=threading.Thread(target=counter, args=(1,))
tEvent=threading.Event()

#####################

After that I have controls setup for a Tkinter box with two buttons, one has
tStart as it's command value, and the other tStop.  When I run the program,
it starts fine, and then the loop stops when I press 'stop', but when I try
to press 'start' again, I get an error:

###########
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\myweb\python\lib\lib-tk\Tkinter.py", line 1345, in __call__
    return self.func(*args)
  File "C:\myweb\python\SNC\Script1.py", line 14, in tStart
    counterThread.start()
  File "C:\myweb\python\lib\threading.py", line 404, in start
    assert not self.__started, "thread already started"
AssertionError: thread already started
############

And why the need for the extra comma in the args value when defining my
instance?

-Stryder

-------------- next part --------------
A non-text attachment was scrubbed...
Name: winmail.dat
Type: application/ms-tnef
Size: 2336 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20040116/965485a8/winmail-0001.bin
From kgomotso at kgatelopele.co.za  Tue Jan 13 06:08:46 2004
From: kgomotso at kgatelopele.co.za (Anthony Tshwane)
Date: Fri Jan 16 13:56:29 2004
Subject: [Tutor] Python
Message-ID: <200401131308.48212.kgomotso@kgatelopele.co.za>

Greetings.

I am new in the python programming language and I presently trying to run 
examples that you have give.I would like to know how are those steps executed 
in linux invironment since IO am using linux Mandrake.i folloed that but I 
started encountering the problam when I have to run the script.May you just 
send me some notes about how to run that in linux.

With thanks
Kgomotso

From firephreek at earthlink.net  Wed Jan 14 16:08:28 2004
From: firephreek at earthlink.net (firephreek)
Date: Fri Jan 16 13:56:35 2004
Subject: [Tutor] Threads and loops
Message-ID: <000201c3dae2$8ebd71b0$6f01010a@Rachel>

Happy Thursday to all,

I'm starting to work with threads, but I'm a little confused.  I understand
the concepts, but not the controls. Why doesn't something like this work:

#############
import threading

def counter(x):
    while tEvent.isSet():
        x+=1
        print x

def tStart():
    tEvent.set()
    if counterThread.isAlive():
        counterThread.join()
    else:
        counterThread.start()

def tStop():
    tEvent.clear()
  
counterThread=threading.Thread(target=counter, args=(1,))
tEvent=threading.Event()

#####################

After that I have controls setup for a Tkinter box with two buttons, one has
tStart as it's command value, and the other tStop.  When I run the program,
it starts fine, and then the loop stops when I press 'stop', but when I try
to press 'start' again, I get an error:

###########
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\myweb\python\lib\lib-tk\Tkinter.py", line 1345, in __call__
    return self.func(*args)
  File "C:\myweb\python\SNC\Script1.py", line 14, in tStart
    counterThread.start()
  File "C:\myweb\python\lib\threading.py", line 404, in start
    assert not self.__started, "thread already started"
AssertionError: thread already started
############

And why the need for the extra comma in the args value when defining my
instance?

-Stryder
-------------- next part --------------
A non-text attachment was scrubbed...
Name: winmail.dat
Type: application/ms-tnef
Size: 2304 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20040114/ab9c50ce/winmail.bin
From dsaussus at jasongeo.com  Fri Jan 16 06:35:35 2004
From: dsaussus at jasongeo.com (Denis Saussus)
Date: Fri Jan 16 13:56:38 2004
Subject: [Tutor] variable length methods?
Message-ID: <200401161135.i0GBZZV24617@uranus.jason.nl>

Hello,

I would like to know if there is a special python version of *vargs
specifically intended to be used with variable length methods instead
of just with variable length arguments.  If there is, fantastic!  If
there isn't, is it still acceptable to 'fudge' *vargs to do what I want?

For instance,

class MyClass:
  def __init__(self, outputdir, *vargs):
    ...

will work without any problems if you do:

MyClass mc(outputdir = 'here/',
           a = 1,
           b = 2,
           c = 4,
           ...)

but what I am seeking to do is:

MyClass mc(outputdir = 'here/',
           plot(x),
           plot(a,b,c),
           plot(w,z),
           ...)

where,

def plot(*vargs):
   ...

Help anyone?

Thanks!

From kiran at mhowlinux.org  Tue Jan 13 07:23:23 2004
From: kiran at mhowlinux.org (kiran@mhowlinux.org)
Date: Fri Jan 16 13:56:49 2004
Subject: [Tutor] to/from binary to/from integer (i.e.'01010101' =85)
Message-ID: <002401c3d9d0$0f18e2e0$cb2fe2dc@VULCAN>

for any positive (int) to binary

a simple function would do the job

import math
def i2b(s):
   #check how many bits are required to represent the integer in binary
    i=int(math.log(s)/math.log(2))+1
    return ''.join([str((s&(2**(i-j-1)))>>(i-j-1)) for j in range(i)])



---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.554 / Virus Database: 346 - Release Date: 12/20/2003

From dyoo at hkn.eecs.berkeley.edu  Fri Jan 16 14:13:19 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri Jan 16 14:13:27 2004
Subject: [Tutor] Reviewing scripts & main statements in function
In-Reply-To: <20040115222021.83828.qmail@web41402.mail.yahoo.com>
Message-ID: <Pine.LNX.4.44.0401161057140.25230-100000@hkn.eecs.berkeley.edu>



On Thu, 15 Jan 2004, Barnaby Scott wrote:

> Thanks very much for that. I was interested to see your comments, and am
> as pleased to receive stylistic help as much as any other kind.
>
> Can I ask one other question, which may have wider relevance for
> others?:
>
> You (or another contributor) put the main statement
> block into a function and then called it with the line
>
> if __name__ == '__main__': main()
>
> I have seen this before - is it universally good practice? What about
> scripts that were only ever intended to be run standalone?


Hi Barnaby,



This convention also works really nicely even with standalone programs.


Let me give a concrete example:

###
def main():
    print "The square of 42 is", square(42)

def square(x):
    return x * x

if __name__ == '__main__':
    main()
###


This code works because by the time the main() function is actually
called, square() is known to the system.


If we don't use the 'if __name__ == "__main__": ...' convention, and just
try it:


###
print "The square of 42 is", square(42)

def square(x):
    return x * x
###


we will find that Python doesn't like this at all, because as it executes
the first line of the program,

    print "The square of 42 is", square(42)

it doesn't yet know what 'square()' is.  To make this work without a real
main() function, we're forced to rearrange things so that the function
definitions are in place before we call them:


###
def square(x):
    return x * x

print "The square of 42 is", square(42)
###



So we can benefit from the 'if __name__ ...' convention, even if we're not
module writers: the convention allows us to push the main functionality of
our program to the very top of our source file, where it'll be noticed
more easily.


I hope this helps!


From dropzone at gjldp.org  Fri Jan 16 15:33:48 2004
From: dropzone at gjldp.org (JD)
Date: Fri Jan 16 15:32:27 2004
Subject: [Tutor] Question about parameters of sys module
Message-ID: <200401162133.48305.dropzone@gjldp.org>

Hi,

I am currently playing around with some "toys" I found on 
Useless Python. In the russianroulette.py script, I found a 
line that I couldn't understand.

It is this one:
[...]
os.system('clear')
[...]

I know what it does: it clears the screen. What made me 
uncertain is that the "clear" value is not documented in 
the sys module documentation.

As it is not a variable defined in the script, I suppose it 
is the parameter of a fonction of the sys module. Where may 
I find more information about it? And chat exactly is this 
'clear'? A variable?

I thank you in advance for your lights.


From carroll at tjc.com  Fri Jan 16 16:17:15 2004
From: carroll at tjc.com (Terry Carroll)
Date: Fri Jan 16 16:19:48 2004
Subject: [Tutor] Question about parameters of sys module
In-Reply-To: <200401162133.48305.dropzone@gjldp.org>
Message-ID: <Pine.LNX.4.44.0401161307300.26758-100000@violet.rahul.net>

On Fri, 16 Jan 2004, JD wrote:

> ...I found a line that I couldn't understand....
> 
> os.system('clear')
> 
> I know what it does: it clears the screen. What made me 
> uncertain is that the "clear" value is not documented in 
> the sys module documentation.
> 
> As it is not a variable defined in the script, I suppose it 
> is the parameter of a fonction of the sys module. Where may 
> I find more information about it? And chat exactly is this 
> 'clear'? A variable?


'clear' is a literal.  os.system() simply takes as its argument a command 
line to be executed by the operating system.  On your operating system, 
there is a command called "clear" that clears the screen.

If you were to replace it with, for example:

 os.system('dir')

the OS would execute the 'dir' command, and you'd see a directory listing.

This isn't limited to simple output commands, by the way.  If you gave it 
os.system('delete filename'), it would execute that, deleting the file 
named "filename".  So be careful with os.system().

Neither Python nor the os.system() method knows what the string it's 
passed actually means.  In this case, neither Python nor os.system gives 
any importance to the string "clear"; it just passes it to the OS for 
execution.  That's why you don't see "clear" documented in any of your 
Python docs.

-- 
Terry Carroll
Santa Clara, CA
carroll@tjc.com
Modell delendus est


From dropzone at gjldp.org  Fri Jan 16 16:32:26 2004
From: dropzone at gjldp.org (JD)
Date: Fri Jan 16 16:32:48 2004
Subject: [Tutor] Question about parameters of sys module
In-Reply-To: <Pine.LNX.4.44.0401161307300.26758-100000@violet.rahul.net>
References: <Pine.LNX.4.44.0401161307300.26758-100000@violet.rahul.net>
Message-ID: <200401162232.26556.dropzone@gjldp.org>

Le Vendredi 16 Janvier 2004 22:17, Terry Carroll a ?crit :
> Neither Python nor the os.system() method knows what the
> string it's passed actually means.  In this case, neither
> Python nor os.system gives any importance to the string
> "clear"; it just passes it to the OS for execution.
>  That's why you don't see "clear" documented in any of
> your Python docs.

I understand.

But as far as I know, this type of commands can be produced 
independently from the OS with the sys module and his 
functions. In which cas would you use the os.sys() method?

When you are building an os specific script I guess, but are 
there others cases.

To make my question simple: is there a rule to determine the 
use of either os.system() or sys module?


From klappnase at freenet.de  Fri Jan 16 17:01:11 2004
From: klappnase at freenet.de (Michael Lange)
Date: Fri Jan 16 17:09:11 2004
Subject: [Tutor] Python
In-Reply-To: <200401131308.48212.kgomotso@kgatelopele.co.za>
References: <200401131308.48212.kgomotso@kgatelopele.co.za>
Message-ID: <20040116230111.6c0aceae.klappnase@freenet.de>

On Tue, 13 Jan 2004 13:08:46 +0200
Anthony Tshwane <kgomotso@kgatelopele.co.za> wrote:

> Greetings.
> 
> I am new in the python programming language and I presently trying to run 
> examples that you have give.I would like to know how are those steps executed 
> in linux invironment since IO am using linux Mandrake.i folloed that but I 
> started encountering the problam when I have to run the script.May you just 
> send me some notes about how to run that in linux.
> 
> With thanks
> Kgomotso
> 

If you want to run a python script on linux save the code to a file and make the file executable:

[pingu@localhost pingu]$  chmod -v 755 path-to-your-file

then you can run the program from a shell with:

[pingu@localhost pingu]$  python path-to-your-file

You can avoid the need to call the python interpreter each time if you put at the first line of your
file:

    #!/usr/bin/env python

If the shell finds this at the first line of your file it will automatically start the python
interpreter, so you can start your script like any other program with

[pingu@localhost pingu]$  path-to-your-file


I hope this helps

Michael

From littledanehren at yahoo.com  Fri Jan 16 17:33:09 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Fri Jan 16 17:33:14 2004
Subject: [Tutor] variable length methods?
In-Reply-To: <200401161135.i0GBZZV24617@uranus.jason.nl>
Message-ID: <20040116223309.45252.qmail@web41812.mail.yahoo.com>


--- Denis Saussus <dsaussus@jasongeo.com> wrote:
> Hello,
> 
> I would like to know if there is a special python
> version of *vargs
> specifically intended to be used with variable
> length methods instead
> of just with variable length arguments.  If there
> is, fantastic!  If
> there isn't, is it still acceptable to 'fudge'
> *vargs to do what I want?

What do you mean "variable length methods"?
> 
> For instance,
> 
> class MyClass:
>   def __init__(self, outputdir, *vargs):
>     ...
> 
> will work without any problems if you do:
> 
> MyClass mc(outputdir = 'here/',
>            a = 1,
>            b = 2,
>            c = 4,
>            ...)
> 
use **kwargs for things like a=1, b=2, c=4, etc. It
will return a dictionary of all of thosekeyword
arguments.

> but what I am seeking to do is:
> 
> MyClass mc(outputdir = 'here/',
>            plot(x),
>            plot(a,b,c),
>            plot(w,z),
>            ...)
> 
> where,
> 
> def plot(*vargs):
>    ...
> 
> Help anyone?
> 
> Thanks!

Where did the x, w, and z come from? I still don't
know what *vargs does. *args excepts however many
arguments you wan,t although it's always preferential
to use a default of None or something like that.

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes
http://hotjobs.sweepstakes.yahoo.com/signingbonus

From littledanehren at yahoo.com  Fri Jan 16 18:02:30 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Fri Jan 16 18:02:36 2004
Subject: [Tutor] to/from binary to/from integer (i.e.'01010101' =85)
In-Reply-To: <002401c3d9d0$0f18e2e0$cb2fe2dc@VULCAN>
Message-ID: <20040116230230.53108.qmail@web41803.mail.yahoo.com>

kiran-at-mhowlinux.org wrote:
> for any positive (int) to binary
> 
> a simple function would do the job
> 
> import math
> def i2b(s):
>    #check how many bits are required to represent
> the integer in binary
>     i=int(math.log(s)/math.log(2))+1
>     return ''.join([str((s&(2**(i-j-1)))>>(i-j-1))
> for j in range(i)])

I have no idea how  that works. A more legible, but
somewhat more verbose, way to do that would be:

octal = {
    '0': '000',
    '1': '001',
    '2': '010',
    '3': '011',
    '4': '100',
    '5': '101',
    '6': '110',
    '7': '111'}

def binary(number):
    numberList = [octal[x] for x in oct(number)[1:]]
    return ''.join(numberList).lstrip('0')

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes
http://hotjobs.sweepstakes.yahoo.com/signingbonus

From lumbricus at gmx.net  Fri Jan 16 19:58:08 2004
From: lumbricus at gmx.net (=?ISO-8859-1?Q?=22J=F6rg_W=F6lke=22?=)
Date: Fri Jan 16 19:58:15 2004
Subject: [Tutor] to/from binary to/from integer (i.e.'01010101' =85)
References: <20040116230230.53108.qmail@web41803.mail.yahoo.com>
Message-ID: <2341.1074301088@www7.gmx.net>

Hello!

> I have no idea how  that works. A more legible, but
> somewhat more verbose, way to do that would be:

Most straightforward IMVHO opinion is this approach:

loop {
    Look wheather the least significant bit is a 1: "number & 1"
    Store result as char ( '0' or '1' ) into String.
    Shift number to the right: "number >>= 1"
} until number == 0 ( because right shifting fills unsigned ints with 0 ) 
return String.
 
> Daniel Ehrenberg

Greetings, J"o!

-- 
"Wir k?nnen alles sehen, was sich bewegt 
und wir k?nnen alles zerst?ren, was wir sehen."
         -- Richard Perle

+++ GMX - die erste Adresse f?r Mail, Message, More +++
Bis 31.1.: TopMail + Digicam f?r nur 29 EUR http://www.gmx.net/topmail


From littledanehren at yahoo.com  Fri Jan 16 20:07:54 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Fri Jan 16 20:07:59 2004
Subject: [Tutor] Python
In-Reply-To: <200401131308.48212.kgomotso@kgatelopele.co.za>
Message-ID: <20040117010754.71924.qmail@web41812.mail.yahoo.com>

Anthony Tshwane wrote:
> Greetings.
> 
> I am new in the python programming language and I
> presently trying to run 
> examples that you have give.I would like to know how
> are those steps executed 
> in linux invironment since IO am using linux
> Mandrake.i folloed that but I 
> started encountering the problam when I have to run
> the script.May you just 
> send me some notes about how to run that in linux.
> 
> With thanks
> Kgomotso

The way the IO works shouldn't be platform-dependent
unless you use a platform-dependent module, so it
doesn't really matter that you're using Mandrake
Linux.  I'm not exactly sure which script you're
refering to, so could be more specific?

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes
http://hotjobs.sweepstakes.yahoo.com/signingbonus

From alan.gauld at blueyonder.co.uk  Sat Jan 17 03:17:09 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Sat Jan 17 03:16:19 2004
Subject: [Tutor] Question about parameters of sys module
References: <Pine.LNX.4.44.0401161307300.26758-100000@violet.rahul.net>
	<200401162232.26556.dropzone@gjldp.org>
Message-ID: <010601c3dcd2$4d281060$6401a8c0@xp>

>> Python nor os.system gives any importance to the string
>> "clear"; it just passes it to the OS for execution.
>
> But as far as I know, this type of commands can be produced 
> independently from the OS with the sys module and his 
> functions. In which cas would you use the os.sys() method?

The os module contains common OS commands that you can 
call from within Python. This is usually more efficient 
than calling os.system() because os.system() starts up 
another process. But not all OS commands are available 
in the os module and for anything else you need to use 
os.system() - or os.popen() etc.

> To make my question simple: is there a rule to determine 
> the use of either os.system() or sys module?

The sys module contains things about the Python system. 
It does not generally contain anything to do with the OS,
that is held in the os module. 

The general rule for use of the os module is that if the 
command exists in os then use it from their, if it doesn't 
and you don't need to capture the output use os.system. 
If os does not have the command and you need to capture 
the output use os.popen()

HTH

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld





From alan.gauld at blueyonder.co.uk  Sat Jan 17 03:21:30 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Sat Jan 17 03:20:41 2004
Subject: [Tutor] Python
References: <200401131308.48212.kgomotso@kgatelopele.co.za>
	<20040116230111.6c0aceae.klappnase@freenet.de>
Message-ID: <010b01c3dcd2$e8e39e20$6401a8c0@xp>

> If you want to run a python script on linux save the code 
> to a file and make the file executable:
> 
> [pingu@localhost pingu]$  chmod -v 755 path-to-your-file
> [pingu@localhost pingu]$  python path-to-your-file

If you call the script using python explicitly then you 
don't need to make the script executable, only readable.

> each time if you put at the first line of your file:
> 
>     #!/usr/bin/env python
>
> If the shell finds this at the first line of your file 
> it will automatically start the python interpreter, 
> so you can start your script like any other program with
> 
> [pingu@localhost pingu]$  path-to-your-file

But to do this the script must be executable.

Being picky,

Alan G.

From klappnase at freenet.de  Sat Jan 17 19:35:58 2004
From: klappnase at freenet.de (Michael Lange)
Date: Sat Jan 17 19:43:59 2004
Subject: Fw: Re: [Tutor] Python
Message-ID: <20040118013558.10648225.klappnase@freenet.de>



Begin forwarded message:

Date: Sun, 18 Jan 2004 01:31:59 +0100
From: Michael Lange <klappnase@freenet.de>
To: Daniel Ehrenberg <littledanehren@yahoo.com>
Subject: Re: [Tutor] Python


On Fri, 16 Jan 2004 17:01:24 -0800 (PST)
Daniel Ehrenberg <littledanehren@yahoo.com> wrote:

> 
> Really? I always thought you could run any text file
> using the python command, 

Ooops, sorry, of course you are right here

and that you need to do
> chmod +x to run it standalone.
> 

you can pass options to chmod in different ways, chmod +x makes the file
executable for anyone (what's well enough here of course), the octals in chmod 755
define the read and write permissions as well.

Regards

Michael





From kp8 at mac.com  Sun Jan 18 00:37:37 2004
From: kp8 at mac.com (kevin parks)
Date: Sun Jan 18 00:38:29 2004
Subject: [Tutor] comparing seqs by successive intervals
Message-ID: <6C723D48-4978-11D8-BFB7-003065555ABC@mac.com>

hi all.

I am trying to take some lists and compares them by measuring the 
intervals or gaps between each successive list item. I should also 
point out that everything here is modulo 12), so if we have a list like 
so:

seq01 = [5, 7, 8, 11]

the interval from list item 0 (5) to list item 1(7) is 2, item 1(7) to 
item 2 (8) is 1, and item 2 (8) to the last (11) is 3.

seq02 = [1, 3, 4, 7]

by this criteria seq02 would be the same as the intervals between each 
successive sequence item is the same:

2-1-3

so it would be great if it indicated whether they were the same or not 
and if so printed out the interval sequence.

Yet i am not quite sure how best to do this. Do i do parallel 
traversals with something like for (x, y) in foo ...? or do i first 
measure the intervals in one list and then the other? What if i have 
more than 2 lists? is that too hairy to deal with? How can i do this 
with lists of different lengths and have it at least compare the 
sequences as far as the shortest list?

hmm.... So many question for such a small brain such as i have. I have 
had a need to do similar things before. I am hoping some one can give 
me a push in the right direction or talk me through the steps. I would 
love to see how something like this would be done. It may seem odd, but 
is something i keep coming across and am not yet able to get my head 
'round.

Help... Anyone...?

cheers,

kevin



From darnold02 at sprynet.com  Sun Jan 18 01:48:38 2004
From: darnold02 at sprynet.com (don arnold)
Date: Sun Jan 18 01:48:58 2004
Subject: [Tutor] comparing seqs by successive intervals
References: <6C723D48-4978-11D8-BFB7-003065555ABC@mac.com>
Message-ID: <00f101c3dd8f$1b0b19c0$2e11ba3f@don2uvsu54fwiq>


----- Original Message -----
From: "kevin parks" <kp8@mac.com>
To: <tutor@python.org>
Sent: Saturday, January 17, 2004 11:37 PM
Subject: [Tutor] comparing seqs by successive intervals


> hi all.
>
> I am trying to take some lists and compares them by measuring the
> intervals or gaps between each successive list item. I should also
> point out that everything here is modulo 12), so if we have a list like
> so:
>
> seq01 = [5, 7, 8, 11]
>
> the interval from list item 0 (5) to list item 1(7) is 2, item 1(7) to
> item 2 (8) is 1, and item 2 (8) to the last (11) is 3.
>
> seq02 = [1, 3, 4, 7]
>
> by this criteria seq02 would be the same as the intervals between each
> successive sequence item is the same:
>
> 2-1-3
>
> so it would be great if it indicated whether they were the same or not
> and if so printed out the interval sequence.
>
> Yet i am not quite sure how best to do this. Do i do parallel
> traversals with something like for (x, y) in foo ...? or do i first
> measure the intervals in one list and then the other? What if i have
> more than 2 lists? is that too hairy to deal with? How can i do this
> with lists of different lengths and have it at least compare the
> sequences as far as the shortest list?
>
> hmm.... So many question for such a small brain such as i have. I have
> had a need to do similar things before. I am hoping some one can give
> me a push in the right direction or talk me through the steps. I would
> love to see how something like this would be done. It may seem odd, but
> is something i keep coming across and am not yet able to get my head
> 'round.

>
> Help... Anyone...?
>
> cheers,
>
> kevin
>

Forgive my asking, but what would this sort of comparison be used for? The
problem seems strange enough to make it sound an awful lot like a homework
assignment.

Don


From missive at hotmail.com  Sun Jan 18 07:30:27 2004
From: missive at hotmail.com (Lee Harr)
Date: Sun Jan 18 07:30:33 2004
Subject: [Tutor] Re: comparing seqs by successive intervals
Message-ID: <BAY2-F138vEjaGjrd5m0001f113@hotmail.com>

>I am trying to take some lists and compares them by measuring the
>intervals or gaps between each successive list item. I should also
>point out that everything here is modulo 12), so if we have a list like
>so:
>
>seq01 = [5, 7, 8, 11]
>
>the interval from list item 0 (5) to list item 1(7) is 2, item 1(7) to
>item 2 (8) is 1, and item 2 (8) to the last (11) is 3.
>
>seq02 = [1, 3, 4, 7]
>
>by this criteria seq02 would be the same as the intervals between each
>successive sequence item is the same:
>
>2-1-3
>


How about "normalizing" each list?

>>>seq01 = [5, 7, 8, 11]
>>>s01 = [s - seq01[0] for s in seq01]
>>>s01
[0, 2, 3, 6]
>>>seq02 = [1, 3, 4, 7]
>>>s02 = [s - seq02[0] for s in seq02]
>>>s02
[0, 2, 3, 6]

_________________________________________________________________
The new MSN 8: advanced junk mail protection and 2 months FREE* 
http://join.msn.com/?page=features/junkmail


From python at keep-trying.com  Sun Jan 18 10:49:49 2004
From: python at keep-trying.com (richard)
Date: Sun Jan 18 10:50:25 2004
Subject: [Tutor] String Substitution
Message-ID: <6.0.0.22.0.20040118152516.01b43ce0@192.168.5.1>

Greetings,

Once again I am stuk on strings. I  wish to get the text entered
in a number of fields and pass it into a dict which I can then use
in an a sql query to update a record (and vice versa). Each control
  is number textCtrl0 to in this case 2.

However when I do the following:

values = []     # create the empty dict
for i in range(3): # create the range
      values.append (self.textCtrl%d.GetValue() % i) # append the contents 
of each ctrl to 'values'

Instead of getting the following:

values = [textCtrl0.data, textCtrl1.data, textCtrl2.data]

I get this:

Traceback (most recent call last):
   File "D:\pythonwork\tesguis\frmfmna.py", line 222, in saveButton
     values.append (self.textCtrl%d.GetValue() % i)
AttributeError: frmfmna instance has no attribute 'textCtrl'

Which is correct as there is  no control called textCtrl

Question is why does it not work?

Richard

Richard


Error Message:

Exception in Tkinter callback
Traceback (most recent call last):
   File "C:\PYTHON22\lib\lib-tk\Tkinter.py", line 1292, in __call__
     return apply(self.func, args)
   File "C:\Python22\fmna4.py", line 29, in add
     print self.code.get()
AttributeError: 'NoneType' object has no attribute 'get'

Script:

# import modules to be used
from Tkinter import *
import Pmw

class GUI:
     def __init__(self):
######################################################################
         self.root = Tk()
         self.root.title('FMNA - Add/Amend/Delete')
         self.root.option_add('*Entry*background',     'lightblue')
         self.root.option_add('*font',   ('verdana', 10, 'bold'))

         Label(self.root, text='Code').grid(row=0, sticky=W)
         self.code=Pmw.EntryField(self.root).grid(row=0, column=1,padx=6, 
pady=2)

         Button(self.root, text='Quit', command=self.quit).grid(row=13, 
column=0, columnspan=2)
         Button(self.root, text='Add', command=self.add).grid(row=13, 
column=3, columnspan=2)

     def quit(self):
         import sys
         sys.quit

     def add(self):
         print self.code.get()

myGUI = GUI()
#myGUI.root.mainloop()

-----------------------------------------
Python 2.2
Platform Win32 


From littledanehren at yahoo.com  Sun Jan 18 12:43:52 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Sun Jan 18 12:43:58 2004
Subject: [Tutor] String Substitution
In-Reply-To: <6.0.0.22.0.20040118152516.01b43ce0@192.168.5.1>
Message-ID: <20040118174352.23104.qmail@web41810.mail.yahoo.com>

richard wrote:
> Greetings,
> 
> Once again I am stuk on strings. I  wish to get the
> text entered
> in a number of fields and pass it into a dict which
> I can then use
> in an a sql query to update a record (and vice
> versa). Each control
>   is number textCtrl0 to in this case 2.
> 
> However when I do the following:
> 
> values = []     # create the empty dict
> for i in range(3): # create the range
>       values.append (self.textCtrl%d.GetValue() % i)
> # append the contents 
> of each ctrl to 'values'
> 
> Instead of getting the following:
> 
> values = [textCtrl0.data, textCtrl1.data,
> textCtrl2.data]
> 
> I get this:
> 
> Traceback (most recent call last):
>    File "D:\pythonwork\tesguis\frmfmna.py", line
> 222, in saveButton
>      values.append (self.textCtrl%d.GetValue() % i)
> AttributeError: frmfmna instance has no attribute
> 'textCtrl'
> 
> Which is correct as there is  no control called
> textCtrl
> 
> Question is why does it not work?
> 
> Richard

You are trying to do a string operation on something
that isn't a string. Instead of writing:

values.append(self.textCtrl%d.GetValue() % i

You have to treat it as a string and then evaluate it.
Here's what you should have written:

values.append(eval('self.textCtrl%d.GetValue()' % i))

That's not very readable, and eval isn't very
efficient, so since it's just three items, you'd
probably be better off writing (instead of the entire
loop):

values.append(self.textCtrl1.GetValue())
values.append(self.textCtrl2.GetValue())
values.append(self.textCtrl3.GetValue())

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes
http://hotjobs.sweepstakes.yahoo.com/signingbonus

From darnold02 at sprynet.com  Sun Jan 18 13:55:26 2004
From: darnold02 at sprynet.com (don arnold)
Date: Sun Jan 18 13:55:46 2004
Subject: [Tutor] comparing seqs by successive intervals
References: <671669EB-49CD-11D8-87EB-003065555ABC@mac.com>
Message-ID: <021a01c3ddf4$a32beef0$2e11ba3f@don2uvsu54fwiq>

----- Original Message ----- 
From: "kevin parks" <kp8@mac.com>
To: "don arnold" <darnold02@sprynet.com>
Sent: Sunday, January 18, 2004 9:45 AM
Subject: Re: [Tutor] comparing seqs by successive intervals


> it would be used for comparing musical sequences to see if they are 
> related by transposition or inversion. Two musical sequences that have 
> different pitch classes are related by inversion or transposition if 
> their interval sequences are preserved. I would be using this to test 
> for that.

Interesting. Here's what I came up with:

def interval(seq):
    res = []
    for i in range(len(seq)-1):
        res.append((seq[i+1] - seq[i]) % 12)
    return res

def isEqual(seq1, seq2):
    int1 = interval(seq1)
    int2 = interval(seq2)
    
    numPlaces = min(len(int1),len(int2))
    if int1[:numPlaces] == int2[:numPlaces]:
        return True, int1[:numPlaces]
    else:
        return False, []
    
a = [5,7,8,11]
b = [1,3,4,7]
c = [1,3,4,7,15]
d = [1,3,4,8]
e = [2,4]

print 'a: %-20s  intervals: %s' % (a, interval(a))
print 'b: %-20s  intervals: %s' % (b, interval(b))
print 'c: %-20s  intervals: %s' % (c, interval(c))
print 'd: %-20s  intervals: %s' % (d, interval(d))
print 'e: %-20s  intervals: %s' % (e, interval(e))
print
print 'a == b : %d    match: %s' % isEqual(a,b)
print 'a == c : %d    match: %s' % isEqual(a,c)
print 'c == a : %d    match: %s' % isEqual(c,a)
print 'c == d : %d    match: %s' % isEqual(c,d)
print 'a == e : %d    match: %s' % isEqual(a,e)


[-- output --]

a: [5, 7, 8, 11]         intervals: [2, 1, 3]
b: [1, 3, 4, 7]          intervals: [2, 1, 3]
c: [1, 3, 4, 7, 15]      intervals: [2, 1, 3, 8]
d: [1, 3, 4, 8]          intervals: [2, 1, 4]
e: [2, 4]                intervals: [2]

a == b : 1    match: [2, 1, 3]
a == c : 1    match: [2, 1, 3]
c == a : 1    match: [2, 1, 3]
c == d : 0    match: []
a == e : 1    match: [2]

<snip>

HTH
Don


From python at keep-trying.com  Sun Jan 18 14:02:20 2004
From: python at keep-trying.com (richard)
Date: Sun Jan 18 14:04:56 2004
Subject: [Tutor] String Substitution
Message-ID: <6.0.0.22.0.20040118190211.01cdf188@192.168.5.1>

At 17:22 18/01/2004, you wrote:
>richard wrote:
> > Greetings,
> >
> > Once again I am stuck on strings. I  wish to get the
> > text entered
> > in a number of fields and pass it into a dict which
>Snip Snip..
>
>You are trying to do a string operation on something
>that isn't a string. Instead of writing:
>
>values.append(self.textCtrl%d.GetValue() % i
>
>You have to treat it as a string and then evaluate it.
>Here's what you should have written:
>
>values.append(eval('self.textCtrl%d.GetValue()' % i))
>
>That's not very readable, and eval isn't very
>efficient, so since it's just three items, you'd
>probably be better off writing (instead of the entire
>loop):
>
>values.append(self.textCtrl1.GetValue())
>values.append(self.textCtrl2.GetValue())
>values.append(self.textCtrl3.GetValue())
>
>Daniel Ehrenberg
I only gave three controls as an example in fact
there are 19 on this particular form. Others will have
any number of them. Up to now I had just just
being adding one control at a time as shown but
decided that it cannot be very good scripting to do
it this way especially with 19 controls and multiple
forms. This is why I was trying to use the loop.

So the new question is, should I be sticking with
one line per control, or if a loop is the way to go how do
I do this if using 'eval' is not efficient. (but does work).

Thanks for help so far,

Richard  


From sigurd at 12move.de  Sun Jan 18 18:51:19 2004
From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=)
Date: Sun Jan 18 19:03:13 2004
Subject: [Tutor] String Substitution
In-Reply-To: <6.0.0.22.0.20040118190211.01cdf188@192.168.5.1> (richard's
	message of "Sun, 18 Jan 2004 19:02:20 +0000")
References: <6.0.0.22.0.20040118190211.01cdf188@192.168.5.1>
Message-ID: <m3llo4bz3d.fsf@hamster.pflaesterer.de>

On 18 Jan 2004, richard <- python@keep-trying.com wrote:

> being adding one control at a time as shown but
> decided that it cannot be very good scripting to do
> it this way especially with 19 controls and multiple
> forms. This is why I was trying to use the loop.

> So the new question is, should I be sticking with
> one line per control, or if a loop is the way to go how do
> I do this if using 'eval' is not efficient. (but does work).

> Thanks for help so far,

What about putting the names of the functions in a list or a dictionary?

class Test(object):
    def __init__(self):
        self.funs = [eval('self.a' + str(f)) for f in xrange(1,5)]
        
    def a1(self): return 1
    def a2(self): return 2
    def a3(self): return 3
    def a4(self): return 4

    def values(self):
        vals = []
        for fun in self.funs:
            vals.append(fun())
        return vals

Here you call eval only once; that shouldn't be a bottleneck (but if you
could easily write the functions yourself).

I don't know if you wanted to store the results in the list (the list
being an attribute of the class) or just return that list, the way I did
it here.


   Karl
-- 
Please do *not* send copies of replies to me.
I read the list


From isrgish at fusemail.com  Sun Jan 18 20:45:06 2004
From: isrgish at fusemail.com (Isr Gish)
Date: Sun Jan 18 20:45:21 2004
Subject: [Tutor] Using a string to get at a Variable
Message-ID: <E1AiOTM-0001A7-6L@fuse1.fusemail.net>

I'm trying to get the data from a variable using a string.
For example I have three variables named apples, grapes, pears. Then I have a list with these 3 names as strings.
Now I would like to do a loop on the list and getsthe data from each name.

Any help would be greatly appreciated.

Thanks in Advance

---------------
Isr Gish


From jb at riseup.net  Sun Jan 18 21:09:24 2004
From: jb at riseup.net (jb)
Date: Sun Jan 18 21:10:39 2004
Subject: [Tutor] Different md5 values for files under Unix and Python?
In-Reply-To: <BC2C5101.151AA%clay@shirky.com>
References: <BC2C5101.151AA%clay@shirky.com>
Message-ID: <20040119020924.GB13042@mubai.sakeos.net>

On Thu, Jan 15, 2004 at 02:15:29PM -0500, Clay Shirky wrote:
> So I'm hashing some files, and I get different outputs for
> 
> os.popen("md5 filename") and hash.update("filename"); digest=hash.digest()
> 
> and I can't figure out what I'm doing wrong. The two md5's should produce
> the same hash, right?

hash = md5.md5()
hash.update("filename")
hash.hexdigest()

will return the md5 hash of the string 'filename'.

what you want to do is something like 
a.update(open('filename').read()), which will read the entire file in a string
and then compute a hash for the string.

later'
jb


From hcohen2 at comcast.net  Sun Jan 18 21:29:03 2004
From: hcohen2 at comcast.net (hcohen2)
Date: Sun Jan 18 21:30:48 2004
Subject: [Tutor] Using a string to get at a Variable
In-Reply-To: <E1AiOTM-0001A7-6L@fuse1.fusemail.net>
References: <E1AiOTM-0001A7-6L@fuse1.fusemail.net>
Message-ID: <400B40EF.3090603@comcast.net>

Isr Gish wrote:

>I'm trying to get the data from a variable using a string.
>For example I have three variables named apples, grapes, pears. Then I have a list with these 3 names as strings.
>Now I would like to do a loop on the list and getsthe data from each name.
>
>Any help would be greatly appreciated.
>
>Thanks in Advance
>
>---------------
>Isr Gish
>
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>  
>
Ist,

You are not very explicit on either on what you on working with nor the 
sort of object that contains the data you are seeking to extract, hence, 
I will just outline an example of my own design.

Let's say you get you set of variables as a tuple: (var_1, var_2, ..., 
var_n) - I am going to assume these variables are names of lists.  So I 
see no real need to convert them to strings.  If that is indeed 
necessary, skip the entire discussion.

#Intermediate result
names_tuple = (var_1, var_2, ..., var_n)
len_tuple = len(names_tuple)
for j in range(len_tuple):
        try:
                len_obj = len(var_j)
                for i in range(len_obj):
                        value_of_obj(i) = var_i[i]
                         try:
                                print 'Show me the value of %s' %   
names_tuple[j],
                                print var_i[i]
                                # Or do whatever you have in mind, e.g. 
storing in a dictionary, etc.
                         except ValueError, TypeError, diag:      # 
regarding the errors I am guessing
                               print str(diag)
       except TypeError, RangeError, diag:
                 print str(diag)

I am not sure how useful you will find this nor how close it is to 
solving the problem you are attacking - just recognize I am new at 
python.  Moreover, I may miss the clues to the type of problem, since my 
specialty is databases and much of the discussion here leaves me a bit 
puzzled as to where they are being applied.

In any case, I hope it helps a bit.
Herschel



From littledanehren at yahoo.com  Sun Jan 18 22:31:17 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Sun Jan 18 22:31:28 2004
Subject: [Tutor] String Substitution
In-Reply-To: <6.0.0.22.0.20040118190211.01cdf188@192.168.5.1>
Message-ID: <20040119033117.27367.qmail@web41802.mail.yahoo.com>

> I only gave three controls as an example in fact
> there are 19 on this particular form. Others will
> have
> any number of them. Up to now I had just just
> being adding one control at a time as shown but
> decided that it cannot be very good scripting to do
> it this way especially with 19 controls and multiple
> forms. This is why I was trying to use the loop.
> 
> So the new question is, should I be sticking with
> one line per control, or if a loop is the way to go
> how do
> I do this if using 'eval' is not efficient. (but
> does work).
> 
> Thanks for help so far,
> 
> Richard  

If you have 19 controls, you should definitely use the
eval solution. If you're already using Python, then
you're valueing less code over efficiency (with
something like C). The speed penalty in this case is
negligible, but in general, use of eval is
discourgaged. A different version with (practically)
no speed penalty, using getattr(), would be

values.append(getattr(self,
'textCtrl%d'%i).GetValue())

Instead of evaluating the whole thing, this uses a
more specific (and therefore faster) mechanism to get
that item from self, and then normal code is used
GetValue(), so it is at full speed.

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes
http://hotjobs.sweepstakes.yahoo.com/signingbonus

From isrgish at fusemail.com  Mon Jan 19 00:37:59 2004
From: isrgish at fusemail.com (Isr Gish)
Date: Mon Jan 19 00:38:08 2004
Subject: [Tutor] Using a string to get at a Variable
Message-ID: <E1AiS6k-0005cx-76@fuse1.fusemail.net>

-----Original Message-----
   >From: "hcohen2"<hcohen2@comcast.net>
   >Sent: 1/18/04 9:29:03 PM
   >To: "Isr Gish"<isrgish@fusemail.com>
   >Cc: "Tutor"<tutor@python.org>
   >Subject: Re: [Tutor] Using a string to get at a Variable
   >
   >Isr Gish wrote:
   >
   >>I'm trying to get the data from a variable using a string.
   >>For example I have three variables named apples, grapes, pears. Then I have a list with these 3 names as strings.
   >>Now I would like to do a loop on the list and getsthe data from each name.
   >>
   >>Any help would be greatly appreciated.
   >>
   >>Thanks in Advance
   >>
   >>---------------
   >>Isr Gish
   >>
   >>
   >>_______________________________________________
   >>Tutor maillist  -  Tutor@python.org
   >>http://mail.python.org/mailman/listinfo/tutor
   >>
   >>  
   >>
   >Ist,
   >
   >You are not very explicit on either on what you on working with nor the 
   >sort of object that contains the data you are seeking to extract, hence, 
   >I will just outline an example of my own design.
   >
   >Let's say you get you set of variables as a tuple: (var_1, var_2, ..., 
   >var_n) - I am going to assume these variables are names of lists.  So I 
   >see no real need to convert them to strings.  If that is indeed 
   >necessary, skip the entire discussion.
   >
   >#Intermediate result
   >names_tuple = (var_1, var_2, ..., var_n)
   >len_tuple = len(names_tuple)
   >for j in range(len_tuple):
   >        try:
   >                len_obj = len(var_j)
   >                for i in range(len_obj):
   >                        value_of_obj(i) = var_i[i]
   >                         try:
   >                                print 'Show me the value of %s' %   
   >names_tuple[j],
   >                                print var_i[i]
   >                                # Or do whatever you have in mind, e.g. 
   >storing in a dictionary, etc.
   >                         except ValueError, TypeError, diag:      # 
   >regarding the errors I am guessing
   >                               print str(diag)
   >       except TypeError, RangeError, diag:
   >                 print str(diag)
   >
   >I am not sure how useful you will find this nor how close it is to 
   >solving the problem you are attacking - just recognize I am new at 
   >python.  Moreover, I may miss the clues to the type of problem, since my 
   >specialty is databases and much of the discussion here leaves me a bit 
   >puzzled as to where they are being applied.
   >
   >In any case, I hope it helps a bit.
   >Herschel
   >

I don't understand the code you wrote, and what exactly its supposed to do.
But this is what I'm looking for.

apples = 10
grapes = 5
pears = 8
fruits = ['apples', 'grapes', 'pears']
Now Iswant to be able to do something like this.
for fruit in fruits:
	print 'You heve %d' % (fruit), fruit

And the output should look like this:
You have 10 apples
You have 5 grapes
You have 8 pears

Thanks for the reply and if anyone can help it would be appreciated.

Isr Gish


From isrgish at fusemail.com  Mon Jan 19 00:46:58 2004
From: isrgish at fusemail.com (Isr Gish)
Date: Mon Jan 19 00:47:04 2004
Subject: [Tutor] Using a string to get at a Variable
Message-ID: <E1AiSFP-0000lj-6h@fuse1.fusemail.net>



-----Original Message-----
   >But this is what I'm looking for.
   >
   >apples = 10
   >grapes = 5
   >pears = 8
   >fruits = ['apples', 'grapes', 'pears']
   >Now Iswant to be able to do something like this.
   >for fruit in fruits:
   >	print 'You heve %d' % (fruit), fruit
   >
   >And the output should look like this:
   >You have 10 apples
   >You have 5 grapes
   >You have 8 pears
   >
   >Thanks for the reply and if anyone can help it would be appreciated.
   >
   >Isr Gish

I think I found the answer to use eval(...)
apples = 10
grapes = 5
pears = 8
fruits = ['apples', 'grapes', 'pears']
Now Iswant to be able to do something like this.
for fruit in fruits:
	print 'You heve %d' % eval(fruit), fruit

Isr


From dyoo at hkn.eecs.berkeley.edu  Mon Jan 19 01:58:07 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon Jan 19 01:58:12 2004
Subject: [Tutor] comparing seqs by successive intervals
In-Reply-To: <6C723D48-4978-11D8-BFB7-003065555ABC@mac.com>
Message-ID: <Pine.LNX.4.44.0401182252040.17642-100000@hkn.eecs.berkeley.edu>



On Sun, 18 Jan 2004, kevin parks wrote:

> I am trying to take some lists and compares them by measuring the
> intervals or gaps between each successive list item.

[some text cut]


> seq02 = [1, 3, 4, 7]
>
> by this criteria seq02 would be the same as the intervals between each
> successive sequence item is the same:
>
> 2-1-3
>
> so it would be great if it indicated whether they were the same or not
> and if so printed out the interval sequence.
>
> Yet i am not quite sure how best to do this.

Hi Kevin,


Try writing a function that takes a single sequence, like

    [5, 7, 8, 11]

and returns the "interval sequence"

    [2, 1, 3]

Don't worry about attacking both sequences at once, but just concentrate
on finding the "interval sequence" for a single sequence.  If you can
write a such a 'find_intervals()' function, then all you'll need to do is
apply that function twice.

Sorta like:

###
first_interval_sequence = interval_sequence(seq1)
second_interval_sequence = interval_sequence(seq2)

if first_interval_sequence == second_interval_sequence:
    print "Equivalent sequences"
###

Does this make sense?  If a problem seems too hard to tackle all at once,
breaking it down into easier subtasks usually does the trick.


Good luck to you!


From kp8 at mac.com  Mon Jan 19 01:58:38 2004
From: kp8 at mac.com (kevin parks)
Date: Mon Jan 19 01:59:29 2004
Subject: [Tutor] comparing seqs by successive intervals
In-Reply-To: <E1AiGKf-0000w1-Ll@mail.python.org>
Message-ID: <E87B6E32-4A4C-11D8-8FBD-003065555ABC@mac.com>

Don asks:

> Forgive my asking, but what would this sort of comparison be used for? 
> The
> problem seems strange enough to make it sound an awful lot like a 
> homework
> assignment.

It would be used for comparing musical sequences to see if they are 
related by transposition or inversion (get to that later). Two musical 
sequences that have different pitches are related by transposition if 
their interval sequences are the same. I would be using this to test 
for that condition.

It is not a homework assignment. It is just something i am trying to 
hack together for my own personal
library of python modules. Mostly cause i am insane and do this on a 
sat night for fun.

Lee suggests:


> How about "normalizing" each list?
>
>>>> seq01 = [5, 7, 8, 11]
>>>> s01 = [s - seq01[0] for s in seq01]
>>>> s01
> [0, 2, 3, 6]
>>>> seq02 = [1, 3, 4, 7]
>>>> s02 = [s - seq02[0] for s in seq02]
>>>> s02
> [0, 2, 3, 6]
>

Actually I am doing something similar to this in some other code. I 
have something that removes duplicates and sorts the items beforehand, 
then normalizes as above. And of course normalizing will show that 
there are indeed transpositions (i have code that does this too) but i 
was intrigued and puzzled by this idea of measuring the intervals 
between successive list items and wanted to see how that could be done 
and then compared to another list, because i eventually find a way to 
see how far away the transposed items are.... eventually.

I see that Don has sent something like is close to what i am trying to 
do, only his seems to work *^-^*, I am going to look at that now.

Thanks for the responses.


-kevin



From dyoo at hkn.eecs.berkeley.edu  Mon Jan 19 02:01:36 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon Jan 19 02:01:52 2004
Subject: [Tutor] Different md5 values for files under Unix and Python?
In-Reply-To: <20040119020924.GB13042@mubai.sakeos.net>
Message-ID: <Pine.LNX.4.44.0401182259030.17642-100000@hkn.eecs.berkeley.edu>



On Mon, 19 Jan 2004, jb wrote:

> > os.popen("md5 filename") and hash.update("filename"); digest=hash.digest()
> >
> > and I can't figure out what I'm doing wrong. The two md5's should
> > produce the same hash, right?
>
> hash = md5.md5()
> hash.update("filename")
> hash.hexdigest()
>
> will return the md5 hash of the string 'filename'.
>
> what you want to do is something like
>
> a.update(open('filename').read()), which will read the entire file in a
> string


And make sure the file is being opened in 'binary mode':

    a.update(open('filename').read('rb'))

This is to ensure that the operating system doesn't try to misguidedly do
newline/carriage return conversions.


From dyoo at hkn.eecs.berkeley.edu  Mon Jan 19 02:16:04 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon Jan 19 02:16:09 2004
Subject: [Tutor] Using a string to get at a Variable
In-Reply-To: <E1AiS6k-0005cx-76@fuse1.fusemail.net>
Message-ID: <Pine.LNX.4.44.0401182302210.17642-100000@hkn.eecs.berkeley.edu>

> I don't understand the code you wrote, and what exactly its supposed to
> do. But this is what I'm looking for.
>
> apples = 10
> grapes = 5
> pears = 8
> fruits = ['apples', 'grapes', 'pears']
> Now Iswant to be able to do something like this.
> for fruit in fruits:
> 	print 'You heve %d' % (fruit), fruit
>
> And the output should look like this:
> You have 10 apples
> You have 5 grapes
> You have 8 pears
>
> Thanks for the reply and if anyone can help it would be appreciated.


Hi Isr,

You may want to look at dictionaries:

    http://www.ibiblio.org/obp/thinkCSpy/chap10.htm

And by "may", I emphatically mean "You really should look at
dictionaries."  *grin*


Instead of using the separate variables 'apples', 'grapes', and 'pears',
we can use a dictionary to collect them all together:

###
>>> fruitbasket = {}
>>> fruitbasket['apples'] = 10
>>> fruitbasket['grapes'] = 5
>>> fruitbasket['pears'] = 8
###



We can take a look at the fruitbasket as a whole:

###
>>> fruitbasket
{'pears': 8, 'apples': 10, 'grapes': 5}
###

or just pick individual fruits out by name:

###
>>> fruitbasket['pears']
8
>>> fruitbasket['grapes']
5
###


Play around with dictionaries more, and you should see how to use them to
make your program run well.


The solution with eval() that you found does work, but it is, well...
truthfully speaking, very nonstandard...  *grin*  Dictionaries are a
concept in almost all programming languages, whereas eval() is not so
widespread.  You'll get better mileage out of understanding dictionaries.


Good luck to you!


From dyoo at hkn.eecs.berkeley.edu  Mon Jan 19 02:19:32 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon Jan 19 02:19:36 2004
Subject: [Tutor] Different md5 values for files under Unix and Python?
In-Reply-To: <Pine.LNX.4.44.0401182259030.17642-100000@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.44.0401182317370.17642-100000@hkn.eecs.berkeley.edu>


> And make sure the file is being opened in 'binary mode':
>
>     a.update(open('filename').read('rb'))
>
> This is to ensure that the operating system doesn't try to misguidedly
> do newline/carriage return conversions.

... duh.  I'm sorry, I screwed that up completely.  My code above there is
totally bogus.


I mean to say:

    a.update(open('filename', 'rb').read())

The 'rb' was meant to be the second argument to the open() function call.
It certainly wasn't supposed to be fed into read()!  *grin*


My apologies again; I'll try to be more careful next time.


From lakmi_ll at yahoo.com  Mon Jan 19 02:24:42 2004
From: lakmi_ll at yahoo.com (Lakmi munasinghe)
Date: Mon Jan 19 02:24:47 2004
Subject: [Tutor] Help - Where and when to use OOP
Message-ID: <20040119072442.6063.qmail@web12204.mail.yahoo.com>


Hi,

I have a little exposure to OOP. I 'd like to know for what kind of programs that I should use OOP programming concepts and for what kind of programs that the stuctured programming would be more suited.

As far as I know if we don't see any repeating processes in our system applying OOP programming will cause no effect.In such cases we should manage with structured programming with functions and procedures where necessary. Am I correct ?

Lakmi



---------------------------------
Do you Yahoo!?
Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20040118/399a34f6/attachment.html
From lakmi_ll at yahoo.com  Mon Jan 19 02:36:48 2004
From: lakmi_ll at yahoo.com (Lakmi munasinghe)
Date: Mon Jan 19 02:36:51 2004
Subject: [Tutor] Help - Where and when to use OOP
Message-ID: <20040119073648.45020.qmail@web12208.mail.yahoo.com>


Hi,

I have a little exposure to OOP. I 'd like to know for what kind of programs that I should use OOP programming concepts and for what kind of programs that the stuctured programming would be more suited.

As far as I know if we don't see any repeating processes in our system applying OOP programming will cause no effect.In such cases we should manage with structured programming with functions and procedures where necessary. Am I correct ?

Lakmi




---------------------------------
Do you Yahoo!?
Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20040118/dc85c550/attachment.html
From darnold02 at sprynet.com  Mon Jan 19 07:00:54 2004
From: darnold02 at sprynet.com (don arnold)
Date: Mon Jan 19 07:01:15 2004
Subject: [Tutor] comparing seqs by successive intervals
References: <BE7BE28A-4A4E-11D8-8FBD-003065555ABC@mac.com>
Message-ID: <03ef01c3de83$e5219050$2e11ba3f@don2uvsu54fwiq>

----- Original Message -----
From: "kevin parks" <kp8@mac.com>
To: "don arnold" <darnold02@sprynet.com>
Sent: Monday, January 19, 2004 1:11 AM
Subject: Re: [Tutor] comparing seqs by successive intervals


> Don,
>
> This is awesome. Very helpful indeed. I am taking a good look at it
>
> So interval() measures the intervals between each successive list
> element and store those measurements in a list the -1 is needed
> that we don't overrun the list right?

Yes. We're calculating each interval measurement by examining the current
element and the one after it. Since there isn't an element after the last
one (not too surprising), we want to stop at the second to the last element.

>
> With IsEqual() you start by taking the input lists and getting the
> interval sequences
> by calling the function interval() and then you use min to make sure we
> compare only the number of elements we have in common
> to both lists and just snub the list elements that are more than min?

Exactly.

> Then the if loop part is the actual comparison...

It isn't a loop. But otherwise correct.

>
> I hope i am understanding this right.... I am going to print this out
> and examine
> it with a red pen.

I'd say you're understanding it perfectly.

>
> Don, thanks for your help. I was really lost on how to change the list
> into a new list which
> was the sequence of intervals. I am not sure i would have gotten that
> part on my own.
>   as the  len(seq)-1, and seq[i+1] - seq[i] parts were eluding me.
>
> I appreciate your taking the time and effort to reply.
>
> -kevin--

No problem. We're here to help.

Don

<snip rest>


From guillermo.fernandez at epfl.ch  Mon Jan 19 08:48:19 2004
From: guillermo.fernandez at epfl.ch (Guillermo Fernandez Castellanos)
Date: Mon Jan 19 08:48:23 2004
Subject: [Tutor] Re: memory problem (II part)
Message-ID: <400BE023.7050702@epfl.ch>

On Fri, 16 Jan 2004 06:40:00 -0500, Rick Pasotto <rick@niof.net> wrote:
> >Could the problem come from the cursor or database variable?
> Have you tried cursor.close() after you've finished processing the
> returned data?

Hi,

It does not work. The only thing that makes the RAM go down is to close the database. I'll try to live with that (closing and opening the database for each command...), even if it's not very clean, and use the del command with closing databases...

Thanks for the help.

Guille



From sigurd at 12move.de  Mon Jan 19 11:27:13 2004
From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=)
Date: Mon Jan 19 11:28:57 2004
Subject: [Tutor] comparing seqs by successive intervals
In-Reply-To: <E87B6E32-4A4C-11D8-8FBD-003065555ABC@mac.com> (kevin parks's
	message of "Mon, 19 Jan 2004 01:58:38 -0500")
References: <E87B6E32-4A4C-11D8-8FBD-003065555ABC@mac.com>
Message-ID: <m3k73newk6.fsf@hamster.pflaesterer.de>

On 19 Jan 2004, kevin parks <- kp8@mac.com wrote:

> Actually I am doing something similar to this in some other code. I
> have something that removes duplicates and sorts the items beforehand,
> then normalizes as above. And of course normalizing will show that
> there are indeed transpositions (i have code that does this too) but i
> was intrigued and puzzled by this idea of measuring the intervals
> between successive list items and wanted to see how that could be done
> and then compared to another list, because i eventually find a way to
> see how far away the transposed items are.... eventually.

Here is a different approach; it traverses the sequences in parallel;
you will first see a difference if you have long sequences (then mine
approach might be a bit faster).

def same_intervp(seq1, seq2):
    i = 0
    res = []
    while True:
        try:
            d1 = seq1[i+1] - seq1[i]
            d2 = seq2[i+1] - seq2[i]
        except IndexError:
            return res
        else:
            if d1 == d2:
                res.append(d1%12)
                i += 1
            else:
                return False



   Karl
-- 
Please do *not* send copies of replies to me.
I read the list


From littledanehren at yahoo.com  Mon Jan 19 11:45:10 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Mon Jan 19 11:45:23 2004
Subject: [Tutor] comparing seqs by successive intervals
In-Reply-To: <m3k73newk6.fsf@hamster.pflaesterer.de>
Message-ID: <20040119164510.36544.qmail@web41801.mail.yahoo.com>


--- Karl Pflästerer <sigurd@12move.de> wrote:
> On 19 Jan 2004, kevin parks <- kp8@mac.com wrote:
> 
> > Actually I am doing something similar to this in
> some other code. I
> > have something that removes duplicates and sorts
> the items beforehand,
> > then normalizes as above. And of course
> normalizing will show that
> > there are indeed transpositions (i have code that
> does this too) but i
> > was intrigued and puzzled by this idea of
> measuring the intervals
> > between successive list items and wanted to see
> how that could be done
> > and then compared to another list, because i
> eventually find a way to
> > see how far away the transposed items are....
> eventually.
> 
> Here is a different approach; it traverses the
> sequences in parallel;
> you will first see a difference if you have long
> sequences (then mine
> approach might be a bit faster).
> 
> def same_intervp(seq1, seq2):
>     i = 0
>     res = []
>     while True:
>         try:
>             d1 = seq1[i+1] - seq1[i]
>             d2 = seq2[i+1] - seq2[i]
>         except IndexError:
>             return res
>         else:
>             if d1 == d2:
>                 res.append(d1%12)
>                 i += 1
>             else:
>                 return False
> 
> 
> 
>    Karl
> -- 
> Please do *not* send copies of replies to me.
> I read the list

In that algorithm, where does it check to make sure
that one of the arrays isn't longer than the other?
They have to be the same length or else the real
application of seeing if they are transpositions of
eachother will not work.

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes
http://hotjobs.sweepstakes.yahoo.com/signingbonus

From littledanehren at yahoo.com  Mon Jan 19 12:11:13 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Mon Jan 19 12:11:22 2004
Subject: [Tutor] Help - Where and when to use OOP
In-Reply-To: <20040119073648.45020.qmail@web12208.mail.yahoo.com>
Message-ID: <20040119171113.88499.qmail@web41806.mail.yahoo.com>

Lakmi munasinghe wrote:
> 
> Hi,
> 
> I have a little exposure to OOP. I 'd like to know
> for what kind of programs that I should use OOP
> programming concepts and for what kind of programs
> that the stuctured programming would be more suited.
> 
> As far as I know if we don't see any repeating
> processes in our system applying OOP programming
> will cause no effect.In such cases we should manage
> with structured programming with functions and
> procedures where necessary. Am I correct ?
> 
> Lakmi

I'm not really sure what you mean my 'repeating
processes'. In general, you should use OOP when you
need more abstraction, reusability, and encapsulation.
Large projects, whether immediately aparent or not,
tend to need this. With small projects, you can go
either way.

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes
http://hotjobs.sweepstakes.yahoo.com/signingbonus

From hcohen2 at comcast.net  Mon Jan 19 13:22:21 2004
From: hcohen2 at comcast.net (hcohen2)
Date: Mon Jan 19 13:24:14 2004
Subject: [Tutor] Using a string to get at a Variable
In-Reply-To: <E1AiS6k-0005cx-76@fuse1.fusemail.net>
References: <E1AiS6k-0005cx-76@fuse1.fusemail.net>
Message-ID: <400C205D.4080301@comcast.net>

Isr Gish wrote:

>-----Original Message-----
>   >From: "hcohen2"<hcohen2@comcast.net>
>   >Sent: 1/18/04 9:29:03 PM
>   >To: "Isr Gish"<isrgish@fusemail.com>
>   >Cc: "Tutor"<tutor@python.org>
>   >Subject: Re: [Tutor] Using a string to get at a Variable
>   >
>   >Isr Gish wrote:
>   >
>   >>I'm trying to get the data from a variable using a string.
>   >>For example I have three variables named apples, grapes, pears. Then I have a list with these 3 names as strings.
>   >>Now I would like to do a loop on the list and getsthe data from each name.
>   >>
>   >>Any help would be greatly appreciated.
>   >>
>   >>Thanks in Advance
>   >>
>   >>---------------
>   >>Isr Gish
>   >>
>   >>
>   >>_______________________________________________
>   >>Tutor maillist  -  Tutor@python.org
>   >>http://mail.python.org/mailman/listinfo/tutor
>   >>
>   >>  
>   >>
>   >Ist,
>   >
>   >You are not very explicit on either on what you on working with nor the 
>   >sort of object that contains the data you are seeking to extract, hence, 
>   >I will just outline an example of my own design.
>   >
>   >Let's say you get you set of variables as a tuple: (var_1, var_2, ..., 
>   >var_n) - I am going to assume these variables are names of lists.  So I 
>   >see no real need to convert them to strings.  If that is indeed 
>   >necessary, skip the entire discussion.
>   >
>   >#Intermediate result
>   >names_tuple = (var_1, var_2, ..., var_n)
>   >len_tuple = len(names_tuple)
>   >for j in range(len_tuple):
>   >        try:
>   >                len_obj = len(var_j)
>   >                for i in range(len_obj):
>   >                        value_of_obj(i) = var_i[i]
>   >                         try:
>   >                                print 'Show me the value of %s' %   
>   >names_tuple[j],
>   >                                print var_i[i]
>   >                                # Or do whatever you have in mind, e.g. 
>   >storing in a dictionary, etc.
>   >                         except ValueError, TypeError, diag:      # 
>   >regarding the errors I am guessing
>   >                               print str(diag)
>   >       except TypeError, RangeError, diag:
>   >                 print str(diag)
>   >
>   >I am not sure how useful you will find this nor how close it is to 
>   >solving the problem you are attacking - just recognize I am new at 
>   >python.  Moreover, I may miss the clues to the type of problem, since my 
>   >specialty is databases and much of the discussion here leaves me a bit 
>   >puzzled as to where they are being applied.
>   >
>   >In any case, I hope it helps a bit.
>   >Herschel
>   >
>
>I don't understand the code you wrote, and what exactly its supposed to do.
>But this is what I'm looking for.
>
>apples = 10
>grapes = 5
>pears = 8
>fruits = ['apples', 'grapes', 'pears']
>Now Iswant to be able to do something like this.
>for fruit in fruits:
>	print 'You heve %d' % (fruit), fruit
>
>And the output should look like this:
>You have 10 apples
>You have 5 grapes
>You have 8 pears
>
>Thanks for the reply and if anyone can help it would be appreciated.
>
>Isr Gish
>
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>  
>
Isr,

Sorry, I tend to look for complex problems and obviously I misread your 
question.  My response is perhaps a reflection of my thoughts: getting a 
intermediate set of objects that are themselves objects that hold data.

Again sorry for the confusion - got too excited wondering what you could 
be after?

Herschel



From sigurd at 12move.de  Mon Jan 19 13:37:47 2004
From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=)
Date: Mon Jan 19 13:40:26 2004
Subject: [Tutor] comparing seqs by successive intervals
In-Reply-To: <20040119164510.36544.qmail@web41801.mail.yahoo.com> (Daniel
	Ehrenberg's message of "Mon, 19 Jan 2004 08:45:10 -0800 (PST)")
References: <20040119164510.36544.qmail@web41801.mail.yahoo.com>
Message-ID: <m3oeszdci4.fsf@hamster.pflaesterer.de>

On 19 Jan 2004, Daniel Ehrenberg <- littledanehren@yahoo.com wrote:

> In that algorithm, where does it check to make sure
> that one of the arrays isn't longer than the other?

Nowhere.  It wasn't specified.

> They have to be the same length or else the real
> application of seeing if they are transpositions of
> eachother will not work.

He didn't wrote that the sequences had to be of the same length.  But if
that's needed it's trivial:

def same_intervp(seq1, seq2):
    i = 0
    res = []
    if len(seq1) == len(seq2):
       [Code]
    else:
        return False

IMO that's more efficient than building two auxiliary lists and
comparing those lists.

If you compute the length anyway the code could be written a bit
different (and simpler):

def same_intervp(seq1, seq2):
    res = []
    L = len(seq1)
    if L == len(seq2):
        for i in xrange(L - 1):
            d1 = seq1[i+1] - seq1[i]
            d2 = seq2[i+1] - seq2[i]
            if d1 == d2: res.append(d1%12)
            else: return False
        return res
    else: return False



   Karl
-- 
Please do *not* send copies of replies to me.
I read the list


From kp8 at mac.com  Mon Jan 19 13:57:12 2004
From: kp8 at mac.com (kevin parks)
Date: Mon Jan 19 13:58:02 2004
Subject: [Tutor] comparing seqs by successive intervals
In-Reply-To: <E1Aicpr-0007Ir-Hl@mail.python.org>
Message-ID: <4A3EE15F-4AB1-11D8-9004-003065555ABC@mac.com>


Karl's code is really cool and works well, but as Daniel points out, it 
doesn't accommodate sequences
of different length as Don's does. Don's function will traverse both 
lists as long as the shortest
one, ignoring the remainder of the longer list by using:

     numPlaces = min(len(int1),len(int2))
     if int1[:numPlaces] == int2[:numPlaces]:

That's actually the behavior that i want. But really like this idea of 
traversing the sequences
in parallel. I wonder if the benefits of both can be merged....

Thanks Karl (and Don, and Danny, and Daniel...)

Back to work,

kevin


> In that algorithm, where does it check to make sure
> that one of the arrays isn't longer than the other?
> They have to be the same length or else the real
> application of seeing if they are transpositions of
> eachother will not work.
>
>
> --- Karl Pfl?sterer <sigurd@12move.de> wrote:
>> On 19 Jan 2004, kevin parks <- kp8@mac.com wrote:
>>
>>> Actually I am doing something similar to this in
>> some other code. I
>>> have something that removes duplicates and sorts
>> the items beforehand,
>>> then normalizes as above. And of course
>> normalizing will show that
>>> there are indeed transpositions (i have code that
>> does this too) but i
>>> was intrigued and puzzled by this idea of
>> measuring the intervals
>>> between successive list items and wanted to see
>> how that could be done
>>> and then compared to another list, because i
>> eventually find a way to
>>> see how far away the transposed items are....
>> eventually.
>>
>> Here is a different approach; it traverses the
>> sequences in parallel;
>> you will first see a difference if you have long
>> sequences (then mine
>> approach might be a bit faster).
>>
>> def same_intervp(seq1, seq2):
>>     i = 0
>>     res = []
>>     while True:
>>         try:
>>             d1 = seq1[i+1] - seq1[i]
>>             d2 = seq2[i+1] - seq2[i]
>>         except IndexError:
>>             return res
>>         else:
>>             if d1 == d2:
>>                 res.append(d1%12)
>>                 i += 1
>>             else:
>>                 return False
>>


From cybersamurai at terra.com.br  Mon Jan 19 14:56:03 2004
From: cybersamurai at terra.com.br (=?iso-8859-1?Q?cybersamurai?=)
Date: Mon Jan 19 14:56:11 2004
Subject: [Tutor] tutorial for python com server
Message-ID: <HRR61F$905236F8D4BEE8203951E1E0628B4650@terra.com.br>

A can?t find a tutorial for make a python com server.
Where can I find a simple nutshell tutorial for that?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20040119/5c23440c/attachment.html
From hcohen2 at comcast.net  Mon Jan 19 15:11:50 2004
From: hcohen2 at comcast.net (hcohen2)
Date: Mon Jan 19 15:13:36 2004
Subject: [Tutor] Re: memory problem (II part)
In-Reply-To: <400BE023.7050702@epfl.ch>
References: <400BE023.7050702@epfl.ch>
Message-ID: <400C3A06.3040804@comcast.net>

Guillermo Fernandez Castellanos wrote:

> On Fri, 16 Jan 2004 06:40:00 -0500, Rick Pasotto <rick@niof.net> wrote:
>
>> >Could the problem come from the cursor or database variable?
>> Have you tried cursor.close() after you've finished processing the
>> returned data?
>
>
> Hi,
>
> It does not work. The only thing that makes the RAM go down is to 
> close the database. I'll try to live with that (closing and opening 
> the database for each command...), even if it's not very clean, and 
> use the del command with closing databases...
>
> Thanks for the help.
>
> Guille
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
Guille,

I am perplexed, what product are you using and how heavily are you 
pounding on it?

Why are you using a cursor, which is a known memory hog?  I was 
forbidden using cursors (as were the others in our group), because it 
impacts performance so extremely under Sybase.  Oracle seems to have 
relied upon cursors much longer than competing products due to its tie 
in with the user interface (and packaged tools).  However, finally they 
too have added temporary tables that are much more efficient and 
automatically cleanup after themselves.

Herschel



From sigurd at 12move.de  Mon Jan 19 15:13:20 2004
From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=)
Date: Mon Jan 19 15:14:46 2004
Subject: [Tutor] comparing seqs by successive intervals
In-Reply-To: <4A3EE15F-4AB1-11D8-9004-003065555ABC@mac.com> (kevin parks's
	message of "Mon, 19 Jan 2004 13:57:12 -0500")
References: <4A3EE15F-4AB1-11D8-9004-003065555ABC@mac.com>
Message-ID: <m3k73nd89u.fsf@hamster.pflaesterer.de>

On 19 Jan 2004, kevin parks <- kp8@mac.com wrote:

> Karl's code is really cool and works well, but as Daniel points out,
> it doesn't accommodate sequences
> of different length as Don's does. Don's function will traverse both
> lists as long as the shortest
> one, ignoring the remainder of the longer list by using:

>      numPlaces = min(len(int1),len(int2))
>      if int1[:numPlaces] == int2[:numPlaces]:

> That's actually the behavior that i want. But really like this idea of
> traversing the sequences
> in parallel. I wonder if the benefits of both can be merged....

I'm not sure if I understand you right.  My code with the while loop
will also find matching sequences if one is longer than the other.
Daniel wrote the sequences should have equal length so I wrote another
version (in <m3oeszdci4.fsf@hamster.pflaesterer.de> ) which only
compares sequences of equal length.

Here's an example:

>>> a = [1,2,3,4,5,6,7,8,9,10] 
>>> b = [11,12]
>>> def same_intervp(seq1, seq2):
...     i = 0
...     res = []
...     while True:
...         try:
         [Code]

>>> same_intervp(a,b)
[1]


Upps I saw something in the code which is not clear to me.  If you have
a sequence [10,11,4] 4-11 => -7; -7%12 =>5.  Should that be the same
as eg. [1,2,7]?  Than you would first have to compute the modulo before
comparing the values.



   Karl
-- 
Please do *not* send copies of replies to me.
I read the list


From dyoo at hkn.eecs.berkeley.edu  Mon Jan 19 17:19:00 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon Jan 19 17:19:09 2004
Subject: [Tutor] Re: memory problem (II part)
In-Reply-To: <400C3A06.3040804@comcast.net>
Message-ID: <Pine.LNX.4.44.0401191349270.16499-100000@hkn.eecs.berkeley.edu>


> I am perplexed, what product are you using and how heavily are you
> pounding on it?
>
> Why are you using a cursor, which is a known memory hog?

We should clarify: the DB API specifies that we access the database
through a Python Cursor:

    http://python.org/peps/pep-0249.html

So if we follow the API, there's no way we can get around "cursors".
*grin*

I think, though, that we're just confusing multiple related uses of the
word "cursor".

> I was forbidden using cursors (as were the others in our group), because
> it impacts performance so extremely under Sybase.  Oracle seems to have
> relied upon cursors much longer than competing products due to its tie
> in with the user interface (and packaged tools).  However, finally they

Your use of "cursor" here may be different from the "cursor" that the DB
API is talking about.



As a concrete example, Pysqlite actually doesn't support real database
cursors --- they are simulated by storing all the results in a temporary
list, and the "cursor" object there is just iterating across that
temporary list.

Ah!  Ok, I think I'm understanding what's happening.  Pysqlite's
connections themselves hold onto cursors in a list, so that when a
connection closes, all its associated cursors can be collected.

But as a result, large queries may end up in memory while we're holding
onto the connection, since those cursors may not necessarily be freed till
much later.

I see that the pysqlite code is using weak references to keep track of all
the cursors associated with a connection:

    http://www.python.org/doc/lib/module-weakref.html

so the cursors should get reclaimed eventually when the garbage collector
kicks in.


Guillermo notes that:

> The only thing that makes the RAM go down is to close the database. I'll
> try to live with that (closing and opening the database for each
> command...),

Instead of closing the connections, what happens if you call each cursor's
close() method after you do a fetch?  Doing a close() on the connection
may be working because it calls close() on all open cursors.  Let's verify
that its the cursors that are holding onto database results in memory.


Hope this helps!


From python at keep-trying.com  Mon Jan 19 17:50:57 2004
From: python at keep-trying.com (richard)
Date: Mon Jan 19 17:51:45 2004
Subject: [Tutor] String Substitution
In-Reply-To: <20040119033117.27367.qmail@web41802.mail.yahoo.com>
References: <6.0.0.22.0.20040118190211.01cdf188@192.168.5.1>
	<20040119033117.27367.qmail@web41802.mail.yahoo.com>
Message-ID: <6.0.0.22.0.20040119224559.01d06c08@192.168.5.1>

Greetings,

Thanks for all the help. Just what I was looking
for. Have adapted for my script/form and now
works fine.

Regards


>If you have 19 controls, you should definitely use the
>eval solution. If you're already using Python, then
>you're valueing less code over efficiency (with
>something like C). The speed penalty in this case is
>negligible, but in general, use of eval is
>discourgaged. A different version with (practically)
>no speed penalty, using getattr(), would be
>
>values.append(getattr(self,
>'textCtrl%d'%i).GetValue())
>
>Instead of evaluating the whole thing, this uses a
>more specific (and therefore faster) mechanism to get
>that item from self, and then normal code is used
>GetValue(), so it is at full speed.
>
>Daniel Ehrenberg
>


From isrgish at fusemail.com  Mon Jan 19 22:07:21 2004
From: isrgish at fusemail.com (Isr Gish)
Date: Mon Jan 19 22:09:08 2004
Subject: [Tutor] Using a string to get at a Variable
Message-ID: <E1AimFy-0006sr-Qv@fuse1.fusemail.net>

Thanks Danny,
I appreciate your help, I'll look into it.

-----Original Message-----
   >From: "Danny Yoo"<dyoo@hkn.eecs.berkeley.edu>
   >Sent: 1/19/04 2:16:04 AM
   >To: "Isr Gish"<isrgish@fusemail.com>
   >Cc: "tutor@python.org"<tutor@python.org>
   >Subject: Re: [Tutor] Using a string to get at a Variable
   >
   >> I don't understand the code you wrote, and what exactly its supposed to
   >> do. But this is what I'm looking for.
   >>
   >> apples = 10
   >> grapes = 5
   >> pears = 8
   >> fruits = ['apples', 'grapes', 'pears']
   >> Now Iswant to be able to do something like this.
   >> for fruit in fruits:
   >> 	print 'You heve %d' % (fruit), fruit
   >>
   >> And the output should look like this:
   >> You have 10 apples
   >> You have 5 grapes
   >> You have 8 pears
   >>
   >> Thanks for the reply and if anyone can help it would be appreciated.
   >
   >
   >Hi Isr,
   >
   >You may want to look at dictionaries:
   >
   >    http://www.ibiblio.org/obp/thinkCSpy/chap10.htm
   >
   >And by "may", I emphatically mean "You really should look at
   >dictionaries."  *grin*
   >
   >
   >Instead of using the separate variables 'apples', 'grapes', and 'pears',
   >we can use a dictionary to collect them all together:
   >
   >###
   >>>> fruitbasket = {}
   >>>> fruitbasket['apples'] = 10
   >>>> fruitbasket['grapes'] = 5
   >>>> fruitbasket['pears'] = 8
   >###
   >
   >
   >
   >We can take a look at the fruitbasket as a whole:
   >
   >###
   >>>> fruitbasket
   >{'pears': 8, 'apples': 10, 'grapes': 5}
   >###
   >
   >or just pick individual fruits out by name:
   >
   >###
   >>>> fruitbasket['pears']
   >8
   >>>> fruitbasket['grapes']
   >5
   >###
   >
   >
   >Play around with dictionaries more, and you should see how to use them to
   >make your program run well.
   >
   >
   >The solution with eval() that you found does work, but it is, well...
   >truthfully speaking, very nonstandard...  *grin*  Dictionaries are a
   >concept in almost all programming languages, whereas eval() is not so
   >widespread.  You'll get better mileage out of understanding dictionaries.
   >
   >
   >Good luck to you!
   >
   >


From abeidson at sbcglobal.net  Mon Jan 19 23:08:10 2004
From: abeidson at sbcglobal.net (abeidson@sbcglobal.net)
Date: Mon Jan 19 23:11:45 2004
Subject: [Tutor] Beginners Help
Message-ID: <002301c3df0b$04b8cc80$900f4844@home>

I am not only new to Python.. but essentially new to programming in general.. (the last program I wrote was in Basic 15 years ago for High school). My job is starting to require me to do some type of programming to interact with databases (DB4, DB2, SQL, and Oracle). From everything I have read Python seems the best to start with.. but with all the books out there I was just looking for some insite.

Thanks
Andy
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20040119/a1ad80c5/attachment.html
From gustabares at verizon.net  Mon Jan 19 23:58:02 2004
From: gustabares at verizon.net (Gus Tabares)
Date: Mon Jan 19 23:58:03 2004
Subject: [Tutor] Beginners Help
In-Reply-To: <002301c3df0b$04b8cc80$900f4844@home>
References: <002301c3df0b$04b8cc80$900f4844@home>
Message-ID: <200401192358.02082.gustabares@verizon.net>

On Monday 19 January 2004 23:08, abeidson@sbcglobal.net wrote:
> I am not only new to Python.. but essentially new to programming in
> general.. (the last program I wrote was in Basic 15 years ago for High
> school). My job is starting to require me to do some type of programming to
> interact with databases (DB4, DB2, SQL, and Oracle). From everything I have
> read Python seems the best to start with.. but with all the books out there
> I was just looking for some insite.
>
> Thanks
> Andy

Hi Andy,

The main Python website (www.python.org) has many resources for beginning 
Python programmers (and beginner programmers in general). Check out this 
link:

http://www.python.org/doc/Intros.html

If you do chose to start with Python (a great idea;) then I would recommend 
either O'Reilly's Learning Python or Core Python Programming. Both are great 
beginner resources for learning Python.


Good luck!

-- 
Gus Tabares


From dyoo at hkn.eecs.berkeley.edu  Tue Jan 20 01:15:08 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue Jan 20 01:15:13 2004
Subject: [Tutor] Beginners Help
In-Reply-To: <200401192358.02082.gustabares@verizon.net>
Message-ID: <Pine.LNX.4.44.0401192205070.4953-100000@hkn.eecs.berkeley.edu>



> On Monday 19 January 2004 23:08, abeidson@sbcglobal.net wrote:
> > I am not only new to Python.. but essentially new to programming in
> > general.. (the last program I wrote was in Basic 15 years ago for High
> > school). My job is starting to require me to do some type of programming to
> > interact with databases (DB4, DB2, SQL, and Oracle).

Hi Andy,


Python.org has details on Database Programming, starting from:

    http://www.python.org/topics/database/

Most documentation on databases and Python will assume that you know the
Python language already --- but if you want a taste of what database
programming looks like, you can look at:

    http://www.devshed.com/c/a/Python/MySQL-Connectivity-With-Python/

It covers handling the MySQLdb database, but the concepts that they talk
about there should apply closely to any SQL-ish database.


But even this tutorial assumes familiarity with Python, so you definitely
sould look at the Intros page that Gus recommended first before tackling
the "Python Database Application Interface" (DB-API).  There's another
page that has more introductory material:

    http://www.python.org/topics/learn/non-prog.html

The "Non-Programmers" page has more emphasis on tutorials for folks that
may not have prior programming experience.

 Pick a tutorial you like, start reading it, and ask questions on Tutor
whenever you hit something that makes no sense.  *grin*


Good luck to you!


From jkaper at maine.rr.com  Sun Jan 18 23:50:13 2004
From: jkaper at maine.rr.com (Joe Kaper)
Date: Tue Jan 20 01:40:49 2004
Subject: [Tutor] jpg to doc conversion
Message-ID: <000601c3de47$ba4a9480$923fc618@maine.rr.com>

I stumbled on this thread in your bulletin board just recently.  I was wondering if there was any answer to the question of how you can convert a jpeg, or similar scanned document, into a .doc file in order to edit it in my word processer?  you can mail me at jkaper@maine.rr.com   thank you  

Joe Kaper
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20040118/a8b799a6/attachment.html
From kp8 at mac.com  Tue Jan 20 01:49:06 2004
From: kp8 at mac.com (kevin parks)
Date: Tue Jan 20 01:49:57 2004
Subject: [Tutor] prepend variable name...
Message-ID: <BE156118-4B14-11D8-9AE6-003065555ABC@mac.com>

Hi,

I have a list of lists and i want to print out what is in each list, 
but also the 'name' of the list.

exI_2a = [11,5,7,2]
exI_2b = [0,10,5]
exI_2c = [7,6,9,1]
exI_2d = [4,7,2,7,11]
exI_2e = [0,2,4,5,7,9,11]
exI_2f = [3,0,11,10,4,7]
exI_2g = [9,11,2,5,9,8,1,2]
exI_2 = [exI_2a, exI_2b, exI_2c, exI_2d, exI_2e, exI_2f, exI_2g]
for i in range(len(exI_2)):
     print exI_2[i]

gives me:

[11, 5, 7, 2]
[0, 10, 5]
[7, 6, 9, 1]
[4, 7, 2, 7, 11]
[0, 2, 4, 5, 7, 9, 11]
[3, 0, 11, 10, 4, 7]
[9, 11, 2, 5, 9, 8, 1, 2]

how can i get it to give me the name first like:

exI_2a
[11,5,7,2]

exI_2b
[0,10,5]

exI_2c
[7,6,9,1]

exI_2d
[4,7,2,7,11]

exI_2e
[0,2,4,5,7,9,11]

exI_2f
[3,0,11,10,4,7]

exI_2g
[9,11,2,5,9,8,1,2]

which is more or less back to the beginning, obviously some other stuff 
will happen in between.


-kp--



From kp8 at mac.com  Tue Jan 20 02:01:11 2004
From: kp8 at mac.com (kevin parks)
Date: Tue Jan 20 02:02:03 2004
Subject: [Tutor] Re: prepend variable name...
In-Reply-To: <BE156118-4B14-11D8-9AE6-003065555ABC@mac.com>
Message-ID: <6DF5B7CE-4B16-11D8-9AE6-003065555ABC@mac.com>

I should add that, i think the answer lies in making a dictionary (with 
zip?), but what i am not sure of is how to then traverse a dictionary 
in order...

gosh... dictionaries... hmm... we didn't have those in C so i find that 
i forget how versatile they are. Anyway, i haven't really answered my 
own question yet... but i am i headed in the right direction?

-kp--


From linuxasking at netscape.net  Wed Jan 21 04:29:47 2004
From: linuxasking at netscape.net (Xuer)
Date: Tue Jan 20 04:29:26 2004
Subject: [Tutor] getopt question
Message-ID: <400E468B.4080309@netscape.net>

an example from 'Python Programming for Beginners'

trygetopt.py
-----------------------------------------------------------------
#!/usr/bin/python

import sys,getopt
try:
        options, xarguments = getopt.getopt(sys.argv[1:],'ha')
except getopt.error:
        pass

print options
------------------------------------------------------------------

./trygetopt.py -ha
get result
[('-h', ''), ('-a', '')]

but ./trygetopt.py -h 123 -a 456
get the result
[('-h', '')]

While I expect the result would be
[('-h', '123'), ('-a', '456')]

what's the matter?
thanks in advance. :)




From darnold02 at sprynet.com  Tue Jan 20 06:54:33 2004
From: darnold02 at sprynet.com (don arnold)
Date: Tue Jan 20 06:54:56 2004
Subject: [Tutor] Re: prepend variable name...
References: <6DF5B7CE-4B16-11D8-9AE6-003065555ABC@mac.com>
Message-ID: <075401c3df4c$2c826f00$2e11ba3f@don2uvsu54fwiq>

----- Original Message -----
From: "kevin parks" <kp8@mac.com>
To: "kevin parks" <kp8@mac.com>
Cc: <tutor@python.org>
Sent: Tuesday, January 20, 2004 1:01 AM
Subject: [Tutor] Re: prepend variable name...


> I should add that, i think the answer lies in making a dictionary (with
> zip?), but what i am not sure of is how to then traverse a dictionary
> in order...
>

Yes, a dictionary is your best option (though zip doesn't enter the picture,
here). In fact, Danny just answered this same question a couple of days ago
with his 'fruitbasket' example. Instead of using a 'regular' variable to
hold your data, you use the variable name as a dictionary key and store your
data there:

myvars = {}
myvars['exI_2a'] = [11,5,7,2]
myvars['exI_2b'] = [0,10,5]
myvars['exI_2c'] = [7,6,9,1]
myvars['exI_2d'] = [4,7,2,7,11]

for key in myvars:
    print key
    print data
    print

[--output--]

exI_2d
[4, 7, 2, 7, 11]

exI_2c
[7, 6, 9, 1]

exI_2b
[0, 10, 5]

exI_2a
[11, 5, 7, 2]

You'll notice that the items aren't necessarily in key order. This is
because a dictionary is an unordered collection. To get around this, you can
use the dicionary's keys() method to generate a list of its keys, then sort
this list before iterating over it.

myvars = {}
myvars['exI_2a'] = [11,5,7,2]
myvars['exI_2b'] = [0,10,5]
myvars['exI_2c'] = [7,6,9,1]
myvars['exI_2d'] = [4,7,2,7,11]

keylist = myvars.keys()
keylist.sort()
for key in keylist:
    print key
    print myvars[key]
    print

[--output--]

exI_2a
[11, 5, 7, 2]

exI_2b
[0, 10, 5]

exI_2c
[7, 6, 9, 1]

exI_2d
[4, 7, 2, 7, 11]


> gosh... dictionaries... hmm... we didn't have those in C so i find that
> i forget how versatile they are. Anyway, i haven't really answered my
> own question yet... but i am i headed in the right direction?
>
> -kp--

Most definitely.

HTH,
Don


From abeidson at sbcglobal.net  Tue Jan 20 07:20:46 2004
From: abeidson at sbcglobal.net (abeidson@sbcglobal.net)
Date: Tue Jan 20 07:24:20 2004
Subject: [Tutor] Beginners Help
References: <002301c3df0b$04b8cc80$900f4844@home>
	<200401192358.02082.gustabares@verizon.net>
Message-ID: <002301c3df4f$d5ade660$2a0f4844@home>

Has anyone used the book Python Programming for the Absolute Beginner by
Michael Dawson?? and if so is it on par or better then the O'Reilly books
(have used those books for SAMBA, Linux, and Sendmail)
----- Original Message ----- 
From: "Gus Tabares" <gustabares@verizon.net>
To: <tutor@python.org>
Sent: Monday, January 19, 2004 11:58 PM
Subject: Re: [Tutor] Beginners Help


> On Monday 19 January 2004 23:08, abeidson@sbcglobal.net wrote:
> > I am not only new to Python.. but essentially new to programming in
> > general.. (the last program I wrote was in Basic 15 years ago for High
> > school). My job is starting to require me to do some type of programming
to
> > interact with databases (DB4, DB2, SQL, and Oracle). From everything I
have
> > read Python seems the best to start with.. but with all the books out
there
> > I was just looking for some insite.
> >
> > Thanks
> > Andy
>
> Hi Andy,
>
> The main Python website (www.python.org) has many resources for beginning
> Python programmers (and beginner programmers in general). Check out this
> link:
>
> http://www.python.org/doc/Intros.html
>
> If you do chose to start with Python (a great idea;) then I would
recommend
> either O'Reilly's Learning Python or Core Python Programming. Both are
great
> beginner resources for learning Python.
>
>
> Good luck!
>
> -- 
> Gus Tabares
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor


From darnold02 at sprynet.com  Tue Jan 20 07:24:13 2004
From: darnold02 at sprynet.com (don arnold)
Date: Tue Jan 20 07:24:35 2004
Subject: [Tutor] Re: prepend variable name...
References: <6DF5B7CE-4B16-11D8-9AE6-003065555ABC@mac.com>
	<075401c3df4c$2c826f00$2e11ba3f@don2uvsu54fwiq>
Message-ID: <077e01c3df50$51838f60$2e11ba3f@don2uvsu54fwiq>


----- Original Message -----
From: "don arnold" <darnold02@sprynet.com>
To: "kevin parks" <kp8@mac.com>
Cc: <tutor@python.org>
Sent: Tuesday, January 20, 2004 5:54 AM
Subject: Re: [Tutor] Re: prepend variable name...


> ----- Original Message -----
> From: "kevin parks" <kp8@mac.com>
> To: "kevin parks" <kp8@mac.com>
> Cc: <tutor@python.org>
> Sent: Tuesday, January 20, 2004 1:01 AM
> Subject: [Tutor] Re: prepend variable name...
>
>
> > I should add that, i think the answer lies in making a dictionary (with
> > zip?), but what i am not sure of is how to then traverse a dictionary
> > in order...
> >
>
> Yes, a dictionary is your best option (though zip doesn't enter the
picture,
> here). In fact, Danny just answered this same question a couple of days
ago
> with his 'fruitbasket' example. Instead of using a 'regular' variable to
> hold your data, you use the variable name as a dictionary key and store
your
> data there:
>
> myvars = {}
> myvars['exI_2a'] = [11,5,7,2]
> myvars['exI_2b'] = [0,10,5]
> myvars['exI_2c'] = [7,6,9,1]
> myvars['exI_2d'] = [4,7,2,7,11]
>
> for key in myvars:
>     print key
>     print data
>     print

Sloppy cut and paste on my part. The above block should read:

for key in myvars:
    print key
    print myvars[key]
    print

>
> [--output--]
>
> exI_2d
> [4, 7, 2, 7, 11]
>
> exI_2c
> [7, 6, 9, 1]
>
> exI_2b
> [0, 10, 5]
>
> exI_2a
> [11, 5, 7, 2]
>
> You'll notice that the items aren't necessarily in key order. This is
> because a dictionary is an unordered collection. To get around this, you
can
> use the dicionary's keys() method to generate a list of its keys, then
sort
> this list before iterating over it.
>
> myvars = {}
> myvars['exI_2a'] = [11,5,7,2]
> myvars['exI_2b'] = [0,10,5]
> myvars['exI_2c'] = [7,6,9,1]
> myvars['exI_2d'] = [4,7,2,7,11]
>
> keylist = myvars.keys()
> keylist.sort()
> for key in keylist:
>     print key
>     print myvars[key]
>     print
>
> [--output--]
>
> exI_2a
> [11, 5, 7, 2]
>
> exI_2b
> [0, 10, 5]
>
> exI_2c
> [7, 6, 9, 1]
>
> exI_2d
> [4, 7, 2, 7, 11]
>
>
> > gosh... dictionaries... hmm... we didn't have those in C so i find that
> > i forget how versatile they are. Anyway, i haven't really answered my
> > own question yet... but i am i headed in the right direction?
> >
> > -kp--
>
> Most definitely.
>
> HTH,
> Don
>

Sorry about that,
Don


From Janssen at rz.uni-frankfurt.de  Tue Jan 20 08:22:44 2004
From: Janssen at rz.uni-frankfurt.de (Michael Janssen)
Date: Tue Jan 20 08:22:57 2004
Subject: [Tutor] getopt question
In-Reply-To: <400E468B.4080309@netscape.net>
References: <400E468B.4080309@netscape.net>
Message-ID: <Pine.A41.4.56.0401201415200.54696@hermes-22.rz.uni-frankfurt.de>

On Wed, 21 Jan 2004, Xuer wrote:

> an example from 'Python Programming for Beginners'
>
> trygetopt.py
> -----------------------------------------------------------------
> #!/usr/bin/python
>
> import sys,getopt
> try:
>         options, xarguments = getopt.getopt(sys.argv[1:],'ha')
> except getopt.error:
>         pass
>
> print options
> ------------------------------------------------------------------
>
> ./trygetopt.py -ha
> get result
> [('-h', ''), ('-a', '')]
>
> but ./trygetopt.py -h 123 -a 456
> get the result
> [('-h', '')]
>
> While I expect the result would be
> [('-h', '123'), ('-a', '456')]
>
> what's the matter?
> thanks in advance. :)

when you want to have a option with a parameter, then you have to
instruct getopt so. getopt.getopt(sys.argv[1:],'h:a:') is the syntax for
this (A colon behind any option that needs a parameter).  It might
be that you then *have* to specify a parameter on commandline.

Why not using optparse? It's newer and worth the change (ease of use,
automatic help output). Consult the Library Reference for this.


Michael


From guillermo.fernandez at epfl.ch  Tue Jan 20 08:50:06 2004
From: guillermo.fernandez at epfl.ch (Guillermo Fernandez Castellanos)
Date: Tue Jan 20 08:50:12 2004
Subject: [Tutor] Re: memory problem (II part)
In-Reply-To: <Pine.LNX.4.44.0401191349270.16499-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0401191349270.16499-100000@hkn.eecs.berkeley.edu>
Message-ID: <400D320E.1010803@epfl.ch>

Hi,

hcohen2 wrote:
 > Guille,
 > I am perplexed, what product are you using and how heavily are you 
pounding on it?
I'm using SQlite. I've a database with a table of about 150.000 (and 
another of 300.000) where the table has 18 columns, some with only a 
date, but another with a full log. The table will be simplified soon, 
but still there will be a lot of information query.

>I see that the pysqlite code is using weak references to keep track of all
>the cursors associated with a connection:
>
>    http://www.python.org/doc/lib/module-weakref.html
>
>so the cursors should get reclaimed eventually when the garbage collector
>kicks in.
>  
>
Maybe there's a way of forcing the garbage collector to do his job...
I tried to put on the postcmd function of the cmd package the collector 
gc.collect()  but does not seem to help much.

>Instead of closing the connections, what happens if you call each cursor's
>close() method after you do a fetch?  Doing a close() on the connection
>may be working because it calls close() on all open cursors.  Let's verify
>that its the cursors that are holding onto database results in memory.  
>
I also tried that, and close a cursor each time I open it (I mean... 
after the query ;-) with no results neither. What seems to free memory 
is to close the database.

Funny thing as well... memory is managed differently from windows to 
linux. That way, in linux once we make a big request, we can do further 
big requests the amount or RAM will never go beyond that point (i.e. 
around 250Mb above the normal use of the system). Use of RAM in Windows 
is different though, as it seems to be incremental. Each time I start a 
new request, the equivalent amount of RAM is used. That means that it 
starts taking 250, then 500, then... without attaining a maximum.

Thanks for your help,

Guille



From hcohen2 at comcast.net  Tue Jan 20 10:37:12 2004
From: hcohen2 at comcast.net (hcohen2)
Date: Tue Jan 20 10:39:10 2004
Subject: [Tutor] Beginners Help
In-Reply-To: <002301c3df0b$04b8cc80$900f4844@home>
References: <002301c3df0b$04b8cc80$900f4844@home>
Message-ID: <400D4B28.6000701@comcast.net>

abeidson@sbcglobal.net wrote:

> I am not only new to Python.. but essentially new to programming in 
> general.. (the last program I wrote was in Basic 15 years ago for High 
> school). My job is starting to require me to do some type of 
> programming to interact with databases (DB4, DB2, SQL, and Oracle). 
> From everything I have read Python seems the best to start with.. but 
> with all the books out there I was just looking for some insite.
>  
> Thanks
> Andy
>
>------------------------------------------------------------------------
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
>  
>
Andy,

I know this is a python forum, but what exactly do you mean by you now 
have the necessity of learning some programming?

If this means you have to construct some views of data, e.g. reports 
there are potentially simpler approaches.  It may be a misnomer, but so 
called end user reporting tools may be what you need.  These do require 
some degree of sophistication in knowing your data structures and what 
your individual elements of your results are comprised of and how they 
are really determined (e.g. calculated/defined).

Learning python for an overall view may do no harm, but from the data 
base products named you should be learning the SQL syntax employed by 
each in their respective 'procedural' SQL tools.  Regarding what you 
call SQL (do you mean SQL Server)  Microsoft or ASE (Adaptive SQL 
Enterprise) Sybase?  They at least share the same base SQL scripting 
language though they have now diverged where each has more sophisticated 
ways of constructing queries: Transact-SQL.  Oracle has PL/SQL used in 
stored procedures and user querying and SQL for interface applications 
and I think reporting.  Sorry no study nor experience with DB2.

Python does have an API to interface with databases, but from a response 
I got to my questioning about that interface it may not be optimal.  It 
just might be that you should start with command line quries to learn 
how much you need to learn.

If you are working with one of the Sybase servers, write to me directly 
and I will give you whatever help I can.  One other thing you should be 
aware of: both Sybase and Oracle will essentially give you a copy to use 
for learning, not licensed for production use.  And I have heard that MS 
SQLServer can be had on essentially the same terms.

Hope I have not confused the issue, but have given you a broader 
perspective.  Learning python will do you no harm.  I am using my time 
to finally come up to speed on this scripting language.

Herschel

PS Regarding the free software the International Sybase Users Group 
gives a NT copy of the most recent Sybase server (at least they have for 
the past two years).  There is an on-line Oracle developers forum that 
offers copies of the most recent versions of their server.




From hcohen2 at comcast.net  Tue Jan 20 11:35:16 2004
From: hcohen2 at comcast.net (hcohen2)
Date: Tue Jan 20 11:37:14 2004
Subject: [Tutor] Is something wrong with my round() function?
Message-ID: <400D58C4.70609@comcast.net>

The obvious answer is 'YES', but what's causing this strange behaviour?

 >>> ans = 48.936
 >>> round(ans, 1)
48.899999999999999
 >>> round(ans, 2)
48.939999999999998
 >>> round(ans, 3)
48.936
 >>> round(ans, 4)
48.936
 >>> round(ans, 2)
48.939999999999998
 >>> round(ans, 1)
48.899999999999999
 >

I have another example were I was using a class to compute the total 
room rates that were supposed to be rounded to the nearest cent and they 
looked like the above sample, however, using the round(<week rate>, 1) 
gave it properly to the nearest dime.

Using python ver 2.2.2 on Linux (Mandrake 9.1) on an IBM laptop.

TIA



From Christian.Wyglendowski at greenville.edu  Tue Jan 20 11:44:39 2004
From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski)
Date: Tue Jan 20 11:44:49 2004
Subject: [Tutor] tutorial for python com server
Message-ID: <CE1475C007B563499EDBF8CDA30AB45B0A38AA@empex.greenville.edu>

You should probably see about picking up a copy of Python Programming on Win32.  Also see this URI:
http://www.python.org/windows/win32com/QuickStartServerCom.html


Christian
http://www.dowski.com

-----Original Message-----
From: cybersamurai [mailto:cybersamurai@terra.com.br] 
Sent: Monday, January 19, 2004 1:56 PM
To: tutor@python.org
Subject: [Tutor] tutorial for python com server


A can?t find a tutorial for make a python com server.
Where can I find a simple nutshell tutorial for that?

From pythontutor at venix.com  Tue Jan 20 12:12:18 2004
From: pythontutor at venix.com (Lloyd Kvam)
Date: Tue Jan 20 12:12:45 2004
Subject: [Tutor] Is something wrong with my round() function?
In-Reply-To: <400D58C4.70609@comcast.net>
References: <400D58C4.70609@comcast.net>
Message-ID: <400D6172.7000205@venix.com>

This is not a Python issue.  Floating Point numbers are normally stored
in a base 2 format.  This means that only those fraactions that have
denominators that are powers of two can be stored exactly.  Python's
repr function shows a floating point number as exactly as it can (in
a decimal format).  the str function will do sensible rounding to show
what you expect.

 >>> x = .125
 >>> x
0.125
 >>> x = .3
 >>> x
0.29999999999999999
 >>> print x
0.3

.125 works exactly because it is 1/8 and 8 is a power of 2.
print uses the str function and displays what you would expect.
The underlying binary representation is not exactly equal to .3
because it can't hold it exactly.  It is the same problem we face
when trying to express 1/3 as a decimal.  We can't do it exactly.

Raymond Hettinger recently published a Python Cookbook recipe for
examining floating point arithmatic and tracking the accumulated
errors.
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/265894

hcohen2 wrote:

> The obvious answer is 'YES', but what's causing this strange behaviour?
> 
>  >>> ans = 48.936
>  >>> round(ans, 1)
> 48.899999999999999
>  >>> round(ans, 2)
> 48.939999999999998
>  >>> round(ans, 3)
> 48.936
>  >>> round(ans, 4)
> 48.936
>  >>> round(ans, 2)
> 48.939999999999998
>  >>> round(ans, 1)
> 48.899999999999999
>  >
> 
> I have another example were I was using a class to compute the total 
> room rates that were supposed to be rounded to the nearest cent and they 
> looked like the above sample, however, using the round(<week rate>, 1) 
> gave it properly to the nearest dime.
> 
> Using python ver 2.2.2 on Linux (Mandrake 9.1) on an IBM laptop.
> 
> TIA
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582


From hcohen2 at comcast.net  Tue Jan 20 13:09:24 2004
From: hcohen2 at comcast.net (hcohen2)
Date: Tue Jan 20 13:11:17 2004
Subject: [Tutor] Is something wrong with my round() function?
In-Reply-To: <400D6172.7000205@venix.com>
References: <400D58C4.70609@comcast.net> <400D6172.7000205@venix.com>
Message-ID: <400D6ED4.2000903@comcast.net>

Lloyd Kvam wrote:

> This is not a Python issue.  Floating Point numbers are normally stored
> in a base 2 format.  This means that only those fraactions that have
> denominators that are powers of two can be stored exactly.  Python's
> repr function shows a floating point number as exactly as it can (in
> a decimal format).  the str function will do sensible rounding to show
> what you expect.
>
> >>> x = .125
> >>> x
> 0.125
> >>> x = .3
> >>> x
> 0.29999999999999999
> >>> print x
> 0.3
>
> .125 works exactly because it is 1/8 and 8 is a power of 2.
> print uses the str function and displays what you would expect.
> The underlying binary representation is not exactly equal to .3
> because it can't hold it exactly.  It is the same problem we face
> when trying to express 1/3 as a decimal.  We can't do it exactly.
>
> Raymond Hettinger recently published a Python Cookbook recipe for
> examining floating point arithmatic and tracking the accumulated
> errors.
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/265894
>
> hcohen2 wrote:
>
>> The obvious answer is 'YES', but what's causing this strange behaviour?
>>
>>  >>> ans = 48.936
>>  >>> round(ans, 1)
>> 48.899999999999999
>>  >>> round(ans, 2)
>> 48.939999999999998
>>  >>> round(ans, 3)
>> 48.936
>>  >>> round(ans, 4)
>> 48.936
>>  >>> round(ans, 2)
>> 48.939999999999998
>>  >>> round(ans, 1)
>> 48.899999999999999
>>  >
>>
>> I have another example were I was using a class to compute the total 
>> room rates that were supposed to be rounded to the nearest cent and 
>> they looked like the above sample, however, using the round(<week 
>> rate>, 1) gave it properly to the nearest dime.
>>
>> Using python ver 2.2.2 on Linux (Mandrake 9.1) on an IBM laptop.
>>
>> TIA
>>
>>
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor@python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
>
Lloyd,

 >>> str(round(ans, 2))
'48.94'

Now that's nicely shown, thanks!

Herschel



From cspears2002 at yahoo.com  Tue Jan 20 13:15:10 2004
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Tue Jan 20 13:15:22 2004
Subject: [Tutor] scripting vs programming
Message-ID: <20040120181510.62307.qmail@web12406.mail.yahoo.com>

What is the difference between scripting and programming?

=====
"I'm the last person to pretend that I'm a radio.  I'd rather go out and be a color television set."
-David Bowie

"Who dares wins"
-British military motto

"Far more creativity, today, goes into the marketing of products than into the products themselves..."
-"Pattern Recognition" by William Gibson

From tpc at csua.berkeley.edu  Tue Jan 20 13:35:21 2004
From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu)
Date: Tue Jan 20 13:35:29 2004
Subject: [Tutor] scripting vs programming
In-Reply-To: <20040120181510.62307.qmail@web12406.mail.yahoo.com>
Message-ID: <20040120103423.O12995-100000@localhost.name>


hi Christopher, I believe there was a thread here several months back that
might help to answer your question:

http://mail.python.org/pipermail/tutor/2003-June/022876.html

I hope that helps you.

On Tue, 20 Jan 2004, Christopher Spears wrote:

> What is the difference between scripting and programming?
>
> =====
> "I'm the last person to pretend that I'm a radio.  I'd rather go out and be a color television set."
> -David Bowie
>
> "Who dares wins"
> -British military motto
>
> "Far more creativity, today, goes into the marketing of products than into the products themselves..."
> -"Pattern Recognition" by William Gibson
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>


From pythontutor at venix.com  Tue Jan 20 13:36:56 2004
From: pythontutor at venix.com (Lloyd Kvam)
Date: Tue Jan 20 13:37:00 2004
Subject: [Tutor] scripting vs programming
In-Reply-To: <20040120181510.62307.qmail@web12406.mail.yahoo.com>
References: <20040120181510.62307.qmail@web12406.mail.yahoo.com>
Message-ID: <400D7548.6010706@venix.com>

I'll bite.

Scripting is programming with a language that does not need to
be (manually) compiled and has close integration to the operating system
commands or to an application.  Many scripting languages are simplistic
and unsuitable for larger scale software projects.

Python is a programming language that fits into the scripting
niche, but is also suitable for a very wide range of applications.

Christopher Spears wrote:

> What is the difference between scripting and programming?
> 
> =====
> "I'm the last person to pretend that I'm a radio.  I'd rather go out and be a color television set."
> -David Bowie
> 
> "Who dares wins"
> -British military motto
> 
> "Far more creativity, today, goes into the marketing of products than into the products themselves..."
> -"Pattern Recognition" by William Gibson
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582


From tpc at csua.berkeley.edu  Tue Jan 20 13:37:14 2004
From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu)
Date: Tue Jan 20 13:37:33 2004
Subject: [Tutor] scripting vs programming
In-Reply-To: <20040120181510.62307.qmail@web12406.mail.yahoo.com>
Message-ID: <20040120103645.E13005-100000@localhost.name>


Hi Christopher, I am sorry.  The start of the thread is here:

http://mail.python.org/pipermail/tutor/2003-June/022862.html

I hope that helps you.

On Tue, 20 Jan 2004, Christopher Spears wrote:

> What is the difference between scripting and programming?
>
> =====
> "I'm the last person to pretend that I'm a radio.  I'd rather go out and be a color television set."
> -David Bowie
>
> "Who dares wins"
> -British military motto
>
> "Far more creativity, today, goes into the marketing of products than into the products themselves..."
> -"Pattern Recognition" by William Gibson
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>


From dyoo at hkn.eecs.berkeley.edu  Tue Jan 20 13:41:12 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue Jan 20 13:41:17 2004
Subject: [Tutor] Is something wrong with my round() function?
In-Reply-To: <400D58C4.70609@comcast.net>
Message-ID: <Pine.LNX.4.44.0401201037550.11168-100000@hkn.eecs.berkeley.edu>



On Tue, 20 Jan 2004, hcohen2 wrote:

> The obvious answer is 'YES', but what's causing this strange behaviour?
>
>  >>> ans = 48.936
>  >>> round(ans, 1)
> 48.899999999999999
>  >>> round(ans, 2)
> 48.939999999999998
>  >>> round(ans, 3)
> 48.936
>  >>> round(ans, 4)
> 48.936
>  >>> round(ans, 2)
> 48.939999999999998
>  >>> round(ans, 1)
> 48.899999999999999
>  >


Hello!


Lloyd mentioned that it's the representation of the numbers as "floating
point" that's causing what looks to be erroneous output.  The Python
Tutorial also talks about this issue, since it pops up every once in a
while:

    http://www.python.org/doc/tut/node15.html


Hope this helps!


From dyoo at hkn.eecs.berkeley.edu  Tue Jan 20 13:50:08 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue Jan 20 13:50:23 2004
Subject: [Tutor] ImportError: No module named klg.. (fwd)
Message-ID: <Pine.LNX.4.44.0401201050050.12854-100000@hkn.eecs.berkeley.edu>



---------- Forwarded message ----------
Date: Mon, 19 Jan 2004 08:47:31 -0600
From: Vishwavasu.Chobari@utstar.com
To: Danny Yoo <dyoo@hkn.eecs.berkeley.edu>
Subject: Re: [Tutor] ImportError: No module named klg..


Danny,
      I am back with another question -
      How do I use double arrays in jython?
I know to use single dimension arrays.

Could you bail me out for the second time?
:))

P.S: Thanks for the earlier reply, there was some problem with my
classpath.

--Vishwa.




Danny Yoo <dyoo@hkn.eecs.berkeley.edu> on 01/06/2004 12:36:58 AM

To:    Vishwavasu Chobari/C/UTStarcom@UTStarcom
cc:    tutor@python.org
Subject:    Re: [Tutor] ImportError: No module named klg..




On Mon, 5 Jan 2004 Vishwavasu.Chobari@utstar.com wrote:

>       I am Vishwa working with JCChart to create a PIE chart. I have the
> following two lines in my code to use JCChart.
>
> from com.klg.jclass.chart import *
> from com.klg.jclass.chart.JCChart import *
>
> Despite setting the python.path, python.home, sys.path et al to the jar
> file that contains these classes, I get the error -
>
>
> 01/05/2004 18:36:16 (E) PythonScript: exception: Traceback (innermost
> last):
>   File "schema\standard\Jobs\scheduledReports\generatePPPStatistics.py",
> line 23 , in ?
> ImportError: No module named klg


Hi Vishwa,


I am confused right now.  Are we talking about a Python module, or a Java
module?  JCChart, as far as I can tell, is a Java package,

http://java.quest.com/support/jclass/dv/docs/api/com/klg/jclass/chart/JCChart.html


so CPython won't work with it.  Instead, you can use Jython to access it.

    http://www.jython.org/

If you use Jython, then adding the JAR to your Java CLASSPATH should do
the trick.


If you have further questions about Jython, there's a mailing list
dedicated to Jython:

    http://lists.sourceforge.net/lists/listinfo/jython-users

Good luck to you.








From dmandini at inet.hr  Tue Jan 20 17:44:58 2004
From: dmandini at inet.hr (djuro)
Date: Tue Jan 20 17:45:03 2004
Subject: [Tutor] curses, key controls ?
Message-ID: <04012023445800.00873@Hal>



Hello!

I am beginner and I'm trying to write simple program in curses but this is 
what confuses me:
How to end this iteration by pressing a certain key, for instance ESC or "q"??

getchar() delays execution and waits for user input, nodelay() breaks when ANY
key is pressed. 
I need a way to specify a certain key for termination.

#######################################
import curses, time

stdscr = curses.initscr()
curses.noecho()
curses.cbreak()
stdscr.keypad(1)

# next f. displays time at given coords. 
# and refreshes after each second 

def dsply_time():       
        t = time.time()
        t = str(t)
        stdscr.addstr(2,2,t)
        stdscr.refresh()
        time.sleep(1)
        dsply_time()

dsply_time()


curses.nocbreak(); stdscr.keypad(0); curses.echo()
curses.endwin()
################################################

Thank you

From alan.gauld at blueyonder.co.uk  Tue Jan 20 18:35:52 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Tue Jan 20 18:35:37 2004
Subject: [Tutor] Re: memory problem (II part)
References: <Pine.LNX.4.44.0401191349270.16499-100000@hkn.eecs.berkeley.edu>
	<400D320E.1010803@epfl.ch>
Message-ID: <006c01c3dfae$245cc930$6401a8c0@xp>

> I'm using SQlite. I've a database with a table of about 150.000 

I may be wrong but isn't SQLlite the one that stores its tables 
in memory? Very good for small databases but if you have a lot 
of data a RAM hog. If my memory (no pun intended!) serves me right 
you may find that simply shifting the data into MySQL or Postgres 
will alleviate the problem - at the possible expense of some 
performance.

OTOH I've never used SQLlite and am going from something I 
think I read someplace...

Alan g.


From alan.gauld at blueyonder.co.uk  Tue Jan 20 18:42:18 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Tue Jan 20 18:42:05 2004
Subject: [Tutor] Help - Where and when to use OOP
References: <20040119171113.88499.qmail@web41806.mail.yahoo.com>
Message-ID: <009401c3dfaf$0a6a5f00$6401a8c0@xp>

> > I have a little exposure to OOP. I 'd like to know
> > for what kind of programs that I should use OOP

> processes'. In general, you should use OOP when you
> need more abstraction, reusability, and encapsulation.
> Large projects, whether immediately aparent or not,
> tend to need this. With small projects, you can go
> either way.
> 
> Daniel Ehrenberg

I agree with all Daniel says here. I'd also add that 
programs where you have to process large amounts of 
identical data in the same way are often easier written 
in a procedural way - a sequence of transforming functions 
- than trying to model the problem as objects.

Another slant is to look for problems where you manipulate 
a variety of different types of data in similar ways. That 
is you perform the same basic operations to many different 
types of thing. This is often a good indicator that the 
things can be modelled as objects and polymorphic methods 
used for the operations.

And anything that mimics the way a real-world situation 
works can usually be modelled in objects.

HTH,

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld

From python at keep-trying.com  Tue Jan 20 18:57:52 2004
From: python at keep-trying.com (richard)
Date: Tue Jan 20 18:58:25 2004
Subject: [Tutor] Formatting String for SQL Insert
Message-ID: <6.0.0.22.0.20040120234113.030f5c20@192.168.5.1>

Greetings,

Despite the help with my other string questions I am struggling
with this problem. Now that I can loop through my controls
(previous emails) I am able to convert the textCrtl data into a list.
This should be simple to pass through to my sql insert query. However
despite formatting, spliting, joining and even pickling? I have been
unable to do this and this is even before  trying to cope with nulls and 
special
characters.

I either get syntax errors, complaints that there are not enough
elements (when using %s) which I do not understand why, or errors
complaining I am trying to mix a string and tuple.

It must be possible to be able to loop it, format it to the correct
string and also allow for nulls and special characters. Infact
having read quite a few postings on google groups I know it
can be done but adapting instructions always fails. Whats
more annoying is that experimenting in the python shell I can
get the result I want.

Any help?? Should I being doing this at the point at which
I append the data from the textctrl into the list??

Regards

Richard

def saveButton(self, event):
         datavalues=[]
         for i in range(21):
             datavalues.append(eval('self.textCtrl%d.GetValue()' %i))
         c = mydb.cursor()
         #values = "'%s,'" %datavalues[0] + "'%s,'" %datavalues[1] + 
"'%s,'" %datavalues[2] + "'%s,'" %datavalues[3] + "'%s,'" %datavalues[4] + 
"'%s,'" %datavalues[5] + "'%s,'" %datavalues[6] + "'%s,'" %datavalues[7] + 
"'%s'," %datavalues[8] + "'%s,'" %datavalues[9] + "'%s,'" %datavalues[10] + 
"'%s,'" %datavalues[11] + "'%s,'" %datavalues[12] + "'%s,'" %datavalues[13] 
+ "'%s,'" %datavalues[14] + "'%s,'" %datavalues[15]+ ""'%s,'"" 
%datavalues[16]+ "'%s,'" %datavalues[17]+ "'%s,'" %datavalues[18]+ "'%s,'" 
%datavalues[19] + "'%s'" %datavalues[20])


values = '%s' '%s' '%s' '%s' '%s' '%s' '%s' '%s' '%s' '%s' '%s' '%s' '%s' 
'%s' '%s' '%s' '%s' '%s' '%s' '%s' '%s' % (datavalues[0], datavalues[1], 
datavalues[2], datavalues[3], datavalues[4], datavalues[5], datavalues[6], 
datavalues[7], datavalues[8], datavalues[9], datavalues[10], 
datavalues[11], datavalues[12], datavalues[13], datavalues[14], 
datavalues[15], datavalues[16], datavalues[17], datavalues[18], 
datavalues[19], datavalues[20])

#values = %s,datavalues

         sqlquery1 = "Insert into fmna values (" + values + ");"
         print sqlquery1
         c.execute(sqlquery1)
         mydb.commit()
         mydb.close() 


From orbitz at ezabel.com  Tue Jan 20 19:19:03 2004
From: orbitz at ezabel.com (orbitz@ezabel.com)
Date: Tue Jan 20 19:19:26 2004
Subject: [Tutor] Formatting String for SQL Insert
In-Reply-To: <6.0.0.22.0.20040120234113.030f5c20@192.168.5.1>
References: <6.0.0.22.0.20040120234113.030f5c20@192.168.5.1>
Message-ID: <20040120191903.3a5ae8bc.orbitz@ezabel.com>

If what you pasted is the actual output, then you have an indentation error.
But it looks messy, I'd just create values in the loop.  Your second values = example won't produce anything like your first one to.

orbitz

On Tue, 20 Jan 2004 23:57:52 +0000
richard <python@keep-trying.com> wrote:

> Greetings,
> 
> Despite the help with my other string questions I am struggling
> with this problem. Now that I can loop through my controls
> (previous emails) I am able to convert the textCrtl data into a list.
> This should be simple to pass through to my sql insert query. However
> despite formatting, spliting, joining and even pickling? I have been
> unable to do this and this is even before  trying to cope with nulls and 
> special
> characters.
> 
> I either get syntax errors, complaints that there are not enough
> elements (when using %s) which I do not understand why, or errors
> complaining I am trying to mix a string and tuple.
> 
> It must be possible to be able to loop it, format it to the correct
> string and also allow for nulls and special characters. Infact
> having read quite a few postings on google groups I know it
> can be done but adapting instructions always fails. Whats
> more annoying is that experimenting in the python shell I can
> get the result I want.
> 
> Any help?? Should I being doing this at the point at which
> I append the data from the textctrl into the list??
> 
> Regards
> 
> Richard
> 
> def saveButton(self, event):
>          datavalues=[]
>          for i in range(21):
>              datavalues.append(eval('self.textCtrl%d.GetValue()' %i))
>          c = mydb.cursor()
>          #values = "'%s,'" %datavalues[0] + "'%s,'" %datavalues[1] + 
> "'%s,'" %datavalues[2] + "'%s,'" %datavalues[3] + "'%s,'" %datavalues[4] + 
> "'%s,'" %datavalues[5] + "'%s,'" %datavalues[6] + "'%s,'" %datavalues[7] + 
> "'%s'," %datavalues[8] + "'%s,'" %datavalues[9] + "'%s,'" %datavalues[10] + 
> "'%s,'" %datavalues[11] + "'%s,'" %datavalues[12] + "'%s,'" %datavalues[13] 
> + "'%s,'" %datavalues[14] + "'%s,'" %datavalues[15]+ ""'%s,'"" 
> %datavalues[16]+ "'%s,'" %datavalues[17]+ "'%s,'" %datavalues[18]+ "'%s,'" 
> %datavalues[19] + "'%s'" %datavalues[20])
> 
> 
> values = '%s' '%s' '%s' '%s' '%s' '%s' '%s' '%s' '%s' '%s' '%s' '%s' '%s' 
> '%s' '%s' '%s' '%s' '%s' '%s' '%s' '%s' % (datavalues[0], datavalues[1], 
> datavalues[2], datavalues[3], datavalues[4], datavalues[5], datavalues[6], 
> datavalues[7], datavalues[8], datavalues[9], datavalues[10], 
> datavalues[11], datavalues[12], datavalues[13], datavalues[14], 
> datavalues[15], datavalues[16], datavalues[17], datavalues[18], 
> datavalues[19], datavalues[20])
> 
> #values = %s,datavalues
> 
>          sqlquery1 = "Insert into fmna values (" + values + ");"
>          print sqlquery1
>          c.execute(sqlquery1)
>          mydb.commit()
>          mydb.close() 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

From pythontutor at venix.com  Tue Jan 20 19:22:19 2004
From: pythontutor at venix.com (Lloyd Kvam)
Date: Tue Jan 20 19:22:34 2004
Subject: [Tutor] Formatting String for SQL Insert
In-Reply-To: <6.0.0.22.0.20040120234113.030f5c20@192.168.5.1>
References: <6.0.0.22.0.20040120234113.030f5c20@192.168.5.1>
Message-ID: <400DC63B.5030803@venix.com>

In the code snippets below,
	tablename is the name of the table (you knew that)
	db_keys is a list with the names of the database fields (attributes)
	db_vals is a list of the corresponding values to go into the database

stmt = 'INSERT INTO %s (%s) VALUES (%s);' % (
	tablename,
	','.join(db_keys),
	','.join(db_values)
	)
This is one simple approach to creating an insert statement.  It will
work so long as the db_values have already been turned into strings
and each string is properly quoted.

An alternative approach depends upon the parameter processing for
you sql module.  Since your example shows %s, I'll assume that's
correct.  the module will have an attribute paramstyle which tells
you how parameters are specified (see the DB API spec).  To use %s,
the paramstyle should be 'format'.

code is UNTESTED but should give correct idea

stmt = 'INSERT INTO %s (%s) VALUES (%s);' % (
	tablename,
	','.join(db_keys),
	','.join(['%s'] * len(db_keys)),
	)
cursor.execute(stmt, tuple(db_values))

This approach puts the burden of converting your values into the proper
format for your DB on the DB module.

HTH

richard wrote:
> Greetings,
> 
> Despite the help with my other string questions I am struggling
> with this problem. Now that I can loop through my controls
> (previous emails) I am able to convert the textCrtl data into a list.
> This should be simple to pass through to my sql insert query. However
> despite formatting, spliting, joining and even pickling? I have been
> unable to do this and this is even before  trying to cope with nulls and 
> special
> characters.
> 
> I either get syntax errors, complaints that there are not enough
> elements (when using %s) which I do not understand why, or errors
> complaining I am trying to mix a string and tuple.
> 
> It must be possible to be able to loop it, format it to the correct
> string and also allow for nulls and special characters. Infact
> having read quite a few postings on google groups I know it
> can be done but adapting instructions always fails. Whats
> more annoying is that experimenting in the python shell I can
> get the result I want.
> 
> Any help?? Should I being doing this at the point at which
> I append the data from the textctrl into the list??
> 
> Regards
> 
> Richard
> 
> def saveButton(self, event):
>         datavalues=[]
>         for i in range(21):
>             datavalues.append(eval('self.textCtrl%d.GetValue()' %i))
>         c = mydb.cursor()
>         #values = "'%s,'" %datavalues[0] + "'%s,'" %datavalues[1] + 
> "'%s,'" %datavalues[2] + "'%s,'" %datavalues[3] + "'%s,'" %datavalues[4] 
> + "'%s,'" %datavalues[5] + "'%s,'" %datavalues[6] + "'%s,'" 
> %datavalues[7] + "'%s'," %datavalues[8] + "'%s,'" %datavalues[9] + 
> "'%s,'" %datavalues[10] + "'%s,'" %datavalues[11] + "'%s,'" 
> %datavalues[12] + "'%s,'" %datavalues[13] + "'%s,'" %datavalues[14] + 
> "'%s,'" %datavalues[15]+ ""'%s,'"" %datavalues[16]+ "'%s,'" 
> %datavalues[17]+ "'%s,'" %datavalues[18]+ "'%s,'" %datavalues[19] + 
> "'%s'" %datavalues[20])
> 
> 
> values = '%s' '%s' '%s' '%s' '%s' '%s' '%s' '%s' '%s' '%s' '%s' '%s' 
> '%s' '%s' '%s' '%s' '%s' '%s' '%s' '%s' '%s' % (datavalues[0], 
> datavalues[1], datavalues[2], datavalues[3], datavalues[4], 
> datavalues[5], datavalues[6], datavalues[7], datavalues[8], 
> datavalues[9], datavalues[10], datavalues[11], datavalues[12], 
> datavalues[13], datavalues[14], datavalues[15], datavalues[16], 
> datavalues[17], datavalues[18], datavalues[19], datavalues[20])
> 
> #values = %s,datavalues
> 
>         sqlquery1 = "Insert into fmna values (" + values + ");"
>         print sqlquery1
>         c.execute(sqlquery1)
>         mydb.commit()
>         mydb.close()
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582


From littledanehren at yahoo.com  Tue Jan 20 22:16:47 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Tue Jan 20 22:16:51 2004
Subject: [Tutor] Help - Where and when to use OOP
In-Reply-To: <009401c3dfaf$0a6a5f00$6401a8c0@xp>
Message-ID: <20040121031647.5540.qmail@web41809.mail.yahoo.com>

> I agree with all Daniel says here. I'd also add that
> programs where you have to process large amounts of 
> identical data in the same way are often easier
> written 
> in a procedural way - a sequence of transforming
> functions 
> - than trying to model the problem as objects.

You would have to go through the data in the exact
same way, because if there were small varations or
multiple things are extracted lazily from the same
data (eg. sometimes only some of it is used), it would
make more sense to use an object-oriented model.

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes
http://hotjobs.sweepstakes.yahoo.com/signingbonus

From alan.gauld at blueyonder.co.uk  Wed Jan 21 03:27:51 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Wed Jan 21 03:27:33 2004
Subject: [Tutor] scripting vs programming
References: <20040120181510.62307.qmail@web12406.mail.yahoo.com>
Message-ID: <00ab01c3dff8$76086150$6401a8c0@xp>


> What is the difference between scripting and programming?

None whatsoever, except....

1) Scripting uses a scripting language, which usually meands 
a non pre-compiled language. Examples being Python, Perl, 
Javascript, Visual Basic/VBSCript, Unix shell.

2) Scripting is usually concerned with either tweaking the 
behaviour of an existing program - writing macros for a 
text editor like vim, say. OR building an application by 
integrating several other applications. In this case 
scripting is thought of rather as if you wewre writing 
the script for a play where the actors are the applications
and the script controls the sequencing and positioning 
and dialog between the actors.

But all scripting is also programming. Scripting is a 
type of programming.

HTH,

Alan G.


From alan.gauld at blueyonder.co.uk  Wed Jan 21 03:32:34 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Wed Jan 21 03:32:14 2004
Subject: [Tutor] curses, key controls ?
References: <04012023445800.00873@Hal>
Message-ID: <00bc01c3dff9$1ea27580$6401a8c0@xp>

> getchar() delays execution and waits for user input, 

Use getch() instead of getchar()

> I need a way to specify a certain key for termination.

Test the return value against the key you are looking for.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld

From pm5 at matilda.fiorile.org  Wed Jan 21 05:32:15 2004
From: pm5 at matilda.fiorile.org (pm5@matilda.fiorile.org)
Date: Wed Jan 21 05:36:13 2004
Subject: [Tutor] Help: get/set attributes via string names
Message-ID: <20040121103215.GF29510@matilda.fiorile.org>

Hi everyone:

Sorry if the is a FAQ but I've searched and googled and still don't get it.

As far as I can tell, there are various way to [1]customize an attribute
for an object.  Consequetly an attribute may be well-defined even if the
name is not in ob.__dict__.  So given a string name, how do I access the
attribute correctly, if I don't know the way it is defined?

 1. http://python.org/doc/2.3.3/ref/attribute-access.html


From kalle at lysator.liu.se  Wed Jan 21 05:49:48 2004
From: kalle at lysator.liu.se (Kalle Svensson)
Date: Wed Jan 21 05:50:04 2004
Subject: [Tutor] Help: get/set attributes via string names
In-Reply-To: <20040121103215.GF29510@matilda.fiorile.org>
References: <20040121103215.GF29510@matilda.fiorile.org>
Message-ID: <20040121104948.GI9193@i92.ryd.student.liu.se>

[pm5@matilda.fiorile.org]
> As far as I can tell, there are various way to [1]customize an
> attribute for an object.  Consequetly an attribute may be
> well-defined even if the name is not in ob.__dict__.  So given a
> string name, how do I access the attribute correctly, if I don't
> know the way it is defined?

Use the built-in functions getattr and setattr.

Peace,
  Kalle
-- 
Kalle Svensson, http://www.juckapan.org/~kalle/
Student, root and saint in the Church of Emacs.

From pm5 at matilda.fiorile.org  Wed Jan 21 05:51:32 2004
From: pm5 at matilda.fiorile.org (pm5@matilda.fiorile.org)
Date: Wed Jan 21 05:55:28 2004
Subject: [Tutor] Help: get/set attributes via string names
In-Reply-To: <20040121104948.GI9193@i92.ryd.student.liu.se>
References: <20040121103215.GF29510@matilda.fiorile.org>
	<20040121104948.GI9193@i92.ryd.student.liu.se>
Message-ID: <20040121105132.GA30046@matilda.fiorile.org>

On Wed, Jan 21, 2004 at 11:49:48AM +0100, Kalle Svensson wrote:
> [pm5@matilda.fiorile.org]
> > As far as I can tell, there are various way to [1]customize an
> > attribute for an object.  Consequetly an attribute may be
> > well-defined even if the name is not in ob.__dict__.  So given a
> > string name, how do I access the attribute correctly, if I don't
> > know the way it is defined?
> 
> Use the built-in functions getattr and setattr.

Thanks.  I should have try this first....

> 
> Peace,
>   Kalle
> -- 
> Kalle Svensson, http://www.juckapan.org/~kalle/
> Student, root and saint in the Church of Emacs.
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

From pythontutor at venix.com  Wed Jan 21 09:50:52 2004
From: pythontutor at venix.com (Lloyd Kvam)
Date: Wed Jan 21 09:51:03 2004
Subject: [Tutor] Formatting String for SQL Insert
In-Reply-To: <400DD460.4010708@comcast.net>
References: <6.0.0.22.0.20040120234113.030f5c20@192.168.5.1>
	<400DC63B.5030803@venix.com> <400DCB58.2010704@comcast.net>
	<400DCF39.40003@venix.com> <400DD460.4010708@comcast.net>
Message-ID: <400E91CC.8010103@venix.com>

hcohen2 wrote:
(snipped)
> Lloyd,
>(snipped) 
> I do have a question, why other than say a web application would one 
> resort to using python and/or perl to process database data when one 
> could call stored procedures?
> 
> Herschel
> 

Well, you call those stored procedures from some application (maybe
Access?).  It's a matter of embedding those calls in the application
of your choice.  Some DB's (such as MySQL) do not have stored procedures.

You face the need to load data into the DB and the need to do something
with the data that you retrieve from the DB.  Python is an ideal language
for this kind of processing.  It can organize various sources of input
data into INDSERT and UPDATE commands.  It can also take the stream
of data returned by SELECT, transform it, and pass it on to
other processes.

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582


From hameedkhaan at yahoo.com  Wed Jan 21 11:00:19 2004
From: hameedkhaan at yahoo.com (Hameed Khan)
Date: Wed Jan 21 11:00:27 2004
Subject: [Tutor] difference between signed integers and unsigned integers
Message-ID: <20040121160019.67908.qmail@web61109.mail.yahoo.com>

Hi,
  i know my question is not directly related to
python. but i just have started the programming in
python. so i am not a profesional programmer or an
expert. and i am only subscribed to the python's
mailing lists. thats why i am asking this question on
this list. i want to know what are signed and unsigned
integers and what is the difference between them.

Thanks,
Hameed Khan

=====
_____________________
 Hameed Ullah Khan

*Try not to become a man of success but rather to become a man of value.*
Albert Einstein

__________________________________
Do you Yahoo!?
Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes
http://hotjobs.sweepstakes.yahoo.com/signingbonus

From amonroe at columbus.rr.com  Wed Jan 21 12:18:39 2004
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Wed Jan 21 12:14:34 2004
Subject: [Tutor] difference between signed integers and unsigned integers
In-Reply-To: <20040121160019.67908.qmail@web61109.mail.yahoo.com>
References: <20040121160019.67908.qmail@web61109.mail.yahoo.com>
Message-ID: <22-1880317213.20040121121839@columbus.rr.com>

> Hi,
>   i know my question is not directly related to
> python. but i just have started the programming in
> python. so i am not a profesional programmer or an
> expert. and i am only subscribed to the python's
> mailing lists. thats why i am asking this question on
> this list. i want to know what are signed and unsigned
> integers and what is the difference between them.

The only difference is in your intentions:

(positive)
1
2 6 3 1
8 4 2 6 8 4 2 1

1 0 0 0 1 0 0 0  = 136

(negative)
1
2 6 3 1
8 4 2 6 8 4 2 1

1 0 0 0 1 0 0 0  = -120

Same bits, different interpretations.

The only thing to consider is that they "roll over" (like an odometer)
so unsigned byte 255+1 = 0, and signed byte 127+1 = -128 (someone is
bound to correct me if I'm off by one here)

Alan


From tpc at csua.berkeley.edu  Wed Jan 21 11:43:21 2004
From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu)
Date: Wed Jan 21 12:17:30 2004
Subject: [Tutor] difference between signed integers and unsigned integers
In-Reply-To: <20040121160019.67908.qmail@web61109.mail.yahoo.com>
Message-ID: <20040121083450.Q20242-100000@localhost.name>


hi Hameed,

Signed integers have one bit allocated to indicate whether the value is
positive or negative.  Unsigned integers do not.  The difference between
them is in certain languages with data types of a specific size, an
unsigned data type can hold more combinations than a signed value.  If
you think of a byte as eight switches, each with the on or off showing,
then a signed byte will have only 7 boxes to store values, as opposed to
the unsigned byte which will have 8 boxes.

I hope that helps you.

On Wed, 21 Jan 2004, Hameed Khan wrote:

> Hi,
>   i know my question is not directly related to
> python. but i just have started the programming in
> python. so i am not a profesional programmer or an
> expert. and i am only subscribed to the python's
> mailing lists. thats why i am asking this question on
> this list. i want to know what are signed and unsigned
> integers and what is the difference between them.
>
> Thanks,
> Hameed Khan
>
> =====
> _____________________
>  Hameed Ullah Khan
>
> *Try not to become a man of success but rather to become a man of value.*
> Albert Einstein
>
> __________________________________
> Do you Yahoo!?
> Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes
> http://hotjobs.sweepstakes.yahoo.com/signingbonus
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>


From arkamir at softhome.net  Wed Jan 21 13:00:05 2004
From: arkamir at softhome.net (arkamir@softhome.net)
Date: Wed Jan 21 13:00:37 2004
Subject: [Tutor] Cgi Fieldstorage cant get quotes
Message-ID: <courier.400EBE25.0000350D@softhome.net>

Does anyone know how to get qoutes from the cgi.FieldStorage. Whenever a 
user inputs data into a html form which contains quotes (", ') I get an 
error message. 

Thanks,
  Conrad

From rha207 at webtv.net  Wed Jan 21 13:43:56 2004
From: rha207 at webtv.net (Ron A)
Date: Wed Jan 21 13:44:02 2004
Subject: [Tutor] shelve error
Message-ID: <21427-400EC86C-198@storefull-3191.bay.webtv.net>

I have Python 2.2 and when I try this program I get a popup with this
message. Can you see what I'm doing wrong? I just want to take some info
I have in a file and (shelve it?). 
PYTHONW caused an invalid page fault in 
module MSVCRT.DLL at 0167:78012473. 
Registers: 
EAX=00000002 CS=0167 EIP=78012473 EFLGS=00010246 
EBX=00750880 SS=016f ESP=0062cdc4 EBP=0062cdcc 
ECX=ffff01f0 DS=016f ESI=00aef68e FS=0f77 
EDX=00000000 ES=016f EDI=00aef70e GS=0000 
Bytes at CS:EIP: 
8a 06 88 07 8a 46 01 c1 e9 02 88 47 01 83 c6 02 
Stack dump: 
0000ff8e 1e03b1d0 0062ce00 00f1812c 00aef70e 00aef68e ffff01f2 00ada1c0
00aef68e 00add470 00aef70e 00adf700 00000008 00000080 1e030200 0062ce48 
This program ass performed an illegal operation and will be shut down. 
### Here's the program ######### 
import cPickle, shelve 
hold = [] 
data = open('inout.txt', 'r') 
while 1: 
    temp = data.readline() 
    if temp == '': 
        break 
    temp = temp[:-1] 
    temp = temp.split('\t') 
    hold.append(temp) 
data.close() 
data = shelve.open('inventory') 
for num in hold: 
    a = num[0] 
    b = num[1] 
    c = num[2] 
    d = num[3] 
    e = num[4] 
    f = num[5] 
    g = num[6] 
    h = num[7] 
    i = num[8] 
    j = num[9] 
    k = num[10] 
    l = num[11] 
    m = num[12] 
    n = num[13] 
    data[b] = [a, c, d, e, f, g, h, i, j, k, l, m, n] 
    data.sync() 
data.close


From alan.gauld at blueyonder.co.uk  Wed Jan 21 14:13:16 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Wed Jan 21 14:13:03 2004
Subject: [Tutor] Formatting String for SQL Insert
References: <6.0.0.22.0.20040120234113.030f5c20@192.168.5.1><400DC63B.5030803@venix.com>
	<400DCB58.2010704@comcast.net><400DCF39.40003@venix.com>
	<400DD460.4010708@comcast.net> <400E91CC.8010103@venix.com>
Message-ID: <002501c3e052$9fe3ea80$6401a8c0@xp>

> > I do have a question, why other than say a web application would
one
> > resort to using python and/or perl to process database data when
one
> > could call stored procedures?
>
> of your choice.  Some DB's (such as MySQL) do not have stored
procedures.

Also if your server is maxed out of CPU stored procedures will be a
big resource hog. If the procedure is doing a lot of processing on a
relatively small amount of data (so the network doesn't die!) then
it is more efficient to move the processing out of the server to
the PC client.

Client/Server computing design is full of these kinds of compromise
choices. Working out which functions to build on the sever vv the
client.
IN an ideal world business logic which should be applied to all
applications should go on the server. Beyond that things which act
on a lot of data(and thus kill the network) should also be done on
the server. Application logic which heavily processes a small
amount of data should go on the client. Anything which straddles
boundaries, or where hardware/network limitations are non ideal
requires some designer intelligence.

Alan g


From alan.gauld at blueyonder.co.uk  Wed Jan 21 14:19:51 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Wed Jan 21 14:19:38 2004
Subject: [Tutor] difference between signed integers and unsigned integers
References: <20040121160019.67908.qmail@web61109.mail.yahoo.com>
Message-ID: <002a01c3e053$8b524d40$6401a8c0@xp>

> this list. i want to know what are signed and unsigned
> integers and what is the difference between them.

A signed integer is one with either a plus or minus sign 
in front. That is it can be either positive or negative.
An unsigned integer is assumed to be positive.

This is important in computing because the numbers are 
stored (usually) as a fixed number of binary digits. For 
a signed integer one bit is used to indicate the sign 
- 1 for negative, zero for positive. Thus a 16 bit signed 
integer only has 15 bits for data whereas a 16 bit unsigned 
integer has all 16 bits available. This means unsigned 
integers can have a value twice as high as signed integers
(but only positive values). On 16 bit computers this was 
significant, since it translates to the difference between
a maximum value of ~32,000 or ~65,000. On 32 bit computers
its far less signifocant since we get 2 billion or 4 billion.
And on 64 bit computers it becomes of academic interest.

IN Python we have large integers which effectively are 
unlimited in size, so we don't really care much! :-)

Alan G.


From python at keep-trying.com  Wed Jan 21 14:26:43 2004
From: python at keep-trying.com (richard)
Date: Wed Jan 21 14:27:36 2004
Subject: [Tutor] Formatting String for SQL Insert
In-Reply-To: <400DC63B.5030803@venix.com>
References: <6.0.0.22.0.20040120234113.030f5c20@192.168.5.1>
	<400DC63B.5030803@venix.com>
Message-ID: <6.0.0.22.0.20040121190931.01c0f5d0@192.168.5.1>

Greetings,

Ok, working on the second example which you gave, (seems
a good idea to let the module do some of the work if it means
less coding and ensuring that the format is correct.)

(connection module is PyPgSQL format string %s)

However when I have tried using the code, virtually as is
apart from the comma at then end of the 4th line. The
script will not compile complaining of a syntax error in
the c.execute line.

If I remove the reference to the table fields (which in this
case I do not need) I then get the error of not enough
attributes. The new code is below. I have added some
comments of what I think the code is doing. It may be
I am misunderstanding something.

-----> Start
def saveButton(self, event):
datavalues=[]  #set up empty list
db_keys = [] #set up empty list
db_keys = 
('code','name','shortname','adds1','adds2','adds3','town','county','pcode','country','shortloc','tel1','tel2','spare1','spare2','mob1','mob2','fax1','type','contact','comments') 
# field names
tablename = 'fmna' # set name of table

for i in range(21): # loop to get datavalues from the the text controls on form
         datavalues.append(eval('self.textCtrl%d.GetValue()' %i))
  c = mydb.cursor() # setup up database query
  sqlquery1 = 'Insert into %s (%s) values (%s);' % (  #string
                     tablename,  # 1st %s
                     ','.join(db_keys), #2nd %s
                     ','.join(join(['%s'] * len(db_keys)) # unsure of this
                     )
  c.execute(sqlquery1, % tuple(datavalues)) # assume this inserts each 
datavalue as correctly
formated for SQL string??

<---- end (spacing is mangled)

More help is once again appreciated.

Regards

Richard



>An alternative approach depends upon the parameter processing for
>you sql module.  Since your example shows %s, I'll assume that's
>correct.  the module will have an attribute paramstyle which tells
>you how parameters are specified (see the DB API spec).  To use %s,
>the paramstyle should be 'format'.
>
>code is UNTESTED but should give correct idea
>
>stmt = 'INSERT INTO %s (%s) VALUES (%s);' % (
>         tablename,
>         ','.join(db_keys),
>         ','.join(['%s'] * len(db_keys)),
>         )
>cursor.execute(stmt, tuple(db_values))
>
>This approach puts the burden of converting your values into the proper
>format for your DB on the DB module.
>
>HTH


From pythontutor at venix.com  Wed Jan 21 14:49:10 2004
From: pythontutor at venix.com (Lloyd Kvam)
Date: Wed Jan 21 14:49:22 2004
Subject: [Tutor] Formatting String for SQL Insert
In-Reply-To: <6.0.0.22.0.20040121190931.01c0f5d0@192.168.5.1>
References: <6.0.0.22.0.20040120234113.030f5c20@192.168.5.1>	<400DC63B.5030803@venix.com>
	<6.0.0.22.0.20040121190931.01c0f5d0@192.168.5.1>
Message-ID: <400ED7B6.8030504@venix.com>

 >  c.execute(sqlquery1, % tuple(datavalues)) # assume this inserts each
                        ^^^
omit the %

You are not doing string interpolation here.  The %s in the sqlquery is
a placeholder for the sql module and not an interpolation marker for
python.

richard wrote:

> Greetings,
> 
> Ok, working on the second example which you gave, (seems
> a good idea to let the module do some of the work if it means
> less coding and ensuring that the format is correct.)
> 
> (connection module is PyPgSQL format string %s)
> 
> However when I have tried using the code, virtually as is
> apart from the comma at then end of the 4th line. The
> script will not compile complaining of a syntax error in
> the c.execute line.
> 
> If I remove the reference to the table fields (which in this
> case I do not need) I then get the error of not enough
> attributes. The new code is below. I have added some
> comments of what I think the code is doing. It may be
> I am misunderstanding something.
> 
> -----> Start
> def saveButton(self, event):
> datavalues=[]  #set up empty list
> db_keys = [] #set up empty list
> db_keys = 
> ('code','name','shortname','adds1','adds2','adds3','town','county','pcode','country','shortloc','tel1','tel2','spare1','spare2','mob1','mob2','fax1','type','contact','comments') 
> # field names
> tablename = 'fmna' # set name of table
> 
> for i in range(21): # loop to get datavalues from the the text controls 
> on form
>         datavalues.append(eval('self.textCtrl%d.GetValue()' %i))
>  c = mydb.cursor() # setup up database query
>  sqlquery1 = 'Insert into %s (%s) values (%s);' % (  #string
>                     tablename,  # 1st %s
>                     ','.join(db_keys), #2nd %s
>                     ','.join(join(['%s'] * len(db_keys)) # unsure of this
>                     )
>  c.execute(sqlquery1, % tuple(datavalues)) # assume this inserts each 
> datavalue as correctly
> formated for SQL string??
> 
> <---- end (spacing is mangled)
> 
> More help is once again appreciated.
> 
> Regards
> 
> Richard
> 
> 
> 
>> An alternative approach depends upon the parameter processing for
>> you sql module.  Since your example shows %s, I'll assume that's
>> correct.  the module will have an attribute paramstyle which tells
>> you how parameters are specified (see the DB API spec).  To use %s,
>> the paramstyle should be 'format'.
>>
>> code is UNTESTED but should give correct idea
>>
>> stmt = 'INSERT INTO %s (%s) VALUES (%s);' % (
>>         tablename,
>>         ','.join(db_keys),
>>         ','.join(['%s'] * len(db_keys)),
>>         )
>> cursor.execute(stmt, tuple(db_values))
>>
>> This approach puts the burden of converting your values into the proper
>> format for your DB on the DB module.
>>
>> HTH
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582


From hcohen2 at comcast.net  Wed Jan 21 15:11:48 2004
From: hcohen2 at comcast.net (hcohen2)
Date: Wed Jan 21 15:13:46 2004
Subject: [Tutor] Formatting String for SQL Insert
In-Reply-To: <002501c3e052$9fe3ea80$6401a8c0@xp>
References: <6.0.0.22.0.20040120234113.030f5c20@192.168.5.1><400DC63B.5030803@venix.com>
	<400DCB58.2010704@comcast.net><400DCF39.40003@venix.com>
	<400DD460.4010708@comcast.net> <400E91CC.8010103@venix.com>
	<002501c3e052$9fe3ea80$6401a8c0@xp>
Message-ID: <400EDD04.2040102@comcast.net>

Alan Gauld wrote:

>>>I do have a question, why other than say a web application would
>>>      
>>>
>one
>  
>
>>>resort to using python and/or perl to process database data when
>>>      
>>>
>one
>  
>
>>>could call stored procedures?
>>>      
>>>
>>of your choice.  Some DB's (such as MySQL) do not have stored
>>    
>>
>procedures.
>
>Also if your server is maxed out of CPU stored procedures will be a
>big resource hog. If the procedure is doing a lot of processing on a
>relatively small amount of data (so the network doesn't die!) then
>it is more efficient to move the processing out of the server to
>the PC client.
>
>Client/Server computing design is full of these kinds of compromise
>choices. Working out which functions to build on the sever vv the
>client.
>IN an ideal world business logic which should be applied to all
>applications should go on the server. Beyond that things which act
>on a lot of data(and thus kill the network) should also be done on
>the server. Application logic which heavily processes a small
>amount of data should go on the client. Anything which straddles
>boundaries, or where hardware/network limitations are non ideal
>requires some designer intelligence.
>
>Alan g
>
>
>  
>
Everyone:

In some ways this was one of my dumber questions (however, I am sure 
there will be some disagreement about that!).  I neglected to mention my 
primary reason for studying python, i.e. validation of data files that 
are to be input into a database.

I really do not like perl.  Moreover, perl is used to process and 
validate data from clients.  Furthermore,  many of those clients insist 
on retaining there symbols that are sometimes difficult to interpret 
even by the human eye (assuming there are brain cells behind the 
former).  It is then necessary to map to the proper column and data 
types, which is not a trivial effort.  Indeed when there are a fair 
number of clients with a new stream of files and perhaps new people 
within those organizations you find serious problems when new, 
unexpected data representations arrive.  Translation: 'batch loading of 
data files crashes'.

Python is so much easier to read, hence, the maintenance load is easier 
for those having to take care of such problems.


From pythontutor at venix.com  Wed Jan 21 15:41:31 2004
From: pythontutor at venix.com (Lloyd Kvam)
Date: Wed Jan 21 15:42:01 2004
Subject: [Tutor] Formatting String for SQL Insert
In-Reply-To: <6.0.0.22.0.20040121203033.01c0ef90@192.168.5.1>
References: <6.0.0.22.0.20040120234113.030f5c20@192.168.5.1>
	<400DC63B.5030803@venix.com>
	<6.0.0.22.0.20040121190931.01c0f5d0@192.168.5.1>
	<400ED7B6.8030504@venix.com>
	<6.0.0.22.0.20040121203033.01c0ef90@192.168.5.1>
Message-ID: <400EE3FB.7000306@venix.com>

Then it's probably an indent issue or a missing
	)
on the previous line.  Python points to the unexpected character,
but may be using the context from an earlier line.

richard wrote:

> Hi,
> 
> Removing the % still gives the following,
> 
>   File "frmfmna.py", line 243
>     c.execute(sqlquery1, tuple(datavalues))
>     ^
> SyntaxError: invalid syntax
> 
> 
> Regards
> 
> 
> At 19:49 21/01/2004, you wrote:
> 
>> >  c.execute(sqlquery1, % tuple(datavalues)) # assume this inserts each
>>                        ^^^
>> omit the %
>>
>> You are not doing string interpolation here.  The %s in the sqlquery is
>> a placeholder for the sql module and not an interpolation marker for
>> python.
>>
>> richard wrote:
>>
>>> Greetings,
>>> Ok, working on the second example which you gave, (seems
>>> a good idea to let the module do some of the work if it means
>>> less coding and ensuring that the format is correct.)
>>> (connection module is PyPgSQL format string %s)
>>> However when I have tried using the code, virtually as is
>>> apart from the comma at then end of the 4th line. The
>>> script will not compile complaining of a syntax error in
>>> the c.execute line.
>>> If I remove the reference to the table fields (which in this
>>> case I do not need) I then get the error of not enough
>>> attributes. The new code is below. I have added some
>>> comments of what I think the code is doing. It may be
>>> I am misunderstanding something.
>>> -----> Start
>>> def saveButton(self, event):
>>> datavalues=[]  #set up empty list
>>> db_keys = [] #set up empty list
>>> db_keys = 
>>> ('code','name','shortname','adds1','adds2','adds3','town','county','pcode','country','shortloc','tel1','tel2','spare1','spare2','mob1','mob2','fax1','type','contact','comments') 
>>> # field names
>>> tablename = 'fmna' # set name of table
>>> for i in range(21): # loop to get datavalues from the the text 
>>> controls on form
>>>         datavalues.append(eval('self.textCtrl%d.GetValue()' %i))
>>>  c = mydb.cursor() # setup up database query
>>>  sqlquery1 = 'Insert into %s (%s) values (%s);' % (  #string
>>>                     tablename,  # 1st %s
>>>                     ','.join(db_keys), #2nd %s
>>>                     ','.join(join(['%s'] * len(db_keys)) # unsure of 
>>> this
>>>                     )
>>>  c.execute(sqlquery1, % tuple(datavalues)) # assume this inserts each 
>>> datavalue as correctly
>>> formated for SQL string??
>>> <---- end (spacing is mangled)
>>> More help is once again appreciated.
>>> Regards
>>> Richard
>>>
>>>
>>>> An alternative approach depends upon the parameter processing for
>>>> you sql module.  Since your example shows %s, I'll assume that's
>>>> correct.  the module will have an attribute paramstyle which tells
>>>> you how parameters are specified (see the DB API spec).  To use %s,
>>>> the paramstyle should be 'format'.
>>>>
>>>> code is UNTESTED but should give correct idea
>>>>
>>>> stmt = 'INSERT INTO %s (%s) VALUES (%s);' % (
>>>>         tablename,
>>>>         ','.join(db_keys),
>>>>         ','.join(['%s'] * len(db_keys)),
>>>>         )
>>>> cursor.execute(stmt, tuple(db_values))
>>>>
>>>> This approach puts the burden of converting your values into the proper
>>>> format for your DB on the DB module.
>>>>
>>>> HTH
>>>
>>>
>>> _______________________________________________
>>> Tutor maillist  -  Tutor@python.org
>>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>> -- 
>> Lloyd Kvam
>> Venix Corp.
>> 1 Court Street, Suite 378
>> Lebanon, NH 03766-1358
>>
>> voice:  603-653-8139
>> fax:    801-459-9582
>>
> 
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582


From python at cairnlin.co.uk  Wed Jan 21 16:05:48 2004
From: python at cairnlin.co.uk (Iain)
Date: Wed Jan 21 16:06:28 2004
Subject: [Tutor] Can't get Python connected to databases
Message-ID: <200401212105.48879.python@cairnlin.co.uk>


I have been trying to get a connection between Python and a back-end database: 
something that I expected to be a trivial exercise.  Unfortunately, I seem

to be getting nowhere and could really do with some help.

My environment : Python 2.3 (#2, Aug 31 2003, 17:27:29)
[GCC 3.3.1 (Mandrake Linux 9.2 3.3.1-1mdk)] on linux2

RPMs installed :
-bash-2.05b$ rpm -qa|grep -iE 'python|mysql|postgres'
python-base-2.3-3mdk
libmysql12-4.0.15-1mdk
MySQL-python2-0.9.2-1
postgresql-server-7.3.4-2mdk
libpython2.2-2.2.2-6mdk
MySQL-client-4.0.15-1mdk
libpython2.3-2.3-3mdk
python-2.3-3mdk
MySQL-4.0.15-1mdk
postgresql-7.3.4-2mdk
postgresql-python-7.3.4-2mdk
MySQL-common-4.0.15-1mdk
libpython2.3-devel-2.3-3mdk
postgresql-devel-7.3.4-2mdk

I don't think I have anything compiled from source or in other package
 formats relevant to this.

1. MySQL

I have tried several versions of the MySQLdb module downloaded from
sourceforge.net/projects/mysql-python.  The MySQL-python2-0.9.2-1 rpm got me
closest.  I managed to get it installed (though had to ignore one dependency
where I had a newer version of the file it was depending on - always a bad
sign) and get the following message when importing the module

>>> import MySQLdb

/usr/lib/python2.3/site-packages/MySQLdb/__init__.py:27: RuntimeWarning:
Python C API version mismatch for module _mysql: This Python has API version
1012, module _mysql has version 1011.
  import _mysql

(The module doesn't work after being imported - I checked that one).

Other source versions, including the latest test version, fail to compile
 with a host of errors.

2. PostgreSQL

I thought I would go for PostgreSQL next because the python module ships with
Mandrake.  What could go wrong?  The module (pg or _pg) loads up fine.  I
still can't connect to the datbase though (I created a database called
"web").

>>> import _pg
>>> db = _pg.connect('web','localhost')

Traceback (most recent call last):
  File "<stdin>", line 1, in ?
_pg.error: could not connect to server: Connection refused
        Is the server running on host localhost and accepting
        TCP/IP connections on port 5432?

I checked and the database is running and is listening on port 5432.

Next I spotted something in the PostgreSQL manual, that I need to run the
createlang command first.  I tried this but no luck :

-bash-2.05b$ createlang plpython web
ERROR:  stat failed on file '$libdir/plpython': No such file or directory
createlang: language installation failed
-bash-2.05b$ createlang plpythonu web
createlang: unsupported language "plpythonu"
Supported languages are plpgsql, pltcl, pltclu, plperl, plperlu, and
 plpython.

I've hunted around and I can't find a plpython file anywhere on my PC so it
isn't installed.  However, I also can't see any rpm than I'm missing.

Many thanks,

Iain


From python at aksdal.net  Wed Jan 21 16:32:07 2004
From: python at aksdal.net (Helge Aksdal)
Date: Wed Jan 21 16:32:11 2004
Subject: [Tutor] Regexp result
Message-ID: <20040121213207.GA15792@aksdal.net>

Hi,

Is there anyway that i can put regexp results into strings?
In Perl i use qr for that operation:

[...]
qr '(\w\w\w)\s(\d+?)\s(\d\d:\d\d:\d\d)',
q  '($month, $day, $time) = ($1, $2, $3)',
[...]

Hope this was clear enough.

-- 
Helge Aksdal

From arkamir at softhome.net  Wed Jan 21 17:28:15 2004
From: arkamir at softhome.net (arkamir@softhome.net)
Date: Wed Jan 21 17:28:20 2004
Subject: [Tutor] Reading directory
Message-ID: <courier.400EFCFF.00001576@softhome.net>

My question is sorta difficult to explain so bear with me. I need to read a 
directory and select distinct files which are distinct before a certain 
point. Similiar to SQL select distinct. So if i had a directory filled with: 

family_01.jpg
family_02.jpg
family_03.jpg
family_03.jpg 

test_01.jpg
test_02.jpg 

It would optimilly select just.
family
test 

Or the whole file name and then filter everything past the _.
I hope I explained this clearly enough. I need this because I'm making an 
online photo album for my family and want to minimize recoding html by 
having the links to each section dynamincally generated. I am using Linux. 

Thanks a lot!!! 

From littledanehren at yahoo.com  Wed Jan 21 17:31:05 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Wed Jan 21 17:31:12 2004
Subject: [Tutor] shelve error
In-Reply-To: <21427-400EC86C-198@storefull-3191.bay.webtv.net>
Message-ID: <20040121223105.30438.qmail@web41808.mail.yahoo.com>

Ron A wrote:
> I have Python 2.2 and when I try this program I get
> a popup with this
> message. Can you see what I'm doing wrong? I just
> want to take some info
> I have in a file and (shelve it?). 
> PYTHONW caused an invalid page fault in 
> module MSVCRT.DLL at 0167:78012473. 
> Registers: 
> EAX=00000002 CS=0167 EIP=78012473 EFLGS=00010246 
> EBX=00750880 SS=016f ESP=0062cdc4 EBP=0062cdcc 
> ECX=ffff01f0 DS=016f ESI=00aef68e FS=0f77 
> EDX=00000000 ES=016f EDI=00aef70e GS=0000 
> Bytes at CS:EIP: 
> 8a 06 88 07 8a 46 01 c1 e9 02 88 47 01 83 c6 02 
> Stack dump: 
> 0000ff8e 1e03b1d0 0062ce00 00f1812c 00aef70e
> 00aef68e ffff01f2 00ada1c0
> 00aef68e 00add470 00aef70e 00adf700 00000008
> 00000080 1e030200 0062ce48 
> This program has performed an illegal operation and
> will be shut down. 
> ### Here's the program ######### 
> import cPickle, shelve 
> hold = [] 
> data = open('inout.txt', 'r') 
> while 1: 
>     temp = data.readline() 
>     if temp == '': 
>         break 
>     temp = temp[:-1] 
>     temp = temp.split('\t') 
>     hold.append(temp) 
> data.close() 
> data = shelve.open('inventory') 
> for num in hold: 
>     a = num[0] 
>     b = num[1] 
>     c = num[2] 
>     d = num[3] 
>     e = num[4] 
>     f = num[5] 
>     g = num[6] 
>     h = num[7] 
>     i = num[8] 
>     j = num[9] 
>     k = num[10] 
>     l = num[11] 
>     m = num[12] 
>     n = num[13] 
>     data[b] = [a, c, d, e, f, g, h, i, j, k, l, m,
> n] 
>     data.sync() 
> data.close

First of all, you should be using Python 2.3. 2.3
resolved many of 2.2's bugs and lets you use
generators.

Second of all, you're algorithm's somewhat
inefficient. Here's how I would implement it:

import shelve #you never used cPickle; why import it?
hold = [] 
input = open('inout.txt') #r is default
for line in input: #loops through lines in file
    temp = line.split('\t') 
    hold.append(temp) 
input.close() 
database = shelve.open('inventory') #don't reuse
variable names
for num in hold: 
    index = num.pop(1) #removes num[1] and returns it
    database[index] = num
    #sync not needed; done automatically when closed
database.close()

I don't see any real bugs in either version, though.
When you get one of those Microsoft errors like that,
it's Windows's fault, not Python's.

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes
http://hotjobs.sweepstakes.yahoo.com/signingbonus

From bwinton at latte.ca  Wed Jan 21 17:38:18 2004
From: bwinton at latte.ca (Blake Winton)
Date: Wed Jan 21 17:38:27 2004
Subject: [Tutor] Reading directory
In-Reply-To: <courier.400EFCFF.00001576@softhome.net>
Message-ID: <006701c3e06f$4440e080$6401a8c0@phantomfiber.com>

> family_01.jpg
> family_02.jpg
> family_03.jpg
> family_03.jpg 
> 
> test_01.jpg
> test_02.jpg 
> 
> It would optimilly select just.
> family
> test 

Okay, I'm going to assume that you have got a list of filenames
like so:
>>> x = ['family_01.jpg', 'family_02.jpg', 'family_03.jpg',
'family_03.jpg', 'test_01.jpg', 'test_02.jpg' ]
If you don't, perhaps you can take some time trying to figure
out how to get that.  Or perhaps you can wait, and someone else
will tell you how to do it.

To go from that to ['family', 'test'], you can use the following
code:
>>> ignore = [y.update({z.split('_')[0]:1}) for z in x]
>>> y
{'test': 1, 'family': 1}
>>> w = y.keys()
>>> w
['test', 'family']

And voila!  :)

Play around with bits of it, to see if you can figure out what
it's doing there.  If you can't quite get it, feel free to email
me, and ask me questions about it.

Later,
Blake.


From bwinton at latte.ca  Wed Jan 21 17:47:50 2004
From: bwinton at latte.ca (Blake Winton)
Date: Wed Jan 21 17:47:55 2004
Subject: [Tutor] Reading directory
In-Reply-To: <006701c3e06f$4440e080$6401a8c0@phantomfiber.com>
Message-ID: <006801c3e070$999cb990$6401a8c0@phantomfiber.com>

> >>> x = ['family_01.jpg', 'family_02.jpg', 'family_03.jpg',
> 'family_03.jpg', 'test_01.jpg', 'test_02.jpg' ]
> 
> To go from that to ['family', 'test'], you can use the following
> code:

Hah!  That'll larn me to go writing code without reading the
documentation first...

If you've installed Python 2.3, you can also write 
>>> import sets
>>> y = sets.Set( [z.split('_')[0] for z in x] )
>>> y
Set(['test', 'family'])

which is a whole lot less code, and hopefully a little more
understandable.

Later,
Blake.


From dyoo at hkn.eecs.berkeley.edu  Wed Jan 21 18:07:09 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Jan 21 18:07:15 2004
Subject: [Tutor] Can't get Python connected to databases
In-Reply-To: <200401212105.48879.python@cairnlin.co.uk>
Message-ID: <Pine.LNX.4.44.0401211425000.13249-100000@hkn.eecs.berkeley.edu>



On Wed, 21 Jan 2004, Iain wrote:

> I have been trying to get a connection between Python and a back-end
> database:  something that I expected to be a trivial exercise.
> Unfortunately, I seem
>
> to be getting nowhere and could really do with some help.

Hi Iain,

Ok, let's take a look:


> My environment : Python 2.3 (#2, Aug 31 2003, 17:27:29)
> [GCC 3.3.1 (Mandrake Linux 9.2 3.3.1-1mdk)] on linux2
>
> RPMs installed :
> -bash-2.05b$ rpm -qa|grep -iE 'python|mysql|postgres'
> python-base-2.3-3mdk
> libmysql12-4.0.15-1mdk
> MySQL-python2-0.9.2-1
> postgresql-server-7.3.4-2mdk
> libpython2.2-2.2.2-6mdk
> MySQL-client-4.0.15-1mdk
> libpython2.3-2.3-3mdk
> python-2.3-3mdk
> MySQL-4.0.15-1mdk
> postgresql-7.3.4-2mdk
> postgresql-python-7.3.4-2mdk
> MySQL-common-4.0.15-1mdk
> libpython2.3-devel-2.3-3mdk
> postgresql-devel-7.3.4-2mdk


Thanks, that RPM list helps us a lot.


Personally, I've had the best success if I compile MySQLdb, so maybe we
should go that route.  I think you may need to install the MySQL devel
RPM.  I'm not too familiar with Mandrake-Linux, but I'm guessing that the
RPM's name begins with:

    libmysql12-devel

You should be able to find this on your Mandrake CD, or from your friendly
RPM mirror.


> I don't think I have anything compiled from source or in other package
> formats relevant to this.
>
> 1. MySQL
>
> I have tried several versions of the MySQLdb module downloaded from
> sourceforge.net/projects/mysql-python.


Once you have that libmysql12-devel RPM installed, try going the source
route again.  You should get farther with it.


> Other source versions, including the latest test version, fail to
> compile with a host of errors.

Show us the errors when you try this again --- some of us know C well
enough to understand what the build errors are actually trying to say.







> 2. PostgreSQL
>
> I thought I would go for PostgreSQL next because the python module ships with
> Mandrake.  What could go wrong?  The module (pg or _pg) loads up fine.  I
> still can't connect to the datbase though (I created a database called
> "web").
>
> >>> import _pg
> >>> db = _pg.connect('web','localhost')


It looks like you're using the PyGreSQL interface:

    http://developer.postgresql.org/docs/postgres/pygresql.html


Don't use '_pg' unless you really mean to: the leading underscore is a
hint that the module is not meant to be used directly.  You should be
using either the stable 'pg' module, or the more recent 'pgdb' DB-API 2.0
driver.



For the moment, let's use 'pgdb', since it's using the standard DB-API
2.0.  The pgdb.connect() function takes several arguments:

###
Help on function connect in module pgdb:

connect(dsn=None, user=None, password=None, host=None, database=None)
    # connects to a database
###


and I get the feeling we need to use keyword parameters: notice that the
first two arguments here are the "Data Source Name" (dsn) and 'user'
parameters, and not the 'database' and 'user' parameters that you expect.
That's probably what is causing the connection error you were seeing
earlier.


For example, here's what you should see on a successful connect:

###
>>> pgdb.connect(database='pub')
<pgdb.pgdbCnx instance at 0x81c380c>
###

Here, we explictely say that the 'database' argument should be the 'pub'
database.



So try:

###
import pgdb
pgdb.connect(database='web', host='localhost')
###

You should get better results from this.




Hope this helps!


From littledanehren at yahoo.com  Wed Jan 21 18:14:43 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Wed Jan 21 18:14:46 2004
Subject: [Tutor] Cgi Fieldstorage cant get quotes
In-Reply-To: <courier.400EBE25.0000350D@softhome.net>
Message-ID: <20040121231443.46221.qmail@web41801.mail.yahoo.com>


--- arkamir@softhome.net wrote:
> Does anyone know how to get qoutes from the
> cgi.FieldStorage. Whenever a 
> user inputs data into a html form which contains
> quotes (", ') I get an 
> error message. 
> 
> Thanks,
>   Conrad

Make sure the quotes within the string are excaped by
prefixing them with a backslash ('\')

__________________________________
Do you Yahoo!?
Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes
http://hotjobs.sweepstakes.yahoo.com/signingbonus

From dyoo at hkn.eecs.berkeley.edu  Wed Jan 21 18:21:48 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Jan 21 18:22:05 2004
Subject: [Tutor] Regexp result
In-Reply-To: <20040121213207.GA15792@aksdal.net>
Message-ID: <Pine.LNX.4.44.0401211509430.13249-100000@hkn.eecs.berkeley.edu>



On Wed, 21 Jan 2004, Helge Aksdal wrote:

> Is there anyway that i can put regexp results into strings?
> In Perl i use qr for that operation:
>
> [...]
> qr '(\w\w\w)\s(\d+?)\s(\d\d:\d\d:\d\d)',
> q  '($month, $day, $time) =3D ($1, $2, $3)',
> [...]
>
> Hope this was clear enough.


Hi Helge,


Ok, the Perl documentation from:

    perldoc perlop

says:

"""
       qr/STRING/imosx
               This operator quotes (and possibly compiles) its
               STRING as a regular expression.  STRING is inter=AD
               polated the same way as PATTERN in "m/PATTERN/".
"""


The closest equivalent to this 'qr' operator in Python is the re.compile()
function:

    http://www.python.org/doc/lib/node106.html#l2h-831



In Python, regular expressions are full-fledged objects, so you may want
to quickly browse through:

    http://www.python.org/doc/lib/module-re.html

Much of the functionality in Python's regular expressions lives in the
library, and not directly in the language, so the documentation on regular
expressions is in the Standard Library docs.



Here's example use of regular expressions:

###
>>> sample_text =3D "this is a test"
>>> pattern =3D re.compile(r"(\w+)\s*(\w+)\s*(\w+)\s*(\w+)")
>>> pattern.search(sample_text).groups()
('this', 'is', 'a', 'test')
###



A.M. Kuchling's Python Regex HOWTO should also help you transition your
Perl regular expression knowledge into Python:

    http://www.amk.ca/python/howto/regex/



I hope this helps!


From sigurd at 12move.de  Wed Jan 21 18:31:56 2004
From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=)
Date: Wed Jan 21 18:34:49 2004
Subject: [Tutor] Regexp result
In-Reply-To: <20040121213207.GA15792@aksdal.net> (Helge Aksdal's message of
	"Wed, 21 Jan 2004 22:32:07 +0100")
References: <20040121213207.GA15792@aksdal.net>
Message-ID: <m3oesxj5x3.fsf@hamster.pflaesterer.de>

On 21 Jan 2004, Helge Aksdal <- python@aksdal.net wrote:

> Is there anyway that i can put regexp results into strings?
> In Perl i use qr for that operation:
> [...]
> qr '(\w\w\w)\s(\d+?)\s(\d\d:\d\d:\d\d)',
> q  '($month, $day, $time) = ($1, $2, $3)',
> [...]

There are some ways; it depends on the kind of verbosity you can accept.

First the most ovious way.

In [11]: re = sre.compile(r'(\w\w\w)\s(\d+?)\s(\d\d:\d\d:\d\d)')

In [12]: s = 'Jan 12 12:12:12'

In [13]: [(mon, day, time)] = re.findall(s)

In [14]: mon, day, time
Out[14]: ('Jan', '12', '12:12:12')

In [15]: mon
Out[15]: 'Jan'


That will only work if you have a match; then `findall' will return here
a list with one tuple which has three elements (one for every group in
the regexp).

So you have to write a little bit more code.

In [16]: re.findall("foo")
Out[16]: []

In [17]: re.findall("foo") or '','',''
Out[17]: (None, None, None)

Here you see what happens if there is no match; an empty list is
returned.  Since that's like a boolean false value we can use `or' to
return a three element tuple so Python doesn't complain.

In [21]: [(mon, day, time)] = re.findall('foo') or [('', '', '')]

In [22]: mon
Out[22]: ''

In [23]:


Instead of the above you could write code with `try' and `except' or you
could compute a match object, see if it is not none and assign the
values.  Or you could give each group a name and use the groupdict
(would be totally overkill here but naming groups is a nice feature).
So pick your favorite.



   Karl
-- 
Please do *not* send copies of replies to me.
I read the list


From sigurd at 12move.de  Wed Jan 21 18:47:39 2004
From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=)
Date: Wed Jan 21 18:51:43 2004
Subject: [Tutor] Regexp result
In-Reply-To: <m3oesxj5x3.fsf@hamster.pflaesterer.de> (Karl
	=?iso-8859-1?q?Pfl=E4sterer's?= message of "Thu,
	22 Jan 2004 00:31:56 +0100")
References: <20040121213207.GA15792@aksdal.net>
	<m3oesxj5x3.fsf@hamster.pflaesterer.de>
Message-ID: <m3k73kkgq3.fsf@hamster.pflaesterer.de>

On 22 Jan 2004, Karl Pfl?sterer <- sigurd@12move.de wrote:

> In [17]: re.findall("foo") or '','',''
> Out[17]: (None, None, None)
            ^^^^^^^^^^^^^^^^
That should be ('', '', ''); don't change code in your newsclient.


   Karl
-- 
Please do *not* send copies of replies to me.
I read the list


From arkamir at softhome.net  Wed Jan 21 19:17:25 2004
From: arkamir at softhome.net (Conrad Koziol)
Date: Wed Jan 21 19:35:43 2004
Subject: [Tutor] Cgi Fieldstorage cant get quotes
Message-ID: <1074730644.5065.15.camel@conradpc>

Make sure the quotes within the string are excaped by
prefixing them with a backslash ('\')

Thats what I thought but the problem is that these are going to be
online and I cant control what user input is. :(



From arkamir at softhome.net  Wed Jan 21 19:20:42 2004
From: arkamir at softhome.net (Conrad Koziol)
Date: Wed Jan 21 19:39:02 2004
Subject: [Tutor] Database connectivity
Message-ID: <1074730841.5065.19.camel@conradpc>

This is what I have on Fedora 1.

MySQL-client-4.0.15-0
MySQL-shared-compat-4.0.15-0
MySQL-server-4.0.15-0
MySQL-python-0.9.1-9

I dont quite remember but I believe you have to compile the MySQL-python
package. But I dont think so. :) The problem is I believe that
MySQL-python doesnt support the newer MySQL, 4.1 I believe.

Hope this help,
	Conrad



From alan.gauld at blueyonder.co.uk  Wed Jan 21 19:43:51 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Wed Jan 21 19:43:34 2004
Subject: [Tutor] Reading directory
References: <courier.400EFCFF.00001576@softhome.net>
Message-ID: <006201c3e080$ce296180$6401a8c0@xp>


> My question is sorta difficult to explain so bear with me. 
> I need to read a directory and 
> select distinct files 

OK, Which bit is giving you grief?
You can read a list of files using the glob module

> family_03.jpg
> family_03.jpg 
> 
> test_01.jpg
> test_02.jpg 
> 
> It would optimilly select just.
> family
> test 

Having got your list of names you can extract the first bit 
in several ways.

If you know that they all use the same format(as shown) then 
you can use the string split method:

for fname in listOfFiles:
   names.append(fname.split('_')[0])

If you don;t know the format you can search for the first 
character which is not a letter and use slicing to pull 
out the bit you want:

index = 0
while fname[index] in string.letters:
      index += 1
name = fname[:index]

Or you can get real fancy and start using regular expressions
to detect more sophisticated patterns.

HTH,

Alan G.

From littledanehren at yahoo.com  Wed Jan 21 22:12:44 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Wed Jan 21 22:12:48 2004
Subject: [Tutor] Help - Where and when to use OOP
In-Reply-To: <20040120051518.65803.qmail@web12201.mail.yahoo.com>
Message-ID: <20040122031244.8050.qmail@web41809.mail.yahoo.com>

Lakmi munasinghe wrote:
> 
> What I meant by a "repeating process" is repeating
> certain behaviors more than once.
> 
> I am doing a blood transfution management system. I
> think my project is a moderate sized one.It contains
> mostly AI modules (coded using FLEX).
> 
> What do you think the applicability of OOP for such
> kind of a project?

Since blood transfusions are complicated, with many
different aspects like diseases, blood type, etc.,
you're probably better off using object orientation.
You would probably only use an object for each
container of blood or something like that, and methods
would do all of the interfacing with donors and
recipients.
> 
> I have another question : If I want to design our
> project using UML is it a must to use a OOP approach
> when I am doing the implementation? Can I use
> Usecases for a project that I dont use OOP concepts
> for coding ?

With Python, I don't see why you wouldn't want to use
OOP. If it is such a big project that you need to
spend a while designing the flow charts, object
orientation will probably be very helpful.

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Yahoo! SiteBuilder - Free web site building tool. Try it!
http://webhosting.yahoo.com/ps/sb/

From rha207 at webtv.net  Wed Jan 21 23:49:29 2004
From: rha207 at webtv.net (Ron A)
Date: Wed Jan 21 23:49:34 2004
Subject: [Tutor] shelve error (Thanks)
Message-ID: <21429-400F5659-195@storefull-3191.bay.webtv.net>

>I don't see any real bugs in either
> version, though.  When you get one of
> those Microsoft errors like that,  it's
> Windows's fault, not Python's. 

Thanks for answering. I'm glad to know it's Window's fault and not
something I did.

Ron A


From isrgish at fusemail.com  Thu Jan 22 00:10:58 2004
From: isrgish at fusemail.com (Isr Gish)
Date: Thu Jan 22 00:11:02 2004
Subject: [Tutor] Problem reading from a file
Message-ID: <E1AjX77-0006UK-8m@fuse1.fusemail.net>

I have a registry file that I'm trying to read. But it is only reading part of the file. When it comes to  certain  text it stops reading.
(I would send along the file but the list doesn't let send attachments).

Any help would be greatly appreciated.
---------------
Isr Gish


From mjxny at hotmail.com  Thu Jan 22 10:59:19 2004
From: mjxny at hotmail.com (Ming Xue)
Date: Thu Jan 22 10:59:26 2004
Subject: [Tutor] Reading directory
Message-ID: <BAY1-F156i9tH5L3Lhp00029620@hotmail.com>


>My question is sorta difficult to explain so bear with me. I need to read a 
>directory and select distinct files which are distinct before a certain 
>point. Similiar to SQL select distinct. So if i had a directory filled 
>with:
>
>family_01.jpg
>family_02.jpg
>family_03.jpg
>family_03.jpg
>
>test_01.jpg
>test_02.jpg
>
>It would optimilly select just.
>family
>test



You can use glob to just read "family" or "test" if they are distinct term.
family_list=glob.glob("path\*family*.jpg")
test_list=glog.glob("path\*test*.jpg")




>Or the whole file name and then filter everything past the _.
>I hope I explained this clearly enough. I need this because I'm making an 
>online photo album for my family and want to minimize recoding html by 
>having the links to each section dynamincally generated. I am using Linux.
>
>Thanks a lot!!!
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor

_________________________________________________________________
Check out the new MSN 9 Dial-up — fast & reliable Internet access with prime 
features! http://join.msn.com/?pgmarket=en-us&page=dialup/home&ST=1


From hameedkhaan at yahoo.com  Thu Jan 22 10:44:20 2004
From: hameedkhaan at yahoo.com (Hameed Khan)
Date: Thu Jan 22 11:48:20 2004
Subject: [Tutor] What is object()
Message-ID: <20040122154420.6597.qmail@web61110.mail.yahoo.com>

hi,
  i was reading library refrence manual. there i found
object() function. they says in library refrence that 
        "Return a new featureless object. object() is
a base for all new style classes. It has the methods
that are common to all instances of new style
classes." 

My questions are whats the use of this function and
the object returned by it? and what are new style
classes?.

Thanks,
Hameed Khan

__________________________________
Do you Yahoo!?
Yahoo! SiteBuilder - Free web site building tool. Try it!
http://webhosting.yahoo.com/ps/sb/

From dyoo at hkn.eecs.berkeley.edu  Thu Jan 22 13:26:22 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Jan 22 13:26:31 2004
Subject: [Tutor] Problem reading from a file
In-Reply-To: <E1AjX77-0006UK-8m@fuse1.fusemail.net>
Message-ID: <Pine.LNX.4.44.0401221023230.17543-100000@hkn.eecs.berkeley.edu>



On Thu, 22 Jan 2004, Isr Gish wrote:

> I have a registry file that I'm trying to read. But it is only reading
> part of the file. When it comes to certain text it stops reading. (I
> would send along the file but the list doesn't let send attachments).

Hi Isr,


Registry files are 'binary' files, and on Windows systems, this detail
matters --- Python may be mistakenly trying to treat the registry file as
a 'text' file.  Are you opening the files in binary mode?



Good luck to you!


From dyoo at hkn.eecs.berkeley.edu  Thu Jan 22 13:37:19 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Jan 22 13:37:23 2004
Subject: [Tutor] shelve error
In-Reply-To: <20040121223105.30438.qmail@web41808.mail.yahoo.com>
Message-ID: <Pine.LNX.4.44.0401221026380.17543-100000@hkn.eecs.berkeley.edu>

> First of all, you should be using Python 2.3. 2.3 resolved many of 2.2's
> bugs and lets you use generators.

Hello!


Python 2.2's version of 'shelve' may depend on the 'bsddb' module.  On my
Linux systems, at least, I know that it has.


bsddb was buggy in 2.2, and was replaced in Python 2.3 with a more stable
implementation:

    http://www.python.org/2.3/highlights.html


The notes don't talk about why the old 'bsddb' module was retired, but
stability seems to be the major issue:

    http://mail.python.org/pipermail/python-bugs-list/2002-May/011705.html

This bug did also effect the Windows version too:

    http://www.deadlybloodyserious.com/Python/2002/05/06.html


So definitely upgrade to Python 2.3.



> I don't see any real bugs in either version, though. When you get one of
> those Microsoft errors like that, it's Windows's fault, not Python's.

It's probably not Microsoft's fault either here... bsddb --- and the
modules that depended on it --- was just broken in Python 2.2, period.
*sigh* Thankfully, things look better now in 2.3.


Hope this helps!


From alan.gauld at blueyonder.co.uk  Thu Jan 22 13:50:25 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Thu Jan 22 13:49:56 2004
Subject: [Tutor] Help - Where and when to use OOP
References: <20040122031244.8050.qmail@web41809.mail.yahoo.com>
Message-ID: <001601c3e118$991c0180$6401a8c0@xp>

> > I am doing a blood transfution management system. I
> > think my project is a moderate sized one.It contains
> > mostly AI modules (coded using FLEX).
> > 
> > What do you think the applicability of OOP for such
> > kind of a project?

Sounds like an ideal candidate for an OOP approach. There 
are lots of objects involved - patients, transfusions, 
units, appointments, tasks, all sorts...

> > I have another question : If I want to design our
> > project using UML is it a must to use a OOP approach

No UML sits above OOP. Although it originated in the OO 
community it can be used for non OO approaches or even 
projects where no software is involved at all.

> > Usecases for a project that I dont use OOP concepts
> > for coding ?

Absolutely, Usecases do not even have a strong link to UML!

Alan G.


From idiot1 at netzero.net  Thu Jan 22 14:53:37 2004
From: idiot1 at netzero.net (Kirk Bailey)
Date: Thu Jan 22 14:56:57 2004
Subject: [Tutor] front end 101
Message-ID: <40102A41.2010203@netzero.net>

OK, I think it is time for me to start to learn something of front 
ending. That is, the part that sticks it's face out at the user, the 
GUI. There have been a couple of times I wanted to write something 
that did not talk to the world through html and a browser, and I am 
tired of tripping over this limitation in myself. And this means 
learning about TL/TCL I am going to bet.

So in this thread, I invite 101 level information about the subject in 
general, and any tutoring on the subject you care to provide.

Also, from time to time I may ask if I can steal posts from here which 
appear to be high grade ore and stick them on the wiki over at my 
tinylist.org site.

-- 


end


   think   http://www.tinylist.org/ - $FREE$ software for liberty
+-------+ http://www.pinellasintergroupsociety.org/ - In Her Service
|  BOX  | http://www.listville.net/ - $FREE$ list hosting services
+-------+ http://www.howlermonkey.net/ - $FREE$ email service
   kniht   http://www.sacredelectron.org/ - My personal SCREED pit
          (C)2004 Kirk D Bailey, all rights reserved- but ask!







From helge at aksdal.net  Wed Jan 21 12:17:53 2004
From: helge at aksdal.net (Helge Aksdal)
Date: Thu Jan 22 15:47:48 2004
Subject: [Tutor] Regexp result
Message-ID: <20040121171753.GA15372@aksdal.net>

Hi,                                                                                                                            
                                                                                                                               
Is there anyway that i can get the result of a regexp match into                                         
strings? In Perl i use qr to do this:

[...]                                                                                                                          
qr '(\w\w\w)\s(\d+?)\w+\s(\d\d:\d\d:\d\d)',                                                                                    
q  '($month, $day, $time) = ($1, $2, $3)',
[...]

Hope this was clear enough. 

-- 
Helge Aksdal

From helge at aksdal.net  Thu Jan 22 14:25:32 2004
From: helge at aksdal.net (Helge Aksdal)
Date: Thu Jan 22 15:47:54 2004
Subject: [Tutor] Regexp result
In-Reply-To: <Pine.LNX.4.44.0401211509430.13249-100000@hkn.eecs.berkeley.edu>
References: <20040121213207.GA15792@aksdal.net>
	<Pine.LNX.4.44.0401211509430.13249-100000@hkn.eecs.berkeley.edu>
Message-ID: <20040122192532.GC17022@aksdal.net>

* Danny Yoo (Thu, Jan 22, 2004 at 00:21 +0100 GMT):
> ###
> >>> sample_text = "this is a test"
> >>> pattern = re.compile(r"(\w+)\s*(\w+)\s*(\w+)\s*(\w+)")
> >>> pattern.search(sample_text).groups()
> ('this', 'is', 'a', 'test')
> ###
> 
> 
> 
> A.M. Kuchling's Python Regex HOWTO should also help you transition your
> Perl regular expression knowledge into Python:
> 
>     http://www.amk.ca/python/howto/regex/
> 
> 
> 
> I hope this helps!

Thank's both of you!
That was indeed helpful!

-- 
Helge Aksdal

From pinard at iro.umontreal.ca  Thu Jan 22 12:03:58 2004
From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard)
Date: Thu Jan 22 15:48:10 2004
Subject: [Tutor] Re: What is object()
In-Reply-To: <20040122154420.6597.qmail@web61110.mail.yahoo.com>
References: <20040122154420.6597.qmail@web61110.mail.yahoo.com>
Message-ID: <20040122170358.GA19330@alcyon.progiciels-bpi.ca>

[Hameed Khan]

> and what are new style classes?.

   http://www.python.org/2.2.3/descrintro.html

is a good read on this subject.

-- 
Fran?ois Pinard   http://www.iro.umontreal.ca/~pinard

From cspears2002 at yahoo.com  Thu Jan 22 17:33:44 2004
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Thu Jan 22 17:33:49 2004
Subject: [Tutor] writing a function
Message-ID: <20040122223344.50235.qmail@web12401.mail.yahoo.com>

This is a programming problem that I have been given:

Write a function that accepts an arbitrary number of
lists and returns a single list with exactly one
occurrence of each element that appears in any of the
input lists.

For some reason, this problem has left me stumped. 
Suggestions, anyone?

-Chris

=====
"I'm the last person to pretend that I'm a radio.  I'd rather go out and be a color television set."
-David Bowie

"Who dares wins"
-British military motto

"Far more creativity, today, goes into the marketing of products than into the products themselves..."
-"Pattern Recognition" by William Gibson

From orbitz at ezabel.com  Thu Jan 22 18:27:18 2004
From: orbitz at ezabel.com (orbitz@ezabel.com)
Date: Thu Jan 22 18:27:48 2004
Subject: [Tutor] writing a function
In-Reply-To: <20040122223344.50235.qmail@web12401.mail.yahoo.com>
References: <20040122223344.50235.qmail@web12401.mail.yahoo.com>
Message-ID: <20040122182718.28e75e47.orbitz@ezabel.com>

http://www.python.org/doc/current/tut/node6.html#SECTION006730000000000000000

Start there.


On Thu, 22 Jan 2004 14:33:44 -0800 (PST)
Christopher Spears <cspears2002@yahoo.com> wrote:

> This is a programming problem that I have been given:
> 
> Write a function that accepts an arbitrary number of
> lists and returns a single list with exactly one
> occurrence of each element that appears in any of the
> input lists.
> 
> For some reason, this problem has left me stumped. 
> Suggestions, anyone?
> 
> -Chris
> 
> =====
> "I'm the last person to pretend that I'm a radio.  I'd rather go out and be a color television set."
> -David Bowie
> 
> "Who dares wins"
> -British military motto
> 
> "Far more creativity, today, goes into the marketing of products than into the products themselves..."
> -"Pattern Recognition" by William Gibson
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

From cspears2002 at yahoo.com  Thu Jan 22 18:31:56 2004
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Thu Jan 22 18:32:00 2004
Subject: [Tutor] using the reduce function
Message-ID: <20040122233156.61832.qmail@web12404.mail.yahoo.com>

Yet another homework problem is giving me fits.  Here
it goes:

Use the reduce function to find the length of the
longest string in a list of strings.

I have been banging my head against the wall with this
one.  Ouch!  I figured out how to do it another way
using control structures:

>>> strings = ['long', 'longer', 'longest']
>>> for i in range(len(strings)):
	count = 0
	if len(strings[i]) > count:
		count = len(strings[i])

		
>>> count
7

So how do I use the logic of this script and apply it
to the problem?

-Chris

=====
"I'm the last person to pretend that I'm a radio.  I'd rather go out and be a color television set."
-David Bowie

"Who dares wins"
-British military motto

"Far more creativity, today, goes into the marketing of products than into the products themselves..."
-"Pattern Recognition" by William Gibson

From littledanehren at yahoo.com  Thu Jan 22 19:06:41 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Thu Jan 22 19:06:46 2004
Subject: [Tutor] What is object()
In-Reply-To: <20040122154420.6597.qmail@web61110.mail.yahoo.com>
Message-ID: <20040123000641.64114.qmail@web41809.mail.yahoo.com>


--- Hameed Khan <hameedkhaan@yahoo.com> wrote:
> hi,
>   i was reading library refrence manual. there i
> found
> object() function. they says in library refrence
> that 
>         "Return a new featureless object. object()
> is
> a base for all new style classes. It has the methods
> that are common to all instances of new style
> classes." 
> 
> My questions are whats the use of this function and
> the object returned by it? and what are new style
> classes?.
> 
> Thanks,
> Hameed Khan

Object is not a function, Python just makes classes
look somewhat like functions. When you call object(),
you're really making an instance of the object class.
This is pretty useless because you cannot change
anything in it. However, it is very useful to subclass
object when making a class, because then you get some
of the more advanced things in object orientation
(like mro(), new-style inheritance, etc.).

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Yahoo! SiteBuilder - Free web site building tool. Try it!
http://webhosting.yahoo.com/ps/sb/

From dyoo at hkn.eecs.berkeley.edu  Thu Jan 22 19:11:11 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Jan 22 19:11:17 2004
Subject: [Tutor] using the reduce function
In-Reply-To: <20040122233156.61832.qmail@web12404.mail.yahoo.com>
Message-ID: <Pine.LNX.4.44.0401221605180.21328-100000@hkn.eecs.berkeley.edu>



On Thu, 22 Jan 2004, Christopher Spears wrote:

> Yet another homework problem is giving me fits.  Here it goes:
>
> Use the reduce function to find the length of the longest string in a
> list of strings.

Hi Christopher,

You may want to simplify the problem.


Here's one possible simplification: can you write a function that, given a
list of strings, returns the longest string?  The input and output here
are more related: rather than deal with both strings and string lengths,
we can just deal with strings.  It might be easier to see a good solution
to this with reduce().


Good luck to you.


From hcohen2 at comcast.net  Thu Jan 22 19:19:02 2004
From: hcohen2 at comcast.net (hcohen2)
Date: Thu Jan 22 19:21:08 2004
Subject: [Tutor] writing a function
In-Reply-To: <20040122182718.28e75e47.orbitz@ezabel.com>
References: <20040122223344.50235.qmail@web12401.mail.yahoo.com>
	<20040122182718.28e75e47.orbitz@ezabel.com>
Message-ID: <40106876.2080903@comcast.net>

Chris,

The link will take care of the unfixed number of lists, then you need to 
stop duplicates.

When building your final result list, just test to make certain that the 
examined value is not in that list. 

    if fromList(value) not in resultList:
          resultList.append(fromList(value)
    else:
          pass (or continue - you will be in at least one loop here)

orbitz@ezabel.com wrote:

>http://www.python.org/doc/current/tut/node6.html#SECTION006730000000000000000
>
>Start there.
>
>
>On Thu, 22 Jan 2004 14:33:44 -0800 (PST)
>Christopher Spears <cspears2002@yahoo.com> wrote:
>
>  
>
>>This is a programming problem that I have been given:
>>
>>Write a function that accepts an arbitrary number of
>>lists and returns a single list with exactly one
>>occurrence of each element that appears in any of the
>>input lists.
>>
>>For some reason, this problem has left me stumped. 
>>Suggestions, anyone?
>>
>>-Chris
>>
>>=====
>>"I'm the last person to pretend that I'm a radio.  I'd rather go out and be a color television set."
>>-David Bowie
>>
>>"Who dares wins"
>>-British military motto
>>
>>"Far more creativity, today, goes into the marketing of products than into the products themselves..."
>>-"Pattern Recognition" by William Gibson
>>
>>_______________________________________________
>>Tutor maillist  -  Tutor@python.org
>>http://mail.python.org/mailman/listinfo/tutor
>>    
>>
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>  
>



From littledanehren at yahoo.com  Thu Jan 22 19:33:50 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Thu Jan 22 19:33:55 2004
Subject: [Tutor] using the reduce function
In-Reply-To: <20040122233156.61832.qmail@web12404.mail.yahoo.com>
Message-ID: <20040123003350.73140.qmail@web41806.mail.yahoo.com>

Christopher Spears wrote:
> Yet another homework problem is giving me fits. 
> Here
> it goes:
> 
> Use the reduce function to find the length of the
> longest string in a list of strings.
> 
> I have been banging my head against the wall with
> this
> one.  Ouch!  I figured out how to do it another way
> using control structures:
> 
> >>> strings = ['long', 'longer', 'longest']
> >>> for i in range(len(strings)):
> 	count = 0
> 	if len(strings[i]) > count:
> 		count = len(strings[i])
> 
> 		
> >>> count
> 7
> 
> So how do I use the logic of this script and apply
> it
> to the problem?
> 
> -Chris

Unfortunately, you can't really use the logic of this
program with the reduce() function, and we're really
not supposed to give you the answer on your homework,
but I can still tell you the basic application logic.
Write a function that, given two strings, finds the
longer one. Then apply that function, using reduce, to
the sequence (in the form reduce(function, sequence)).
You will have the longest string. Then it's just a
matter of finding that string's length.

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Yahoo! SiteBuilder - Free web site building tool. Try it!
http://webhosting.yahoo.com/ps/sb/

From dyoo at hkn.eecs.berkeley.edu  Thu Jan 22 19:36:06 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Jan 22 19:36:11 2004
Subject: [Tutor] writing a function
In-Reply-To: <20040122223344.50235.qmail@web12401.mail.yahoo.com>
Message-ID: <Pine.LNX.4.44.0401221614320.21328-100000@hkn.eecs.berkeley.edu>



On Thu, 22 Jan 2004, Christopher Spears wrote:

> This is a programming problem that I have been given:

Hi Christopher,


Before we go further, we have to state outright that we are prohibited
from giving much help on homework problems.  We'll try to point you toward
tutorial resources that should make a concept more clear.


If you find yourself getting really stuck, we suggest you take a look at
G. Polya's "How To Solve It":

    http://www.math.utah.edu/~alfeld/math/polya.html

His cookbook approach to solving difficult problems is invaluable.  His
target audience was mathematicians, but his advice applies remarkably well
for programmers too.



> Write a function that accepts an arbitrary number of lists and returns a
> single list with exactly one occurrence of each element that appears in
> any of the input lists.
>
> For some reason, this problem has left me stumped.  Suggestions, anyone?

Tell us what about the problem is getting you stuck.  You've stated the
problem, but you've neglected to tell us what you're having difficulty
with.  What have you tried so far?



Have you tried to simplify the problem?  If you're having problem with the
word "arbitrary" in:

    "Write a function that accepts an arbitrary number of lists..."

then you may want to modify the problem slightly.  Modifying the problem
is often a good strategy in solving problems.  It gives you more leeway to
experiment with solutions, and the progress you make on the modified
problem may be very helpful when you're solving the original.


One way to simplify it is:

    "Write a function that accepts two lists..."


Can you make progress on this version of the problem?




Good luck to you.


From sigurd at 12move.de  Thu Jan 22 19:37:18 2004
From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=)
Date: Thu Jan 22 19:42:08 2004
Subject: [Tutor] using the reduce function
In-Reply-To: <20040122233156.61832.qmail@web12404.mail.yahoo.com> (Christopher
	Spears's message of "Thu, 22 Jan 2004 15:31:56 -0800 (PST)")
References: <20040122233156.61832.qmail@web12404.mail.yahoo.com>
Message-ID: <m33ca7h6j8.fsf@hamster.pflaesterer.de>

On 23 Jan 2004, Christopher Spears <- cspears2002@yahoo.com wrote:

> Yet another homework problem is giving me fits.  Here
> it goes:

> Use the reduce function to find the length of the
> longest string in a list of strings.

> I have been banging my head against the wall with this
> one.  Ouch!  I figured out how to do it another way
> using control structures:

>>>> strings = ['long', 'longer', 'longest']
>>>> for i in range(len(strings)):
> 	count = 0
> 	if len(strings[i]) > count:
> 		count = len(strings[i])

> 		
>>>> count
> 7

> So how do I use the logic of this script and apply it
> to the problem?

You don't use it.  Above is an imperative style solution but with reduce
you have to think functional.

First, think what reduce does; it takes a sequence, a function with two
values and calls that function several times on the items of the
sequence.  The sequence is processed from left to right.  The first call
takes item0 and item1 from the sequence applies the function to them and
calls the function again with the return value and item2 and calls the
function again with the return value and itemm3 and calls ...

Above ism't ever true since you can give an initial value to reduce as
third argument.  Then the first call will apply the function to initial
value and item0.  From then on it's the same.

The value of the last function call is the return value of reduce.

So what you need is a function which tells you if one string is longer
than another.

That should be simple:

def longer (seq1, seq2):
    if len(seq1) > len(seq2): return seq1
    else: return seq2


So and now you just have to combine it with reduce.

def longest (seq):
    return reduce(longer, seq)


That returns the string but you need the length.


def longest (seq):
    return len(reduce(longer, seq))


If you are in the real functional mood (that's a good one to have) you
can write it as one function; you just have to write the if clause a bit
different since Python lambdas are weak.

def longest (seq):
    return len(reduce(lambda seq1, seq2: len(seq1) > len(seq2) and seq1 or seq2,
                      seq))

lambda seq1, seq2: len(seq1) > len(seq2) and seq1 or seq2
is the longer function; read about booleans and short circuit evaluation
to understand how it works.



   Karl
-- 
Please do *not* send copies of replies to me.
I read the list


From sigurd at 12move.de  Thu Jan 22 19:57:33 2004
From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=)
Date: Thu Jan 22 19:58:49 2004
Subject: [Tutor] using the reduce function
In-Reply-To: <m33ca7h6j8.fsf@hamster.pflaesterer.de> (Karl
	=?iso-8859-1?q?Pfl=E4sterer's?= message of "Fri,
	23 Jan 2004 01:37:18 +0100")
References: <20040122233156.61832.qmail@web12404.mail.yahoo.com>
	<m33ca7h6j8.fsf@hamster.pflaesterer.de>
Message-ID: <m3ad4fcwn9.fsf@hamster.pflaesterer.de>

On 23 Jan 2004, Karl Pfl?sterer <- sigurd@12move.de wrote:

[Code]

here is another solution; it's a bit nearer to the imperative one.  It
uses reduce with a default value (it wil also be a bit faster than the
first one).

def longer2 (ln, seq):
    lns = len(seq)
    if ln > lns: return ln
    else: return lns

def longest2 (seq):
    return reduce(longer2, seq, 0)


I think there is no further explaination necessary.


   Karl
-- 
Please do *not* send copies of replies to me.
I read the list


From missive at hotmail.com  Thu Jan 22 20:25:09 2004
From: missive at hotmail.com (Lee Harr)
Date: Thu Jan 22 20:25:14 2004
Subject: [Tutor] Re: front end 101
Message-ID: <BAY2-F138MIzD0HWISG000028b5@hotmail.com>

>OK, I think it is time for me to start to learn something of front
>ending. That is, the part that sticks it's face out at the user, the
>GUI. There have been a couple of times I wanted to write something
>that did not talk to the world through html and a browser, and I am
>tired of tripping over this limitation in myself. And this means
>learning about TL/TCL I am going to bet.
>
>So in this thread, I invite 101 level information about the subject in
>general, and any tutoring on the subject you care to provide.
>


http://www.ferg.org/thinking_in_tkinter/

_________________________________________________________________
Protect your PC - get McAfee.com VirusScan Online 
http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963


From isrgish at fusemail.com  Thu Jan 22 21:11:50 2004
From: isrgish at fusemail.com (Isr Gish)
Date: Thu Jan 22 21:11:53 2004
Subject: [Tutor] Problem reading from a file
Message-ID: <E1AjqnF-0007yU-Vy@fuse1.fusemail.net>

Thanks Danny.

Best Wishes
Isr

-----Original Message-----
   >From: "Danny Yoo"<dyoo@hkn.eecs.berkeley.edu>
   >Sent: 1/22/04 1:26:22 PM
   >To: "Isr Gish"<isrgish@fusemail.com>
   >Cc: "tutor@python.org"<tutor@python.org>
   >Subject: Re: [Tutor] Problem reading from a file
     >
   >
   >On Thu, 22 Jan 2004, Isr Gish wrote:
   >
   >> I have a registry file that I'm trying to read. But it is only reading
   >> part of the file. When it comes to certain text it stops reading. (I
   >> would send along the file but the list doesn't let send attachments).
   >
   >Hi Isr,
   >
   >
   >Registry files are 'binary' files, and on Windows systems, this detail
   >matters --- Python may be mistakenly trying to treat the registry file as
   >a 'text' file.  Are you opening the files in binary mode?
   >
   >
   >
   >Good luck to you!
   >
   >
   >


From dyoo at hkn.eecs.berkeley.edu  Thu Jan 22 21:16:14 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Jan 22 21:16:20 2004
Subject: [Tutor] Answers to homework assignments?  No!
In-Reply-To: <m3ad4fcwn9.fsf@hamster.pflaesterer.de>
Message-ID: <Pine.LNX.4.44.0401221729480.29396-100000@hkn.eecs.berkeley.edu>



> [Code]
>
> here is another solution; it's a bit nearer to the imperative one.  It
> uses reduce with a default value (it wil also be a bit faster than the
> first one).

[solution cut]


Hi Karl,


I know this post is preachy, but it's something that I need to say: if you
think that someone's asking a question because it's a homework assignment,
and if you realy want to help that person, please don't give direct
solutions.


In this case, Chris has explictely stated that it's homework, so we don't
even have to guess.  It's homework, and most online communities will treat
such questions, for the most part, as out-of-bounds:

    http://www.catb.org/~esr/faqs/smart-questions.html#homework


Chris is having problems with the assigment because there's an obstacle
somewhere in his knowledge.  The best thing we can do for him is to
identify those obstacles, and show him good climbing techniques that apply
to more than that single problem instance.


But to just skylift him by helicopter and drop him across doesn't help him
in the long run.  In fact, it does him great harm.


I personally do get excited myself by questions, so much that that I
occasionally blurt out an answer, too.  But most of the time, I try to
resist and to keep John Holt's "How Children Fail" in mind:

    http://educationreformbooks.net/failure.htm


It is not cruel to not give an immediate answer to a question.



Talk to you later!


From rmangaliag at slu.edu.ph  Thu Jan 22 22:36:38 2004
From: rmangaliag at slu.edu.ph (ali)
Date: Thu Jan 22 22:31:01 2004
Subject: [Tutor] report ala jasper
Message-ID: <004b01c3e162$1ccc46e0$da19a8c0@slu.edu.ph>

is there a python counterpart to jasperreports of java?

thanks...


From cspears2002 at yahoo.com  Thu Jan 22 23:39:42 2004
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Thu Jan 22 23:39:46 2004
Subject: [Tutor] using the reduce function
In-Reply-To: <m33ca7h6j8.fsf@hamster.pflaesterer.de>
Message-ID: <20040123043942.7107.qmail@web12406.mail.yahoo.com>

Thanks for the help!  I actually did not expect to be
given the answer.  That would be cheating.  However,
the suggestions concerning the basic logic of the
problem were really helpful.

I do have a question.  What is the difference between
functional logic and the imperative style of logic.

-Chris

=====
"I'm the last person to pretend that I'm a radio.  I'd rather go out and be a color television set."
-David Bowie

"Who dares wins"
-British military motto

"Far more creativity, today, goes into the marketing of products than into the products themselves..."
-"Pattern Recognition" by William Gibson

From peterabrown at froggy.com.au  Thu Jan 22 23:51:03 2004
From: peterabrown at froggy.com.au (Peter Brown)
Date: Thu Jan 22 23:50:59 2004
Subject: [Tutor] using the reduce function
In-Reply-To: <20040123043942.7107.qmail@web12406.mail.yahoo.com>
References: <m33ca7h6j8.fsf@hamster.pflaesterer.de>
	<20040123043942.7107.qmail@web12406.mail.yahoo.com>
Message-ID: <6.0.0.22.0.20040123154834.02d3bdb0@mail.froggy.com.au>

Chris,

You really should use Google to do searching. If you do this you will learn 
so much faster.

I just googled and there was a wealth of information available to answer 
your questions.

If you don't know how to use advanced google I would be happy to show you how.

Peter

At 20:39 22/01/04 -0800, you wrote:
>Thanks for the help!  I actually did not expect to be
>given the answer.  That would be cheating.  However,
>the suggestions concerning the basic logic of the
>problem were really helpful.
>
>I do have a question.  What is the difference between
>functional logic and the imperative style of logic.
>
>-Chris
>
>=====
>"I'm the last person to pretend that I'm a radio.  I'd rather go out and 
>be a color television set."
>-David Bowie
>
>"Who dares wins"
>-British military motto
>
>"Far more creativity, today, goes into the marketing of products than into 
>the products themselves..."
>-"Pattern Recognition" by William Gibson
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor

Peter Brown
CEO
IP Telephonics 



From dyoo at hkn.eecs.berkeley.edu  Fri Jan 23 00:33:11 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri Jan 23 00:33:17 2004
Subject: [Tutor] using the reduce function
In-Reply-To: <20040123043942.7107.qmail@web12406.mail.yahoo.com>
Message-ID: <Pine.LNX.4.44.0401222122170.23457-100000@hkn.eecs.berkeley.edu>



On Thu, 22 Jan 2004, Christopher Spears wrote:

> What is the difference between functional logic and the imperative style
> of logic.

Hi Christopher,

David Mertz has written a lot of articles on functional programming in
Python.  He's a functional programming nut... in a good way!  *grin*

His series is a good introduction:

    http://www-106.ibm.com/developerworks/linux/library/l-prog.html
    http://www-106.ibm.com/developerworks/library/l-prog2.html


John Hughes has written a very readable paper called "Why Functional
Programming Matters":

    http://www.math.chalmers.se/~rjmh/Papers/whyfp.html

Although it was written in the 1980's, it's still quite fresh.  Hughes
gives concrete examples of the functional style of programming in
real-life situations, and where functional programming can really pay off.
Highly recommended.


Good luck to you!


From alan.gauld at blueyonder.co.uk  Fri Jan 23 03:15:26 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Fri Jan 23 03:14:48 2004
Subject: [Tutor] front end 101
References: <40102A41.2010203@netzero.net>
Message-ID: <003f01c3e189$0ebea490$6401a8c0@xp>

> that did not talk to the world through html and a browser, and I am
> tired of tripping over this limitation in myself. And this means
> learning about TL/TCL I am going to bet.

I assume you mean Tcl/Tk? The toolkit behind Tkinter?
In fact the Tkinter stuff is so well done that you very
rarely need to delve into Tcl.

> So in this thread, I invite 101 level information about the subject
in
> general, and any tutoring on the subject you care to provide.

Visit my tutor and look at the GUI page. It covers the most
basic concepts of GUIs in general, some simple Tkinter scripts
and a comparison with wxPython.

The semi-official tutor on Tkinter (linked from the Tkinter
area of python.org) will then provide the detail needed to
dig deeper.

Once you undestand the basics you might then want to invrestigate
a GUI builder like Glade or PyCard. I've never used Glade for
anything serious but I see good reports about it from others.

Alan G.


From alan.gauld at blueyonder.co.uk  Fri Jan 23 03:18:09 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Fri Jan 23 03:17:31 2004
Subject: [Tutor] writing a function
References: <20040122223344.50235.qmail@web12401.mail.yahoo.com>
Message-ID: <004601c3e189$6fbf6810$6401a8c0@xp>

> This is a programming problem that I have been given:
> 
> Write a function that accepts an arbitrary number of
> lists and returns a single list with exactly one
> occurrence of each element that appears in any of the
> input lists.
> 
> For some reason, this problem has left me stumped. 
> Suggestions, anyone?

Assuming the hard bit is how to get a function with 
an arbitrary number of lists as argument then go look 
at the *args stuff in the official tutor.

One you have your list of lists the rest can be done 
easily using a dictionary or, in 2.3, the new set type.

Alan G.

From alan.gauld at blueyonder.co.uk  Fri Jan 23 03:22:22 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Fri Jan 23 03:21:43 2004
Subject: [Tutor] using the reduce function
References: <20040122233156.61832.qmail@web12404.mail.yahoo.com>
Message-ID: <004d01c3e18a$06714990$6401a8c0@xp>


> Yet another homework problem is giving me fits.  Here
> it goes:

Coz its homework I'll only give a clue...

> Use the reduce function to find the length of the
> longest string in a list of strings.

Reduce takes the first two elements of a list and 
replaces them with the result of a function, then 
repeats until the list is single valued.

So to get the longest string just compare two 
strings and return the longest one. The final list 
contains the longest string in the original list.

Easy... :-)

Take a look at the Functional Programming page of 
my tutor for more on reduce() and its friends.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld

From alan.gauld at blueyonder.co.uk  Fri Jan 23 05:08:04 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Fri Jan 23 05:07:24 2004
Subject: [Tutor] using the reduce function
References: <20040123043942.7107.qmail@web12406.mail.yahoo.com>
Message-ID: <007901c3e198$ca7798e0$6401a8c0@xp>

> I do have a question.  What is the difference between
> functional logic and the imperative style of logic.

My Functional Programming page gives a quick overview 
of the diffenences in philosophy.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld

From saadijani at hotmail.com  Fri Jan 23 05:21:52 2004
From: saadijani at hotmail.com (sweet cute)
Date: Fri Jan 23 05:21:56 2004
Subject: [Tutor] Error While installing Thuban!!
Message-ID: <BAY2-F64QyrmsrVJ17l00043c29@hotmail.com>

Hi,
I am Adnan Younas from Malaysia, I was having problems while installing 
thuban pre-requsites its ok now for some things but now i m facing problems 
with Pysqlite and thuban when i give the command "python setup.py buildl" or 
"python setup.py Install" or "python setup.py Install_local" it gives me 
error of " command 'cl.exe' failed: No such file or directory"..............
can any one pls help me in this regard.....i'll be thankfull for any help in 
this regard.....waiting for reply,
bye.
Adnan Younas
MS Student ("GIS")
Information System Department,
Faculty of computer Science and Information System,
Universiti Teknologi Malaysia

_________________________________________________________________
MSN 8 with e-mail virus protection service: 2 months FREE* 
http://join.msn.com/?page=features/virus


From darnold02 at sprynet.com  Fri Jan 23 06:36:01 2004
From: darnold02 at sprynet.com (don arnold)
Date: Fri Jan 23 06:36:10 2004
Subject: [Tutor] using the reduce function
References: <20040122233156.61832.qmail@web12404.mail.yahoo.com><m33ca7h6j8.fsf@hamster.pflaesterer.de>
	<m3ad4fcwn9.fsf@hamster.pflaesterer.de>
Message-ID: <113201c3e1a5$149c31e0$2e11ba3f@don2uvsu54fwiq>


----- Original Message -----
From: "Karl Pfl?sterer" <sigurd@12move.de>
To: <tutor@python.org>
Sent: Thursday, January 22, 2004 6:57 PM
Subject: Re: [Tutor] using the reduce function


On 23 Jan 2004, Karl Pfl?sterer <- sigurd@12move.de wrote:

[Code]

here is another solution; it's a bit nearer to the imperative one.  It
uses reduce with a default value (it wil also be a bit faster than the
first one).

def longer2 (ln, seq):
    lns = len(seq)
    if ln > lns: return ln
    else: return lns

def longest2 (seq):
    return reduce(longer2, seq, 0)


I think there is no further explaination necessary.


   Karl
--

[my reply:]

I may be off-base here (since I've never used reduce() before), but can't
you just do this:

>>> reduce(lambda x,y: max(x,len(y)),['123456','23','1234567','1'],0)
7

Don


From Janssen at rz.uni-frankfurt.de  Fri Jan 23 07:47:49 2004
From: Janssen at rz.uni-frankfurt.de (Michael Janssen)
Date: Fri Jan 23 07:48:07 2004
Subject: [Tutor] using the reduce function
In-Reply-To: <6.0.0.22.0.20040123154834.02d3bdb0@mail.froggy.com.au>
References: <m33ca7h6j8.fsf@hamster.pflaesterer.de>
	<20040123043942.7107.qmail@web12406.mail.yahoo.com>
	<6.0.0.22.0.20040123154834.02d3bdb0@mail.froggy.com.au>
Message-ID: <Pine.A41.4.56.0401231253250.78520@hermes-22.rz.uni-frankfurt.de>

On Fri, 23 Jan 2004, Peter Brown wrote:

> You really should use Google to do searching. If you do this you will learn
> so much faster.

and a second possibility is to bring this question (what is the
functional programming paradigm) back to school/university. It seems a
bit odd, when your educational insitute gives you homework that leads to
functional programming but doesn't discuss the why and when.

Would be sad education where you have to work on how you can "do
something just another way" for school but find out the why on your
own with google.

Christopher, was this homework given in a class, that will explore
functional programming or was it just for additional work ala "We know
how to do it obvious, now try it nonobviously"? Just curious.

Michael

From magnus at thinkware.se  Fri Jan 23 07:49:29 2004
From: magnus at thinkware.se (Magnus Lycka)
Date: Fri Jan 23 07:49:36 2004
Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gRXJyb3IgV2hpbGUgaW5zdGFsbGluZyBUaHViYW4hIQ==?=
Message-ID: <think001_4011170945565@webmail.thinkware.se>

Adnan Younas wrote:
> I am Adnan Younas from Malaysia, I was having problems while installing 
> thuban pre-requsites its ok now for some things but now i m facing problems 
> with Pysqlite and thuban when i give the command "python setup.py buildl" or 
> "python setup.py Install" or "python setup.py Install_local" it gives me 
> error of " command 'cl.exe' failed: No such file or directory".............
> can any one pls help me in this regard.....i'll be thankfull for any help in 
> this regard.....waiting for reply,
> bye.

cl.exe is Microsoft's C/C++ compiler/linker. The setup script obviously
needs to compile and/or link C or C++ code.

If you have MS Visual Studio installed and get this problem, there is
a problem with your environment setup in Windows. The same problem
should occur if you try to build C or C++ soruce code at a command
prompt.

If you don't have access to MS Visual Studio, you need to find a
setup with compiled binaries, or--if possible, change the setup
script to use some other C or C++ compiler / linker.

I don't know anything about Thuban, so I can't help you much further.

-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se

From magnus at thinkware.se  Fri Jan 23 09:53:28 2004
From: magnus at thinkware.se (Magnus Lycka)
Date: Fri Jan 23 09:53:35 2004
Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gcmVwb3J0IGFsYSBqYXNwZXI=?=
Message-ID: <think001_40112e83273ff@webmail.thinkware.se>

> is there a python counterpart to jasperreports of java?

I guess RML2PDF is the closest, but it costs thousands of
dollars...

It's based on ReportLab, which is free though. ReportLab 
is a fairly generic PDF API, and it's not more aimed at 
producing reports than CAD drawings or books. Actually,
I think the same could be said about RML2PDF, but it's 
XML-based (like Jasper), while ReportLab is a Python API.

See www.reportlab.com

If you are using Windows, you can also use the COM interface
in win32all to feed data into Excel etc.

-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se

From cspears2002 at yahoo.com  Fri Jan 23 10:30:48 2004
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Fri Jan 23 10:30:52 2004
Subject: [Tutor] using the reduce function
In-Reply-To: <Pine.A41.4.56.0401231253250.78520@hermes-22.rz.uni-frankfurt.de>
Message-ID: <20040123153048.42849.qmail@web12407.mail.yahoo.com>

I'm taking an online course through UC Berkeley
Extensions.  We have arrived at the section on
functions.  Hence, the assignments...  I was told that
you need some programming experience for the class.  I
don't really have any programming experience though I
have learned to shell script and have been playing
with MEL (Maya's scripting language).

-Chris

=====
"I'm the last person to pretend that I'm a radio.  I'd rather go out and be a color television set."
-David Bowie

"Who dares wins"
-British military motto

"Far more creativity, today, goes into the marketing of products than into the products themselves..."
-"Pattern Recognition" by William Gibson

From tpc at csua.berkeley.edu  Fri Jan 23 13:25:16 2004
From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu)
Date: Fri Jan 23 13:25:47 2004
Subject: [Tutor] difference between signed integers and unsigned integers
In-Reply-To: <20040121083450.Q20242-100000@localhost.name>
Message-ID: <20040123101146.F37018-100000@localhost.name>


hi Hameed, I wanted to correct an erroneous statement I made before
about an unsigned data type having more combinations than a signed data
type.  That is untrue.  A signed data type will have the same range as an
unsigned data type because the signed data type has negative values as
well as positive, whereas the signed data type has only positive.
Let's say you have a 3 bit data type, one signed the other unsigned.
The possible combinations for this unsigned is 2^3 with a range of
0 to (2^3 - 1):

0, 1, 2, 3, 4, 5, 6, 7

while the possible combinations unsigned is also 2^3 with a range of -2^2
to 2^2:

-4, -3, -2, -1, 0, 1, 2, 3, 4

Sorry for the confusion.  I hope that helps you.

On Wed, 21 Jan 2004 tpc@csua.berkeley.edu wrote:

>
> hi Hameed,
>
> Signed integers have one bit allocated to indicate whether the value is
> positive or negative.  Unsigned integers do not.  The difference between
> them is in certain languages with data types of a specific size, an
> unsigned data type can hold more combinations than a signed value.  If
> you think of a byte as eight switches, each with the on or off showing,
> then a signed byte will have only 7 boxes to store values, as opposed to
> the unsigned byte which will have 8 boxes.
>
> I hope that helps you.
>
> On Wed, 21 Jan 2004, Hameed Khan wrote:
>
> > Hi,
> >   i know my question is not directly related to
> > python. but i just have started the programming in
> > python. so i am not a profesional programmer or an
> > expert. and i am only subscribed to the python's
> > mailing lists. thats why i am asking this question on
> > this list. i want to know what are signed and unsigned
> > integers and what is the difference between them.
> >
> > Thanks,
> > Hameed Khan
> >
> > =====
> > _____________________
> >  Hameed Ullah Khan
> >
> > *Try not to become a man of success but rather to become a man of value.*
> > Albert Einstein
> >
> > __________________________________
> > Do you Yahoo!?
> > Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes
> > http://hotjobs.sweepstakes.yahoo.com/signingbonus
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
>
>


From hcohen2 at comcast.net  Fri Jan 23 15:29:14 2004
From: hcohen2 at comcast.net (hcohen2)
Date: Fri Jan 23 15:31:24 2004
Subject: [Tutor] Need suggestions on how to join a Python project.
Message-ID: <4011841A.5090508@comcast.net>

Everyone:

I know the standard method: propose patches to existing code.  That 
usually takes a considerable period of time and a skill level I have not 
yet obtained.

I have some free time to really learn python this time, and for me 
working on a real project accerates the process.  The down side would be 
that I would require some extra effort directing my work.  However, in 
the longer term I could become an asset.  Moreover, I have well nearly 
fifteen years experience as a professional coder.

Anyone have any ideas?   (Forget Ask Slashdot, my post was rejected.)

Thanks,
Herschel



From bwinton at latte.ca  Fri Jan 23 15:44:55 2004
From: bwinton at latte.ca (Blake Winton)
Date: Fri Jan 23 15:45:31 2004
Subject: [Tutor] Need suggestions on how to join a Python project.
In-Reply-To: <4011841A.5090508@comcast.net>
Message-ID: <002d01c3e1f1$c2154e50$6401a8c0@phantomfiber.com>

> I know the standard method: propose patches to existing code.
> That usually takes a considerable period of time and a skill
> level I have not yet obtained.
> 
> I have some free time to really learn python this time, and
> for me working on a real project accerates the process.  The
> down side would be that I would require some extra effort
> directing my work.  However, in the longer term I could become
> an asset.  Moreover, I have well nearly fifteen years
> experience as a professional coder.
> 
> Anyone have any ideas?   (Forget Ask Slashdot, my post was rejected.)

Ask Slashdot.  ;)

Okay, seriously, is there a project related to anything you're
interested in?

If you're just looking for ideas, I'ld love to see a plugin
for PyBlosxom (http://roughingit.subtlehints.net/pyblosxom/ )
that outputs an RSS2 feed of the comments for a particular
entry.  I've got some sample code that outputs the RSS2 feed
for the comments for all the entries, so it just needs to be
modified to take into account the extra path information, and
use it when generating the rss.  Feel free to email me personally,
or the whole PyBlosxom Developer's List with whatever you come
up with.

As a side note, PyBlosxom was started as a learning project by
the main developer.  He certainly got a lot of good feedback as
people started adding code to the project, and planning out
code changes for later releases.

Later,
Blake.


From cspears2002 at yahoo.com  Fri Jan 23 16:02:51 2004
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Fri Jan 23 16:05:17 2004
Subject: [Tutor] using the reduce function
In-Reply-To: <007901c3e198$ca7798e0$6401a8c0@xp>
Message-ID: <20040123210251.8371.qmail@web12402.mail.yahoo.com>

Thanks!  Your webpage was very insightful.

-Chris

=====
"I'm the last person to pretend that I'm a radio.  I'd rather go out and be a color television set."
-David Bowie

"Who dares wins"
-British military motto

"Far more creativity, today, goes into the marketing of products than into the products themselves..."
-"Pattern Recognition" by William Gibson

From scot at possum.in-berlin.de  Fri Jan 23 16:07:29 2004
From: scot at possum.in-berlin.de (Scot W. Stevenson)
Date: Fri Jan 23 16:15:07 2004
Subject: [Tutor] Figuring out a protocol for fun and education
Message-ID: <200401232207.29267.scot@possum.in-berlin.de>

Hello there, 

SuSE Linux includes a little program called "smpppd" (SuSE Meta PPP Daemon) 
that controls several internet connections: You have one machine (with 
smpppd) that actually can start the connection for your network, and a bunch 
of other machines on your little local net that can tell this machine to do 
so (called cinternet for the command line or kinternet for KDE). In KDE, for 
example, you just click a little plug icon in the lower left corner, and 
stuff happens.

For obvious reasons there are no versions of this program for Windows, and I 
still have one Windows machine on my network (soon to be replaced with a 
Mac, but the problem will be the same). Doing "telnet" everytime is a 
bummer, and so I want to write my own version of cinternet, and of course I 
want to do it in Python. All of these programs are GPL and I have the source 
sitting around here, so in theory all I have do is sit down and wade through 
the C and C++ code and rewrite the result in Python.

But then I started wondering if it wouldn't be more fun to try to figure out 
the protocol the hard way, by playing around with the setup and analyzing 
the responses the server is giving. I was wondering if anybody here could 
give me some suggestions on how to do this best, as I know absolutely zip 
about what to expect in a protocol such as this one.

So far, I have been testing the server (smpppd) by trying to send it codes to 
get a response with this little snippet:
==================================
import socket

socket.setdefaulttimeout(30)

HOST = '192.168.1.20'
SOCKET = 3185

sockobj = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sockobj.connect((HOST, SOCKET))

while True:
    message = raw_input('Message: ')
    if message == 'quit':
        break
    sockobj.send(message)
    data = sockobj.recv(1024)
    print 'Got ', data

sockobj.close()
===================================
(Note this is Python 2.3). The first time I send something -- anything -- I 
get "SuSE Meta pppd (smpppd), Version 1.00" as a response, which proves that 
I'm reaching the right socket etc. However, anything after that is met with 
silence until the time out is reached.

Since this is getting frustrating, I'm wondering about creating a transparent 
proxy instead, that I would do nothing more than pass along the stuff it 
receives from cinternet to smpppd and vice versa while printing out a log of 
what it is doing. Haven't gotten around to coding it yet, though.

This can't be a new problem, and I wonder if there is a standard way of 
approaching it that I am simply not aware of and somebody could point me to 
before I get too frustrated and just read the code. Again, this is not a 
cracking attempt of any sort -- the original author of smpppd is given as 
Arvin Schnell <arvin@suse.de>, if anybody wants to check with him -- but an 
exercise in problem solving. 

And yes, I spend way too much time reading Poe's "The Goldbug" when I was 
younger...

Thank you for any pointers,
Y, Scot

-- 
                Scot W. Stevenson - Panketal, Germany


From sigurd at 12move.de  Fri Jan 23 16:16:55 2004
From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=)
Date: Fri Jan 23 16:22:54 2004
Subject: [Tutor] using the reduce function
In-Reply-To: <113201c3e1a5$149c31e0$2e11ba3f@don2uvsu54fwiq> (don arnold's
	message of "Fri, 23 Jan 2004 05:36:01 -0600")
References: <20040122233156.61832.qmail@web12404.mail.yahoo.com>
	<m33ca7h6j8.fsf@hamster.pflaesterer.de>
	<m3ad4fcwn9.fsf@hamster.pflaesterer.de>
	<113201c3e1a5$149c31e0$2e11ba3f@don2uvsu54fwiq>
Message-ID: <m3k73iiczd.fsf@hamster.pflaesterer.de>

On 23 Jan 2004, don arnold <- darnold02@sprynet.com wrote:

> I may be off-base here (since I've never used reduce() before), but can't
> you just do this:

>>>> reduce(lambda x,y: max(x,len(y)),['123456','23','1234567','1'],0)

Sure you can.  There are multiple solutions possible; which one you
choose may be a matter of taste and simply the fact that in that moment
I didn't thouhgt of Python having `max'.  So I wrote it myself.


   Karl
-- 
Please do *not* send copies of replies to me.
I read the list


From sigurd at 12move.de  Fri Jan 23 16:40:47 2004
From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=)
Date: Fri Jan 23 16:43:40 2004
Subject: [Tutor] Answers to homework assignments?  No!
In-Reply-To: <Pine.LNX.4.44.0401221729480.29396-100000@hkn.eecs.berkeley.edu>
	(Danny Yoo's message of "Thu, 22 Jan 2004 18:16:14 -0800 (PST)")
References: <Pine.LNX.4.44.0401221729480.29396-100000@hkn.eecs.berkeley.edu>
Message-ID: <m3fze6icvl.fsf@hamster.pflaesterer.de>

On 23 Jan 2004, Danny Yoo <- dyoo@hkn.eecs.berkeley.edu wrote:

> think that someone's asking a question because it's a homework assignment,
> and if you realy want to help that person, please don't give direct
> solutions.

Most of ther time I don't but here I saw no harm in doing so.  The OP
was so honest to state it was homework but he also showed that he had
first tried finding a solution himself.  That's not the kind of question
you imagine if you think of the typical homework question: 'Hi folks; My
friend has such and such problem; Who can write a solution'.  If I read
something like this I don't answer.

> In this case, Chris has explictely stated that it's homework, so we don't
> even have to guess.  It's homework, and most online communities will treat
> such questions, for the most part, as out-of-bounds:

Well but we are individuals and have to decide each on our own if is
approbiate to naswer or not and if yes in what way we answer.

>     http://www.catb.org/~esr/faqs/smart-questions.html#homework

I know these papers from ESR (if simply he wouldn't have such an odd
attitude concerning weapons (but that absolutely OT here)).  His 'smart
questions' is a good paper (sometimes a bit harsh).

> Chris is having problems with the assigment because there's an obstacle
> somewhere in his knowledge.  The best thing we can do for him is to
> identify those obstacles, and show him good climbing techniques that apply
> to more than that single problem instance.

Maybe yes maybe no.  In nearly every case I would write the same as you
(here I'm a bit biased :-) ) but don't forget sometimes the easiest way
to understanding is a clear and simple solution.

> But to just skylift him by helicopter and drop him across doesn't help him
> in the long run.  In fact, it does him great harm.

Here in that case I didn't saw it that way; above I explained why.  I
first thought about rot13 the answers (as kind of spoiler space) but
decided then against it.

> resist and to keep John Holt's "How Children Fail" in mind:

>     http://educationreformbooks.net/failure.htm

I don't know the book; at first glance it seems to be reasonable.  But I
don't want to say more since I didn't read it (only the abstract) and
because that's absolutely OT here (as my answer).

So if you think there's more to say please use pm so not to disturb the
mailing list.


   Karl
-- 
Please do *not* send copies of replies to me.
I read the list


From dyoo at hkn.eecs.berkeley.edu  Fri Jan 23 16:46:58 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri Jan 23 16:47:04 2004
Subject: [Tutor] using the reduce function
In-Reply-To: <m3k73iiczd.fsf@hamster.pflaesterer.de>
Message-ID: <Pine.LNX.4.44.0401231330280.26186-100000@hkn.eecs.berkeley.edu>



On Fri, 23 Jan 2004, Karl [iso-8859-1] Pfl=E4sterer wrote:

> On 23 Jan 2004, don arnold <- darnold02@sprynet.com wrote:
>
> > I may be off-base here (since I've never used reduce() before), but can=
't
> > you just do this:
>
> >>>> reduce(lambda x,y: max(x,len(y)),['123456','23','1234567','1'],0)
>
> Sure you can.  There are multiple solutions possible; which one you
> choose may be a matter of taste and simply the fact that in that moment
> I didn't thouhgt of Python having `max'.  So I wrote it myself.


Hi Karl,


Not only can max take in two arguments, but it can also take in a list as
input:


###
>>> max([3, 5, 42, 19, 255, 91])
255
###


If we aren't forced to use reduce(), then Chris's max-string-length
problem ends up being a concise and pretty combination of the len(),
map(), and max() functions.  Chris, if you know already about map(), try
it out.


Functional programming is nice because of its emphasis on powerful
function composition.



Hope this helps!


From project5 at redrival.net  Fri Jan 23 16:47:20 2004
From: project5 at redrival.net (Andrei)
Date: Fri Jan 23 16:50:43 2004
Subject: [Tutor] Re: Need suggestions on how to join a Python project.
References: <4011841A.5090508@comcast.net>
Message-ID: <1lyyuu7xc2y65.1eks9v0nhama5.dlg@40tude.net>

hcohen2 wrote on Fri, 23 Jan 2004 15:29:14 -0500:

<snip>
> I have some free time to really learn python this time, and for me 
> working on a real project accerates the process.  The down side would be 
> that I would require some extra effort directing my work.
<snip>
> Anyone have any ideas?   (Forget Ask Slashdot, my post was rejected.)

I don't know if you're interested in GUI stuff, but my suggestions concern
wxPy-based projects. 
- Spe (http://spe.pycs.net/): I think it's a very promising and useful
project. 
- wxGlade (http://wxglade.sourceforge.net/) is also a very good one - you
could probably start on something relatively small, like adding support for
a single widget to it. 
- A wxPy port of EasyGUI (http://www.ferg.org/easygui/) - this would be
something really easy to do.
- Boa (http://boa-constructor.sourceforge.net/) - for the really big stuff

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.


From lumbricus at gmx.net  Fri Jan 23 18:00:29 2004
From: lumbricus at gmx.net (=?ISO-8859-1?Q?=22J=F6rg_W=F6lke=22?=)
Date: Fri Jan 23 18:00:35 2004
Subject: [Tutor] Figuring out a protocol for fun and education
References: <200401232207.29267.scot@possum.in-berlin.de>
Message-ID: <4515.1074898829@www28.gmx.net>

> Hello there, 

Hallo!

[ snip ]

> import socket
> 
> socket.setdefaulttimeout(30)
> 
> HOST = '192.168.1.20'
> SOCKET = 3185
> 
> sockobj = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> sockobj.connect((HOST, SOCKET))
> 
> while True:
>     message = raw_input('Message: ')
>     if message == 'quit':
>         break
>     sockobj.send(message)
>     data = sockobj.recv(1024)
>     print 'Got ', data
> 
> sockobj.close()
> ===================================
> (Note this is Python 2.3). The first time I send something -- anything --
> I 
> get "SuSE Meta pppd (smpppd), Version 1.00" as a response, which proves
> that 
> I'm reaching the right socket etc. However, anything after that is met
> with 
> silence until the time out is reached.

Is there a line terminator at the end of the message you send ("\015\012")?
Perhaps you need to flush the output filedescriptor after sending?
 
> Since this is getting frustrating, I'm wondering about creating a
> transparent 
> proxy instead, that I would do nothing more than pass along the stuff it 
> receives from cinternet to smpppd and vice versa while printing out a log
> of 
> what it is doing. Haven't gotten around to coding it yet, though.
> 
> This can't be a new problem, and I wonder if there is a standard way of 
> approaching it that I am simply not aware of and somebody could point me
> to 
> before I get too frustrated and just read the code.

man tcpdump

[ snip ]

> Thank you for any pointers,
> Y, Scot

HTH und Gruss, J"o!

-- 
Sie d?rfen diesen Satz zitieren.

+++ GMX - die erste Adresse f?r Mail, Message, More +++
Bis 31.1.: TopMail + Digicam f?r nur 29 EUR http://www.gmx.net/topmail


From arkamir at softhome.net  Fri Jan 23 17:56:09 2004
From: arkamir at softhome.net (Conrad Koziol)
Date: Fri Jan 23 18:14:25 2004
Subject: [Tutor] Cgi Fieldstorage cant get quotes-Solution
In-Reply-To: <4010BB0B.1050707@netzero.net>
References: <1074730644.5065.15.camel@conradpc>
	<4010263D.9030101@netzero.net> <1074820391.4332.55.camel@conradpc>
	<4010BB0B.1050707@netzero.net>
Message-ID: <1074897761.9756.3.camel@conradpc>

Thanks a lot Kirk Bailey for the help. Heres the final solution:

class Form_filter(Top):
	def __init__(self):
		super(Form_filter, self).__init__()
	def filter(self):
		illegal = {r'"': r'\"', r"'": r'\''}
		regex = re.compile('|'.join(map(re.escape, illegal.keys())))
		for item in self.dict.keys():
			self.dict[item] = regex.sub(lambda match: illegal[match.group(0)],
self.dict[item])
		

I think my email client is going to mess it up. :(
It basically the Replacing multiple patterns in a single pass Cookbook
recipe wiht a slight modification. Self.dict is where i store my form
values.There basically the fieldstorage values put into a dictionary for
easier use.


From helena_b2001 at yahoo.com  Fri Jan 23 20:08:10 2004
From: helena_b2001 at yahoo.com (helena bhaska)
Date: Fri Jan 23 20:08:14 2004
Subject: [Tutor] python at boot time
Message-ID: <20040124010810.5661.qmail@web20421.mail.yahoo.com>

Hi,
I wrote a python program that I would like to start
running at boot time.  I tried adding a line like
this:
python program.py & 
to rc.local - however that doesn't work.  What is the
correct way to do this?
Thanks!

__________________________________
Do you Yahoo!?
Yahoo! SiteBuilder - Free web site building tool. Try it!
http://webhosting.yahoo.com/ps/sb/

From fleming.j at comcast.net  Fri Jan 23 20:25:31 2004
From: fleming.j at comcast.net (john fleming)
Date: Fri Jan 23 20:26:22 2004
Subject: [Tutor] Need suggestions on how to join a Python project.
In-Reply-To: <4011841A.5090508@comcast.net>
References: <4011841A.5090508@comcast.net>
Message-ID: <4011C98B.7030507@comcast.net>

hcohen2 wrote:

> Everyone:
>
> I know the standard method: propose patches to existing code.  That 
> usually takes a considerable period of time and a skill level I have 
> not yet obtained.
>
> I have some free time to really learn python this time, and for me 
> working on a real project accerates the process.  The down side would 
> be that I would require some extra effort directing my work.  However, 
> in the longer term I could become an asset.  Moreover, I have well 
> nearly fifteen years experience as a professional coder.
>
> Anyone have any ideas?   (Forget Ask Slashdot, my post was rejected.)


This isn't exactly what you are asking but I have been waiting for an 
appropriate way to ask this in a general post. I am still a begging 
programer ,python being my first language and the one I would like to 
concentrate on. I  have been frustrated with some of  the  lists I have 
been on because they consist of dissccusions about little snippets for 
begginers or stuff over my head.

   I have a website through an offer from 1&1, and would like to start 
an interactive python tutor site
that has members post code and answer questions from newer members (one 
of which would be me), and at the same time build an open source 
project. I can see the possibilities branch off and mushroom from there.

 My longest range interest is to get an understanding of game engines 
with a python api. But that is a
looooonnnng way from where I am an it would probably get past my 
understang fast, although
if I were farther along I would  branch the Quake-Darkplaces engine and 
build an api to that
so if  anyone is into that sort of thing or headed that way let me know. 
I happen to know Joseph
Carter who worked on the port of Quake to linux and he might be willing 
to make some suggestions here and there if that project were to jell 
somehow. The book on python game programming by Sean Riley might fit 
into that somewhere.

  Another thing that would help me would be a networking project that 
would offer an opportunity to learn the basics of network programming 
with python from the ground up. Maybe start with a chat program as a 
tutorial. Then explore the pyblosxom example or various other RSS2 apps 
after several newbies were following along sucessfully.

Livewires,or pygsear would also be fun ones to explore starting with 
small games and grow as we go.

  So anyone interested?
                                                                                                                         
John F.
   

>  
>




From shaleh at speakeasy.net  Fri Jan 23 21:38:35 2004
From: shaleh at speakeasy.net (Sean 'Shaleh' Perry)
Date: Fri Jan 23 21:38:51 2004
Subject: [Tutor] Help - Where and when to use OOP
In-Reply-To: <20040119073648.45020.qmail@web12208.mail.yahoo.com>
References: <20040119073648.45020.qmail@web12208.mail.yahoo.com>
Message-ID: <200401231838.35141.shaleh@speakeasy.net>

On Sunday 18 January 2004 23:36, Lakmi munasinghe wrote:
> Hi,
>
> I have a little exposure to OOP. I 'd like to know for what kind of
> programs that I should use OOP programming concepts and for what kind of
> programs that the stuctured programming would be more suited.
>
> As far as I know if we don't see any repeating processes in our system
> applying OOP programming will cause no effect.In such cases we should
> manage with structured programming with functions and procedures where
> necessary. Am I correct ?
>

From my experience I find OOP excels at GUI coding.  This is because, as Alan 
points out, you often refer to distinct things like "window", "mouse", 
"sprite", etc.

A lot of daemon / server code can be written either in procedural or OO 
fashion.  I tend to use procedural more often but then again I began life as 
a C coder.

I find OOP beneficial when I am sharing code because it is easy to wrap things 
up nicely and define safe points.

As for your project, will you have actors and things acting with / on them?  
An example from a programming class in college was a video rental system in 
which there were patron and video objects which acted on each other.


From klappnase at freenet.de  Fri Jan 23 22:24:08 2004
From: klappnase at freenet.de (Michael Lange)
Date: Fri Jan 23 22:32:21 2004
Subject: [Tutor] python at boot time
In-Reply-To: <20040124010810.5661.qmail@web20421.mail.yahoo.com>
References: <20040124010810.5661.qmail@web20421.mail.yahoo.com>
Message-ID: <20040124042408.30097e9a.klappnase@freenet.de>

On Fri, 23 Jan 2004 17:08:10 -0800 (PST)
helena bhaska <helena_b2001@yahoo.com> wrote:

> Hi,
> I wrote a python program that I would like to start
> running at boot time.  I tried adding a line like
> this:
> python program.py & 
> to rc.local - however that doesn't work.  What is the
> correct way to do this?
> Thanks!
> 
Hi Helena,

I guess the problem might be that your PATH has not been set when rc.local runs.
In this case try:

/usr/bin/python path-to-program.py &

instead (or the actual path to your python executable if it is not /usr/bin/python of course) .

I personally would prefer to put a #!/usr/bin/env python at the top of the script
and make it executable, so I could call it with just 

path-to-program.py &

(but that's probably just a matter of taste).

I hope this helped

Michael

From nicholas_wieland at yahoo.it  Fri Jan 23 22:40:24 2004
From: nicholas_wieland at yahoo.it (Nicholas Wieland)
Date: Fri Jan 23 22:36:19 2004
Subject: [Tutor] automating tests
Message-ID: <1074915624.2384.12.camel@debaser.pixie.home>

Hi all,
  I need to automate my unit testing, but before writing something I
want to know if there's something in the library, or if someone has
already solved this problem.
I have a /src and a /tests directory, the /src directory contains the
modules I need to test, the /tests directory, obviously, the tests, in
different files. All my tests use the standard unittest framework.
Can I use test.regrtest, or it's only for internal usage ?

TIA,
  nicholas


From littledanehren at yahoo.com  Fri Jan 23 23:01:10 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Fri Jan 23 23:01:17 2004
Subject: [Tutor] report ala jasper
In-Reply-To: <004b01c3e162$1ccc46e0$da19a8c0@slu.edu.ph>
Message-ID: <20040124040110.93396.qmail@web41809.mail.yahoo.com>


--- ali <rmangaliag@slu.edu.ph> wrote:
> is there a python counterpart to jasperreports of
> java?
> 
> thanks...

No, sorry. That's kinda like asking if there's a
Python version of OpenOffice. JasperReports is a
specific application that uses XML as a Java-specific
database. You can continue using JasperReports within
Python by using Jython (or this Java-to-CPython bridge
that I can't find).

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Yahoo! SiteBuilder - Free web site building tool. Try it!
http://webhosting.yahoo.com/ps/sb/

From lakmi_ll at yahoo.com  Fri Jan 23 23:20:40 2004
From: lakmi_ll at yahoo.com (Lakmi munasinghe)
Date: Fri Jan 23 23:20:45 2004
Subject: [Tutor] OOP programming using  VB
Message-ID: <20040124042040.74931.qmail@web12203.mail.yahoo.com>

Hi,
I have never done OO programming using VB . Anyway I have used OOP concepts with C++. I have no clear idea of how to use OOP concepts with VB forms and all, because I used to do programmimn in VB by writing codes to button clicks,combo box change event etc. I have heard that VB supports OOP ; but I have no idea of how it is done.
Can you give me an example of how it is being done ?
Lakmi



---------------------------------
Do you Yahoo!?
Yahoo! SiteBuilder - Free web site building tool. Try it!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20040123/ab72c44e/attachment.html
From carroll at tjc.com  Sat Jan 24 00:16:41 2004
From: carroll at tjc.com (Terry Carroll)
Date: Sat Jan 24 00:16:45 2004
Subject: [Tutor] Need suggestions on how to join a Python project.
In-Reply-To: <4011841A.5090508@comcast.net>
Message-ID: <Pine.LNX.4.44.0401232111510.23714-100000@violet.rahul.net>

On Fri, 23 Jan 2004, hcohen2 wrote:

> I know the standard method: propose patches to existing code.  That 
> usually takes a considerable period of time and a skill level I have not 
> yet obtained.

Not necessarily.  Try using a program you like and then think of what 
you'd like to have in it.

In my case, I was using nntplib, and found that I wished it had an option 
to return newsgroup headers to a file, rather than in memory (sometimes 
there can be a *lot* of headers).  I modified nntplib to acept a File 
parameter, and now it's part of Python 2.3.

(In fairness, all the heavy lifting was done by a previous developer who 
put in similar support, but only for the NNTP BODY command; I just 
extended it to the other NNTP commands, which turned out to be amazingly 
simple, given the prior work.)

-- 
Terry Carroll
Santa Clara, CA
carroll@tjc.com
Modell delendus est


From carroll at tjc.com  Sat Jan 24 00:59:12 2004
From: carroll at tjc.com (Terry Carroll)
Date: Sat Jan 24 00:59:16 2004
Subject: [Tutor] Figuring out a protocol for fun and education
In-Reply-To: <200401232207.29267.scot@possum.in-berlin.de>
Message-ID: <Pine.LNX.4.44.0401232154130.23714-100000@violet.rahul.net>

On Fri, 23 Jan 2004, Scot W. Stevenson wrote:

> 
> HOST = '192.168.1.20'
> SOCKET = 3185

> (Note this is Python 2.3). The first time I send something -- anything -- I 
> get "SuSE Meta pppd (smpppd), Version 1.00" as a response, which proves that 
> I'm reaching the right socket etc. However, anything after that is met with 
> silence until the time out is reached.

I find a nice way to play with this is to telnet to it, e.g.:

 telnet 192.1681.20 3185

and try your commands.

However, my guess is that the smpppd is not designed to be interrogated, 
and probably just is silent on unexpected input.  I'd cheat at least a 
little and look at the source code to the other implementations you have 
available; or at least the code to smpppd itself.

A lot of servers like to see two consecutive returns to end a command; 
you might want to try that.

> Since this is getting frustrating, I'm wondering about creating a transparent 
> proxy instead, that I would do nothing more than pass along the stuff it 
> receives from cinternet to smpppd and vice versa while printing out a log of 
> what it is doing. Haven't gotten around to coding it yet, though.

I think you'd find that telnet would do this sort of thing for you.

I can appreciate your frustration.  In a prior career, I was a computer 
architect for a company that made IBM-compatible mainframes, and I had the 
frequent task of trying things on the IBM we had, to try to figure out what 
sequences made it jump through this or that hoop, so we could do the same.

-- 
Terry Carroll
Santa Clara, CA
carroll@tjc.com
Modell delendus est


From carroll at tjc.com  Sat Jan 24 01:07:52 2004
From: carroll at tjc.com (Terry Carroll)
Date: Sat Jan 24 01:07:56 2004
Subject: [Tutor] OOP programming using  VB
In-Reply-To: <20040124042040.74931.qmail@web12203.mail.yahoo.com>
Message-ID: <Pine.LNX.4.44.0401232204290.23714-100000@violet.rahul.net>

On Fri, 23 Jan 2004, Lakmi munasinghe wrote:

> I have never done OO programming using VB . Anyway I have used OOP
> concepts with C++. I have no clear idea of how to use OOP concepts with
> VB forms and all, because I used to do programmimn in VB by writing
> codes to button clicks,combo box change event etc. I have heard that VB
> supports OOP ; but I have no idea of how it is done. Can you give me an
> example of how it is being done ?

Hi Lakmi --

This group is devoted to the Python programming language, so you probably 
won't have a lot of luck looking for Visual Basic advice here.  You might 
want to look for a mailing list or usenet newsgroup that focuses on VB.

Two usenet newsgroups are comp.lang.basic.visual and 
comp.lang.basic.visual.misc; I don't know enough about the VB world to 
suggest which one might be best.

-- 
Terry Carroll
Santa Clara, CA
carroll@tjc.com
Modell delendus est


From carroll at tjc.com  Sat Jan 24 02:39:52 2004
From: carroll at tjc.com (Terry Carroll)
Date: Sat Jan 24 02:39:58 2004
Subject: [Tutor] Figuring out a protocol for fun and education
In-Reply-To: <Pine.LNX.4.44.0401232154130.23714-100000@violet.rahul.net>
Message-ID: <Pine.LNX.4.44.0401232334550.23714-100000@violet.rahul.net>


> On Fri, 23 Jan 2004, Scot W. Stevenson wrote:
> 
> > (Note this is Python 2.3). The first time I send something -- anything -- I 
> > get "SuSE Meta pppd (smpppd), Version 1.00" as a response, which proves that 
> > I'm reaching the right socket etc. However, anything after that is met with 
> > silence until the time out is reached.

Hey, Scott, taking a look at 
<http://www.suse.de/us/private/products/suse_linux/i386/packages_personal/smpppd.html>, 
you should have a file on the system with smpppd installed:

  /usr/share/doc/packages/smpppd/protocol.html

It will probably help; although it says "This document is outdated. The 
smpppd uses a modified protocol since version 1.00", it's probably a good 
start.

Note also, at the end:

  Note: If something is unclear (I'm sure there is), you may look at the 
  source code of smpppd, cinternet and kinternet or ask me (arvin@suse.de) 
  directly.

-- 
Terry Carroll
Santa Clara, CA
carroll@tjc.com
Modell delendus est


From hameedkhaan at yahoo.com  Sat Jan 24 03:07:53 2004
From: hameedkhaan at yahoo.com (Hameed Khan)
Date: Sat Jan 24 11:38:31 2004
Subject: [Tutor] there is no exitfunc in sys module
Message-ID: <20040124080753.97159.qmail@web61109.mail.yahoo.com>

hi,
 i was reading the manual for sys module. i found a
description for a function known as exitfunc. and it
says the function installed by
sys.exitfunc(cleanUpFunc) call will be called when the
interpreter exits. but when i try to call this
function on Python interactive prompt it says there is
no attribute named exitfunc in sys module.

###
>>> sys.exitfunc
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'module' object has no attribute
'exitfunc'
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__',
'__name__', '__stderr__', '__stdin__', '__stdout_
_', '_getframe', 'api_version', 'argv',
'builtin_module_names', 'byteorder', 'call_tracing',
'call
stats', 'copyright', 'displayhook', 'dllhandle',
'exc_clear', 'exc_info', 'exc_type', 'excepthook'
, 'exec_prefix', 'executable', 'exit',
'getcheckinterval', 'getdefaultencoding',
'getfilesystemenc
oding', 'getrecursionlimit', 'getrefcount',
'getwindowsversion', 'hexversion', 'last_traceback', '
last_type', 'last_value', 'maxint', 'maxunicode',
'meta_path', 'modules', 'path', 'path_hooks', 'p
ath_importer_cache', 'platform', 'prefix', 'ps1',
'ps2', 'setcheckinterval', 'setprofile', 'setrec
ursionlimit', 'settrace', 'stderr', 'stdin', 'stdout',
'version', 'version_info', 'warnoptions', '
winver']
###

i am wondering that only i dont have this in my sys
module or it is being deleted from sys module. and if
only i dont have this function what reason it could be
that i dont have this function.

### Version information
>>> sys.version
'2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit
(Intel)]'

Thanks,
Hameed Khan

__________________________________
Do you Yahoo!?
Yahoo! SiteBuilder - Free web site building tool. Try it!
http://webhosting.yahoo.com/ps/sb/

From carroll at tjc.com  Sat Jan 24 12:30:05 2004
From: carroll at tjc.com (Terry Carroll)
Date: Sat Jan 24 12:30:11 2004
Subject: [Tutor] there is no exitfunc in sys module
In-Reply-To: <20040124080753.97159.qmail@web61109.mail.yahoo.com>
Message-ID: <Pine.LNX.4.44.0401240924080.23714-100000@violet.rahul.net>

On Sat, 24 Jan 2004, Hameed Khan wrote:

>  i was reading the manual for sys module. i found a
> description for a function known as exitfunc. and it
> says the function installed by
> sys.exitfunc(cleanUpFunc) call will be called when the
> interpreter exits. but when i try to call this
> function on Python interactive prompt it says there is
> no attribute named exitfunc in sys module.

It doesn't exist by default.  It's a function that you set up to be 
called at terminatio.  Try this::

  import sys

  def outtahere():
      print "Okay, I quit"

  sys.exitfunc=outtahere

  print "program starting"
  # do something
  print "program done, now exiting"



From orbitz at ezabel.com  Sat Jan 24 12:48:24 2004
From: orbitz at ezabel.com (orbitz@ezabel.com)
Date: Sat Jan 24 12:49:03 2004
Subject: [Tutor] there is no exitfunc in sys module
In-Reply-To: <Pine.LNX.4.44.0401240924080.23714-100000@violet.rahul.net>
References: <20040124080753.97159.qmail@web61109.mail.yahoo.com>
	<Pine.LNX.4.44.0401240924080.23714-100000@violet.rahul.net>
Message-ID: <20040124124824.5dad314e.orbitz@ezabel.com>

The python.org module help says:
exitfunc
    This value is not actually defined by the module, but can be set by
the user (or by a program) to specify a clean-up action at program exit.
When set, it should be a parameterless function. This function will be
called when the interpreter exits. Only one function may be installed in
this way; to allow multiple functions which will be called at
termination, use the atexit module. Note: The exit function is not
called when the program is killed by a signal, when a Python fatal
internal error is detected, or when os._exit() is called. 


On Sat, 24 Jan 2004 09:30:05 -0800 (PST)
Terry Carroll <carroll@tjc.com> wrote:

> On Sat, 24 Jan 2004, Hameed Khan wrote:
> 
> >  i was reading the manual for sys module. i found a
> > description for a function known as exitfunc. and it
> > says the function installed by
> > sys.exitfunc(cleanUpFunc) call will be called when the
> > interpreter exits. but when i try to call this
> > function on Python interactive prompt it says there is
> > no attribute named exitfunc in sys module.
> 
> It doesn't exist by default.  It's a function that you set up to be 
> called at terminatio.  Try this::
> 
>   import sys
> 
>   def outtahere():
>       print "Okay, I quit"
> 
>   sys.exitfunc=outtahere
> 
>   print "program starting"
>   # do something
>   print "program done, now exiting"
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

From alan.gauld at blueyonder.co.uk  Sat Jan 24 12:56:10 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Sat Jan 24 12:56:12 2004
Subject: [Tutor] there is no exitfunc in sys module
References: <20040124080753.97159.qmail@web61109.mail.yahoo.com>
Message-ID: <005501c3e2a3$59bb0040$6401a8c0@xp>

>  i was reading the manual for sys module. i found a
> description for a function known as exitfunc....
> interpreter exits. but when i try to call this
> function on Python interactive prompt it says there is
> no attribute named exitfunc in sys module.

Doing help(sys) yields this:

exitfunc -- if sys.exitfunc exists, this routine is called when Python
exits
      Assigning to sys.exitfunc is deprecated; use the atexit module
instead.

So the note tells us that exitfunc does not exist by default
you have to create it. However it also tells us that this is
deprecated - ie old fashioned and becoming obsolete - you should
use atexit instead

However just to illustrate how exitfun can be used:

>>> import sys
>>> def f(): print "GOOOODBYEEEE!"
...
>>> sys.exitfunc = f
>>> sys.exit()
GOOOODBYEEEE!

So you assign a function to sys.exitfunc and when you call
sys.exit() to exit it in turn calls your exit function.

HTH,

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


From glingl at aon.at  Sat Jan 24 12:59:07 2004
From: glingl at aon.at (Gregor Lingl)
Date: Sat Jan 24 12:58:10 2004
Subject: [Tutor] problem when subclassing tuple
Message-ID: <4012B26B.2050100@aon.at>

Hi Pythonistas!

I'm trying to define a fancy subclass of tuple: ;-)

class Vec(tuple):
   def __init__(self, v):
       tuple.__init__(v)

and some more methods ...

Works fine.

Actually I want my Vec class objects to be constructed
like this:

a = Vec(1,2,3)

But when I tried to overwrite the constructor of tuple
with a new one with a different number of parameters, I failed:

First I tried to pass three arguments:

class Vec2(tuple):
   def __init__(self, x, y, z):
       tuple.__init__((x,y,z))

trying this out, I get:

>>> v = Vec2(1,2,3)
Traceback (most recent call last):
 File "<pyshell#24>", line 1, in ?
   v = Vec2(1,2,3)
TypeError: tuple() takes at most 1 argument (3 given)

Same result when trying a starred parameter:

class Vec3(tuple):
   def __init__(self, *args):
       tuple.__init__(args)

>>> v = Vec3(1,2,3,4,5)
Traceback (most recent call last):
 File "<pyshell#25>", line 1, in ?
   v = Vec3(1,2,3,4,5)
TypeError: tuple() takes at most 1 argument (5 given)

Trying out a recipe from the cookbook also failed:

class Vec4(tuple):
   def __init__(self, *args):
       super(Vec4,self).__init__(args)

>>> v = Vec4(1,2,3,4,5)
Traceback (most recent call last):
 File "<pyshell#38>", line 1, in ?
   v = Vec4(1,2,3,4,5)
TypeError: tuple() takes at most 1 argument (5 given)

So it seems, that one cannot overwrite the constructor of
tuple (or of built-in types in general)?

Maybe I'm on a completely wrong road.
So does someone know a way how to define a subclass of
tuple so its objects can be constructed the way
mentioned above?

Hints as well as solutions are highly appreciated,
pointers to appropriate sections of the docs also.

Regards and thanks in advance

Gregor


P. S.: No homework assignment  ;-)







From alan.gauld at blueyonder.co.uk  Sat Jan 24 13:07:26 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Sat Jan 24 13:07:31 2004
Subject: [Tutor] OOP programming using  VB
References: <20040124042040.74931.qmail@web12203.mail.yahoo.com>
Message-ID: <005d01c3e2a4$ecb7faa0$6401a8c0@xp>

> I have never done OO programming using VB . Anyway I have used OOP
> concepts with C++. I have no clear idea of how to use OOP concepts
> with VB forms and all,

Its pretty similar to C++. A form is an object in VB and it has
methods etc which you can call. When you add components you
define an action or event handler which is effectively a
method of the form object.

You can also define your own classes using a blank code page
like this rather trivial example copied from the paper version
of my book...

Class Message
    Private theText
    Public Property Let Text(S)
        theText = S
    End Property
    Pubic Sub Print()
        If theText = "" Then
            WSCript.echo "No Message"
        Else
            For n = 1 to 3
                WSCript.echo theText
            Next
        End If
    End Sub
End Class

Dim Msg
set Msg = new Message
Msg.Text = "Hello world"
Msg.Print()

The equivalent code in Python (Since this is a Python mailing
list) is as follows:

class Message:
   def __init__(self, text = ""):
      self.theText = text
   def Print(self):
       if self.theText == "":
            print "No Message"
       else:
            for n in range(3):
                print self.theText

msg = Message("Hello world")
msg.Print()

I'll let you figure out the equivalent C++ (Or you can buy the book!
:-)

NOTE the above example is actually in VBScript. There might be
some minor syntax diffrences in VB proper but its very similar.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


From sigurd at 12move.de  Sat Jan 24 17:21:13 2004
From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=)
Date: Sat Jan 24 17:21:50 2004
Subject: [Tutor] problem when subclassing tuple
In-Reply-To: <4012B26B.2050100@aon.at> (Gregor Lingl's message of "Sat, 24
	Jan 2004 18:59:07 +0100")
References: <4012B26B.2050100@aon.at>
Message-ID: <m38yjxovep.fsf@hamster.pflaesterer.de>

On 24 Jan 2004, Gregor Lingl <- glingl@aon.at wrote:

> I'm trying to define a fancy subclass of tuple: ;-)

> class Vec(tuple):
>    def __init__(self, v):
>        tuple.__init__(v)

> and some more methods ...

> Works fine.

> Actually I want my Vec class objects to be constructed
> like this:

> a = Vec(1,2,3)

Maybe I don't understand what you want to achieve exactly but what about
overriding __new__ instead of __init__? (I had the idea when I read
descintro.html)
class vec(tuple):
    def __new__(cls, x,y,z):
        return tuple.__new__(cls, [x,y,z])



> But when I tried to overwrite the constructor of tuple
> with a new one with a different number of parameters, I failed:


[...]
> So does someone know a way how to define a subclass of
> tuple so its objects can be constructed the way
> mentioned above?

Perhaps like the above solution.

> Hints as well as solutions are highly appreciated,
> pointers to appropriate sections of the docs also.

,----[ descintro.html ]
|     * If you want to change the constructor's signature, you often have to override both
|        __new__ and __init__ to accept the new signature. However, most built-in types ignore
|        the arguments to the method they don't use; in particular, the immutable types (int,
|        long, float, complex, str, unicode, and tuple) have a dummy __init__, while the
|        mutable types (dict, list, file, and also super, classmethod, staticmethod, and
|        property) have a dummy __new__. The built-in type 'object' has a dummy __new__ and a
|        dummy __init__ (which the others inherit). The built-in type 'type' is special in many
|        respects; see the section on [55]metaclasses.
`----

This writing about the dummy init method seems to describe your problem.
If that won't help perhaps we have to dig in metaclasses; would be
interesting I didn't explore them myself yet.


   Karl
-- 
Please do *not* send copies of replies to me.
I read the list


From rha207 at webtv.net  Sat Jan 24 22:05:00 2004
From: rha207 at webtv.net (Ron A)
Date: Sat Jan 24 22:05:05 2004
Subject: [Tutor] 2.3.3 problem windows 98 IE
Message-ID: <27573-4013325C-2862@storefull-3194.bay.webtv.net>

I was having a problem with shelve on python 2.2. I downloaded python
2.3.3 on windows 98 and that fixed the shelve problem, but now when I
click on a drop down menu like file it jerks of stutters as it drops
down. Also, it takes 20 to 25 seconds for idle to start up when I click
on it. 

Should I go back to an earlier version, and if so which would you
recommend.

Ron A


From rha207 at webtv.net  Sat Jan 24 22:51:56 2004
From: rha207 at webtv.net (Ron A)
Date: Sat Jan 24 22:52:00 2004
Subject: [Tutor] (no subject)
Message-ID: <27574-40133D5C-2115@storefull-3194.bay.webtv.net>

>Try uninstalling Python and seeing if it
> still happens (it might be something
> else). Does the bug happen when you
> start the computer or start Python? 

>Daniel Ehrenberg


##########################

I uninstalled and reinstalled python and it still happens. It only
happens in the python programs everything else is working normally.
Other than that it seems to work all right, and I guess it's not too bad
although a little irritating.
Ron A


From kim.branson at csiro.au  Sun Jan 25 02:44:03 2004
From: kim.branson at csiro.au (Kim Branson)
Date: Sun Jan 25 02:43:59 2004
Subject: [Tutor] file i.o
Message-ID: <3EF0A6AA-4F0A-11D8-9EB4-000A9579AE94@csiro.au>

hi all,

i'm learning python and to help me do this i'm replacing alot of perl 
scripts i have with python. I'm using mac python 2.3 running on panther 
( it wasn't a clean install of panther) so its possible there are two 
pythons on the system, but it seems to work ok.

i'm unable to write to a file, i can read and print to the shell but 
only empty files are created. for a quick example below, if i import * 
from os i get the following error. not importing os does not give this 
error. Looking at the docs seems to imply the buffer option i presume 
is the missing integer is set to -1 (system by default).


Traceback (most recent call last):
   File "/Users/kbranson/Desktop/test.py", line 6, in -toplevel-
     output = open('numbers','wa')
TypeError: an integer is required
 >>>

from os import *

output = open('numbers','wa')
counter = 0
while (counter<10):
     output.write("%f\n" % (counter))
     print counter
     counter = counter + 1

one other question, what would the python equivalent of this (below) 
be? i.e executing another programs and grabbing the output straight 
into a list. I haven't been able to find out how to do this, but i'm 
sure there is a way.

open (XLOGP, "/usr/local/dock/bin/xlogp dock_nrg.mol2 |");
$xlogp =<XLOGP>;


cheers

Kim


From dyoo at hkn.eecs.berkeley.edu  Sun Jan 25 03:22:32 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun Jan 25 03:22:42 2004
Subject: [Tutor] file i.o
In-Reply-To: <3EF0A6AA-4F0A-11D8-9EB4-000A9579AE94@csiro.au>
Message-ID: <Pine.LNX.4.44.0401242356320.22840-100000@hkn.eecs.berkeley.edu>


> i'm unable to write to a file, i can read and print to the shell but
> only empty files are created. for a quick example below, if i import *
> from os i get the following error.

Hi Kim,


Don't do that.  *grin*

os.open() is a low-level function: it's not meant to be used unless you
really know what you're doing.  Most Python programmers will never touch
that particular function.

(For reference: Python's os.open() is similar to Perl's sysopen()
function.)


In general, try to avoid the statement 'from some_module import *' in
Python unless the module documentation says that it's ok.  The problem is
that it clobbers the local namespace with all the names in the module, and
that's usually a bad thing.


The 'os' module, in particular, isn't a good candidate for that technique,
because it overrides the standard 'open()' function that you normally
should use.  The Python tutorial talks more about the problems with 'from
some_module import *':

    http://www.python.org/doc/tut/node8.html#SECTION008410000000000000000

near the end of section 6.4.1.


So let's take out that 'from os import *' statement, and look at the rest
of your program:

> output = open('numbers','wa')
                           ^^

The mode here is a little odd.  'w' is meant to destructively clear out a
file and prepare it for writing, and 'a' is meant to nondestructively
"append" to an existing file.  That is, the two modes aren't supposed to
be compatible.  So choose one, not both.  *grin* To tell the truth, I have
no idea which mode will win out here.


> counter = 0
> while (counter<10):
>      output.write("%f\n" % (counter))
>      print counter
>      counter = counter + 1

Ok, this looks fine.  You need to add one more statement at the end: the
file needs to be 'close()'ed for the content to be saved into the file:

    output.close()

should do the trick.  Closing a file properly clears out the buffers that
the operating system keeps in memory, and this ensures that the content is
saved to disk.  (In Perl, too, you should make sure to close any open file
handles to make sure the buffers flush properly.)



> one other question, what would the python equivalent of this (below)
> be? i.e executing another programs and grabbing the output straight into
> a list. I haven't been able to find out how to do this, but i'm sure
> there is a way.
>
> open (XLOGP, "/usr/local/dock/bin/xlogp dock_nrg.mol2 |");
> $xlogp =<XLOGP>;

os.popen() is the function you're probably looking for: it returns a
file-like object.  So you can do something like:

###
import os
listing = os.popen("ls")
print listing.readlines()
###

to print out the contents of the current directory as a large list.



By the way, in Perl, you may be used to doing something like:

### Perl
while (my $line = <FILEHANDLE>) {
    ## do something with the line.
}

to handle a file line-by-line.

There's an equivalent statement in Python:

### Python
for line in filehandle:
    # do something with the file.
###

A 'filehandle' in Python can be treated as a "iterable" object, so the for
loop works on it beautifully.

It does sound like you've had some programming under your belt; you may
find the official Python Tutorial useful to get up to speed:

    http://www.python.org/doc/tut/


If you have more questions, please feel free to ask!  Good luck to you.


From dyoo at hkn.eecs.berkeley.edu  Sun Jan 25 03:26:45 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun Jan 25 03:26:52 2004
Subject: [Tutor] report ala jasper
In-Reply-To: <20040124040110.93396.qmail@web41809.mail.yahoo.com>
Message-ID: <Pine.LNX.4.44.0401250023590.22840-100000@hkn.eecs.berkeley.edu>



> > is there a python counterpart to jasperreports of java?
> >
> > thanks...
>
> No, sorry. That's kinda like asking if there's a Python version of
> OpenOffice. JasperReports is a specific application that uses XML as a
> Java-specific database. You can continue using JasperReports within
> Python by using Jython (or this Java-to-CPython bridge that I can't
> find).

I haven't looked too closely to Jasperreports, but if it's PDF generation
that you're going after, you may want to look at ReportLab:

    http://www.reportlab.org/


I hope this helps!


From kim.branson at csiro.au  Sun Jan 25 03:51:41 2004
From: kim.branson at csiro.au (Kim Branson)
Date: Sun Jan 25 03:51:55 2004
Subject: [Tutor] file i.o
In-Reply-To: <Pine.LNX.4.44.0401242356320.22840-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0401242356320.22840-100000@hkn.eecs.berkeley.edu>
Message-ID: <B1DB3C45-4F13-11D8-9077-000A9579AE94@csiro.au>

>
> Hi Kim,
>
>
>
> Don't do that.? *grin*
>
i see, that makes sense now.
so one should always do a import string rather than from string import *
is there a way of warning about clobbering the namespaces ? so if i 
write my own module i can drag it in without worrying about mixing and 
matching module functions. the module.function() syntax could get a bit 
tedious, or is that part of the python way?
> The mode here is a little odd.? 'w' is meant to destructively clear 
> out a
> file and prepare it for writing, and 'a' is meant to nondestructively
> "append" to an existing file.? That is, the two modes aren't supposed 
> to
> be compatible.? So choose one, not both.? *grin* To tell the truth, I 
> have
> no idea which mode will win out here.
>

oops sorry i was playing with it. i was trying append (a right) and 
creation. i'd like a if it exists append to the file otherwise make it. 
not closing filehandle *doh* makes sense now.  I would have thought 
file handles were closed on completion. bad perl coding style showing 
through. (part of the reason i'm learning python)
> os.popen() is the function you're probably looking for: it returns a
> file-like object.? So you can do something like:
>
> ###
> import os
> listing = os.popen("ls")
> print listing.readlines()
> ###
>
great. thats exactly what i want. even works for me first time.
> ### Python
> for line in filehandle:
> ??? # do something with the file.
> ###
>
> A 'filehandle' in Python can be treated as a "iterable" object, so the 
> for
> loop works on it beautifully.
>
neat.

> It does sound like you've had some programming under your belt; you may
> find the official Python Tutorial useful to get up to speed:
i have a copy of the oreilly learning python, but i've been told the 
essential ref might be good also. any other books i should look for ?
>
> If you have more questions, please feel free to ask!? Good luck to you.
thanks for your help, i'm sure there will be more.
cheers
Kim
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: text/enriched
Size: 3664 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20040125/e6704ddf/attachment.bin
From tayi177 at hotmail.com  Sun Jan 25 04:31:32 2004
From: tayi177 at hotmail.com (Tadey from SLO)
Date: Sun Jan 25 04:43:56 2004
Subject: [Tutor] Three questions about Python (and bundled software) in
	general
Message-ID: <BAY8-DAV51MGKQMw3op0000273d@hotmail.com>



Hello ...




I am resuming my Python learning after some time (need to hard-study for some time), and I "notice", that some basic terms are not cleared for me, even if they are mentioned in various tutorials ...


What is Tkinter, and what is Tcl/Tk  ??


- For Tcl/Tk I imagine, from what I read in Alan tutorial, that Tcl/Tk is some sort of "foundation", kind of basis for "translating" to machine/binary code, for Python coding being possible at all ...

(in common language, please)


- And for Thinkter, it says it is Python's GUI programming system. But what this actually means, how to interprete it to myself  ??

As far as I know, IDLE is GUI for Python, so this must be something else, some kind of root for GUI being able, or GUI in meaning some "programming system" for GUI programming (to program some GUI, and not "console/command line" program)



Text from Alan Gauld tutorial:

#########################################

Tcl/Tk

As just mentioned the Python 1.5.2 distribution for Windows comes with Tcl/Tk so that's no problem. If you have a different Python version or are on a platform where it's not included then you can get Tcl/Tk from Scriptics:

Python

Python version 1.5.2 is the latest release at the time of writing and comes with Tcl/Tk version 8.0 thrown in for free. This is because Python's GUI programming system(Tkinter) is built on top of Tcl/Tk. For our purposes this is 'a good thing'(TM) but it does mean the Python download is very big (about 5Mb for the Windows binary version. For Linux/Unix you can get source and have to build it - see your sys admin!! It comes prebuilt in most Linux distributions these days.)

#########################################



- Second, I have question, if anyone knows what could "corrupt" my Python (to be more precise - IDLE) installation. After double-clicking on "idle.pyw", I get message that "tcl84.dll" is missing, and re-installing product will help, but I am certain, I didn't delete this dll, nor in Python directory, nor in %SystemRoot%\system32 directory ..





Thak you all for your friendly effort ...

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20040125/7b4e6d49/attachment.html
From project5 at redrival.net  Sun Jan 25 05:31:19 2004
From: project5 at redrival.net (Andrei)
Date: Sun Jan 25 05:34:37 2004
Subject: [Tutor] Re: Three questions about Python (and bundled software) in
	general
References: <BAY8-DAV51MGKQMw3op0000273d@hotmail.com>
Message-ID: <1jvjdbhlgglmw.69lnrbp26jik.dlg@40tude.net>

Tadey from SLO wrote on Sun, 25 Jan 2004 10:31:32 +0100:

> Hello ...
> 
> 
> What is Tkinter, and what is Tcl/Tk  ??

TCL is a programming language. Tk is a toolkit for creating GUI's (windows
with buttons and the likes), written for TCL I believe. Tkinter is the
Python wrapper for Tk. I don't use Tkinter, but if I'm not mistaken the
Python distro comes with a TCL interpreter which is used to talk to Tk.

> - For Tcl/Tk I imagine, from what I read in Alan tutorial, that Tcl/Tk is 
> some sort of "foundation", kind of basis for "translating" to machine/binary 
> code, for Python coding being possible at all ...

I don't think you understood it properly, since what you're talking about
would be a compiler. You don't need Tkinter in order to write Python
programs - programs can work just fine from the command line, not all need
a GUI; you don't even need it to write GUI programs, you can use other GUI
libraries like wxPython (which is the Python wrapper for the wxWindows
toolkit).

> - And for Thinkter, it says it is Python's GUI programming system. But what 
> this actually means, how to interprete it to myself  ??

Basic Python only allows you to write programs with command line interface
(that's that black DOS screen in Windows or e.g. Bash in Linux). They're
not particularly user-friendly. You need an additional toolkit to write
modern apps with windows and controls on them. As I said above, Tkinter is
what ships with Python, but there are others.

> As far as I know, IDLE is GUI for Python, so this must be something else, 
> some kind of root for GUI being able, or GUI in meaning some "programming 
> system" for GUI programming (to program some GUI, and not "console/command 
> line" program)

No, IDLE is not a GUI, but it does have a GUI. GUI means Graphical User
Interface. IDLE is a programming editor or IDE. IDLE is written in Python
though and it does use Tkinter for its GUI. Again, you don't need IDLE to
program in Python and you also don't need it for GUI programming. In fact,
I write both GUI and non-GUI programs without ever touching IDLE. I use
SciTE, wxGlade and Spe.

> - Second, I have question, if anyone knows what could "corrupt" my Python 
> (to be more precise - IDLE) installation. After double-clicking on "idle.pyw", 
> I get message that "tcl84.dll" is missing, and re-installing product will help, 
> but I am certain, I didn't delete this dll, nor in Python directory, nor in 
> %SystemRoot%\system32 directory ..

Perhaps you didn't install the full Python, you left out TCL. Things
usually don't get corrupted on their own. Just do a full reinstallation and
all should be solved. I see you're on Windows. I recommend you to get the
ActiveState Python distro
(http://www.activestate.com/Products/ActivePython/ and click on the
Download link in the upper left corner). It includes PythonWin, which is a
better editor than IDLE (at least IMO). It doesn't use Tkinter btw.

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.


From glingl at aon.at  Sun Jan 25 06:28:59 2004
From: glingl at aon.at (Gregor Lingl)
Date: Sun Jan 25 06:28:03 2004
Subject: [Tutor] problem when subclassing tuple
In-Reply-To: <m38yjxovep.fsf@hamster.pflaesterer.de>
References: <4012B26B.2050100@aon.at> <m38yjxovep.fsf@hamster.pflaesterer.de>
Message-ID: <4013A87B.90206@aon.at>



Thanks, Karl, for this idea ...

>Maybe I don't understand what you want to achieve exactly but what about
>overriding __new__ instead of __init__? (I had the idea when I read
>descintro.html)
>class vec(tuple):
>    def __new__(cls, x,y,z):
>        return tuple.__new__(cls, [x,y,z])
>
>
>  
>
It works well. And also for your hint to 
http://www.python.org/2.2.2/descrintro.html,
which contains all the information I need.

Gregor


From darnold02 at sprynet.com  Sun Jan 25 10:28:12 2004
From: darnold02 at sprynet.com (Don Arnold)
Date: Sun Jan 25 10:26:48 2004
Subject: [Tutor] file i.o
In-Reply-To: <B1DB3C45-4F13-11D8-9077-000A9579AE94@csiro.au>
References: <Pine.LNX.4.44.0401242356320.22840-100000@hkn.eecs.berkeley.edu>
	<B1DB3C45-4F13-11D8-9077-000A9579AE94@csiro.au>
Message-ID: <168FC9FB-4F4B-11D8-AC74-000A95C4F940@sprynet.com>


On Jan 25, 2004, at 2:51 AM, Kim Branson wrote:

>>
>> Hi Kim,
>>
>> Don't do that.? *grin*
>>
> i see, that makes sense now.
> so one should always do a import string rather than from string import 
> *
> is there a way of warning about clobbering the namespaces ? so if i 
> write my own module i can drag it in without worrying about mixing and 
> matching module functions. the module.function() syntax could get a 
> bit tedious, or is that part of the python way?

Actually, it is. But if you want to save yourself some typing, you can 
always do:

import MyReallyLongModuleName as my

That way, you can refer to my.function1(), my.function2(), etc.

<snip>

> i have a copy of the oreilly learning python, but i've been told the 
> essential ref might be good also. any other books i should look for ?

I can't recommend Alex Martelli's "Python In A Nutshell" highly enough. 
It's easily the best Python book I own.

<snip>

HTH,
Don
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: text/enriched
Size: 1161 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20040125/c57eb459/attachment.bin
From lumbricus at gmx.net  Sun Jan 25 11:45:30 2004
From: lumbricus at gmx.net (=?ISO-8859-1?Q?=22J=F6rg_W=F6lke=22?=)
Date: Sun Jan 25 11:45:35 2004
Subject: [Tutor] file i.o
References: <168FC9FB-4F4B-11D8-AC74-000A95C4F940@sprynet.com>
Message-ID: <2773.1075049130@www28.gmx.net>

Hola!
 
> On Jan 25, 2004, at 2:51 AM, Kim Branson wrote:
[ snip ]

> > matching module functions. the module.function() syntax could get a=20
> > bit tedious, or is that part of the python way?
> 
> Actually, it is. But if you want to save yourself some typing, you can=20=

Well, there are modules said to be safe for doing "from xyz import *":
Tkinter for example. Just be sure your module contains only methods
garanteed to have unique names.
 
> always do:
> 
> import MyReallyLongModuleName as my
> 
> That way, you can refer to my.function1(), my.function2(), etc.

[ snip ]
 
> HTH,
> Don=

Dito and Greets, J"o!


-- 
Sie d?rfen diesen Satz zitieren.

+++ GMX - die erste Adresse f?r Mail, Message, More +++
Bis 31.1.: TopMail + Digicam f?r nur 29 EUR http://www.gmx.net/topmail


From alan.gauld at blueyonder.co.uk  Sun Jan 25 13:34:08 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Sun Jan 25 13:33:57 2004
Subject: [Tutor] Three questions about Python (and bundled software) in
	general
References: <BAY8-DAV51MGKQMw3op0000273d@hotmail.com>
Message-ID: <00d701c3e371$d46a6d20$6401a8c0@xp>

Welcome back Tadey,

> What is Tkinter, and what is Tcl/Tk  ??
>
> For Tcl/Tk I imagine, from what I read in Alan tutorial, that Tcl/Tk
> is some sort of "foundation", kind of basis for "translating" to
> machine/binary code,

Not quite. Tcl is a completely separate programming language.
Tcl stands for "Tool Control Language" and Tk stands for "Toolkit".
The Tk toolkit is a set of programming objects that the Tcl programmer
can use to create GUI programs (with windows, menus etc).

Tkinter is a Python version of that same Tk toolkit. The Python code
inside Tkinter actually calls the Tcl/Tk code and that's why, for
Tkinter
to work, you also need the Tcl and Tk libraries installed.

> And for Thinkter, it says it is Python's GUI programming system.
> But what this actually means, how to interprete it to myself  ??

Tkinter is the set of Python commands you use to create GUI programs
using Python.

> As far as I know, IDLE is GUI for Python,

IDLE is a GUI program written using Tkinter. Technically IDLE is
an IDE (Integrated Development Environment) for Python. Virtually
all programs that use Windows, menus etc ate GUI programs, IDLE
is one such. Unfortunately the Python installer insists on calling the
Start menu entry for IDLE (Python GUI) rather than (Python IDE).

Pyhonwin is another IDE but it is written using a different GUI
toolkit,
one which is Windows specific. One reason the Tk toolkit os so
popular is that programs written using it will work on Windows,
Macintosh, Unix and any other computers that can run Tcl. Since
Python also works on the same computers we can combine them
in the shape of Tkinter and write GUI programs that will run on
almost any computer.

> meaning some "programming system" for GUI programming
> (to program some GUI, and not "console/command line" program)

Exactly correct.

> Second, I have question, if anyone knows what could "corrupt" my
> Python (to be more precise - IDLE) installation. After
double-clicking
> on "idle.pyw", I get message that "tcl84.dll" is missing, and
re-installing
> product will help, but I am certain, I didn't delete this dll, nor
in Python
> directory, nor in %SystemRoot%\system32 directory ..

Sadly this error seems very common and it usually means that the
library
got deleted somehow (maybe by an over zealous uninstall program?)
Usually reinstalling Python fixes it.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


From littledanehren at yahoo.com  Sun Jan 25 14:42:16 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Sun Jan 25 14:42:22 2004
Subject: [Tutor] file i.o
In-Reply-To: <3EF0A6AA-4F0A-11D8-9EB4-000A9579AE94@csiro.au>
Message-ID: <20040125194216.37464.qmail@web41805.mail.yahoo.com>

> from os import *
> 
> output = open('numbers','wa')
> counter = 0
> while (counter<10):
>      output.write("%f\n" % (counter))
>      print counter
>      counter = counter + 1
> Kim

I think someone already corrected you on the from os
import * command, so I'll just talk about the while
loop. In Python, while loops aren't used with counters
like for loops are in other languages. In Python, we
still use for loops, but they are used to iterate over
a range(). In this case, we'd iterate over range(0,
10). Here's how I would write the loop:

for counter in range(0, 10):
    output.write('%f\n' % counter)
    print counter

That's two lines shorter and a lot easier to read.

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Yahoo! SiteBuilder - Free web site building tool. Try it!
http://webhosting.yahoo.com/ps/sb/

From dyoo at hkn.eecs.berkeley.edu  Sun Jan 25 16:20:36 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun Jan 25 16:21:13 2004
Subject: [Tutor] Three questions about Python (and bundled software) in
	general
In-Reply-To: <00d701c3e371$d46a6d20$6401a8c0@xp>
Message-ID: <Pine.LNX.4.44.0401251315530.30190-100000@hkn.eecs.berkeley.edu>



> > What is Tkinter, and what is Tcl/Tk  ??
> >
> > For Tcl/Tk I imagine, from what I read in Alan tutorial, that Tcl/Tk
> > is some sort of "foundation", kind of basis for "translating" to
> > machine/binary code,
>
> Not quite. Tcl is a completely separate programming language. Tcl stands
> for "Tool Control Language" and Tk stands for "Toolkit". The Tk toolkit
> is a set of programming objects that the Tcl programmer can use to
> create GUI programs (with windows, menus etc).


Hi Tadey,

I think Alan's tutorial covers Tcl in some depth:

    http://www.freenetpages.co.uk/hp/alan.gauld/


But there another tutorial written by Phil Greenspun, "Tcl for Web Nerds":

    http://philip.greenspun.com/tcl/

It's a great resource if you want to dive into Tcl.


Good luck!


From dyoo at hkn.eecs.berkeley.edu  Sun Jan 25 16:15:37 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun Jan 25 16:25:20 2004
Subject: [Tutor] file i.o
In-Reply-To: <2773.1075049130@www28.gmx.net>
Message-ID: <Pine.LNX.4.44.0401251250520.30190-100000@hkn.eecs.berkeley.edu>


On Sun, 25 Jan 2004, [ISO-8859-1] "J=F6rg W=F6lke" wrote:

> > > matching module functions. the module.function() syntax could get
> > > a bit tedious, or is that part of the python way?
>
> > Actually, it is. But if you want to save yourself some typing, you can

Hello!


I wouldn't call it tedium.  Even in Perl, you want to avoid doing an
uncontrolled import like that.  In fact, the Perl module documentation at:

    http://www.perldoc.com/perl5.6/lib/Exporter.html

says:

"""
Do not export method names!

Do not export anything else by default without a good reason!

Exports pollute the namespace of the module user. If you must export try
to use @EXPORT_OK in preference to @EXPORT and avoid short or common
symbol names to reduce the risk of name clashes.
"""

Sound familiar?


It's the exact same issue in Python.  The cosmetic difference here is that
the Perl folks define @EXPORT/@EXPORT_OK arrays, and the Python folks use
the 'from module import */import' statements.  The majority of the Perl
folks handle namespace pollution just like the Python folks in saying:
don't do it!  *grin*



> Well, there are modules said to be safe for doing "from xyz import *":
> Tkinter for example. Just be sure your module contains only methods
> garanteed to have unique names.
>
> > always do:
> >
> > import MyReallyLongModuleName as my


Another way to say this is:

###
import MyReallyLongModuleName
my =3D MyReallyLongModuleName
###

Imported modules can be treated as objects, just like numbers and strings,
so it's fairly easy just to rebind them with another name.  We can even
keep them in a list if we're in a wacky mood:

###
>>> import re
>>> import os
>>> import math
>>> modules =3D [re, os, math]
>>> modules
[<module 're' from
'/System/Library/Frameworks/Python.framework/Versions/2.3/lib/
    python2.3/re.pyc'>,
<module 'os' from
'/System/Library/Frameworks/Python.framework/Versions/2.3/lib/
    python2.3/os.pyc'>,
<module 'math' from
'/System/Library/Frameworks/Python.framework/Versions/2.3/lib/
    python2.3/lib-dynload/math.so'>]
###

Sorry, I guess I'm getting off track.  *grin*


There are other shortcuts that are kosher when we want to easily access
module functions.  Although 'from xyz import *' is usually not a good
idea, there's a weaker version that's pretty safe:

    from xyz import some_function


Instead of pulling everything, we can pull out a controlled number of
functions.  For the os.popen() example, it's perfectly ok to do:

###
from os import popen
###

and then use 'popen()' anywhere you want.


One advantage of this form is that it makes it much easier to pull
functions from multiple modules without everything being one muddled mess.
This form of the statement is more explicit about what kinds of things
we'll pull from the module, and much nicer from a program maintainer's
point of view.


Good luck to you!


From dyoo at hkn.eecs.berkeley.edu  Sun Jan 25 16:30:43 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun Jan 25 16:31:44 2004
Subject: [Tutor] file i.o
In-Reply-To: <Pine.LNX.4.44.0401251250520.30190-100000@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.44.0401251324120.30190-100000@hkn.eecs.berkeley.edu>


> It's the exact same issue in Python.  The cosmetic difference here is
> that the Perl folks define @EXPORT/@EXPORT_OK arrays, and the Python
> folks use the 'from module import */import' statements.

Hi everyone,


My apologies: the parallelism in the original statement was wrong. I
wasn't as careful as I should have been when I wrote that.  I should have
said:

   It's the exact same issue in Python.  The cosmetic difference here is
   that the Perl folks use different forms of the 'use' statement, and the
   Python folks use the 'import/from module import *' statements.


If I had wanted to form a parallel for @EXPORT/@EXPORT_OK, I should have
continued:


Perl's @EXPORT arrays have a counterpart in Python's '__all__' list:

http://www.python.org/doc/tut/node8.html#SECTION008410000000000000000

But unlike Perl, Python doesn't pulls all of __all__ into the current
namespace unless we use the 'from foo import *' form.



Anyway, sorry for the confusion!


From kp8 at mac.com  Sun Jan 25 15:57:37 2004
From: kp8 at mac.com (kevin parks)
Date: Sun Jan 25 17:25:19 2004
Subject: [Tutor] comment stripper script
Message-ID: <1B3B6094-4F79-11D8-84AA-003065555ABC@mac.com>

Hi all. I am hacking together something to strip commented lines from a  
file. I have some programs that generate these files, but the  
application that takes these on input sometimes chokes on these files  
now. So, as a work around, i am filtering these input files with the  
following script, which i wrote, and, well, doesn't work. It is  
supposed to make a new file with just the 'legit' lines in it, but this  
seems to give me the original file with no changes. hmmm...

Can anyone see why? I can't. Perhaps i just need another, more fresh,  
pair of eyes.

Cheers,

kevin

------------------------------ 
[snip]-------------------------------------------------
#!/usr/bin/env python

"""filter out commented lines from a Csound or Cmix score file

Usage: commentfilter('/Users/kevin/in.sco', '/Users/kevin/out.sco')

This will filter out commented lines (lines begining with ';' or
'c' or '#') so that the score will be smaller in size giving the buggy
score srt routine in Csound some much needed help. It also strips
leading and trailing whitespaces. It would be great if this also
sorted the score by start time (second parameter field). ^-^

"""

__author__ = 'kevin parks'
__version__ = 'Sunday, January 25, 2004 02:56:08'


# 1. Perhaps this should also replace tabs and double spaces with
# single spaces
#
# 2. Would be nice if it allowed you to specify the comment
# characters to zap at runtime ('#', ';', '--', '//', '/*') and
# trailing '*/'
#
# 3. Shouldn't have to specify output name it should just generate
# one, by catting the filename with _out. + suffix ('.sco' ,.'txt') or  
what have you.

def commentfilter(infilename, outfilename):
	"""this will copy a file with commented lines filtered out
	
	Usage: commentfilter('~/in.sco', '~/out.sco')
	"""
	infile = open(infilename, 'r')
	f = open(outfilename, 'w')
	for line in infile.xreadlines():
		line.strip()
		if not (line.startswith(';') or line.startswith('c') or  
line.startswith('#')):
			f.write(line)
	infile.close()
	f.close()
	
if __name__ == '__main__':
	commentfilter('/Users/kevin/scripts/fio/h.sco',  
'/Users/kevin/scripts/fio/h_out.sco')
	
-- sample input file snip here -----

c -------------------------- foo.sco11-------------------------------
t 0 60
i1 1.000 16.990 607 0 45.372395833 1 0.259 7.896 8 0.683 0.005 0.001  
0.100 0.874 0.500 0.010 28 9 14 15 1 0.905 0.077 0.984 0.021 0.457  
0.092 0.122 1.805
  ci1 1.250 16.940 603 0 58.3359375 1 0.161 12.995 1 0.919 0.004 0.001  
0.100 0.812 0.500 0.010 24 25 18 31 1 0.969 0.974 0.543 0.065 0.904  
0.943 0.085 1.232 <rest>
  ci1 1.450 16.803 608 0 45.372395833 1 0.296 13.839 6 0.490 0.001 0.001  
0.100 1.186 0.500 0.010 8 21 14 19 1 0.503 0.958 0.589 0.963 0.440  
0.413 0.372 3.723 <rest>
  ci1 1.512 16.830 607 0 68.05859375 1 0.412 10.724 8 0.795 0.001 0.001  
0.100 0.847 0.500 0.010 12 9 30 15 1 0.595 0.043 0.406 0.526 0.949  
0.961 0.196 1.155 <rest>
  ci1 1.603 16.803 502 0 45.372395833 1 0.412 8.316 1 0.867 0.001 0.001  
0.100 1.116 0.500 0.010 20 21 10 31 1 0.579 0.017 0.549 0.519 0.540  
0.047 0.086 2.546 <rest>
  ci1 1.665 16.865 606 0 68.05859375 1 0.482 9.290 8 0.193 0.005 0.001  
0.100 1.089 0.500 0.010 28 25 30 7 1 0.572 0.954 0.462 0.489 0.031  
0.409 0.269 1.393 <rest>
  ci1 1.790 16.907 603 0 45.372395833 1 0.301 14.196 1 0.846 0.002 0.001  
0.100 0.967 0.500 0.010 8 13 26 31 1 0.048 0.431 0.034 0.098 0.512  
0.427 0.277 2.482 <rest>
  ci1 1.957 16.865 609 0 58.3359375 1 0.405 9.234 2 0.816 0.002 0.001  
0.100 0.966 0.500 0.010 16 17 10 23 1 0.432 0.910 0.917 0.475 0.550  
0.974 0.151 3.501 <rest>
  ci1 2.082 16.840 701 0 38.890625 1 0.431 14.155 1 0.471 0.001 0.001  
0.100 1.068 0.500 0.010 24 25 14 27 1 0.466 0.525 0.590 0.591 0.588  
0.926 0.216 3.219 <rest>
  ci1 2.182 16.830 609 0 45.372395833 1 0.475  9.761 7 0.863 0.003 0.001  
0.100 1.039 0.500 0.010 20 21 10 15 1 0.402 0.011 0.909 0.903 0.534  
0.415 0.081 1.475 <rest>
  ci1 2.272 16.840 503 0 38.890625 1 0.448 11.125 6 0.119 0.003 0.001  
0.100 0.945 0.500 0.010 8 17 26 27 1 0.583 0.924 0.536 0.064 0.092  
0.402 0.268 0.370 <rest>
  ci1 2.372 16.990 606 0 58.3359375 1 0.287 8.308 3 0.872 0.004 0.001  
0.100 0.810 0.500 0.010 20 25 10 7 1 0.965 0.053 0.595 0.938 0.986  
0.489 0.261 1.407 <rest>
  ci1 2.622 16.883 702 0 68.05859375 1 0.276 14.757 5 0.153 0.004 0.001  
0.100 0.818 0.500 0.010 12 17 26 23 1 0.470 0.562 0.415 0.455 0.911  
0.406 0.443 1.956 <rest>
  ci1 2.764 16.940 702 0 58.3359375 1 0.152 13.760 11 0.387 0.004 0.001  
0.100 1.246 0.500 0.010 28 21 30 15 1 0.981 0.480 0.543 0.911 0.951  
0.099 0.274 0.895 <rest>
  ci1 2.965 16.990 608 0 45.372395833 1 0.146 7.938 10 0.511 0.003 0.001  
0.100 0.943 0.500 0.010 16 9 14 11 1 0.940 0.042 0.052 0.081 0.038  
0.054 0.264 0.334 <rest>
  ci1 3.215 16.803 501 0 68.05859375 1 0.450 14.562 4 0.130 0.004 0.001  
0.100 1.100 0.500 0.010 24 17 30 31 1 0.028 0.526 0.981 0.098 0.983  
0.411 0.338 2.739 <rest>
  ci1 3.277 16.907 603 0 45.372395833 1 0.476 8.362 4 0.822 0.002 0.001  
0.100 0.919 0.500 0.010 16 21 14 11 1 0.043 0.472 0.097 0.474 0.936  
0.911 0.006 3.472 <rest>
  ci1 3.444 16.940 609 0 58.3359375 1 0.192 10.026 3 0.071 0.003 0.001  
0.100 0.996 0.500 0.010 28 29 18 7 1 0.429 0.091 0.553 0.049 0.572  
0.026 0.218 3.708 <rest>
  ci1 3.644 16.990 608 0 68.05859375 1 0.471 11.476 10 0.428 0.003 0.001  
0.100 1.009 0.500 0.010 16 21 10 23 1 0.015 0.585 0.945 0.466 0.094  
0.021 0.207 2.495 <rest>
  ci1 3.894 16.940 608 0 58.3359375 1 0.197 12.139 6 0.824 0.005 0.001  
0.100 1.129 0.500 0.010 8 25 30 15 1 0.925 0.917 0.038 0.416 0.580  
0.459 0.196 0.022 <rest>
  ci1 4.094 16.830 702 0 38.890625 1 0.464  9.814 2 0.436 0.005 0.001  
0.100 1.132 0.500 0.010 24 17 18 19 1 0.593 0.907 0.044 0.066 0.013  
0.952 0.191 4.145 <rest>
  ci1 4.184 16.840 608 0 45.372395833 1 0.487 12.480 8 0.644 0.004 0.001  
0.100 0.919 0.500 0.010 16 21 14 27 1 0.923 0.940 0.546 0.974 0.467  
0.987 0.162 2.512 <rest>
   i1 4.284 16.865 609 0 38.890625 1 0.463 14.981 4 0.340 0.001 0.001  
0.100 1.048 0.500 0.010 8 17 18 23 1 0.064 0.567 0.440 0.019 0.423  
0.488 0.093 3.977
  ci1 4.409 16.907 702 0 68.05859375 1 0.488 8.853 4 0.711 0.005 0.001  
0.100 1.074 0.500 0.010 12 29 10 11 1 0.530 0.941 0.580 0.966 0.429  
0.475 0.219 0.467 <rest>
  ci1 4.575 16.840 609 0 38.890625 1 0.495 8.360 9 0.642 0.001 0.001  
0.100 0.874 0.500 0.010 20 13 30 31 1 0.017 0.023 0.907 0.457 0.051  
0.469 0.421 3.080 <rest>
  ci1 4.675 16.940 701 0 68.05859375 1 0.212 12.246 7 0.803 0.005 0.001  
0.100 0.913 0.500 0.010 28 29 10 23 1 0.046 0.933 0.021 0.431 0.982  
0.922 0.359 0.249 <rest>
  ci1 4.875 16.840 702 0 38.890625 1 0.410 13.505 5 0.834 0.001 0.001  
0.100 1.065 0.500 0.010 12 21 30 11 1 0.033 0.545 0.963 0.582 0.595  
0.961 0.027 1.848 <rest>
  ci1 4.975 16.851 502 0 45.372395833 1 0.452 11.553 3 0.440 0.001 0.001  
0.100 1.152 0.500 0.010 16 25 26 27 1 0.011 0.559 0.573 0.059 0.944  
0.922 0.173 2.325 <rest>
  ci1 5.086 16.940 607 0 68.05859375 1 0.156 8.314 3 0.400 0.002 0.001  
0.100 0.853 0.500 0.010 24 13 14 19 1 0.508 0.969 0.975 0.461 0.972  
0.958 0.279 2.361 <rest>
  ci1 5.286 16.865 701 0 68.05859375 1 0.441 7.566 9 0.087 0.004 0.001  
0.100 0.984 0.500 0.010 16 29 30 27 1 0.097 0.562 0.074 0.503 0.019  
0.447 0.201 4.119 <rest>
  ci1 5.411 16.883 603 0 58.3359375 1 0.274 11.056 11 0.101 0.002 0.001  
0.100 1.109 0.500 0.010 24 25 22 23 1 0.915 0.469 0.912 0.929 0.430  
0.981 0.075 0.950 <rest>
  ci1 5.554 16.840 702 0 68.05859375 1 0.419 11.495 11 0.480 0.004 0.001  
0.100 0.812 0.500 0.010 16 9 14 19 1 0.913 0.973 0.955 0.528 0.592  
0.517 0.142 4.136 <rest>
  ci1 5.654 16.883 610 0 58.3359375 1 0.413 10.273 11 0.697 0.005 0.001  
0.100 0.825 0.500 0.010 28 25 10 7 1 0.931 0.096 0.576 0.915 0.484  
0.083 0.061 3.942 <rest>
  ci1 5.797 16.990 607 0 68.05859375 1 0.469 7.857 8 0.228 0.005 0.001  
0.100 0.958 0.500 0.010 16 13 18 11 1 0.916 0.081 0.074 0.022 0.062  
0.912 0.244 1.005 <rest>
  ci1 6.047 16.883 610 0 58.3359375 1 0.276 8.301 4 0.278 0.002 0.001  
0.100 0.814 0.500 0.010 28 21 30 15 1 0.958 0.532 0.066 0.020 0.581  
0.943 0.057 1.907 <rest>
  ci1 6.190 16.907 501 0 38.890625 1 0.236 13.001 4 0.733 0.004 0.001  
0.100 1.073 0.500 0.010 24 25 18 27 1 0.453 0.412 0.523 0.442 0.442  
0.951 0.242 1.650 <rest>
  ci1 6.357 16.851 702 0 68.05859375 1 0.450 8.419 7 0.862 0.003 0.001  
0.100 0.825 0.500 0.010 28 21 14 7 1 0.035 0.412 0.491 0.043 0.968  
0.092 0.206 0.520 <rest>
  ci1 6.468 16.883 503 0 58.3359375 1 0.430 12.198 2 0.641 0.001 0.001  
0.100 0.909 0.500 0.010 12 9 22 19 1 0.570 0.489 0.565 0.962 0.936  
0.069 0.268 2.432 <rest>
  ci1 6.611 16.990 702 0 38.890625 1 0.486 11.302 11 0.897 0.001 0.001  
0.100 1.201 0.500 0.010 8 17 26 15 1 0.950 0.026 0.429 0.586 0.044  
0.052 0.088 2.093 <rest>
  ci1 6.861 16.851 701 0 45.372395833 1 0.180 12.152 1 0.138 0.002 0.001  
0.100 0.827 0.500 0.010 16 29 30 27 1 0.047 0.924 0.091 0.522 0.925  
0.022 0.258 2.725 <rest>
  ci1 6.972 16.907 610 0 38.890625 1 0.468 10.395 4 0.575 0.001 0.001  
0.100 0.972 0.500 0.010 8 17 18 19 1 0.056 0.471 0.476 0.961 0.566  
0.963 0.353 3.837 <rest>
  ci1 7.138 16.883 702 0 38.890625 1 0.462 14.899 9 0.200 0.004 0.001  
0.100 1.172 0.500 0.010 28 9 10 31 1 0.451 0.515 0.913 0.077 0.011  
0.084 0.092 1.799 <rest>
  ci1 7.281 16.865 701 0 45.372395833 1 0.233 14.902 10 0.641 0.002  
0.001 0.100 0.829 0.500 0.010 8 29 22 23 1 0.938 0.584 0.926 0.984  
0.512 0.516 0.327 0.812 <rest>
  ci1 7.406 16.840 609 0 68.05859375 1 0.496 12.072 6 0.869 0.002 0.001  
0.100 0.934 0.500 0.010 12 21 26 15 1 0.527 0.493 0.401 0.013 0.944  
0.400 0.002 1.641 <rest>
  ci1 7.506 16.865 603 0 68.05859375 1 0.476 10.107 9 0.094 0.005 0.001  
0.100 0.919 0.500 0.010 24 9 22 11 1 0.045 0.066 0.488 0.940 0.567  
0.023 0.109 3.066 <rest>
  ci1 7.631 16.883 606 0 58.3359375 1 0.238 7.827 9 0.808 0.005 0.001  
0.100 1.146 0.500 0.010 8 13 30 19 1 0.082 0.411 0.031 0.417 0.032  
0.021 0.345 3.317 <rest>
  ci1 7.774 16.865 503 0 68.05859375 1 0.205 8.396 4 0.799 0.004 0.001  
0.100 1.241 0.500 0.010 28 17 22 27 1 0.050 0.014 0.041 0.405 0.563  
0.908 0.147 1.350 <rest>
  ci1 7.899 16.830 609 0 68.05859375 1 0.244  9.951 3 0.785 0.005 0.001  
0.100 1.179 0.500 0.010 12 21 18 7 1 0.081 0.975 0.548 0.067 0.954  
0.051 0.170 1.656 <rest>
  ci1 7.989 16.865 701 0 45.372395833 1 0.405 12.980 5 0.331 0.004 0.001  
0.100 0.960 0.500 0.010 20 9 22 19 1 0.513 0.047 0.555 0.519 0.530  
0.583 0.421 1.006 <rest>
  ci1 8.114 16.883 608 0 45.372395833 1 0.429 10.614 6 0.258 0.003 0.001  
0.100 1.003 0.500 0.010 8 13 26 27 1 0.407 0.032 0.499 0.587 0.909  
0.467 0.050 2.014 <rest>
  ci1 8.257 16.803 701 0 68.05859375 1 0.489 11.566 10 0.275 0.004 0.001  
0.100 0.973 0.500 0.010 16 25 10 15 1 0.010 0.044 0.018 0.551 0.418  
0.086 0.301 4.368 <rest>
  ci1 8.319 16.907 609 0 58.3359375 1 0.169 7.716 11 0.128 0.002 0.001  
0.100 1.193 0.500 0.010 8 13 14 7 1 0.076 0.968 0.525 0.501 0.914 0.461  
0.281 4.581 <rest>
  ci1 8.486 16.990 608 0 45.372395833 1 0.441 13.475 9 0.633 0.003 0.001  
0.100 1.067 0.500 0.010 24 21 30 15 1 0.063 0.944 0.401 0.047 0.554  
0.438 0.108 1.474 <rest>
  ci1 8.736 16.907 607 0 38.890625 1 0.290 10.265 3 0.703 0.003 0.001  
0.100 0.969 0.500 0.010 8 17 26 11 1 0.090 0.942 0.557 0.071 0.088  
0.060 0.139 4.472 <rest>
  ci1 8.903 16.830 701 0 38.890625 1 0.426 8.955 10 0.706 0.003 0.001  
0.100 1.233 0.500 0.010 16 29 22 27 1 0.459 0.020 0.589 0.471 0.954  
0.505 0.206 0.200 <rest>
  ci1 8.993 16.907 702 0 45.372395833 1 0.293 12.233 5 0.708 0.002 0.001  
0.100 1.029 0.500 0.010 12 21 10 23 1 0.513 0.969 0.924 0.011 0.477  
0.051 0.427 2.804 <rest>
  ci1 9.159 16.851 607 0 68.05859375 1 0.108 11.762 5 0.039 0.003 0.001  
0.100 1.079 0.500 0.010 16 29 22 15 1 0.546 0.032 0.520 0.910 0.917  
0.097 0.153 2.665 <rest>
  ci1 9.270 16.940 701 0 68.05859375 1 0.197 11.058 2 0.308 0.004 0.001  
0.100 0.859 0.500 0.010 8 25 14 27 1 0.058 0.988 0.900 0.585 0.037  
0.505 0.334 3.440 <rest>
  ci1 9.470 16.851 610 0 58.3359375 1 0.458 8.630 6 0.094 0.004 0.001  
0.100 0.968 0.500 0.010 16 9 18 11 1 0.083 0.509 0.900 0.509 0.491  
0.923 0.044 3.168 <rest>
  ci1  9.582 16.990 701 0 45.372395833 1 0.126 8.972 9 0.552 0.005 0.001  
0.100 0.836 0.500 0.010 12 25 10 19 1 0.440 0.466 0.013 0.418 0.957  
0.435 0.304 0.954 <rest>
  ci1  9.832 16.830 502 0 58.3359375 1 0.409 13.494 2 0.659 0.003 0.001  
0.100 1.164 0.500 0.010 16 9 14 31 1 0.438 0.982 0.975 0.930 0.456  
0.507 0.068 1.987 <rest>
  ci1  9.922 16.865 608 0 45.372395833 1 0.414 10.444 2 0.711 0.004  
0.001 0.100 0.820 0.500 0.010 28 29 22 19 1 0.982 0.087 0.054 0.080  
0.586 0.483 0.381 3.837 <rest>
  ci1 10.047 16.907 702 0 38.890625 1 0.101 14.368 3 0.860 0.004 0.001  
0.100 0.962 0.500 0.010 8 17 10 31 1 0.968 0.519 0.497 0.954 0.044  
0.049 0.408 3.784 <rest>
  ci1 10.213 16.840 503 0 45.372395833 1 0.462 8.160 4 0.088 0.004 0.001  
0.100 0.801 0.500 0.010 20 9 22 7 1 0.470 0.498 0.421 0.512 0.424 0.916  
0.148 3.796 <rest>
  ci1 10.313 16.865 610 0 38.890625 1 0.110 11.404 3 0.919 0.005 0.001  
0.100 1.066 0.500 0.010 8 25 14 23 1 0.527 0.409 0.920 0.935 0.484  
0.503 0.021 1.654 <rest>
  ci1 10.438 16.830 503 0 58.3359375 1 0.440 10.418 9 0.091 0.002 0.001  
0.100 1.177 0.500 0.010 28 29 30 19 1 0.469 0.581 0.476 0.439 0.457  
0.594 0.385 3.019 <rest>
  ci1 10.528 16.840 606 0 45.372395833 1 0.254  9.548 5 0.591 0.003  
0.001 0.100 1.098 0.500 0.010 16 9 18 7 1 0.026 0.903 0.976 0.595 0.088  
0.051 0.156 0.320 <rest>
  ci1 10.628 16.851 603 0 38.890625 1 0.465 9.344 8 0.143 0.003 0.001  
0.100 1.198 0.500 0.010 20 29 10 31 1 0.437 0.980 0.559 0.462 0.530  
0.976 0.384 3.972 <rest>
  ci1 10.739 16.840 701 0 45.372395833 1 0.179  9.978 1 0.832 0.003  
0.001 0.100 0.837 0.500 0.010 12 25 22 7 1 0.909 0.950 0.029 0.514  
0.558 0.579 0.251 4.424 <rest>
  ci1 10.839 16.907 609 0 68.05859375 1 0.496 13.835 8 0.336 0.005 0.001  
0.100 0.846 0.500 0.010 28 21 26 15 1 0.400 0.026 0.938 0.472 0.048  
0.459 0.027 0.715 <rest>
  ci1 11.006 16.865 702 0 38.890625 1 0.109 13.051 5 0.009 0.005 0.001  
0.100 1.168 0.500 0.010 8 13 10 11 1 0.424 0.983 0.075 0.965 0.949  
0.920 0.431 1.376 <rest>
  ci1 11.131 16.840 606 0 45.372395833 1 0.482 8.511 5 0.110 0.003 0.001  
0.100 1.098 0.500 0.010 16 21 22 7 1 0.442 0.968 0.482 0.553 0.442  
0.087 0.161 1.669 <rest>
  ci1 11.231 16.803 608 0 58.3359375 1 0.496 10.138 2 0.438 0.003 0.001  
0.100 1.026 0.500 0.010 12 13 18 31 1 0.088 0.920 0.925 0.440 0.449  
0.912 0.179 4.035 <rest>
  ci1 11.293 16.907 702 0 68.05859375 1 0.428 13.909 10 0.339 0.004  
0.001 0.100 1.208 0.500 0.010 16 29 10 23 1 0.420 0.488 0.045 0.962  
0.516 0.491 0.437 3.621 <rest>
  ci1 11.460 16.803 702 0 58.3359375 1 0.268 13.200 8 0.650 0.004 0.001  
0.100 1.068 0.500 0.010 12 25 14 27 1 0.033 0.945 0.053 0.454 0.930  
0.059 0.088 3.621 <rest>
  ci1 11.522 16.851 608 0 45.372395833 1 0.124 7.641 7 0.036 0.005 0.001  
0.100 1.034 0.500 0.010 16 29 22 23 1 0.574 0.063 0.515 0.100 0.418  
0.510 0.404 3.939 <rest>
  ci1 11.634 16.803 608 0 68.05859375 1 0.465 7.816 3 0.347 0.004 0.001  
0.100 1.028 0.500 0.010 24 9 26 31 1 0.491 0.965 0.903 0.936 0.982  
0.055 0.244 3.805 <rest>
  ci1 11.696 16.883 501 0 68.05859375 1 0.111 12.809 3 0.317 0.002 0.001  
0.100 0.965 0.500 0.010 20 21 18 11 1 0.430 0.018 0.415 0.440 0.559  
0.041 0.157 0.895 <rest>
  ci1 11.839 16.940 607 0 45.372395833 1 0.432  9.920 7 0.468 0.003  
0.001 0.100 1.227 0.500 0.010 16 9 22 7 1 0.596 0.041 0.484 0.519 0.425  
0.014 0.008 1.086 <rest>
  ci1 12.039 16.830 608 0 38.890625 1 0.261 11.199 8 0.121 0.001 0.001  
0.100 0.857 0.500 0.010 8 17 10 15 1 0.019 0.028 0.016 0.451 0.566  
0.032 0.091 2.623 <rest>
  ci1 12.129 16.840 702 0 38.890625 1 0.230 11.969 5 0.497 0.003 0.001  
0.100 1.210 0.500 0.010 20 29 30 23 1 0.047 0.019 0.955 0.439 0.087  
0.904 0.101 1.924 <rest>
   i1 12.229 16.883 609 0 58.3359375 1 0.473 11.121 6 0.512 0.005 0.001  
0.100 0.885 0.500 0.010 28 9 22 31 1 0.489 0.591 0.024 0.075 0.036  
0.916 0.436 2.180
  ci1 12.372 16.990 608 0 68.05859375 1 0.405 14.173 11 0.120 0.004  
0.001 0.100 1.150 0.500 0.010 12 13 10 15 1 0.097 0.990 0.980 0.964  
0.578 0.094 0.244 1.284 <rest>
  ci1 12.622 16.840 610 0 58.3359375 1 0.491  9.762 8 0.549 0.004 0.001  
0.100 1.116 0.500 0.010 8 9 26 31 1 0.039 0.500 0.507 0.913 0.094 0.075  
0.451 3.354 <rest>
  ci1 12.722 16.851 608 0 38.890625 1 0.415 11.358 2 0.417 0.001 0.001  
0.100 0.984 0.500 0.010 24 29 10 15 1 0.921 0.545 0.931 0.089 0.942  
0.903 0.054 3.974 <rest>
  ci1 12.833 16.883 603 0 68.05859375 1 0.428 12.791 1 0.382 0.001 0.001  
0.100 1.115 0.500 0.010 16 9 14 19 1 0.510 0.541 0.076 0.977 0.070  
0.520 0.095 0.342 <rest>
  ci1 12.976 16.851 609 0 45.372395833 1 0.277 8.748 6 0.508 0.004 0.001  
0.100 1.165 0.500 0.010 12 13 10 31 1 0.417 0.964 0.916 0.083 0.582  
0.922 0.142 1.122 <rest>
  ci1 13.087 16.883 702 0 58.3359375 1 0.476 12.269 6 0.176 0.001 0.001  
0.100 1.008 0.500 0.010 28 29 14 27 1 0.518 0.953 0.014 0.056 0.978  
0.096 0.045 0.548 <rest>
  ci1 13.230 16.907 502 0 45.372395833 1 0.431 8.913 2 0.735 0.004 0.001  
0.100 1.055 0.500 0.010 8 25 10 19 1 0.051 0.011 0.493 0.507 0.526  
0.032 0.142 2.853 <rest>
  ci1 13.396 16.803 702 0 45.372395833 1 0.484 10.225 3 0.248 0.004  
0.001 0.100 1.054 0.500 0.010 16 9 30 11 1 0.918 0.524 0.502 0.033  
0.926 0.029 0.407 0.559 <rest>
  ci1 13.459 16.851 503 0 58.3359375 1 0.290 10.037 10 0.102 0.001 0.001  
0.100 1.238 0.500 0.010 24 13 18 27 1 0.902 0.984 0.916 0.056 0.916  
0.452 0.255 0.156 <rest>
  ci1 13.570 16.865 701 0 68.05859375 1 0.484 9.096 3 0.116 0.002 0.001  
0.100 1.060 0.500 0.010 16 17 22 19 1 0.473 0.019 0.437 0.423 0.053  
0.092 0.410 3.535 <rest>
   i1 13.695 16.990 607 0 38.890625 1 0.452 11.307 3 0.594 0.002 0.001  
0.100 1.059 0.500 0.010 24 21 26 15 1 0.054 0.062 0.955 0.953 0.978  
0.590 0.004 0.515
  ci1 13.945 16.940 503 0 68.05859375 1 0.416  9.948 6 0.202 0.002 0.001  
0.100 0.963 0.500 0.010 12 29 22 23 1 0.437 0.547 0.526 0.426 0.453  
0.542 0.292 2.994 <rest>


--------


From alan.gauld at blueyonder.co.uk  Sun Jan 25 19:29:17 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Sun Jan 25 19:28:57 2004
Subject: [Tutor] comment stripper script
References: <1B3B6094-4F79-11D8-84AA-003065555ABC@mac.com>
Message-ID: <001a01c3e3a3$6ee6cde0$6401a8c0@xp>

> following script, which i wrote, and, well, doesn't work. It is
> supposed to make a new file with just the 'legit' lines in it, but
this
> seems to give me the original file with no changes. hmmm...

Have you tried a print statement every time you find a comment?
I suspect the search isn't finding the comment markers for
some reason... Maybe they aren't the first character in the line?

I dunno, its late and I just scanned it. Also there's no
indentation showing up so I gave up. But its a guess...

Alan G.


From carroll at tjc.com  Sun Jan 25 22:36:58 2004
From: carroll at tjc.com (Terry Carroll)
Date: Sun Jan 25 22:37:03 2004
Subject: [Tutor] comment stripper script
In-Reply-To: <1B3B6094-4F79-11D8-84AA-003065555ABC@mac.com>
Message-ID: <Pine.LNX.4.44.0401251934490.17317-100000@violet.rahul.net>

On Sun, 25 Jan 2004, kevin parks wrote:

> Can anyone see why? I can't. Perhaps i just need another, more fresh,  
> pair of eyes.

Yep, I think so:

> 		line.strip()

Unless I miss my guess, this is your problem.  The above wil not modify 
line; you need:
                line = line.strip()

Otherwise, when you get to the next line of code:

> 		if not (line.startswith(';') or line.startswith('c') or  
> line.startswith('#')):

This condition fails, because the leading blanks are stil there.

-- 
Terry Carroll
Santa Clara, CA
carroll@tjc.com
Modell delendus est


From kp8 at mac.com  Mon Jan 26 00:23:42 2004
From: kp8 at mac.com (kevin parks)
Date: Mon Jan 26 00:24:35 2004
Subject: [Tutor] Python equiv of perltidy?
Message-ID: <CE11151C-4FBF-11D8-B8AD-003065555ABC@mac.com>

Is there a python equivalent of perltidy or some of the pretty printers 
that you see for c?

I drag a lot of stuff off of the net and from my other platforms and 
such and there is always
extra whitespace and line ending Tab and indentation issues and just 
plain funkiness. I usually
fix it by hand, but it suddenly occurred to me that if i had such a 
thing to send my scripts
through before i posted them here, i might not have the problem that 
Alan G. just pointed out to
me and that is that the code i just posted looked pretty in my mail 
prog, but came out doody on
his end cause i probably forgot to convert to do the entab detab dance.

cheers,

kevin

(of course no matter how much you tidy perl, it's still perl, which by 
its very nature is untidy)


From dyoo at hkn.eecs.berkeley.edu  Mon Jan 26 00:28:11 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon Jan 26 00:28:15 2004
Subject: [Tutor] comment stripper script
In-Reply-To: <1B3B6094-4F79-11D8-84AA-003065555ABC@mac.com>
Message-ID: <Pine.LNX.4.44.0401252114480.21032-100000@hkn.eecs.berkeley.edu>



On Sun, 25 Jan 2004, kevin parks wrote:

> Hi all. I am hacking together something to strip commented lines from a
> file. I have some programs that generate these files, but the
> application that takes these on input sometimes chokes on these files
> now. So, as a work around, i am filtering these input files with the
> following script, which i wrote, and, well, doesn't work. It is supposed
> to make a new file with just the 'legit' lines in it, but this seems to
> give me the original file with no changes. hmmm...


Hi Kevin,


You can try making the program a little easier to test by breaking out the
comment-detector as a separate function.  At the moment, the program has
an inner loop that does a few things:

###
for line in infile.xreadlines():
    line.strip()
    if not (line.startswith(';') or line.startswith('c') or
        line.startswith('#')):
    f.write(line)
###


If we have a function that can detect commented lines, like
is_commented_line(line),

###
def is_commented_line(line):
    line.strip()
    if not (line.startswith(';') or line.startswith('c') or
            line.startswith('#')):
        return False
    else:
        return True
###


then we can rewrite the loop as:

###
for line in infile.xreadlines():
    if not is_commented_line(line):
        f.write(line)
###

Note that no bugs are fixed yet: we're just shifting code around.  (And
is_commented_line() is buggy: look at Terry's reply for a hint on how to
fix it.  *grin*)


Moving code like this is not useless or aimless:  this reorganization can
help because is_commented_line() only needs to deal with a single line; it
doesn't have to care about files.  And as a side benefit, the code ends up
being easier to test from the interactive interpreter, since you can then
do things like:

###
>>> is_commented_line(' c test')
False
>>> is_commented_line('c test')
True
>>> is_commented_line(' c')
False
###

and see that there's something wacky happening with the comment-line
detection.  It's not completely broken: it is sorta working, except when
there's leading whitespace on the line.


The big idea is to break things down into functions.  By doing so, when
bugs are discovered, tracing and fixing them becomes easier because of the
relative isolation that functions give us.


Hope this helps!


From dyoo at hkn.eecs.berkeley.edu  Mon Jan 26 00:53:12 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon Jan 26 00:53:17 2004
Subject: [Tutor] Python equiv of perltidy?
In-Reply-To: <CE11151C-4FBF-11D8-B8AD-003065555ABC@mac.com>
Message-ID: <Pine.LNX.4.44.0401252128200.21032-100000@hkn.eecs.berkeley.edu>



On Mon, 26 Jan 2004, kevin parks wrote:

> Is there a python equivalent of perltidy or some of the pretty printers
> that you see for c?

Hi Kevin,

    http://www.python.org/doc/current/lib/module-tabnanny.html

should detect wacky things like ambiguous indentation.  Python also has a
command line option '-t' that warns against inconsistent tab-space usage.
But other than the tab/space issue, Python code is usually pretty anyway,
and properly indented by syntactic necessity.

If you stick to using spaces alone, should should be fairly safe.  But
your text editor should really be handling this detail for you anyway.
What text editor are you using to write Python?


By the way, there is a lint-like utility for Python that detects weird
Python usage.  The utility is called 'PyChecker':

    http://pychecker.sourceforge.net/

Rather than checking syntax, it checks the semantics of a program, and
looks for things like weird parameter passing or misspelling identifiers.
It's a very useful program.


> (of course no matter how much you tidy perl, it's still perl, which by
> its very nature is untidy)

Not necessarily true.  I have seen some pretty nice Perl code before.
(Why do I suddently feel like a heretic?)

Perl, as written by its practitioners now, is often messy.  But it doesn't
remove the possibility that the Perl folks can choose to restrict
themselves to a managable subset of that language.  It's just that the
Perl folks respect obfuscated code a little too much.  *grin*


Talk to you later!



From syrinx at simplecom.net  Mon Jan 26 01:35:26 2004
From: syrinx at simplecom.net (Scott)
Date: Mon Jan 26 01:36:40 2004
Subject: [Tutor] Limiting variable size
Message-ID: <20040126003526.364af534.syrinx@simplecom.net>

Is there a way to set the maximum numeric value of a variable?  I want x
to roll over if it gets to over four bytes.  I've got a little routine
to *and*  them with "0xffffffff."  But seems like there's a better way!

Thanks guys!



From hcohen2 at comcast.net  Mon Jan 26 09:33:57 2004
From: hcohen2 at comcast.net (hcohen2)
Date: Mon Jan 26 09:36:15 2004
Subject: [Tutor] Questions regarding class documentation ...
Message-ID: <40152555.3080803@comcast.net>


Because the Core Python Programming book was so out of date regarding 
class and objects discussion I switched over to reading the Alan Gauld 
tutorial on the topic; afterward I directed my attention to the 
documentation on the python.org site.

[ Here are some facts to keep in mind as you read the discussion below: 
documentation was for version 2.2.3 and I am using 2.2.2.  I have so far 
reproduced the results exactly when I ran it interactively.  I am trying 
to prepare myself to create applications independently, hence, I try to 
go beyond the text samples and use more general approaches.]

Rather than running the code, in section: Subclassing built-in types,  
interactively I pasted the class definition in a file.  Moreover, to 
keep it general I gave the file a name different from the class defined 
in the file, since I would expect I would have many unrelated class 
definitions within a single file that I would load to run a custom 
application.

So within the python interpreter I imported the file containing the 
defaultdict class:

 >>>import sampledict  # name sampledict.py

however, when I attempted to run the sample code in the documentation:

 >>> print defaultdict
...
NameError: name 'defaultdict' is not defined

Running dir() shows, indeed, 'sampledict' is listed but not 
'defaultdict, despite the importing of the file that contains the 
latter's definition.

Perhaps what I did next was due to my having a tenuous grasp on this 
topic I remembered the problems with unbound method discussion.  Hence, 
I tried to created an instance, but I got the same error.  At that point 
I became suspicious of the success the importing command.  Though I know 
it is bad style and a command to be avoided I gave the command:

 >>> from sampledict import defaultdict
 >>> print defaultdict
<class 'sampledict.defaultdict'>
 >>> dictIns = defaultdict()
 >>> print dictIns
{}
 >>> type(dictIns)
<class 'sampledict.defaultdict'>

Now the print dictIns 'works', but I have a number of questions!

Again the interactive reproduction of the code works exactly as 
described (as far as I have gone).  While I can reproduce the results, 
why doesn't the simple import command work for the file?  What happened 
to seeing an instance rather than the type now being class for dictIns?

Could someone enlighten me regarding these questions without citing 
further documentation that might just add to my confusion as to what may 
be happening.  When I created instances previously that were identified 
as instances not as a class.  [Regarding the last statement: on this 
machine with this version of Python.]

It is very difficult to gain a firm grasp of this topic when the results 
are so haphazard and not internally consistent.

I would like to thank anyone that can clarify why I have run into these 
difficulties.


From littledanehren at yahoo.com  Mon Jan 26 12:28:59 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Mon Jan 26 12:29:06 2004
Subject: [Tutor] Limiting variable size
In-Reply-To: <20040126003526.364af534.syrinx@simplecom.net>
Message-ID: <20040126172859.71152.qmail@web41810.mail.yahoo.com>

Scott wrote:
> Is there a way to set the maximum numeric value of a
> variable?  I want x
> to roll over if it gets to over four bytes.  I've
> got a little routine
> to *and*  them with "0xffffffff."  But seems like
> there's a better way!
> 
> Thanks guys!

I don't think there's a way to do it besides just
doing a mod like below:

x %= 4294967296 #four bytes

This will only work when you explicitly do this on a
value; it won't overflow automatically. Although ints
are limited in value, when they overflow they are
automatically converted to longs, which top out at
some very large, system-dependent value. The only way
I can think of changing the maximum value is to hack
Python itself.

Why do you want to do this, anyway?

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Yahoo! SiteBuilder - Free web site building tool. Try it!
http://webhosting.yahoo.com/ps/sb/

From orbitz at ezabel.com  Mon Jan 26 13:23:18 2004
From: orbitz at ezabel.com (orbitz@ezabel.com)
Date: Mon Jan 26 13:23:46 2004
Subject: [Tutor] Questions regarding class documentation ...
In-Reply-To: <40152555.3080803@comcast.net>
References: <40152555.3080803@comcast.net>
Message-ID: <20040126132318.637e68c4.orbitz@ezabel.com>

When you import a module, you tell python that you will be using these symbols.  On the 'import' statement, the symbols in your module are not loaded into the global namespace.  This is good, since there is always the change of two modules having the same class/function names in their namespace and you don't want them to conflict.  so when you do import sampledict, it loads the module but all of the object it defines are located in the sampledict namespace.  If you were sure you wanted defaultdict to be imported into the global namespace you could do:

from sampledict import defaultdict.

now your print defaultdict will work.

I hope this helps.


On Mon, 26 Jan 2004 09:33:57 -0500
hcohen2 <hcohen2@comcast.net> wrote:

> 
> Because the Core Python Programming book was so out of date regarding 
> class and objects discussion I switched over to reading the Alan Gauld 
> tutorial on the topic; afterward I directed my attention to the 
> documentation on the python.org site.
> 
> [ Here are some facts to keep in mind as you read the discussion below: 
> documentation was for version 2.2.3 and I am using 2.2.2.  I have so far 
> reproduced the results exactly when I ran it interactively.  I am trying 
> to prepare myself to create applications independently, hence, I try to 
> go beyond the text samples and use more general approaches.]
> 
> Rather than running the code, in section: Subclassing built-in types,  
> interactively I pasted the class definition in a file.  Moreover, to 
> keep it general I gave the file a name different from the class defined 
> in the file, since I would expect I would have many unrelated class 
> definitions within a single file that I would load to run a custom 
> application.
> 
> So within the python interpreter I imported the file containing the 
> defaultdict class:
> 
>  >>>import sampledict  # name sampledict.py
> 
> however, when I attempted to run the sample code in the documentation:
> 
>  >>> print defaultdict
> ...
> NameError: name 'defaultdict' is not defined
> 
> Running dir() shows, indeed, 'sampledict' is listed but not 
> 'defaultdict, despite the importing of the file that contains the 
> latter's definition.
> 
> Perhaps what I did next was due to my having a tenuous grasp on this 
> topic I remembered the problems with unbound method discussion.  Hence, 
> I tried to created an instance, but I got the same error.  At that point 
> I became suspicious of the success the importing command.  Though I know 
> it is bad style and a command to be avoided I gave the command:
> 
>  >>> from sampledict import defaultdict
>  >>> print defaultdict
> <class 'sampledict.defaultdict'>
>  >>> dictIns = defaultdict()
>  >>> print dictIns
> {}
>  >>> type(dictIns)
> <class 'sampledict.defaultdict'>
> 
> Now the print dictIns 'works', but I have a number of questions!
> 
> Again the interactive reproduction of the code works exactly as 
> described (as far as I have gone).  While I can reproduce the results, 
> why doesn't the simple import command work for the file?  What happened 
> to seeing an instance rather than the type now being class for dictIns?
> 
> Could someone enlighten me regarding these questions without citing 
> further documentation that might just add to my confusion as to what may 
> be happening.  When I created instances previously that were identified 
> as instances not as a class.  [Regarding the last statement: on this 
> machine with this version of Python.]
> 
> It is very difficult to gain a firm grasp of this topic when the results 
> are so haphazard and not internally consistent.
> 
> I would like to thank anyone that can clarify why I have run into these 
> difficulties.
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

From hcohen2 at comcast.net  Mon Jan 26 13:36:36 2004
From: hcohen2 at comcast.net (hcohen2)
Date: Mon Jan 26 13:38:49 2004
Subject: [Tutor] Questions regarding class documentation ...
In-Reply-To: <20040126132318.637e68c4.orbitz@ezabel.com>
References: <40152555.3080803@comcast.net>
	<20040126132318.637e68c4.orbitz@ezabel.com>
Message-ID: <40155E34.6010803@comcast.net>

Sorry not sure what your is to address you by.  However, your 
explanation does take care of why the straight import <file name> did 
not work.  I used the from <file name> import <class name> and it did 
work.  Nonetheless, having seen so much discussion on why one should not 
use from ... import ... I thought it odd this seemed necessary.

I am, however, still bothered by my seeing an instance type()ed as a 
class and not an instance.

Thanks,
Herschel

orbitz@ezabel.com wrote:

>When you import a module, you tell python that you will be using these symbols.  On the 'import' statement, the symbols in your module are not loaded into the global namespace.  This is good, since there is always the change of two modules having the same class/function names in their namespace and you don't want them to conflict.  so when you do import sampledict, it loads the module but all of the object it defines are located in the sampledict namespace.  If you were sure you wanted defaultdict to be imported into the global namespace you could do:
>
>from sampledict import defaultdict.
>
>now your print defaultdict will work.
>
>I hope this helps.
>
>
>On Mon, 26 Jan 2004 09:33:57 -0500
>hcohen2 <hcohen2@comcast.net> wrote:
>
>  
>
>>Because the Core Python Programming book was so out of date regarding 
>>class and objects discussion I switched over to reading the Alan Gauld 
>>tutorial on the topic; afterward I directed my attention to the 
>>documentation on the python.org site.
>>
>>[ Here are some facts to keep in mind as you read the discussion below: 
>>documentation was for version 2.2.3 and I am using 2.2.2.  I have so far 
>>reproduced the results exactly when I ran it interactively.  I am trying 
>>to prepare myself to create applications independently, hence, I try to 
>>go beyond the text samples and use more general approaches.]
>>
>>Rather than running the code, in section: Subclassing built-in types,  
>>interactively I pasted the class definition in a file.  Moreover, to 
>>keep it general I gave the file a name different from the class defined 
>>in the file, since I would expect I would have many unrelated class 
>>definitions within a single file that I would load to run a custom 
>>application.
>>
>>So within the python interpreter I imported the file containing the 
>>defaultdict class:
>>
>> >>>import sampledict  # name sampledict.py
>>
>>however, when I attempted to run the sample code in the documentation:
>>
>> >>> print defaultdict
>>...
>>NameError: name 'defaultdict' is not defined
>>
>>Running dir() shows, indeed, 'sampledict' is listed but not 
>>'defaultdict, despite the importing of the file that contains the 
>>latter's definition.
>>
>>Perhaps what I did next was due to my having a tenuous grasp on this 
>>topic I remembered the problems with unbound method discussion.  Hence, 
>>I tried to created an instance, but I got the same error.  At that point 
>>I became suspicious of the success the importing command.  Though I know 
>>it is bad style and a command to be avoided I gave the command:
>>
>> >>> from sampledict import defaultdict
>> >>> print defaultdict
>><class 'sampledict.defaultdict'>
>> >>> dictIns = defaultdict()
>> >>> print dictIns
>>{}
>> >>> type(dictIns)
>><class 'sampledict.defaultdict'>
>>
>>Now the print dictIns 'works', but I have a number of questions!
>>
>>Again the interactive reproduction of the code works exactly as 
>>described (as far as I have gone).  While I can reproduce the results, 
>>why doesn't the simple import command work for the file?  What happened 
>>to seeing an instance rather than the type now being class for dictIns?
>>
>>Could someone enlighten me regarding these questions without citing 
>>further documentation that might just add to my confusion as to what may 
>>be happening.  When I created instances previously that were identified 
>>as instances not as a class.  [Regarding the last statement: on this 
>>machine with this version of Python.]
>>
>>It is very difficult to gain a firm grasp of this topic when the results 
>>are so haphazard and not internally consistent.
>>
>>I would like to thank anyone that can clarify why I have run into these 
>>difficulties.
>>
>>
>>_______________________________________________
>>Tutor maillist  -  Tutor@python.org
>>http://mail.python.org/mailman/listinfo/tutor
>>    
>>
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>  
>



From littledanehren at yahoo.com  Mon Jan 26 15:08:51 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Mon Jan 26 15:08:56 2004
Subject: [Tutor] comment stripper script
In-Reply-To: <Pine.LNX.4.44.0401252114480.21032-100000@hkn.eecs.berkeley.edu>
Message-ID: <20040126200851.31610.qmail@web41803.mail.yahoo.com>

> for line in infile.xreadlines():
>     if not is_commented_line(line):
>         f.write(line)

You can leave out the .xreadlines(); it is implied as
of version 2.0

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Yahoo! SiteBuilder - Free web site building tool. Try it!
http://webhosting.yahoo.com/ps/sb/

From glingl at aon.at  Mon Jan 26 15:11:38 2004
From: glingl at aon.at (Gregor Lingl)
Date: Mon Jan 26 15:10:42 2004
Subject: [Tutor] Limiting variable size
In-Reply-To: <20040126172859.71152.qmail@web41810.mail.yahoo.com>
References: <20040126172859.71152.qmail@web41810.mail.yahoo.com>
Message-ID: <4015747A.7080000@aon.at>



Daniel Ehrenberg schrieb:

>Scott wrote:
>  
>
>>Is there a way to set the maximum numeric value of a
>>variable?  I want x
>>to roll over if it gets to over four bytes. 
>>
>I don't think there's a way to do it besides just
>doing a mod like below:
>
>x %= 4294967296 #four bytes
>
>This will only work when you explicitly do this on a
>value; it won't overflow automatically. 
>
Two days ago Karl taught me how to use __new__ for subclassing tuple.
A similar approach could be done here (In my example I use 10 instead of 
2**32)

 >>> class boundedInt(int):
        def __new__(cls, n):
            return int.__new__(cls, n%10)
        def __add__(self, other):
            return boundedInt( int.__add__(self,other) )

 >>> a = boundedInt(14)
 >>> a
4
 >>> b = boundedInt(19)
 >>> b
9
 >>> a+b
3
 >>>

Just a funny idea. (But very probably not what you want (or need))
Nevertheless: it seems that studying "New Classes" could be rewarding.

Gregor





From pythontutor at venix.com  Mon Jan 26 15:19:24 2004
From: pythontutor at venix.com (Lloyd Kvam)
Date: Mon Jan 26 15:19:31 2004
Subject: [Tutor] Questions regarding class documentation ...
In-Reply-To: <40155E34.6010803@comcast.net>
References: <40152555.3080803@comcast.net>	<20040126132318.637e68c4.orbitz@ezabel.com>
	<40155E34.6010803@comcast.net>
Message-ID: <4015764C.20705@venix.com>

After importing a module, the "stuff" the module provides is referenced
from within the module's namespace.

What you want is:

import sampledict

print sampledict.defaultdict


In general each python source file represents a separate namespace.

hcohen2 wrote:

> Sorry not sure what your is to address you by.  However, your 
> explanation does take care of why the straight import <file name> did 
> not work.  I used the from <file name> import <class name> and it did 
> work.  Nonetheless, having seen so much discussion on why one should not 
> use from ... import ... I thought it odd this seemed necessary.
> 
> I am, however, still bothered by my seeing an instance type()ed as a 
> class and not an instance.
> 
> Thanks,
> Herschel
> 
> orbitz@ezabel.com wrote:
> 
>> When you import a module, you tell python that you will be using these 
>> symbols.  On the 'import' statement, the symbols in your module are 
>> not loaded into the global namespace.  This is good, since there is 
>> always the change of two modules having the same class/function names 
>> in their namespace and you don't want them to conflict.  so when you 
>> do import sampledict, it loads the module but all of the object it 
>> defines are located in the sampledict namespace.  If you were sure you 
>> wanted defaultdict to be imported into the global namespace you could do:
>>
>> from sampledict import defaultdict.
>>
>> now your print defaultdict will work.
>>
>> I hope this helps.
>>
>>
>> On Mon, 26 Jan 2004 09:33:57 -0500
>> hcohen2 <hcohen2@comcast.net> wrote:
>>
>>  
>>
>>> Because the Core Python Programming book was so out of date regarding 
>>> class and objects discussion I switched over to reading the Alan 
>>> Gauld tutorial on the topic; afterward I directed my attention to the 
>>> documentation on the python.org site.
>>>
>>> [ Here are some facts to keep in mind as you read the discussion 
>>> below: documentation was for version 2.2.3 and I am using 2.2.2.  I 
>>> have so far reproduced the results exactly when I ran it 
>>> interactively.  I am trying to prepare myself to create applications 
>>> independently, hence, I try to go beyond the text samples and use 
>>> more general approaches.]
>>>
>>> Rather than running the code, in section: Subclassing built-in 
>>> types,  interactively I pasted the class definition in a file.  
>>> Moreover, to keep it general I gave the file a name different from 
>>> the class defined in the file, since I would expect I would have many 
>>> unrelated class definitions within a single file that I would load to 
>>> run a custom application.
>>>
>>> So within the python interpreter I imported the file containing the 
>>> defaultdict class:
>>>
>>> >>>import sampledict  # name sampledict.py
>>>
>>> however, when I attempted to run the sample code in the documentation:
>>>
>>> >>> print defaultdict
>>> ...
>>> NameError: name 'defaultdict' is not defined
>>>
>>> Running dir() shows, indeed, 'sampledict' is listed but not 
>>> 'defaultdict, despite the importing of the file that contains the 
>>> latter's definition.
>>>
>>> Perhaps what I did next was due to my having a tenuous grasp on this 
>>> topic I remembered the problems with unbound method discussion.  
>>> Hence, I tried to created an instance, but I got the same error.  At 
>>> that point I became suspicious of the success the importing command.  
>>> Though I know it is bad style and a command to be avoided I gave the 
>>> command:
>>>
>>> >>> from sampledict import defaultdict
>>> >>> print defaultdict
>>> <class 'sampledict.defaultdict'>
>>> >>> dictIns = defaultdict()
>>> >>> print dictIns
>>> {}
>>> >>> type(dictIns)
>>> <class 'sampledict.defaultdict'>
>>>
>>> Now the print dictIns 'works', but I have a number of questions!
>>>
>>> Again the interactive reproduction of the code works exactly as 
>>> described (as far as I have gone).  While I can reproduce the 
>>> results, why doesn't the simple import command work for the file?  
>>> What happened to seeing an instance rather than the type now being 
>>> class for dictIns?
>>>
>>> Could someone enlighten me regarding these questions without citing 
>>> further documentation that might just add to my confusion as to what 
>>> may be happening.  When I created instances previously that were 
>>> identified as instances not as a class.  [Regarding the last 
>>> statement: on this machine with this version of Python.]
>>>
>>> It is very difficult to gain a firm grasp of this topic when the 
>>> results are so haphazard and not internally consistent.
>>>
>>> I would like to thank anyone that can clarify why I have run into 
>>> these difficulties.
>>>
>>>
>>> _______________________________________________
>>> 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
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582


From hcohen2 at comcast.net  Mon Jan 26 15:58:18 2004
From: hcohen2 at comcast.net (hcohen2)
Date: Mon Jan 26 16:00:45 2004
Subject: [Tutor] Questions regarding class documentation ...
In-Reply-To: <4015764C.20705@venix.com>
References: <40152555.3080803@comcast.net>	<20040126132318.637e68c4.orbitz@ezabel.com>
	<40155E34.6010803@comcast.net> <4015764C.20705@venix.com>
Message-ID: <40157F6A.8030703@comcast.net>

Lloyd,

Works fine as you described, thanks!  Have any idea why I am not seeing 
seeing the instance typed properly?

 >>> import sampledict
 >>> dictIns = sampledict.defaultdict()
 >>> type(dictIns)
<class 'sampledict.defaultdict'>

What is the difference here, other than the simplicity of the class 
definition?

 >>> class C:
...     print 'This is class C'
...
This is class C
 >>> c = C()
 >>> type(c)
<type 'instance'>

Is this explained by metaclass programming: "... Any class whose 
instances are themselves classes, is a metaclass. When we talk about an 
instance that's not a class, the instance's metaclass is the class of 
its class ..."

Not crystal clear to me yet, but I am beginning to think that many of 
the other times I have seen instances they were really derived from the 
old built-in types.  That is, the instance is itself a simple number 
(could be complex) or string type object.

Not sure I am really happy with this, but this may be route to my 
understanding this seeming discrepancy.

Thanks,
Herschel


Lloyd Kvam wrote:

> After importing a module, the "stuff" the module provides is referenced
> from within the module's namespace.
>
> What you want is:
>
> import sampledict
>
> print sampledict.defaultdict
>
>
> In general each python source file represents a separate namespace.
>
> hcohen2 wrote:
>
>> Sorry not sure what your is to address you by.  However, your 
>> explanation does take care of why the straight import <file name> did 
>> not work.  I used the from <file name> import <class name> and it did 
>> work.  Nonetheless, having seen so much discussion on why one should 
>> not use from ... import ... I thought it odd this seemed necessary.
>>
>> I am, however, still bothered by my seeing an instance type()ed as a 
>> class and not an instance.
>>
>> Thanks,
>> Herschel
>>
>> orbitz@ezabel.com wrote:
>>
>>> When you import a module, you tell python that you will be using 
>>> these symbols.  On the 'import' statement, the symbols in your 
>>> module are not loaded into the global namespace.  This is good, 
>>> since there is always the change of two modules having the same 
>>> class/function names in their namespace and you don't want them to 
>>> conflict.  so when you do import sampledict, it loads the module but 
>>> all of the object it defines are located in the sampledict 
>>> namespace.  If you were sure you wanted defaultdict to be imported 
>>> into the global namespace you could do:
>>>
>>> from sampledict import defaultdict.
>>>
>>> now your print defaultdict will work.
>>>
>>> I hope this helps.
>>>
>>>
>>> On Mon, 26 Jan 2004 09:33:57 -0500
>>> hcohen2 <hcohen2@comcast.net> wrote:
>>>
>>>  
>>>
>>>> Because the Core Python Programming book was so out of date 
>>>> regarding class and objects discussion I switched over to reading 
>>>> the Alan Gauld tutorial on the topic; afterward I directed my 
>>>> attention to the documentation on the python.org site.
>>>>
>>>> [ Here are some facts to keep in mind as you read the discussion 
>>>> below: documentation was for version 2.2.3 and I am using 2.2.2.  I 
>>>> have so far reproduced the results exactly when I ran it 
>>>> interactively.  I am trying to prepare myself to create 
>>>> applications independently, hence, I try to go beyond the text 
>>>> samples and use more general approaches.]
>>>>
>>>> Rather than running the code, in section: Subclassing built-in 
>>>> types,  interactively I pasted the class definition in a file.  
>>>> Moreover, to keep it general I gave the file a name different from 
>>>> the class defined in the file, since I would expect I would have 
>>>> many unrelated class definitions within a single file that I would 
>>>> load to run a custom application.
>>>>
>>>> So within the python interpreter I imported the file containing the 
>>>> defaultdict class:
>>>>
>>>> >>>import sampledict  # name sampledict.py
>>>>
>>>> however, when I attempted to run the sample code in the documentation:
>>>>
>>>> >>> print defaultdict
>>>> ...
>>>> NameError: name 'defaultdict' is not defined
>>>>
>>>> Running dir() shows, indeed, 'sampledict' is listed but not 
>>>> 'defaultdict, despite the importing of the file that contains the 
>>>> latter's definition.
>>>>
>>>> Perhaps what I did next was due to my having a tenuous grasp on 
>>>> this topic I remembered the problems with unbound method 
>>>> discussion.  Hence, I tried to created an instance, but I got the 
>>>> same error.  At that point I became suspicious of the success the 
>>>> importing command.  Though I know it is bad style and a command to 
>>>> be avoided I gave the command:
>>>>
>>>> >>> from sampledict import defaultdict
>>>> >>> print defaultdict
>>>> <class 'sampledict.defaultdict'>
>>>> >>> dictIns = defaultdict()
>>>> >>> print dictIns
>>>> {}
>>>> >>> type(dictIns)
>>>> <class 'sampledict.defaultdict'>
>>>>
>>>> Now the print dictIns 'works', but I have a number of questions!
>>>>
>>>> Again the interactive reproduction of the code works exactly as 
>>>> described (as far as I have gone).  While I can reproduce the 
>>>> results, why doesn't the simple import command work for the file?  
>>>> What happened to seeing an instance rather than the type now being 
>>>> class for dictIns?
>>>>
>>>> Could someone enlighten me regarding these questions without citing 
>>>> further documentation that might just add to my confusion as to 
>>>> what may be happening.  When I created instances previously that 
>>>> were identified as instances not as a class.  [Regarding the last 
>>>> statement: on this machine with this version of Python.]
>>>>
>>>> It is very difficult to gain a firm grasp of this topic when the 
>>>> results are so haphazard and not internally consistent.
>>>>
>>>> I would like to thank anyone that can clarify why I have run into 
>>>> these difficulties.
>>>>
>>>>
>>>> _______________________________________________
>>>> 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
>>
>



From pythontutor at venix.com  Mon Jan 26 16:15:54 2004
From: pythontutor at venix.com (Lloyd Kvam)
Date: Mon Jan 26 16:16:10 2004
Subject: [Tutor] Questions regarding class documentation ...
In-Reply-To: <40157F6A.8030703@comcast.net>
References: <40152555.3080803@comcast.net>	<20040126132318.637e68c4.orbitz@ezabel.com>
	<40155E34.6010803@comcast.net> <4015764C.20705@venix.com>
	<40157F6A.8030703@comcast.net>
Message-ID: <4015838A.5060500@venix.com>

Isn't defaultdict a class?

Can you enter(?):
dd = defaultdict()

I expect type(dd) would then be an instance.

Also try doing:
	type(C)
and
	type(c)

hcohen2 wrote:

> Lloyd,
> 
> Works fine as you described, thanks!  Have any idea why I am not seeing 
> seeing the instance typed properly?
> 
>  >>> import sampledict
>  >>> dictIns = sampledict.defaultdict()
>  >>> type(dictIns)
> <class 'sampledict.defaultdict'>
> 
> What is the difference here, other than the simplicity of the class 
> definition?
> 
>  >>> class C:
> ...     print 'This is class C'
> ...
> This is class C
>  >>> c = C()
>  >>> type(c)
> <type 'instance'>
> 
> Is this explained by metaclass programming: "... Any class whose 
> instances are themselves classes, is a metaclass. When we talk about an 
> instance that's not a class, the instance's metaclass is the class of 
> its class ..."
> 
> Not crystal clear to me yet, but I am beginning to think that many of 
> the other times I have seen instances they were really derived from the 
> old built-in types.  That is, the instance is itself a simple number 
> (could be complex) or string type object.
> 
> Not sure I am really happy with this, but this may be route to my 
> understanding this seeming discrepancy.
> 
> Thanks,
> Herschel
> 
> 
> Lloyd Kvam wrote:
> 
>> After importing a module, the "stuff" the module provides is referenced
>> from within the module's namespace.
>>
>> What you want is:
>>
>> import sampledict
>>
>> print sampledict.defaultdict
>>
>>
>> In general each python source file represents a separate namespace.
>>
>> hcohen2 wrote:
>>
>>> Sorry not sure what your is to address you by.  However, your 
>>> explanation does take care of why the straight import <file name> did 
>>> not work.  I used the from <file name> import <class name> and it did 
>>> work.  Nonetheless, having seen so much discussion on why one should 
>>> not use from ... import ... I thought it odd this seemed necessary.
>>>
>>> I am, however, still bothered by my seeing an instance type()ed as a 
>>> class and not an instance.
>>>
>>> Thanks,
>>> Herschel
>>>
>>> orbitz@ezabel.com wrote:
>>>
>>>> When you import a module, you tell python that you will be using 
>>>> these symbols.  On the 'import' statement, the symbols in your 
>>>> module are not loaded into the global namespace.  This is good, 
>>>> since there is always the change of two modules having the same 
>>>> class/function names in their namespace and you don't want them to 
>>>> conflict.  so when you do import sampledict, it loads the module but 
>>>> all of the object it defines are located in the sampledict 
>>>> namespace.  If you were sure you wanted defaultdict to be imported 
>>>> into the global namespace you could do:
>>>>
>>>> from sampledict import defaultdict.
>>>>
>>>> now your print defaultdict will work.
>>>>
>>>> I hope this helps.
>>>>
>>>>
>>>> On Mon, 26 Jan 2004 09:33:57 -0500
>>>> hcohen2 <hcohen2@comcast.net> wrote:
>>>>
>>>>  
>>>>
>>>>> Because the Core Python Programming book was so out of date 
>>>>> regarding class and objects discussion I switched over to reading 
>>>>> the Alan Gauld tutorial on the topic; afterward I directed my 
>>>>> attention to the documentation on the python.org site.
>>>>>
>>>>> [ Here are some facts to keep in mind as you read the discussion 
>>>>> below: documentation was for version 2.2.3 and I am using 2.2.2.  I 
>>>>> have so far reproduced the results exactly when I ran it 
>>>>> interactively.  I am trying to prepare myself to create 
>>>>> applications independently, hence, I try to go beyond the text 
>>>>> samples and use more general approaches.]
>>>>>
>>>>> Rather than running the code, in section: Subclassing built-in 
>>>>> types,  interactively I pasted the class definition in a file.  
>>>>> Moreover, to keep it general I gave the file a name different from 
>>>>> the class defined in the file, since I would expect I would have 
>>>>> many unrelated class definitions within a single file that I would 
>>>>> load to run a custom application.
>>>>>
>>>>> So within the python interpreter I imported the file containing the 
>>>>> defaultdict class:
>>>>>
>>>>> >>>import sampledict  # name sampledict.py
>>>>>
>>>>> however, when I attempted to run the sample code in the documentation:
>>>>>
>>>>> >>> print defaultdict
>>>>> ...
>>>>> NameError: name 'defaultdict' is not defined
>>>>>
>>>>> Running dir() shows, indeed, 'sampledict' is listed but not 
>>>>> 'defaultdict, despite the importing of the file that contains the 
>>>>> latter's definition.
>>>>>
>>>>> Perhaps what I did next was due to my having a tenuous grasp on 
>>>>> this topic I remembered the problems with unbound method 
>>>>> discussion.  Hence, I tried to created an instance, but I got the 
>>>>> same error.  At that point I became suspicious of the success the 
>>>>> importing command.  Though I know it is bad style and a command to 
>>>>> be avoided I gave the command:
>>>>>
>>>>> >>> from sampledict import defaultdict
>>>>> >>> print defaultdict
>>>>> <class 'sampledict.defaultdict'>
>>>>> >>> dictIns = defaultdict()
>>>>> >>> print dictIns
>>>>> {}
>>>>> >>> type(dictIns)
>>>>> <class 'sampledict.defaultdict'>
>>>>>
>>>>> Now the print dictIns 'works', but I have a number of questions!
>>>>>
>>>>> Again the interactive reproduction of the code works exactly as 
>>>>> described (as far as I have gone).  While I can reproduce the 
>>>>> results, why doesn't the simple import command work for the file?  
>>>>> What happened to seeing an instance rather than the type now being 
>>>>> class for dictIns?
>>>>>
>>>>> Could someone enlighten me regarding these questions without citing 
>>>>> further documentation that might just add to my confusion as to 
>>>>> what may be happening.  When I created instances previously that 
>>>>> were identified as instances not as a class.  [Regarding the last 
>>>>> statement: on this machine with this version of Python.]
>>>>>
>>>>> It is very difficult to gain a firm grasp of this topic when the 
>>>>> results are so haphazard and not internally consistent.
>>>>>
>>>>> I would like to thank anyone that can clarify why I have run into 
>>>>> these difficulties.
>>>>>
>>>>>
>>>>> _______________________________________________
>>>>> 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
>>>
>>
> 
> 
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582


From hcohen2 at comcast.net  Mon Jan 26 16:34:37 2004
From: hcohen2 at comcast.net (hcohen2)
Date: Mon Jan 26 16:37:02 2004
Subject: [Tutor] Questions regarding class documentation ...
In-Reply-To: <4015838A.5060500@venix.com>
References: <40152555.3080803@comcast.net>	<20040126132318.637e68c4.orbitz@ezabel.com>
	<40155E34.6010803@comcast.net> <4015764C.20705@venix.com>
	<40157F6A.8030703@comcast.net> <4015838A.5060500@venix.com>
Message-ID: <401587ED.5080908@comcast.net>

Lloyd - going to the snip and insert comments:

Lloyd Kvam wrote:

> Isn't defaultdict a class?

Certainly is defined as such.

>
> Can you enter(?):
> dd = defaultdict()

Did it and type(dd) is
 >>> dd = defaultdict()
 >>> type(dd)
<class 'sampledict.defaultdict'>
 >>> type(defaultdict())
<class 'sampledict.defaultdict'>

>
> I expect type(dd) would then be an instance.
>
> Also try doing:
>     type(C) 

type(C) is a class, did this many times.

>
> and
>     type(c) 

and type(c) is an instance.

Thanks,
Herschel

>
>
> hcohen2 wrote:
>
>> Lloyd,
>>
>> Works fine as you described, thanks!  Have any idea why I am not 
>> seeing seeing the instance typed properly?
>>
>>  >>> import sampledict
>>  >>> dictIns = sampledict.defaultdict()
>>  >>> type(dictIns)
>> <class 'sampledict.defaultdict'>
>>
>> What is the difference here, other than the simplicity of the class 
>> definition?
>>
>>  >>> class C:
>> ...     print 'This is class C'
>> ...
>> This is class C
>>  >>> c = C()
>>  >>> type(c)
>> <type 'instance'>
>>
>> Is this explained by metaclass programming: "... Any class whose 
>> instances are themselves classes, is a metaclass. When we talk about 
>> an instance that's not a class, the instance's metaclass is the class 
>> of its class ..."
>>
>> Not crystal clear to me yet, but I am beginning to think that many of 
>> the other times I have seen instances they were really derived from 
>> the old built-in types.  That is, the instance is itself a simple 
>> number (could be complex) or string type object.
>>
>> Not sure I am really happy with this, but this may be route to my 
>> understanding this seeming discrepancy.
>>
>> Thanks,
>> Herschel
>>
>>
>> Lloyd Kvam wrote:
>>
>>> After importing a module, the "stuff" the module provides is referenced
>>> from within the module's namespace.
>>>
>>> What you want is:
>>>
>>> import sampledict
>>>
>>> print sampledict.defaultdict
>>>
>>>
>>> In general each python source file represents a separate namespace.
>>>
>>> hcohen2 wrote:
>>>
>>>> Sorry not sure what your is to address you by.  However, your 
>>>> explanation does take care of why the straight import <file name> 
>>>> did not work.  I used the from <file name> import <class name> and 
>>>> it did work.  Nonetheless, having seen so much discussion on why 
>>>> one should not use from ... import ... I thought it odd this seemed 
>>>> necessary.
>>>>
>>>> I am, however, still bothered by my seeing an instance type()ed as 
>>>> a class and not an instance.
>>>>
>>>> Thanks,
>>>> Herschel
>>>>
>>>> orbitz@ezabel.com wrote:
>>>>
>>>>> When you import a module, you tell python that you will be using 
>>>>> these symbols.  On the 'import' statement, the symbols in your 
>>>>> module are not loaded into the global namespace.  This is good, 
>>>>> since there is always the change of two modules having the same 
>>>>> class/function names in their namespace and you don't want them to 
>>>>> conflict.  so when you do import sampledict, it loads the module 
>>>>> but all of the object it defines are located in the sampledict 
>>>>> namespace.  If you were sure you wanted defaultdict to be imported 
>>>>> into the global namespace you could do:
>>>>>
>>>>> from sampledict import defaultdict.
>>>>>
>>>>> now your print defaultdict will work.
>>>>>
>>>>> I hope this helps.
>>>>>
>>>>>
>>>>> On Mon, 26 Jan 2004 09:33:57 -0500
>>>>> hcohen2 <hcohen2@comcast.net> wrote:
>>>>>
>>>>>  
>>>>>
>>>>>> Because the Core Python Programming book was so out of date 
>>>>>> regarding class and objects discussion I switched over to reading 
>>>>>> the Alan Gauld tutorial on the topic; afterward I directed my 
>>>>>> attention to the documentation on the python.org site.
>>>>>>
>>>>>> [ Here are some facts to keep in mind as you read the discussion 
>>>>>> below: documentation was for version 2.2.3 and I am using 2.2.2.  
>>>>>> I have so far reproduced the results exactly when I ran it 
>>>>>> interactively.  I am trying to prepare myself to create 
>>>>>> applications independently, hence, I try to go beyond the text 
>>>>>> samples and use more general approaches.]
>>>>>>
>>>>>> Rather than running the code, in section: Subclassing built-in 
>>>>>> types,  interactively I pasted the class definition in a file.  
>>>>>> Moreover, to keep it general I gave the file a name different 
>>>>>> from the class defined in the file, since I would expect I would 
>>>>>> have many unrelated class definitions within a single file that I 
>>>>>> would load to run a custom application.
>>>>>>
>>>>>> So within the python interpreter I imported the file containing 
>>>>>> the defaultdict class:
>>>>>>
>>>>>> >>>import sampledict  # name sampledict.py
>>>>>>
>>>>>> however, when I attempted to run the sample code in the 
>>>>>> documentation:
>>>>>>
>>>>>> >>> print defaultdict
>>>>>> ...
>>>>>> NameError: name 'defaultdict' is not defined
>>>>>>
>>>>>> Running dir() shows, indeed, 'sampledict' is listed but not 
>>>>>> 'defaultdict, despite the importing of the file that contains the 
>>>>>> latter's definition.
>>>>>>
>>>>>> Perhaps what I did next was due to my having a tenuous grasp on 
>>>>>> this topic I remembered the problems with unbound method 
>>>>>> discussion.  Hence, I tried to created an instance, but I got the 
>>>>>> same error.  At that point I became suspicious of the success the 
>>>>>> importing command.  Though I know it is bad style and a command 
>>>>>> to be avoided I gave the command:
>>>>>>
>>>>>> >>> from sampledict import defaultdict
>>>>>> >>> print defaultdict
>>>>>> <class 'sampledict.defaultdict'>
>>>>>> >>> dictIns = defaultdict()
>>>>>> >>> print dictIns
>>>>>> {}
>>>>>> >>> type(dictIns)
>>>>>> <class 'sampledict.defaultdict'>
>>>>>>
>>>>>> Now the print dictIns 'works', but I have a number of questions!
>>>>>>
>>>>>> Again the interactive reproduction of the code works exactly as 
>>>>>> described (as far as I have gone).  While I can reproduce the 
>>>>>> results, why doesn't the simple import command work for the 
>>>>>> file?  What happened to seeing an instance rather than the type 
>>>>>> now being class for dictIns?
>>>>>>
>>>>>> Could someone enlighten me regarding these questions without 
>>>>>> citing further documentation that might just add to my confusion 
>>>>>> as to what may be happening.  When I created instances previously 
>>>>>> that were identified as instances not as a class.  [Regarding the 
>>>>>> last statement: on this machine with this version of Python.]
>>>>>>
>>>>>> It is very difficult to gain a firm grasp of this topic when the 
>>>>>> results are so haphazard and not internally consistent.
>>>>>>
>>>>>> I would like to thank anyone that can clarify why I have run into 
>>>>>> these difficulties.
>>>>>>
>>>>>>
>>>>>> _______________________________________________
>>>>>> 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
>>>>
>>>
>>
>>
>>
>



From hcohen2 at comcast.net  Mon Jan 26 16:38:34 2004
From: hcohen2 at comcast.net (hcohen2)
Date: Mon Jan 26 16:40:57 2004
Subject: RE[Tutor] Questions regarding class documentation ...: 
Message-ID: <401588DA.9030906@comcast.net>

Sorry did not hit reply all - sending partial copy.

RE: it's not an instance. It's just a class. You have not instantiated one

Both "Learning Python" and "Core Python Programming", page 153 ist 
edition 1999 printing and page 420 2001 printing, respectively,  seemed 
to define this as creating an instance.

Also see the example I sent to Lloyd Kvam, which typed to an instance.

Herschel

orbitz@ezabel.com wrote:

Because it's not an instance. It's just a class. You have not 
instantiated one of it yet.

sampledict.defaultdict is a class
x = sampledict.defaultdict() makes a new class.

Read the section in the tutorial on classes.


On Mon, 26 Jan 2004 13:36:36 -0500
hcohen2 <hcohen2@comcast.net> wrote:



From pythontutor at venix.com  Mon Jan 26 16:41:51 2004
From: pythontutor at venix.com (Lloyd Kvam)
Date: Mon Jan 26 16:41:59 2004
Subject: [Tutor] Questions regarding class documentation ...
In-Reply-To: <4015838A.5060500@venix.com>
References: <40152555.3080803@comcast.net>	<20040126132318.637e68c4.orbitz@ezabel.com>
	<40155E34.6010803@comcast.net> <4015764C.20705@venix.com>
	<40157F6A.8030703@comcast.net> <4015838A.5060500@venix.com>
Message-ID: <4015899F.2020003@venix.com>

Sorry about this post.  I misread what you had done.  For now old-style classes
and new style classes are both available in Python, but give slightly
different type information.  Below class C is an old-style class and
D is a new-style class.  I hope this makes it clear.

 >>> class C:
... 	pass
...
 >>> class D(object):
... 	pass
...
 >>> c = C()
 >>> d = D()
 >>> type(c)
<type 'instance'>
 >>> type(d)
<class '__main__.D'>


Lloyd Kvam wrote:

> Isn't defaultdict a class?
> 
> Can you enter(?):
> dd = defaultdict()
> 
> I expect type(dd) would then be an instance.
> 
> Also try doing:
>     type(C)
> and
>     type(c)
> 
> hcohen2 wrote:
> 
>> Lloyd,
>>
>> Works fine as you described, thanks!  Have any idea why I am not 
>> seeing seeing the instance typed properly?
>>
>>  >>> import sampledict
>>  >>> dictIns = sampledict.defaultdict()
>>  >>> type(dictIns)
>> <class 'sampledict.defaultdict'>
>>
>> What is the difference here, other than the simplicity of the class 
>> definition?
>>
>>  >>> class C:
>> ...     print 'This is class C'
>> ...
>> This is class C
>>  >>> c = C()
>>  >>> type(c)
>> <type 'instance'>
>>
>> Is this explained by metaclass programming: "... Any class whose 
>> instances are themselves classes, is a metaclass. When we talk about 
>> an instance that's not a class, the instance's metaclass is the class 
>> of its class ..."
>>
>> Not crystal clear to me yet, but I am beginning to think that many of 
>> the other times I have seen instances they were really derived from 
>> the old built-in types.  That is, the instance is itself a simple 
>> number (could be complex) or string type object.
>>
>> Not sure I am really happy with this, but this may be route to my 
>> understanding this seeming discrepancy.
>>
>> Thanks,
>> Herschel
>>
>>
>> Lloyd Kvam wrote:
>>
>>> After importing a module, the "stuff" the module provides is referenced
>>> from within the module's namespace.
>>>
>>> What you want is:
>>>
>>> import sampledict
>>>
>>> print sampledict.defaultdict
>>>
>>>
>>> In general each python source file represents a separate namespace.
>>>
>>> hcohen2 wrote:
>>>
>>>> Sorry not sure what your is to address you by.  However, your 
>>>> explanation does take care of why the straight import <file name> 
>>>> did not work.  I used the from <file name> import <class name> and 
>>>> it did work.  Nonetheless, having seen so much discussion on why one 
>>>> should not use from ... import ... I thought it odd this seemed 
>>>> necessary.
>>>>
>>>> I am, however, still bothered by my seeing an instance type()ed as a 
>>>> class and not an instance.
>>>>
>>>> Thanks,
>>>> Herschel
>>>>
>>>> orbitz@ezabel.com wrote:
>>>>
>>>>> When you import a module, you tell python that you will be using 
>>>>> these symbols.  On the 'import' statement, the symbols in your 
>>>>> module are not loaded into the global namespace.  This is good, 
>>>>> since there is always the change of two modules having the same 
>>>>> class/function names in their namespace and you don't want them to 
>>>>> conflict.  so when you do import sampledict, it loads the module 
>>>>> but all of the object it defines are located in the sampledict 
>>>>> namespace.  If you were sure you wanted defaultdict to be imported 
>>>>> into the global namespace you could do:
>>>>>
>>>>> from sampledict import defaultdict.
>>>>>
>>>>> now your print defaultdict will work.
>>>>>
>>>>> I hope this helps.
>>>>>
>>>>>
>>>>> On Mon, 26 Jan 2004 09:33:57 -0500
>>>>> hcohen2 <hcohen2@comcast.net> wrote:
>>>>>
>>>>>  
>>>>>
>>>>>> Because the Core Python Programming book was so out of date 
>>>>>> regarding class and objects discussion I switched over to reading 
>>>>>> the Alan Gauld tutorial on the topic; afterward I directed my 
>>>>>> attention to the documentation on the python.org site.
>>>>>>
>>>>>> [ Here are some facts to keep in mind as you read the discussion 
>>>>>> below: documentation was for version 2.2.3 and I am using 2.2.2.  
>>>>>> I have so far reproduced the results exactly when I ran it 
>>>>>> interactively.  I am trying to prepare myself to create 
>>>>>> applications independently, hence, I try to go beyond the text 
>>>>>> samples and use more general approaches.]
>>>>>>
>>>>>> Rather than running the code, in section: Subclassing built-in 
>>>>>> types,  interactively I pasted the class definition in a file.  
>>>>>> Moreover, to keep it general I gave the file a name different from 
>>>>>> the class defined in the file, since I would expect I would have 
>>>>>> many unrelated class definitions within a single file that I would 
>>>>>> load to run a custom application.
>>>>>>
>>>>>> So within the python interpreter I imported the file containing 
>>>>>> the defaultdict class:
>>>>>>
>>>>>> >>>import sampledict  # name sampledict.py
>>>>>>
>>>>>> however, when I attempted to run the sample code in the 
>>>>>> documentation:
>>>>>>
>>>>>> >>> print defaultdict
>>>>>> ...
>>>>>> NameError: name 'defaultdict' is not defined
>>>>>>
>>>>>> Running dir() shows, indeed, 'sampledict' is listed but not 
>>>>>> 'defaultdict, despite the importing of the file that contains the 
>>>>>> latter's definition.
>>>>>>
>>>>>> Perhaps what I did next was due to my having a tenuous grasp on 
>>>>>> this topic I remembered the problems with unbound method 
>>>>>> discussion.  Hence, I tried to created an instance, but I got the 
>>>>>> same error.  At that point I became suspicious of the success the 
>>>>>> importing command.  Though I know it is bad style and a command to 
>>>>>> be avoided I gave the command:
>>>>>>
>>>>>> >>> from sampledict import defaultdict
>>>>>> >>> print defaultdict
>>>>>> <class 'sampledict.defaultdict'>
>>>>>> >>> dictIns = defaultdict()
>>>>>> >>> print dictIns
>>>>>> {}
>>>>>> >>> type(dictIns)
>>>>>> <class 'sampledict.defaultdict'>
>>>>>>
>>>>>> Now the print dictIns 'works', but I have a number of questions!
>>>>>>
>>>>>> Again the interactive reproduction of the code works exactly as 
>>>>>> described (as far as I have gone).  While I can reproduce the 
>>>>>> results, why doesn't the simple import command work for the file?  
>>>>>> What happened to seeing an instance rather than the type now being 
>>>>>> class for dictIns?
>>>>>>
>>>>>> Could someone enlighten me regarding these questions without 
>>>>>> citing further documentation that might just add to my confusion 
>>>>>> as to what may be happening.  When I created instances previously 
>>>>>> that were identified as instances not as a class.  [Regarding the 
>>>>>> last statement: on this machine with this version of Python.]
>>>>>>
>>>>>> It is very difficult to gain a firm grasp of this topic when the 
>>>>>> results are so haphazard and not internally consistent.
>>>>>>
>>>>>> I would like to thank anyone that can clarify why I have run into 
>>>>>> these difficulties.
>>>>>>
>>>>>>
>>>>>> _______________________________________________
>>>>>> 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
>>>>
>>>
>>
>>
>>
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582


From hcohen2 at comcast.net  Mon Jan 26 17:24:30 2004
From: hcohen2 at comcast.net (hcohen2)
Date: Mon Jan 26 17:26:48 2004
Subject: [Tutor] Questions regarding class documentation ...
In-Reply-To: <4015899F.2020003@venix.com>
References: <40152555.3080803@comcast.net>	<20040126132318.637e68c4.orbitz@ezabel.com>
	<40155E34.6010803@comcast.net> <4015764C.20705@venix.com>
	<40157F6A.8030703@comcast.net> <4015838A.5060500@venix.com>
	<4015899F.2020003@venix.com>
Message-ID: <4015939E.1070408@comcast.net>

Lloyd,

Do not be sorry, I think you have answered my question. 

As too being sorry it should be I look at my most recent return post to 
orbitz@ezabel.com that I forwarded.  I was citing old style class 
definitions!

It may be in the discussion of metaclasses, but that is over my head at 
this moment.

Thank you very much for your efforts to enlighten me.  I appreciate the 
help.

Herschel

Lloyd Kvam wrote:

> Sorry about this post.  I misread what you had done.  For now 
> old-style classes
> and new style classes are both available in Python, but give slightly
> different type information.  Below class C is an old-style class and
> D is a new-style class.  I hope this makes it clear.
>
> >>> class C:
> ...     pass
> ...
> >>> class D(object):
> ...     pass
> ...
> >>> c = C()
> >>> d = D()
> >>> type(c)
> <type 'instance'>
> >>> type(d)
> <class '__main__.D'>
>
>
> Lloyd Kvam wrote:
>
>> Isn't defaultdict a class?
>>
>> Can you enter(?):
>> dd = defaultdict()
>>
>> I expect type(dd) would then be an instance.
>>
>> Also try doing:
>>     type(C)
>> and
>>     type(c)
>>
>> hcohen2 wrote:
>>
>>> Lloyd,
>>>
>>> Works fine as you described, thanks!  Have any idea why I am not 
>>> seeing seeing the instance typed properly?
>>>
>>>  >>> import sampledict
>>>  >>> dictIns = sampledict.defaultdict()
>>>  >>> type(dictIns)
>>> <class 'sampledict.defaultdict'>
>>>
>>> What is the difference here, other than the simplicity of the class 
>>> definition?
>>>
>>>  >>> class C:
>>> ...     print 'This is class C'
>>> ...
>>> This is class C
>>>  >>> c = C()
>>>  >>> type(c)
>>> <type 'instance'>
>>>
>>> Is this explained by metaclass programming: "... Any class whose 
>>> instances are themselves classes, is a metaclass. When we talk about 
>>> an instance that's not a class, the instance's metaclass is the 
>>> class of its class ..."
>>>
>>> Not crystal clear to me yet, but I am beginning to think that many 
>>> of the other times I have seen instances they were really derived 
>>> from the old built-in types.  That is, the instance is itself a 
>>> simple number (could be complex) or string type object.
>>>
>>> Not sure I am really happy with this, but this may be route to my 
>>> understanding this seeming discrepancy.
>>>
>>> Thanks,
>>> Herschel
>>>
>>>
>>> Lloyd Kvam wrote:
>>>
>>>> After importing a module, the "stuff" the module provides is 
>>>> referenced
>>>> from within the module's namespace.
>>>>
>>>> What you want is:
>>>>
>>>> import sampledict
>>>>
>>>> print sampledict.defaultdict
>>>>
>>>>
>>>> In general each python source file represents a separate namespace.
>>>>
>>>> hcohen2 wrote:
>>>>
>>>>> Sorry not sure what your is to address you by.  However, your 
>>>>> explanation does take care of why the straight import <file name> 
>>>>> did not work.  I used the from <file name> import <class name> and 
>>>>> it did work.  Nonetheless, having seen so much discussion on why 
>>>>> one should not use from ... import ... I thought it odd this 
>>>>> seemed necessary.
>>>>>
>>>>> I am, however, still bothered by my seeing an instance type()ed as 
>>>>> a class and not an instance.
>>>>>
>>>>> Thanks,
>>>>> Herschel
>>>>>
>>>>> orbitz@ezabel.com wrote:
>>>>>
>>>>>> When you import a module, you tell python that you will be using 
>>>>>> these symbols.  On the 'import' statement, the symbols in your 
>>>>>> module are not loaded into the global namespace.  This is good, 
>>>>>> since there is always the change of two modules having the same 
>>>>>> class/function names in their namespace and you don't want them 
>>>>>> to conflict.  so when you do import sampledict, it loads the 
>>>>>> module but all of the object it defines are located in the 
>>>>>> sampledict namespace.  If you were sure you wanted defaultdict to 
>>>>>> be imported into the global namespace you could do:
>>>>>>
>>>>>> from sampledict import defaultdict.
>>>>>>
>>>>>> now your print defaultdict will work.
>>>>>>
>>>>>> I hope this helps.
>>>>>>
>>>>>>
>>>>>> On Mon, 26 Jan 2004 09:33:57 -0500
>>>>>> hcohen2 <hcohen2@comcast.net> wrote:
>>>>>>
>>>>>>  
>>>>>>
>>>>>>> Because the Core Python Programming book was so out of date 
>>>>>>> regarding class and objects discussion I switched over to 
>>>>>>> reading the Alan Gauld tutorial on the topic; afterward I 
>>>>>>> directed my attention to the documentation on the python.org site.
>>>>>>>
>>>>>>> [ Here are some facts to keep in mind as you read the discussion 
>>>>>>> below: documentation was for version 2.2.3 and I am using 
>>>>>>> 2.2.2.  I have so far reproduced the results exactly when I ran 
>>>>>>> it interactively.  I am trying to prepare myself to create 
>>>>>>> applications independently, hence, I try to go beyond the text 
>>>>>>> samples and use more general approaches.]
>>>>>>>
>>>>>>> Rather than running the code, in section: Subclassing built-in 
>>>>>>> types,  interactively I pasted the class definition in a file.  
>>>>>>> Moreover, to keep it general I gave the file a name different 
>>>>>>> from the class defined in the file, since I would expect I would 
>>>>>>> have many unrelated class definitions within a single file that 
>>>>>>> I would load to run a custom application.
>>>>>>>
>>>>>>> So within the python interpreter I imported the file containing 
>>>>>>> the defaultdict class:
>>>>>>>
>>>>>>> >>>import sampledict  # name sampledict.py
>>>>>>>
>>>>>>> however, when I attempted to run the sample code in the 
>>>>>>> documentation:
>>>>>>>
>>>>>>> >>> print defaultdict
>>>>>>> ...
>>>>>>> NameError: name 'defaultdict' is not defined
>>>>>>>
>>>>>>> Running dir() shows, indeed, 'sampledict' is listed but not 
>>>>>>> 'defaultdict, despite the importing of the file that contains 
>>>>>>> the latter's definition.
>>>>>>>
>>>>>>> Perhaps what I did next was due to my having a tenuous grasp on 
>>>>>>> this topic I remembered the problems with unbound method 
>>>>>>> discussion.  Hence, I tried to created an instance, but I got 
>>>>>>> the same error.  At that point I became suspicious of the 
>>>>>>> success the importing command.  Though I know it is bad style 
>>>>>>> and a command to be avoided I gave the command:
>>>>>>>
>>>>>>> >>> from sampledict import defaultdict
>>>>>>> >>> print defaultdict
>>>>>>> <class 'sampledict.defaultdict'>
>>>>>>> >>> dictIns = defaultdict()
>>>>>>> >>> print dictIns
>>>>>>> {}
>>>>>>> >>> type(dictIns)
>>>>>>> <class 'sampledict.defaultdict'>
>>>>>>>
>>>>>>> Now the print dictIns 'works', but I have a number of questions!
>>>>>>>
>>>>>>> Again the interactive reproduction of the code works exactly as 
>>>>>>> described (as far as I have gone).  While I can reproduce the 
>>>>>>> results, why doesn't the simple import command work for the 
>>>>>>> file?  What happened to seeing an instance rather than the type 
>>>>>>> now being class for dictIns?
>>>>>>>
>>>>>>> Could someone enlighten me regarding these questions without 
>>>>>>> citing further documentation that might just add to my confusion 
>>>>>>> as to what may be happening.  When I created instances 
>>>>>>> previously that were identified as instances not as a class.  
>>>>>>> [Regarding the last statement: on this machine with this version 
>>>>>>> of Python.]
>>>>>>>
>>>>>>> It is very difficult to gain a firm grasp of this topic when the 
>>>>>>> results are so haphazard and not internally consistent.
>>>>>>>
>>>>>>> I would like to thank anyone that can clarify why I have run 
>>>>>>> into these difficulties.
>>>>>>>
>>>>>>>
>>>>>>> _______________________________________________
>>>>>>> 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
>>>>>
>>>>
>>>
>>>
>>>
>>
>



From bgart5 at hotmail.com  Mon Jan 26 22:29:10 2004
From: bgart5 at hotmail.com (Mike McMullen)
Date: Mon Jan 26 22:29:17 2004
Subject: [Tutor] exporting?  saving?  whatever you want to call it.
Message-ID: <BAY8-F70dZwsKgCoV4Q0001925a@hotmail.com>

I have a small program written that you can enter your employment info into 
(date you started, date you ended, supervisor's name, job title, etc.)

It's a niffty little program (if I do say so myslef) but I was wondering if 
there is anyway I can save it (or export it) to a database (excell like) or 
something like Microsoft Word.

If you need some more info or even the code itself just tell me.  Still 
learning the ropes.

Thanks.

_________________________________________________________________
Scope out the new MSN Plus Internet Software — optimizes dial-up to the max! 
   http://join.msn.com/?pgmarket=en-us&page=byoa/plus&ST=1


From abc-100036 at apc.edu.ph  Tue Jan 27 01:25:11 2004
From: abc-100036 at apc.edu.ph (abc-100036@apc.edu.ph)
Date: Tue Jan 27 01:25:23 2004
Subject: [Tutor] Tkinter - TOP LEVEL WINDOW Questions
Message-ID: <20040127062511.49E64797DD@cerveza.apc.edu.ph>

I have a problem regarding displaying a new top level window using tkinter codes. Whenever 
I ran the script. The top level window shows up in the topmost left corner of my screen.  
 
Given that, how do I make the top level window to display in the center of the screen. 
 
Thanx.    
 
 

________________________________________________________________________________________

This email message was delivered to you by <http://www.apc.edu.ph> Asia Pacific College.
Scanning and Virus Filtering is delivered by <http:///www.ravantivirus.com> RAV Antivirus.
For more information, please visit our website or email the system administrators at
mailto:sysadmins@apc.edu.ph.




From glingl at aon.at  Tue Jan 27 02:50:37 2004
From: glingl at aon.at (Gregor Lingl)
Date: Tue Jan 27 02:49:40 2004
Subject: [Tutor] Tkinter - TOP LEVEL WINDOW Questions
In-Reply-To: <20040127062511.49E64797DD@cerveza.apc.edu.ph>
References: <20040127062511.49E64797DD@cerveza.apc.edu.ph>
Message-ID: <4016184D.2090302@aon.at>



abc-100036@apc.edu.ph schrieb:

>I have a problem regarding displaying a new top level window using tkinter codes. Whenever 
>I ran the script. The top level window shows up in the topmost left corner of my screen.  
>  
>
You have to use winfo_screenwidth() and winfo_screenheight() methods to 
determine screensize
and the use geometry method to place your window.

Example:

 >>> from Tkinter import *
 >>> root = Tk()
 >>> w=root.winfo_screenwidth()
 >>> h=root.winfo_screenheight()
 >>> root.geometry("400x300+%d+%d" % ( (w-400)/2, (h-300)/2 ) )
''
 >>>

HTH, Gregor

> 
>Given that, how do I make the top level window to display in the center of the screen. 
> 
>Thanx.    
>
>  
>


From ATrautman at perryjudds.com  Tue Jan 27 12:19:06 2004
From: ATrautman at perryjudds.com (Alan Trautman)
Date: Tue Jan 27 12:19:11 2004
Subject: [Tutor] OOP programming using  VB
Message-ID: <06738462136C054B8F8872D69DA140DB01C08C5C@corp-exch-1.pjinet.com>

Lakimi,

Until the .NET (ignore the released and pulled back ver 7.0) version of VB.
It has never supported true objects. You could program around that and make
things that behave similar to objects but weren't really quite there.

If you want the use object programming in vb you'll need .NET and any decent
.NET book on programming. Most of the tutorial site also have something
similar. .NET forces the programmer to use things close to Python in terms
of namespaces and objects. It will also be closer to the C++ you already
know.

There are also book on making object like classes in VB 6.0. Again a quick
search of the tutorial site will find this. I like the book "Data Structures
in VB 6.0" {probably not exactly correct) it is old enough I'm sure to be
cheap used. 

HTH,
Alan


-----Original Message-----
From: Lakmi munasinghe [mailto:lakmi_ll@yahoo.com]
Sent: Friday, January 23, 2004 10:21 PM
To: Tutor@python.org
Subject: [Tutor] OOP programming using VB


Hi,
I have never done OO programming using VB . Anyway I have used OOP concepts
with C++. I have no clear idea of how to use OOP concepts with VB forms and
all, because I used to do programmimn in VB by writing codes to button
clicks,combo box change event etc. I have heard that VB supports OOP ; but I
have no idea of how it is done.
Can you give me an example of how it is being done ?
Lakmi


Do you Yahoo!?
Yahoo! SiteBuilder - Free web site building tool. Try it!

From littledanehren at yahoo.com  Tue Jan 27 13:59:37 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Tue Jan 27 13:59:43 2004
Subject: [Tutor] exporting?  saving?  whatever you want to call it.
In-Reply-To: <BAY8-F70dZwsKgCoV4Q0001925a@hotmail.com>
Message-ID: <20040127185937.93372.qmail@web41810.mail.yahoo.com>

Mike McMullen wrote:
> I have a small program written that you can enter
> your employment info into 
> (date you started, date you ended, supervisor's
> name, job title, etc.)
> 
> It's a niffty little program (if I do say so myslef)
> but I was wondering if 
> there is anyway I can save it (or export it) to a
> database (excell like) or 
> something like Microsoft Word.
> 
> If you need some more info or even the code itself
> just tell me.  Still 
> learning the ropes.
> 
> Thanks.

You can use the win32all module to interface with the
MFC, but if you want a more cross-platform solution,
you should probably use something else. One option is
reportlab (www.reportlab.org), a free, open source,
cross-platform PDF generation library. Another option
would be to use a true SQL database like MySQL. The
standardized Python/SQL interface makes it so that you
can switch database backends without changing your
code much. You could always just use a text file
(possibly in CSV format for excel).

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Yahoo! SiteBuilder - Free web site building tool. Try it!
http://webhosting.yahoo.com/ps/sb/

From hcohen2 at comcast.net  Tue Jan 27 14:54:08 2004
From: hcohen2 at comcast.net (hcohen2)
Date: Tue Jan 27 14:56:25 2004
Subject: [Tutor] When was interned strings dropped (and why)?
Message-ID: <4016C1E0.8020407@comcast.net>

As you have heard from me too many times: I am using ver. 2.2.2 and 
everytime I id the identical string it has a new location.

It was there in version 2.0.  Supposedly it had an advantage in 
performance, which should not be the primary reason for its inclusion.

What were its drawbacks, for it has obviously been dropped.

I am guessing, but doing a quick search it seems that making the 
formally built-in types objects that are subclassable sort of broken the 
single location for these base type objects.  When it is assigned to a 
variable (instance) it remains at that location.

Am I on the right track?


From littledanehren at yahoo.com  Tue Jan 27 15:29:46 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Tue Jan 27 15:29:51 2004
Subject: [Tutor] When was interned strings dropped (and why)?
In-Reply-To: <4016C1E0.8020407@comcast.net>
Message-ID: <20040127202947.91777.qmail@web41807.mail.yahoo.com>

hcohen2 wrote:
> As you have heard from me too many times: I am using
> ver. 2.2.2 and 
> everytime I id the identical string it has a new
> location.
> 
> It was there in version 2.0.  Supposedly it had an
> advantage in 
> performance, which should not be the primary reason
> for its inclusion.
> 
> What were its drawbacks, for it has obviously been
> dropped.
> 
> I am guessing, but doing a quick search it seems
> that making the 
> formally built-in types objects that are
> subclassable sort of broken the 
> single location for these base type objects.  When
> it is assigned to a 
> variable (instance) it remains at that location.
> 
> Am I on the right track?


Switch to 2.3. That's what I'm using and I don't have
that bug. Even identical tuples have the same id.

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Yahoo! SiteBuilder - Free web site building tool. Try it!
http://webhosting.yahoo.com/ps/sb/

From alan.gauld at blueyonder.co.uk  Tue Jan 27 17:36:57 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Tue Jan 27 17:36:11 2004
Subject: [Tutor] Questions regarding class documentation ...
References: <40152555.3080803@comcast.net>
Message-ID: <003d01c3e526$12944250$6401a8c0@xp>

> class and objects discussion I switched over to reading the Alan
Gauld
> tutorial on the topic;

Maybe you should have read the modules topic too :-)

>  >>>import sampledict  # name sampledict.py
>
> however, when I attempted to run the sample code in the
documentation:
>
>  >>> print defaultdict
> ...
> NameError: name 'defaultdict' is not defined

As I'm sure others have replied by now (but I'm just back from a
business trip and catching up by digest) import only makes the
module name visible. You need to use that to qualify the names
inside the module.

> It is very difficult to gain a firm grasp of this topic when the
results
> are so haphazard and not internally consistent.

Maybe reading the modules bit of my tutor plus the "Whats in a
name?" topic might help. But really its easy enough one the
light-bulb comes on, it's just about adjusting to a new way
of working having come from a C/C++ background.
import is not the same as #include

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


From gil at tuckers.de  Tue Jan 27 18:13:22 2004
From: gil at tuckers.de (gil@tuckers.de)
Date: Tue Jan 27 18:12:39 2004
Subject: [Tutor] problems with py 2.3.2
Message-ID: <000601c3e52b$3c82def0$6500a8c0@p933>



greetings,
                 I wonder if anyone is or has had problems
installing the latest Python release. Well several times
I tried to get it right after downloading- Getting it on Windows
2000 pro isw easy but it never works properly for the IDE
doesn`t come when you call it. The command side in DOS is 
fine but the GUI and ther modules never show up.
When I install I try to put it in different filkes, but no way.

So I giave up and just use the Python 2.1 release. Maybe 
some one somewhere mighthave sometip or tips,
 sincereley gil




From littledanehren at yahoo.com  Tue Jan 27 18:53:22 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Tue Jan 27 18:53:27 2004
Subject: [Tutor] problems with py 2.3.2
In-Reply-To: <000601c3e52b$3c82def0$6500a8c0@p933>
Message-ID: <20040127235322.42943.qmail@web41801.mail.yahoo.com>


--- gil@tuckers.de wrote:
> 
> 
> greetings,
>                  I wonder if anyone is or has had
> problems
> installing the latest Python release. Well several
> times
> I tried to get it right after downloading- Getting
> it on Windows
> 2000 pro isw easy but it never works properly for
> the IDE
> doesn`t come when you call it. The command side in
> DOS is 
> fine but the GUI and ther modules never show up.
> When I install I try to put it in different filkes,
> but no way.
> 
> So I giave up and just use the Python 2.1 release.
> Maybe 
> some one somewhere mighthave sometip or tips,
>  sincereley gil

Just so you know, the current version is 2.3.3, not
2.3.2. This probably isn't the source of your problem, though.

__________________________________
Do you Yahoo!?
Yahoo! SiteBuilder - Free web site building tool. Try it!
http://webhosting.yahoo.com/ps/sb/

From hans at zephyrfalcon.org  Tue Jan 27 20:23:13 2004
From: hans at zephyrfalcon.org (Hans Nowak)
Date: Tue Jan 27 20:20:45 2004
Subject: [Tutor] Re: problems with py 2.3.2
In-Reply-To: <000601c3e52b$3c82def0$6500a8c0@p933>
References: <000601c3e52b$3c82def0$6500a8c0@p933>
Message-ID: <40170F01.8040906@zephyrfalcon.org>

gil@tuckers.de wrote:
> 
> greetings,
>                  I wonder if anyone is or has had problems
> installing the latest Python release. Well several times
> I tried to get it right after downloading- Getting it on Windows
> 2000 pro isw easy but it never works properly for the IDE
> doesn`t come when you call it. The command side in DOS is 
> fine but the GUI and ther modules never show up.
> When I install I try to put it in different filkes, but no way.
> 
> So I giave up and just use the Python 2.1 release. Maybe 
> some one somewhere mighthave sometip or tips,
>  sincereley gil

Python 2.3's IDLE doesn't work for me either, because my Tcl/Tk installed is 
messed up, and I am too lazy^H^H^H^Hbusy to fix it.  The problem might be 
related to the fact that I have various Pythons installed (1.5.2, 2.1, 2.2, 
2.3) plus some other things that installed their own Tk libraries.

To find out if you have the same problem, grab a command shell and do:

cd c:\python23\Tools\idle
c:\python23\python.exe idle.py

(assuming you installed in c:\python23)

I get a bunch of errors here complaining about Tcl.  The errors on your screen 
may be of a different nature, I don't know.

It's not the end of the world if IDLE doesn't work, though.  There are other 
shells and IDEs around.  If you're using it primarily as an interactive 
interpreter, try PyCrust (bundled with wxPython).  If you're using it as an 
editor, there are oodles of alternatives around: Komodo, SPE, LEO, vi, emacs, 
Zeus, PythonWin, etc.

HTH,

-- 
Hans (hans@zephyrfalcon.org)
http://zephyrfalcon.org/



From Harm_Kirchhoff at mail.digital.co.jp  Tue Jan 27 21:23:55 2004
From: Harm_Kirchhoff at mail.digital.co.jp (Harm_Kirchhoff@mail.digital.co.jp)
Date: Tue Jan 27 21:24:07 2004
Subject: [Tutor] exporting? saving? whatever you want to call it. (Mike
	McMullen)
Message-ID: <OF3D01246B.F58F8542-ON49256E29.000BB302-49256E29.000CFF59@jp.schneider-electric.com>

There is a very convenient way: the csv module. I use it all the time to 
save & read data from csv files, which can be read by any spreach sheet 
and word porcessing software. Check the python docu. If you need code 
examples, mail me.
 


From mjyuen at hotmail.com  Tue Jan 27 21:49:38 2004
From: mjyuen at hotmail.com (Mike Yuen)
Date: Tue Jan 27 21:49:42 2004
Subject: [Tutor] Simple question: Creating a string with a directory
	structure
Message-ID: <BAY10-F107eH17XiwJe00023a06@hotmail.com>

What i'm trying to do concatenate a bunch of strings to make a file path.  
For example,

A = "c:/WINNT"
B = "/"
C = "Program Files"

When I go:
D = A+B+C
print D # hoping to get c:/winnt/program files.

INstead, when I output D, I get <type 'str'>
How do I fix this?

_________________________________________________________________
Add photos to your e-mail with MSN 8. Get 2 months FREE*.  
http://join.msn.com/?page=features/photos&pgmarket=en-ca&RU=http%3a%2f%2fjoin.msn.com%2f%3fpage%3dmisc%2fspecialoffers%26pgmarket%3den-ca


From carroll at tjc.com  Tue Jan 27 22:51:13 2004
From: carroll at tjc.com (Terry Carroll)
Date: Tue Jan 27 22:51:17 2004
Subject: [Tutor] Simple question: Creating a string with a directory
	structure
In-Reply-To: <BAY10-F107eH17XiwJe00023a06@hotmail.com>
Message-ID: <Pine.LNX.4.44.0401271943100.28102-100000@violet.rahul.net>

On Tue, 27 Jan 2004, Mike Yuen wrote:

> What i'm trying to do concatenate a bunch of strings to make a file path.  
> For example,
> 
> A = "c:/WINNT"
> B = "/"
> C = "Program Files"
> 
> When I go:
> D = A+B+C
> print D # hoping to get c:/winnt/program files.
> 
> INstead, when I output D, I get <type 'str'>
> How do I fix this?

Can you do a copy & paste and show us exactly what you're putting in and 
what you're getting?

That works alright for me:

>>> A = "c:/WINNT"
>>> B = "/"
>>> C = "Program Files"
>>> D=A+B+C
>>> D
'c:/WINNT/Program Files'

You might however, look into using os.path.join, which is made for this 
kind of thing and takes care of escapes and stuff:

>>> X = "C:"
>>> Y = "\\WINNT"
>>> Z = "Program Files"
>>> os.path.join(X,Y,Z)
'C:\\WINNT\\Program Files'



From schalla at vasoftware.com  Wed Jan 28 05:07:13 2004
From: schalla at vasoftware.com (Shobhan)
Date: Wed Jan 28 05:00:33 2004
Subject: [Tutor] jpg to doc conversion
In-Reply-To: <000601c3de47$ba4a9480$923fc618@maine.rr.com>
References: <000601c3de47$ba4a9480$923fc618@maine.rr.com>
Message-ID: <1074748535.6265.0.camel@shobs.cybernetsoft.com>

Well, I couldn't find good apps for this but for good scanned documents
you can use OCR software like Clara OCR (www.claraocr.org). Open google
and search for GPL'd OCR. But most of them give good results only if the
scanned document is good.


On Mon, 2004-01-19 at 10:20, Joe Kaper wrote:
> I stumbled on this thread in your bulletin board just recently.  I was
> wondering if there was any answer to the question of how you can
> convert a jpeg, or similar scanned document, into a .doc file in order
> to edit it in my word processer?  you can mail me at
> jkaper@maine.rr.com   thank you  
>  
> Joe Kaper
> 
> ______________________________________________________________________
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
-- 
?h?bh??


From hcohen2 at comcast.net  Wed Jan 28 11:03:07 2004
From: hcohen2 at comcast.net (hcohen2)
Date: Wed Jan 28 11:05:44 2004
Subject: [Tutor] Have any idea why I do not have access to MY files?
Message-ID: <4017DD3B.7080202@comcast.net>

These are excution functions: system() and popen().  For the same file 
with the former I can see the contents:

 >>> result = os.system('cat new2text.py')
y = 0
print 'y is currently:', y
while y < 8:
    y += 1
    print 'incrementing y to: ', y
 
whereas, if I try to read it - suddenly it does not belong to me!

 >>> f = os.popen('import2.py -a')
 >>> sh: line 1: ./import2.py: Permission denied

But if I do this, its mine!

 >>> result = os.system('ls -l new2text.py')
-rw-r--r--    1 prime_dev prime_dev       93 Jan 26 11:09 new2text.py

Adding a full path has no effect, with popen() still claims I have no 
rights.

Thanks for any insights!


From mhansen at cso.atmel.com  Wed Jan 28 10:23:36 2004
From: mhansen at cso.atmel.com (Mike Hansen)
Date: Wed Jan 28 11:15:13 2004
Subject: [Tutor] parsing email
Message-ID: <4017D3F8.8030504@cso.atmel.com>

Getting attacked by MyDoom at our site, our NT Admin asked if we could 
write a script to delete messages. In the time it would have taken us to 
write the script and have him install the appropriate language(Perl 
and/or Python),  he would have had it cleaned up already. Anyway, I 
thought I'd try to write a script for when this happens in the 
future.(Another virus, another mess)

Is there a method of the email parser that can retrieve the subject? Is 
there a dictionary that has a key with the subject? Is using the email 
parser the best way to do this?

A nudge in the right direction is all I think I need right now. Perhaps 
a link to an example?

Thanks,

Mike

From david at graniteweb.com  Wed Jan 28 11:05:48 2004
From: david at graniteweb.com (David Rock)
Date: Wed Jan 28 11:15:53 2004
Subject: [Tutor] Have any idea why I do not have access to MY files?
In-Reply-To: <4017DD3B.7080202@comcast.net>
References: <4017DD3B.7080202@comcast.net>
Message-ID: <20040128160548.GA14026@wdfs.graniteweb.com>

* hcohen2 <hcohen2@comcast.net> [2004-01-28 11:03]:
> These are excution functions: system() and popen().  For the same file 
> with the former I can see the contents:
> 
> >>> result = os.system('cat new2text.py')
> y = 0
> print 'y is currently:', y
> while y < 8:
>    y += 1
>    print 'incrementing y to: ', y
> 
> whereas, if I try to read it - suddenly it does not belong to me!
> 
> >>> f = os.popen('import2.py -a')
> >>> sh: line 1: ./import2.py: Permission denied
> 
> But if I do this, its mine!
> 
> >>> result = os.system('ls -l new2text.py')
> -rw-r--r--    1 prime_dev prime_dev       93 Jan 26 11:09 new2text.py
> 
> Adding a full path has no effect, with popen() still claims I have no 
> rights.

Maybe I'm not understanding something, but it doesn't look like you are
trying to access the same file...

> >>> result = os.system('cat new2text.py')
> >>> f = os.popen('import2.py -a')

Is it new2test.py or import2.py?

-- 
David Rock
david at graniteweb dot com
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20040128/2fa94b62/attachment.bin
From Janssen at rz.uni-frankfurt.de  Wed Jan 28 11:32:03 2004
From: Janssen at rz.uni-frankfurt.de (Michael Janssen)
Date: Wed Jan 28 11:32:16 2004
Subject: [Tutor] Have any idea why I do not have access to MY files?
In-Reply-To: <4017DD3B.7080202@comcast.net>
References: <4017DD3B.7080202@comcast.net>
Message-ID: <Pine.A41.4.56.0401281720460.47532@hermes-22.rz.uni-frankfurt.de>

On Wed, 28 Jan 2004, hcohen2 wrote:

> These are excution functions: system() and popen().  For the same file
> with the former I can see the contents:
>
>  >>> result = os.system('cat new2text.py')
> y = 0
> print 'y is currently:', y
> while y < 8:
>     y += 1
>     print 'incrementing y to: ', y
>
> whereas, if I try to read it - suddenly it does not belong to me!
>
>  >>> f = os.popen('import2.py -a')
>  >>> sh: line 1: ./import2.py: Permission denied
>
> But if I do this, its mine!
>
>  >>> result = os.system('ls -l new2text.py')
> -rw-r--r--    1 prime_dev prime_dev       93 Jan 26 11:09 new2text.py

execute permissions are lacking (umm, I supose no differences between
import2.py and new2text.py. But anyway this is what the error message
indicates). Add them with "chmod u+x [filename]". And make sure this
script has a proper shebang line within:
#! /usr/bin/env python

Michael

From hcohen2 at comcast.net  Wed Jan 28 11:49:30 2004
From: hcohen2 at comcast.net (hcohen2)
Date: Wed Jan 28 11:52:36 2004
Subject: [Tutor] Have any idea why I do not have access to MY files?
In-Reply-To: <Pine.A41.4.56.0401281720460.47532@hermes-22.rz.uni-frankfurt.de>
References: <4017DD3B.7080202@comcast.net>
	<Pine.A41.4.56.0401281720460.47532@hermes-22.rz.uni-frankfurt.de>
Message-ID: <4017E81A.10804@comcast.net>

Michael Janssen wrote:

>On Wed, 28 Jan 2004, hcohen2 wrote:
>
>  
>
>>These are excution functions: system() and popen().  For the same file
>>with the former I can see the contents:
>>
>> >>> result = os.system('cat new2text.py')
>>y = 0
>>print 'y is currently:', y
>>while y < 8:
>>    y += 1
>>    print 'incrementing y to: ', y
>>
>>whereas, if I try to read it - suddenly it does not belong to me!
>>
>> >>> f = os.popen('import2.py -a')
>> >>> sh: line 1: ./import2.py: Permission denied
>>
>>But if I do this, its mine!
>>
>> >>> result = os.system('ls -l new2text.py')
>>-rw-r--r--    1 prime_dev prime_dev       93 Jan 26 11:09 new2text.py
>>    
>>
>
>execute permissions are lacking (umm, I supose no differences between
>import2.py and new2text.py. But anyway this is what the error message
>indicates). Add them with "chmod u+x [filename]". And make sure this
>script has a proper shebang line within:
>#! /usr/bin/env python
>
>Michael
>
>  
>
Mike,

Odd, but you are correct - changed it to execute just for myself and I 
am in but at the EOF, that's probably due to it has been run by the exec 
command that once run will not repeat.

Thanks,
Herschel



From hcohen2 at comcast.net  Wed Jan 28 11:53:17 2004
From: hcohen2 at comcast.net (hcohen2)
Date: Wed Jan 28 11:58:55 2004
Subject: [Tutor] Have any idea why I do not have access to MY files?
In-Reply-To: <20040128160548.GA14026@wdfs.graniteweb.com>
References: <4017DD3B.7080202@comcast.net>
	<20040128160548.GA14026@wdfs.graniteweb.com>
Message-ID: <4017E8FD.3080004@comcast.net>

David Rock wrote:

>* hcohen2 <hcohen2@comcast.net> [2004-01-28 11:03]:
>  
>
>>These are excution functions: system() and popen().  For the same file 
>>with the former I can see the contents:
>>
>>    
>>
>>>>>result = os.system('cat new2text.py')
>>>>>          
>>>>>
>>y = 0
>>print 'y is currently:', y
>>while y < 8:
>>   y += 1
>>   print 'incrementing y to: ', y
>>
>>whereas, if I try to read it - suddenly it does not belong to me!
>>
>>    
>>
>>>>>f = os.popen('import2.py -a')
>>>>>sh: line 1: ./import2.py: Permission denied
>>>>>          
>>>>>
>>But if I do this, its mine!
>>
>>    
>>
>>>>>result = os.system('ls -l new2text.py')
>>>>>          
>>>>>
>>-rw-r--r--    1 prime_dev prime_dev       93 Jan 26 11:09 new2text.py
>>
>>Adding a full path has no effect, with popen() still claims I have no 
>>rights.
>>    
>>
>
>Maybe I'm not understanding something, but it doesn't look like you are
>trying to access the same file...
>
>  
>
>>>>>result = os.system('cat new2text.py')
>>>>>f = os.popen('import2.py -a')
>>>>>          
>>>>>
>
>Is it new2test.py or import2.py?
>
>  
>
>------------------------------------------------------------------------
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
>  
>
David,

That was a typo - it fails when it is typed correctly.  Giving myself 
execute rights as was suggested to me and it has started to work.

Thanks,
Herschel

PS I usually try several attempts on a problem before I post a 
question.  You do not know how many times I have aborted a message due 
to finding a solution.


From alan.gauld at blueyonder.co.uk  Wed Jan 28 12:10:18 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Wed Jan 28 12:09:14 2004
Subject: [Tutor] Have any idea why I do not have access to MY files?
References: <4017DD3B.7080202@comcast.net>
Message-ID: <00f801c3e5c1$9ac24e60$6401a8c0@xp>

>  >>> result = os.system('cat new2text.py')

> whereas, if I try to read it - suddenly it does not belong to me!
>
>  >>> f = os.popen('import2.py -a')
>  >>> sh: line 1: ./import2.py: Permission denied

You are not trying to read it you are trying to execute it, but...

>  >>> result = os.system('ls -l new2text.py')
> -rw-r--r--    1 prime_dev prime_dev       93 Jan 26 11:09
new2text.py

IT doesn't have execute permission.

Try:

>>> f = os.popen('cat import2.py').read()

You need to run the command as if it were os.system() and
then read() the output into your variable.

HTH

Alan G.




From mhansen at cso.atmel.com  Wed Jan 28 12:20:54 2004
From: mhansen at cso.atmel.com (Mike Hansen)
Date: Wed Jan 28 12:21:01 2004
Subject: [Tutor] parsing email
In-Reply-To: <Pine.A41.4.56.0401281732530.47532@hermes-22.rz.uni-frankfurt.de>
References: <4017D3F8.8030504@cso.atmel.com>
	<Pine.A41.4.56.0401281732530.47532@hermes-22.rz.uni-frankfurt.de>
Message-ID: <4017EF76.3040004@cso.atmel.com>

Hi Michael,

Thanks for the reply. I'm told they are text files with each message 
having its own text file.

Mike

Michael Janssen wrote:

>On Wed, 28 Jan 2004, Mike Hansen wrote:
>
>  
>
>>Getting attacked by MyDoom at our site, our NT Admin asked if we could
>>write a script to delete messages. In the time it would have taken us to
>>write the script and have him install the appropriate language(Perl
>>and/or Python),  he would have had it cleaned up already. Anyway, I
>>thought I'd try to write a script for when this happens in the
>>future.(Another virus, another mess)
>>
>>Is there a method of the email parser that can retrieve the subject? Is
>>there a dictionary that has a key with the subject? Is using the email
>>parser the best way to do this?
>>    
>>
>
>From where do you want to delete the mails? When they have made it into
>the System-Inbox (Or how it's named on NT. The place from where the user
>get mails via POP or IMAP)?
>
>The first task is to get a *single* mail out of a mailbox (or split it
>into several mails). Then you might look out for subjects or want might
>be good enough as a distinction between virus <-> legitmate mail.
>
>When you want to work on your System-Inboxes - are they in plain text or
>binary?
>
>
>Michael
>
>
>  
>

From Janssen at rz.uni-frankfurt.de  Wed Jan 28 12:05:20 2004
From: Janssen at rz.uni-frankfurt.de (Michael Janssen)
Date: Wed Jan 28 12:22:08 2004
Subject: [Tutor] parsing email
In-Reply-To: <4017D3F8.8030504@cso.atmel.com>
References: <4017D3F8.8030504@cso.atmel.com>
Message-ID: <Pine.A41.4.56.0401281732530.47532@hermes-22.rz.uni-frankfurt.de>

On Wed, 28 Jan 2004, Mike Hansen wrote:

> Getting attacked by MyDoom at our site, our NT Admin asked if we could
> write a script to delete messages. In the time it would have taken us to
> write the script and have him install the appropriate language(Perl
> and/or Python),  he would have had it cleaned up already. Anyway, I
> thought I'd try to write a script for when this happens in the
> future.(Another virus, another mess)
>
> Is there a method of the email parser that can retrieve the subject? Is
> there a dictionary that has a key with the subject? Is using the email
> parser the best way to do this?

>From where do you want to delete the mails? When they have made it into
the System-Inbox (Or how it's named on NT. The place from where the user
get mails via POP or IMAP)?

The first task is to get a *single* mail out of a mailbox (or split it
into several mails). Then you might look out for subjects or want might
be good enough as a distinction between virus <-> legitmate mail.

When you want to work on your System-Inboxes - are they in plain text or
binary?


Michael


From ATrautman at perryjudds.com  Wed Jan 28 12:32:00 2004
From: ATrautman at perryjudds.com (Alan Trautman)
Date: Wed Jan 28 12:32:06 2004
Subject: [Tutor] Re: problems with py 2.3.2
Message-ID: <06738462136C054B8F8872D69DA140DB01C08C5E@corp-exch-1.pjinet.com>


Hans,

I have had this happen to me and I have found 2 solutions:
1. Go to the Tcl site and install the latest version of Tcl
http://www.scriptics.com/
2. Install active state python and that seems to fix it.
http://www.activestate.com/Products/ActivePython/

Both of these have worked although the first seems more reliable.

Alan

-----Original Message-----
From: Hans Nowak [mailto:hans@zephyrfalcon.org]
Sent: Tuesday, January 27, 2004 7:23 PM
To: tutor@python.org
Subject: [Tutor] Re: problems with py 2.3.2


gil@tuckers.de wrote:
> 
> greetings,
>                  I wonder if anyone is or has had problems
> installing the latest Python release. Well several times
> I tried to get it right after downloading- Getting it on Windows
> 2000 pro isw easy but it never works properly for the IDE
> doesn`t come when you call it. The command side in DOS is 
> fine but the GUI and ther modules never show up.
> When I install I try to put it in different filkes, but no way.
> 
> So I giave up and just use the Python 2.1 release. Maybe 
> some one somewhere mighthave sometip or tips,
>  sincereley gil

Python 2.3's IDLE doesn't work for me either, because my Tcl/Tk installed is

messed up, and I am too lazy^H^H^H^Hbusy to fix it.  The problem might be 
related to the fact that I have various Pythons installed (1.5.2, 2.1, 2.2, 
2.3) plus some other things that installed their own Tk libraries.

To find out if you have the same problem, grab a command shell and do:

cd c:\python23\Tools\idle
c:\python23\python.exe idle.py

(assuming you installed in c:\python23)

I get a bunch of errors here complaining about Tcl.  The errors on your
screen 
may be of a different nature, I don't know.

It's not the end of the world if IDLE doesn't work, though.  There are other

shells and IDEs around.  If you're using it primarily as an interactive 
interpreter, try PyCrust (bundled with wxPython).  If you're using it as an 
editor, there are oodles of alternatives around: Komodo, SPE, LEO, vi,
emacs, 
Zeus, PythonWin, etc.

HTH,

-- 
Hans (hans@zephyrfalcon.org)
http://zephyrfalcon.org/



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

From vicki at thepenguin.org  Wed Jan 28 12:58:38 2004
From: vicki at thepenguin.org (Vicki Stanfield)
Date: Wed Jan 28 12:58:46 2004
Subject: [Tutor] How to write list to file
Message-ID: <37439.206.53.226.235.1075312718.squirrel@www.thepenguin.org>

I have the following code:

print bytearray[0:bytetotal]
outfile.write("[")
for byte in bytearray[0:bytetotal]:
    outfile.write(byte)
outfile.write("]")

The print statement prints this:

['F', '8', '\t']

but the outfile has only this:

[40	]

I think the problem is that the program is trying to write [40 46 30 38
\t], but for some reason stops at the 40. Why would the different way of
writing cause this behavior?

--vicki

From vicki at thepenguin.org  Wed Jan 28 13:14:29 2004
From: vicki at thepenguin.org (Vicki Stanfield)
Date: Wed Jan 28 13:14:35 2004
Subject: [Tutor] How to write list to file
Message-ID: <38892.206.53.226.235.1075313669.squirrel@www.thepenguin.org>

> I have the following code:
>
> print bytearray[0:bytetotal]
> outfile.write("[")
> for byte in bytearray[0:bytetotal]:
>     outfile.write(byte)
> outfile.write("]")
>
> The print statement prints this:
>
> ['F', '8', '\t']
>
> but the outfile has only this:
>
> [40	]
>
> I think the problem is that the program is trying to write [40 46 30 38
\t], but for some reason stops at the 40. Why would the different way of
writing cause this behavior?
>
Actually what I was thinking doesn't make sense. I know that the F is a 46
and the 8 is a 38 in hex. I am not sure where the 40 comes from.

--vicki


From dyoo at hkn.eecs.berkeley.edu  Wed Jan 28 13:33:00 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Jan 28 13:33:05 2004
Subject: [Tutor] How to write list to file
In-Reply-To: <38892.206.53.226.235.1075313669.squirrel@www.thepenguin.org>
Message-ID: <Pine.LNX.4.44.0401281017230.32557-100000@hkn.eecs.berkeley.edu>



On Wed, 28 Jan 2004, Vicki Stanfield wrote:

> > I have the following code:
> >
> > print bytearray[0:bytetotal]
> > outfile.write("[")
> > for byte in bytearray[0:bytetotal]:
> >     outfile.write(byte)
> > outfile.write("]")
> >
> > The print statement prints this:
> >
> > ['F', '8', '\t']
> >
> > but the outfile has only this:
> >
> > [40	]
> >
> > I think the problem is that the program is trying to write [40 46 30 38
> \t], but for some reason stops at the 40. Why would the different way of
> writing cause this behavior?
> >
> Actually what I was thinking doesn't make sense. I know that the F is a
> 46 and the 8 is a 38 in hex. I am not sure where the 40 comes from.



Hi Vicki,

I'm not quite sure I understand quite yet this problem.  *grin*



But I'm guessing that '40\t' is meant to be interpreted as the characters
'4', '0', and '\t', but not as the number '40' followed by a tab.


Assuming that 'bytetotal' is 3, the three characters that you're writing:

    ['F', '8', '\t']

should correspond to the three bytes that you see in your file (plus the
two from the brackets).



Before we try figure out any more: is that code snippet the only part of
your program, or do you do some additional writing to file either before
or after this snippet?  What I don't get quite yet is how you're getting
'40\t' from the outfile:


> > but the outfile has only this:
> >
> > [40	]


There's something slightly irrational here, and I can't help but feel
we're not seeing something obvious.  *grin*


Given that the array contained ['F', '8', '\t'], after the loop, you
should be seeing

###
[F8	]
###

in your file.  Are you doing any file seek()ing after this snippet?  And
have you made sure to explicitely close() the outfile?


Good luck to you!


From sigurd at 12move.de  Wed Jan 28 13:41:37 2004
From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=)
Date: Wed Jan 28 13:47:30 2004
Subject: [Tutor] parsing email
In-Reply-To: <4017D3F8.8030504@cso.atmel.com> (Mike Hansen's message of
	"Wed, 28 Jan 2004 08:23:36 -0700")
References: <4017D3F8.8030504@cso.atmel.com>
Message-ID: <m3ad48rllz.fsf@hamster.pflaesterer.de>

On 28 Jan 2004, Mike Hansen <- mhansen@cso.atmel.com wrote:

> Getting attacked by MyDoom at our site, our NT Admin asked if we could
> write a script to delete messages. In the time it would have taken us

It's nice to have an admin who gives you such freedom.

> thought I'd try to write a script for when this happens in the
> future.(Another virus, another mess)

Right.  And don't forget the fun of learning how to do the task.

> Is there a method of the email parser that can retrieve the subject? 

I think you mix two different subjects: parsing the e-mail and fetching
it.

> Is there a dictionary that has a key with the subject? Is using the
> email parser the best way to do this?

IMO no.  If you use pop3 to fetch the e-mails use poplib.  Then fetch
the header of the e-mail and look at the values; perhaps you could use
TOP to fetch some of the first lines of an e-mail to filter on those
first lines.  That will help decreasing traffic.  Alternatively use
imaplib.

If you have the whole e-mail already in your spool and you just want to
decide if they are to be deleted you may want to look at
http://spambayes.sourceforge.net/

But if you want to use the email parser you can read the files and then
there is indeed a dictionary with the header entries names as keys.

Suppose I had a message in the file 64856.msg then I could parse it
with:

>>> import email
>>> msg = email.message_from_file(file("64856.msg"))
>>> msg.keys()
['Received', 'X-Hamster-Info', 'From', 'To', 'Date', 'Subject', 'Message-ID', 'Return-Path']
>>> 

Now I could use these keys to retrieve the values and decide if the
e-mail is spam.


   Karl
-- 
Please do *not* send copies of replies to me.
I read the list


From cspears2002 at yahoo.com  Wed Jan 28 13:53:16 2004
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Wed Jan 28 13:53:23 2004
Subject: [Tutor] raw_input function
Message-ID: <20040128185316.42182.qmail@web12401.mail.yahoo.com>

Where can I go to get some general information on how
the raw_input function works?

-Chris

=====
"I'm the last person to pretend that I'm a radio.  I'd rather go out and be a color television set."
-David Bowie

"Who dares wins"
-British military motto

"Far more creativity, today, goes into the marketing of products than into the products themselves..."
-"Pattern Recognition" by William Gibson

From mhansen at cso.atmel.com  Wed Jan 28 14:03:32 2004
From: mhansen at cso.atmel.com (Mike Hansen)
Date: Wed Jan 28 14:03:36 2004
Subject: [Tutor] parsing email
In-Reply-To: <m3ad48rllz.fsf@hamster.pflaesterer.de>
References: <4017D3F8.8030504@cso.atmel.com>
	<m3ad48rllz.fsf@hamster.pflaesterer.de>
Message-ID: <40180784.7090003@cso.atmel.com>

Thanks Karl.

That's what I was looking for.

I'll also look at spambayes.

Mike

Karl Pfl?sterer wrote:

>On 28 Jan 2004, Mike Hansen <- mhansen@cso.atmel.com wrote:
>
>  
>
>>Getting attacked by MyDoom at our site, our NT Admin asked if we could
>>write a script to delete messages. In the time it would have taken us
>>    
>>
>
>It's nice to have an admin who gives you such freedom.
>
>  
>
>>thought I'd try to write a script for when this happens in the
>>future.(Another virus, another mess)
>>    
>>
>
>Right.  And don't forget the fun of learning how to do the task.
>
>  
>
>>Is there a method of the email parser that can retrieve the subject? 
>>    
>>
>
>I think you mix two different subjects: parsing the e-mail and fetching
>it.
>
>  
>
>>Is there a dictionary that has a key with the subject? Is using the
>>email parser the best way to do this?
>>    
>>
>
>IMO no.  If you use pop3 to fetch the e-mails use poplib.  Then fetch
>the header of the e-mail and look at the values; perhaps you could use
>TOP to fetch some of the first lines of an e-mail to filter on those
>first lines.  That will help decreasing traffic.  Alternatively use
>imaplib.
>
>If you have the whole e-mail already in your spool and you just want to
>decide if they are to be deleted you may want to look at
>http://spambayes.sourceforge.net/
>
>But if you want to use the email parser you can read the files and then
>there is indeed a dictionary with the header entries names as keys.
>
>Suppose I had a message in the file 64856.msg then I could parse it
>with:
>
>  
>
>>>>import email
>>>>msg = email.message_from_file(file("64856.msg"))
>>>>msg.keys()
>>>>        
>>>>
>['Received', 'X-Hamster-Info', 'From', 'To', 'Date', 'Subject', 'Message-ID', 'Return-Path']
>  
>
>
>Now I could use these keys to retrieve the values and decide if the
>e-mail is spam.
>
>
>   Karl
>  
>

From sigurd at 12move.de  Wed Jan 28 14:15:53 2004
From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=)
Date: Wed Jan 28 14:18:58 2004
Subject: [Tutor] raw_input function
In-Reply-To: <20040128185316.42182.qmail@web12401.mail.yahoo.com> (Christopher
	Spears's message of "Wed, 28 Jan 2004 10:53:16 -0800 (PST)")
References: <20040128185316.42182.qmail@web12401.mail.yahoo.com>
Message-ID: <m31xpjsx5s.fsf@hamster.pflaesterer.de>

On 28 Jan 2004, Christopher Spears <- cspears2002@yahoo.com wrote:

> Where can I go to get some general information on how
> the raw_input function works?

I think you have to look in the source code (C).


   Karl
-- 
Please do *not* send copies of replies to me.
I read the list


From hcohen2 at comcast.net  Wed Jan 28 14:21:19 2004
From: hcohen2 at comcast.net (hcohen2)
Date: Wed Jan 28 14:23:54 2004
Subject: [Tutor] raw_input function
In-Reply-To: <20040128185316.42182.qmail@web12401.mail.yahoo.com>
References: <20040128185316.42182.qmail@web12401.mail.yahoo.com>
Message-ID: <40180BAF.2080001@comcast.net>

Christopher Spears wrote:

>Where can I go to get some general information on how
>the raw_input function works?
>
>-Chris
>
>=====
>"I'm the last person to pretend that I'm a radio.  I'd rather go out and be a color television set."
>-David Bowie
>
>"Who dares wins"
>-British military motto
>
>"Far more creativity, today, goes into the marketing of products than into the products themselves..."
>-"Pattern Recognition" by William Gibson
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>  
>
Chris,

Look at some of the books on python, e.g. 'Learning Python' new edition 
recently released or 'Core Python Programming'.

var_name = raw_input('Enter some information: ')

will always give you a sting result, even if you enter a list or some 
numeric type.  To convert to a particular type use a function on it:

var_float = float(raw_input('Enter some information: ')),

but I would enclose something like this within a try: ... except: construct.

Also you could use

var_name = input('Enter...')

this will return the actual type you entered.

Hope that helps a bit,
Herschel



From dyoo at hkn.eecs.berkeley.edu  Wed Jan 28 15:16:01 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Jan 28 15:16:09 2004
Subject: [Tutor] raw_input function
In-Reply-To: <m31xpjsx5s.fsf@hamster.pflaesterer.de>
Message-ID: <Pine.LNX.4.44.0401281202580.12489-100000@hkn.eecs.berkeley.edu>



> > Where can I go to get some general information on how the raw_input
> > function works?
>
> I think you have to look in the source code (C).


Hi Chris,


Let's pull up the Library Documentation:

    http://www.python.org/doc/lib/built-in-funcs.html#l2h-56

"""If the prompt argument is present, it is written to standard output
without a trailing newline. The function then reads a line from input,
converts it to a string (stripping a trailing newline), and returns that.
When EOF is read, EOFError is raised."""


Although the docs are just describing the function, it's written well
enough that we can almost see the pseudocode in that paragraph.  *grin*



If we wanted to make our own raw_input(), we can follow the documentation
closely: we can use the 'readline()' method of the standard input
'sys.stdin', as well as the 'write()' method of our standard output
'stdout' file, and end up with something that does most of what
raw_input() does.




Hope this helps!


From python at keep-trying.com  Wed Jan 28 15:19:17 2004
From: python at keep-trying.com (richard)
Date: Wed Jan 28 15:20:25 2004
Subject: [Tutor] Calling Dialog Box from a Class
Message-ID: <6.0.0.22.0.20040128200323.020366d0@192.168.5.1>

Folks,

I am attempting when a button is pressed for an OK dialog box to
pop up. Now when I script it directly info the button def. it works
ok. However when I try to put it in a seperate class and then
call it fails. Code is shown below.

         def OnButton1Button(self, event):
                         messagebox.Info('This is a test','This Caption')

class messagebox:
     def Info(self, message,caption):
         dlg = wxMessageDialog(self,message, caption, wxOK | 
wxICON_INFORMATION)
         dlg.ShowModal()
         dlg.Destroy()

Now how I understand it is that I have called my dialog box Info and assigned
it the two attributes message and caption. So when I want to call it from
my button function I should just first describe the class it belongs to 
'messagebox'
then assign Info as the instance which I wish to call followed by the two 
attributes
in brackets which Info require. Up then should pop the button with the relevant
caption and relvent text. However Python disagrees and returns this error:

Traceback (most recent call last):
   File "D:\pythonwork\tesguis\mainmenu.py", line 65, in OnButton1Button
     messagebox.Info('This is a test','This Caption')
TypeError: unbound method Info() must be called with messagebox instance as
first argument (got str instance instead)

Which I do not understand why , when it is the first instance being 
called?? and
why is Info unbound??
I have been reading through the past tutor archives and the most recent thread
on classes some of which confused me further, but this is not making sense.

Any help

Python 2.3, wxwindows.

Thanks,

Richard



From gerrit at nl.linux.org  Wed Jan 28 15:27:59 2004
From: gerrit at nl.linux.org (Gerrit Holl)
Date: Wed Jan 28 15:29:10 2004
Subject: [Tutor] raw_input function
In-Reply-To: <m31xpjsx5s.fsf@hamster.pflaesterer.de>
References: <20040128185316.42182.qmail@web12401.mail.yahoo.com>
	<m31xpjsx5s.fsf@hamster.pflaesterer.de>
Message-ID: <20040128202759.GA6749@nl.linux.org>

Karl Pfl=E4sterer wrote:
> On 28 Jan 2004, Christopher Spears <- cspears2002@yahoo.com wrote:
>=20
> > Where can I go to get some general information on how
> > the raw_input function works?
>=20
> I think you have to look in the source code (C).

Or the Python source code:
>>> def py_raw_input(s):
...     sys.stdout.write(s)
...     return sys.stdin.readline()[:-1] # strip of trailing newline

Gerrit.

--=20
192. If a son of a paramour or a prostitute say to his adoptive father
or mother: "You are not my father, or my mother," his tongue shall be cut
off.
          -- 1780 BC, Hammurabi, Code of Law
--=20
PrePEP: Builtin path type
    http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html
Asperger's Syndrome - a personal approach:
	http://people.nl.linux.org/~gerrit/english/

From scorp_ar at yahoo.com  Wed Jan 28 16:04:56 2004
From: scorp_ar at yahoo.com (Pedro Furnari)
Date: Wed Jan 28 16:16:36 2004
Subject: [Tutor] executable in windows?
Message-ID: <20040128210456.32777.qmail@web60506.mail.yahoo.com>

Please
I can´t set any program like executable in windows.
How can I do this? Thanks. 
Pedro Furnari

scorp_ar@yahoo.com 


__________________________________
Do you Yahoo!?
Yahoo! SiteBuilder - Free web site building tool. Try it!
http://webhosting.yahoo.com/ps/sb/

From brian at connellyman.com  Wed Jan 28 16:36:59 2004
From: brian at connellyman.com (Brian Connelly)
Date: Wed Jan 28 16:37:03 2004
Subject: [Tutor] Finding and replacing a space in a string.
Message-ID: <1097839.1075325819048.SLOX.WebMail.wwwrun@mail.connellyman.com>

Hey guys and gals...

I'm working with the csv module...I have a row[1] which is a ID.
let's call  ID = row[1].

My problem is that row[1] or ID is  6 characters or less and in some casses it has a '  '  space which i need to replace with a '-' and if  it does not have a space I would like to leave it alone.

Any sugestions ?

for example:

>>> id
'ZURE A'

newid  should become 'ZURE-A'

and if  id = 'WHITO'  newid = 'WHITO'


Thanks for the help :)
BCC
Learning python and loving it !




From peterabrown at froggy.com.au  Wed Jan 28 16:54:07 2004
From: peterabrown at froggy.com.au (Peter Brown)
Date: Wed Jan 28 16:54:03 2004
Subject: [Tutor] Finding and replacing a space in a string.
In-Reply-To: <1097839.1075325819048.SLOX.WebMail.wwwrun@mail.connellyman .com>
References: <1097839.1075325819048.SLOX.WebMail.wwwrun@mail.connellyman.com>
Message-ID: <6.0.0.22.0.20040129084630.02d46c50@mail.froggy.com.au>

At 16:36 28/01/04 -0500, you wrote:
>Hey guys and gals...
>
>I'm working with the csv module...I have a row[1] which is a ID.
>let's call  ID = row[1].
>
>My problem is that row[1] or ID is  6 characters or less and in some 
>casses it has a '  '  space which i need to replace with a '-' and if  it 
>does not have a space I would like to leave it alone.
>
>Any sugestions ?
>
>for example:
>
> >>> id
>'ZURE A'
>
>newid  should become 'ZURE-A'
>
>and if  id = 'WHITO'  newid = 'WHITO'
 >>> id ='ZUE A'
 >>> id1='ZUREA'
 >>> id1= id1.replace(' ','-')
 >>> id1
'ZUREA'
 >>> id= id.replace(' ','-')
 >>> id
'ZUE-A'
 >>>
In other words if id doesn't have a space it doesn't treat the command as 
an error. So you are free to apply to every line, where there is a space it 
will replace it, otherwise id is not chnaged.

HTH

>Thanks for the help :)
>BCC
>Learning python and loving it !
>
>
>
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor

Peter Brown



From orbitz at ezabel.com  Wed Jan 28 16:56:55 2004
From: orbitz at ezabel.com (orbitz@ezabel.com)
Date: Wed Jan 28 16:57:22 2004
Subject: [Tutor] How to write list to file
In-Reply-To: <37439.206.53.226.235.1075312718.squirrel@www.thepenguin.org>
References: <37439.206.53.226.235.1075312718.squirrel@www.thepenguin.org>
Message-ID: <20040128165655.5ac88c9e.orbitz@ezabel.com>

Why don't you simply use repr()?
Also, make sure your bytetotal is correct.

>>> sys.stdout.write(repr(['1', '2', '\t']))
['1', '2', '\t']

this way you can just use eval to make your list again.  Also why not
use pickle?


On Wed, 28 Jan 2004 12:58:38 -0500 (EST)
Vicki Stanfield <vicki@thepenguin.org> wrote:

> I have the following code:
> 
> print bytearray[0:bytetotal]
> outfile.write("[")
> for byte in bytearray[0:bytetotal]:
>     outfile.write(byte)
> outfile.write("]")
> 
> The print statement prints this:
> 
> ['F', '8', '\t']
> 
> but the outfile has only this:
> 
> [40	]
> 
> I think the problem is that the program is trying to write [40 46 30
> 38\t], but for some reason stops at the 40. Why would the different
> way of writing cause this behavior?
> 
> --vicki
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

From sigurd at 12move.de  Wed Jan 28 17:15:16 2004
From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=)
Date: Wed Jan 28 17:20:00 2004
Subject: [Tutor] Finding and replacing a space in a string.
In-Reply-To: <1097839.1075325819048.SLOX.WebMail.wwwrun@mail.connellyman.com>
	(Brian
	Connelly's message of "Wed, 28 Jan 2004 16:36:59 -0500 (EST)")
References: <1097839.1075325819048.SLOX.WebMail.wwwrun@mail.connellyman.com>
Message-ID: <m3smhzrao2.fsf@hamster.pflaesterer.de>

On 28 Jan 2004, Brian Connelly <- brian@connellyman.com wrote:

> My problem is that row[1] or ID is 6 characters or less and in some
> casses it has a ' ' space which i need to replace with a '-' and if it
> does not have a space I would like to leave it alone.

> Any sugestions ?

> for example:

>>>> id 'ZURE A'

> newid should become 'ZURE-A'

> and if id = 'WHITO' newid = 'WHITO'

If it's so simple you can use the `replace' method of strings.
E.g.:

>>> s = "I am a string with space"
>>> s = s.replace(' ', '-')
>>> s
'I-am-a-string-with-space'
>>> 

If you wanted only the first occurence to be replaced you could write:

>>> s = "I am a string with space"
>>> s = s.replace(' ', '-', 1)
>>> s
'I-am a string with space'
>>> 

If there are no spaces in the string nothing happens.

>>> s = "foo"
>>> s = s.replace(' ', '-', 1)
>>> s
'foo'
>>> 


What helped me a lot when I started using Python was using the
interactive read-eval-print-loop (REPL).  If I didn't knew what methods
a class had I simply typed:

>>> s = "foo"
>>> dir(s)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__str__', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'replace', 'rfind', 'rindex', 'rjust', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>> 

Now I read replace which looks promising but I don't know what it does;
but I can ask Python.  So I type:

>>> help(s.replace)
Help on built-in function replace:

replace(...)
    S.replace (old, new[, count]) -> string
    
    Return a copy of string S with all occurrences of substring
    old replaced by new.  If the optional argument count is
    given, only the first count occurrences are replaced.
(END) 




   Karl
-- 
Please do *not* send copies of replies to me.
I read the list


From glingl at aon.at  Wed Jan 28 17:33:59 2004
From: glingl at aon.at (Gregor Lingl)
Date: Wed Jan 28 17:33:03 2004
Subject: [Tutor] what? (late nite entertainment) (*)
Message-ID: <401838D7.2000000@aon.at>

What is this? Another version of the well known ...

def what(n):
    x,y = range(n), [0]*n
    x[1]= 0
    z = 0
    while z*z <= n:
        z+=1
        if x[z]: x[z*z:n:z]=y[z*z:n:z]
    return [z for z in x if z]

Regards,
Gregor

(*) at least in good old Europe


From alan.gauld at blueyonder.co.uk  Wed Jan 28 17:53:44 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Wed Jan 28 17:52:34 2004
Subject: [Tutor] How to write list to file
References: <37439.206.53.226.235.1075312718.squirrel@www.thepenguin.org>
Message-ID: <013c01c3e5f1$95015f40$6401a8c0@xp>

> print bytearray[0:bytetotal]
> outfile.write("[")
> for byte in bytearray[0:bytetotal]:
>     outfile.write(byte)
> outfile.write("]")


Dunno why you get the result you do, but this seems a convoluted 
way of writing the list to a file (depending what you want it 
for of course). Whats wrong with

outfile.write(str(bytearray[0:bytesize]))

which should give you something very similar to:

> The print statement prints this:
> 
> ['F', '8', '\t']

Since this is just the string representation of the list...

Alan G.
(Dodging the issue and dangerously simplifying! :-)

From alan.gauld at blueyonder.co.uk  Wed Jan 28 17:55:18 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Wed Jan 28 17:54:10 2004
Subject: [Tutor] raw_input function
References: <20040128185316.42182.qmail@web12401.mail.yahoo.com>
Message-ID: <014101c3e5f1$ccd89190$6401a8c0@xp>

> Where can I go to get some general information on how
> the raw_input function works?

What kind of information beyond what help() and the python 
manual gives do you require? Assuming you looked at those 
two places first, always a good idea!

Alan G?

From alan.gauld at blueyonder.co.uk  Wed Jan 28 18:00:21 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Wed Jan 28 17:59:13 2004
Subject: [Tutor] raw_input function
References: <20040128185316.42182.qmail@web12401.mail.yahoo.com>
	<m31xpjsx5s.fsf@hamster.pflaesterer.de>
Message-ID: <014a01c3e5f2$81d852b0$6401a8c0@xp>

> > Where can I go to get some general information on how
> > the raw_input function works?
> 
> I think you have to look in the source code (C).

Aha! I hadn't thought of that interpretation. You want to understamd 
how the function is actually written? As Karl says you can read 
the C source code or conceptually think of it as being a little 
like this:

def raw_input(prompt):
   print prompt,
   return sys.stdin.readline()
   
Its actually a wee bit cleverer than that I think, but so far as 
we the users go its pretty close.

Does that help?

Alan G.

From fredm at smartypantsco.com  Wed Jan 28 18:57:08 2004
From: fredm at smartypantsco.com (Alfred Milgrom)
Date: Wed Jan 28 18:58:56 2004
Subject: [Tutor] what? (late nite entertainment) (*)
In-Reply-To: <401838D7.2000000@aon.at>
Message-ID: <5.1.0.14.0.20040129104059.0395f220@192.168.1.1>

Hi Gregor:

Hard to work out what is what :) as there seems to be a typo in one line of 
your code:

        if x[z]: x[z*z:n:z]=y[z*z:n:z]

(At least it doesn't work on my machine with Python 2.2)
And unfortunately I can't guess what this line is supposed to be :((

Also the subroutine breaks for n = 1 or less.
Maybe you need a line at the start to say
         if n <2 : return [0]

Fred

At 11:33 PM 28/01/04 +0100, Gregor Lingl wrote:
>What is this? Another version of the well known ...
>
>def what(n):
>    x,y = range(n), [0]*n
>    x[1]= 0
>    z = 0
>    while z*z <= n:
>        z+=1
>        if x[z]: x[z*z:n:z]=y[z*z:n:z]
>    return [z for z in x if z]
>
>Regards,
>Gregor
>
>(*) at least in good old Europe



From cspears2002 at yahoo.com  Wed Jan 28 19:48:45 2004
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Wed Jan 28 19:48:51 2004
Subject: [Tutor] EOF problems
Message-ID: <20040129004845.46084.qmail@web12402.mail.yahoo.com>

I've been trying to write a script that uses a while
function and raw_input.  Basically, I want to be able
to keep typing input until I type in an EOF signal. 
Here is the script: 

s = []

while s != "":
    s = raw_input ('Type a string:')

My instructor claims that Ctrl-Z in Windows is the
equivalent of an EOF.  However, this is not what I
have discovered.  Ctrl-Z is the undo command in IDLE. 
Instead, I used Ctrl-C, which is the copy command. 
Since there was an empty string, the script stopped. 
Here is the result:

>>> 
Type a string:asdfjk;l
Type a string:asdfj;
Type a string:asdfj

Traceback (most recent call last):
  File "C:\Documents and Settings\Christstopher
Spears\My Documents\python\unit7question2.py", line 4,
in -toplevel-
    s = raw_input ('Type a string:')
TypeError: object.readline() returned non-string
>>> 

Ok, so the script works, but what is the EOF signal in
IDLE?  Reading the docs, I seemed to gather that when
reading a file, Python sees an empty string as the
EOF.  Am I wrong?  Is there some variable that can be
used to signal EOF to Python?  I have already tried
eof.

-Chris



From littledanehren at yahoo.com  Wed Jan 28 19:56:18 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Wed Jan 28 19:56:22 2004
Subject: [Tutor] executable in windows?
In-Reply-To: <20040128210456.32777.qmail@web60506.mail.yahoo.com>
Message-ID: <20040129005618.72387.qmail@web41809.mail.yahoo.com>

Pedro Furnari wrote:
> Please
> I can´t set any program like executable in windows.
> How can I do this? Thanks. 
> Pedro Furnari
> 
> scorp_ar@yahoo.com 

You can use py2exe. It converts Python code with a
distutils script into an executable and dll. It can be
found at http://py2exe.sourceforge.net/

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Yahoo! SiteBuilder - Free web site building tool. Try it!
http://webhosting.yahoo.com/ps/sb/

From littledanehren at yahoo.com  Wed Jan 28 21:54:32 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Wed Jan 28 21:54:38 2004
Subject: [Tutor] Have any idea why I do not have access to MY files?
In-Reply-To: <4017DD3B.7080202@comcast.net>
Message-ID: <20040129025432.35804.qmail@web41812.mail.yahoo.com>

hcohen2 wrote:
> These are excution functions: system() and popen(). 
> For the same file 
> with the former I can see the contents:
> 
>  >>> result = os.system('cat new2text.py')
> y = 0
> print 'y is currently:', y
> while y < 8:
>     y += 1
>     print 'incrementing y to: ', y
>  
> whereas, if I try to read it - suddenly it does not
> belong to me!
> 
>  >>> f = os.popen('import2.py -a')
>  >>> sh: line 1: ./import2.py: Permission denied
> 
> But if I do this, its mine!
> 
>  >>> result = os.system('ls -l new2text.py')
> -rw-r--r--    1 prime_dev prime_dev       93 Jan 26
> 11:09 new2text.py
> 
> Adding a full path has no effect, with popen() still
> claims I have no 
> rights.
> 
> Thanks for any insights!

It's not that you can't read the file, it's that you
can't execute it. Give it executable privilages by
doing chmod +x import2.py. Then do ./import2.py -a.
Otherwise it will search in $PATH for import2.py.

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Yahoo! SiteBuilder - Free web site building tool. Try it!
http://webhosting.yahoo.com/ps/sb/

From david at graniteweb.com  Wed Jan 28 22:42:10 2004
From: david at graniteweb.com (David Rock)
Date: Wed Jan 28 22:52:08 2004
Subject: [Tutor] EOF problems
In-Reply-To: <20040129004845.46084.qmail@web12402.mail.yahoo.com>
References: <20040129004845.46084.qmail@web12402.mail.yahoo.com>
Message-ID: <20040129034210.GB15894@wdfs.graniteweb.com>

* Christopher Spears <cspears2002@yahoo.com> [2004-01-28 16:48]:
> 
> My instructor claims that Ctrl-Z in Windows is the
> equivalent of an EOF.  However, this is not what I
> have discovered.  Ctrl-Z is the undo command in IDLE. 
> Instead, I used Ctrl-C, which is the copy command. 
> Since there was an empty string, the script stopped. 

Ctrl-D is often used for EOF. The python interpreter in IDLE may accept
that. Unfortunately, things are not always consistent ;-)

-- 
David Rock
david at graniteweb dot com
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20040128/884b9f73/attachment.bin
From glingl at aon.at  Thu Jan 29 01:09:38 2004
From: glingl at aon.at (Gregor Lingl)
Date: Thu Jan 29 01:08:43 2004
Subject: [Tutor] what? (late nite entertainment) (*)
In-Reply-To: <5.1.0.14.0.20040129104059.0395f220@192.168.1.1>
References: <5.1.0.14.0.20040129104059.0395f220@192.168.1.1>
Message-ID: <4018A3A2.6080103@aon.at>


Now:  early morning corrections ...

Alfred Milgrom wrote:

> Hi Gregor:
>
> Hard to work out what is what :) as there seems to be a typo in one 
> line of your code:
>
>        if x[z]: x[z*z:n:z]=y[z*z:n:z]
>
> (At least it doesn't work on my machine with Python 2.2)
>
Yeah, I had the idea when playing around with some new features of 
Python 2.3, as
I do sometimes late at night - before shutting down my computer. This 
one I found at:

http://www.python.org/doc/2.3.3/whatsnew/section-slices.html

and I looked for an example for use of "assignment with extended slices" ...

> Also the subroutine breaks for n = 1 or less.
> Maybe you need a line at the start to say
>         if n <2 : return [0]
>
what() was intended to generate all primes less than n. (In fact it's
an implementation of the sieve of Eratosthenes). The bugs came not
only from not beeing interested in primes less than 2  ;-) but also from
beeing a little tired already. Sorry.

I think the following version repairs that - and hopefully uses less
obfuscating variable names (which in fact originally was part of the
"riddle"):

def primes(n):
    sieve, zeros = range(n), [0]*n
    sieve[:2]= 0,0
    i = 1
    while i*i < n:
        if sieve[i]: sieve[i*i:n:i]=zeros[i*i:n:i]
        i += 1
    return [p for p in sieve if p]

Regards,
Gregor


>

From isrgish at fusemail.com  Thu Jan 29 05:58:28 2004
From: isrgish at fusemail.com (Isr Gish)
Date: Thu Jan 29 05:58:39 2004
Subject: [Tutor] raw_input function
Message-ID: <E1Am9sS-0001bO-CA@fuse1.fusemail.net>

     >Christopher Spears wrote:
   >
   >>Where can I go to get some general information on how
   >>the raw_input function works?


Hershel Wrote:
   >Look at some of the books on python, e.g. 'Learning Python' new edition 
   >recently released or 'Core Python Programming'.
   >
   >var_name = raw_input('Enter some information: ')
   >
   >will always give you a sting result, even if you enter a list or some 
   >numeric type.  To convert to a particular type use a function on it:
   >
   >var_float = float(raw_input('Enter some information: ')),
   >
   >but I would enclose something like this within a try: ... except: construct.
   >
   >Also you could use
   >
   >var_name = input('Enter...')
   >
   >this will return the actual type you entered.
   >
 I don't think its a good idea to use input.
Because input uses eval(...) to return the input, and someone who knows whatbthere doing can make some troble. For example they could type in a comand like this:
os.removedirs('c:\\')
Which would wipe out the whole harddrive.

Good luck

Isr


From Janssen at rz.uni-frankfurt.de  Thu Jan 29 06:26:19 2004
From: Janssen at rz.uni-frankfurt.de (Michael Janssen)
Date: Thu Jan 29 06:50:11 2004
Subject: [Tutor] parsing email
In-Reply-To: <4017EF76.3040004@cso.atmel.com>
References: <4017D3F8.8030504@cso.atmel.com>
	<Pine.A41.4.56.0401281732530.47532@hermes-22.rz.uni-frankfurt.de>
	<4017EF76.3040004@cso.atmel.com>
Message-ID: <Pine.A41.4.56.0401291223050.204744@hermes-22.rz.uni-frankfurt.de>

On Wed, 28 Jan 2004, Mike Hansen wrote:

> Thanks for the reply. I'm told they are text files with each message
> having its own text file.

when each eMail is on a single file - why not just run a virus scanner
about them? The virus scanner can savely delete all virus mails.


Michael

From Janssen at rz.uni-frankfurt.de  Thu Jan 29 09:04:10 2004
From: Janssen at rz.uni-frankfurt.de (Michael Janssen)
Date: Thu Jan 29 09:04:19 2004
Subject: [Tutor] EOF problems
In-Reply-To: <20040129004845.46084.qmail@web12402.mail.yahoo.com>
References: <20040129004845.46084.qmail@web12402.mail.yahoo.com>
Message-ID: <Pine.A41.4.56.0401291444130.204744@hermes-22.rz.uni-frankfurt.de>

On Wed, 28 Jan 2004, Christopher Spears wrote:

> My instructor claims that Ctrl-Z in Windows is the
> equivalent of an EOF.  However, this is not what I
> have discovered.  Ctrl-Z is the undo command in IDLE.
> Instead, I used Ctrl-C, which is the copy command.
> Since there was an empty string, the script stopped.
> Here is the result:

the gui or the application might catch every controlkey before it gets
passed to python and raw_input. Try to receive alt+F4 with raw_input and
you know what I mean ;-)

When idle catches crtl-Z, there's not much you can do about (unless
configure/rewrite idle). Once I have defined a shortcut strg-alt-Q
unders w98 and I needed a long time to realize why the heck notepad
didn't want and @ sign any longer (uhm, under windows - w98 at least
- strg+alt modifier acts the same like "Alt Gr").

Besides such wonders, your task wouldn't be solved once you found a EOF
key. What is python supposed to do, when an function like raw_input
recieved EOF instead of string-input? raw_input then can't return a
string and must therefore throw an exception to inform the user, there
is no string, not even the empty string.

Look here under linux where EOF is crtl-D:

>>> raw_input("I will type in ctrl+D soon: ")
I will type in ctrl+D soon: Traceback (most recent call last):
  File "<stdin>", line 1, in ?
EOFError

This means, when you want to interrupt a while+raw_input loop with
non-string-input, you must catch the exception:

while 1:
    try:
        s = raw_input("prompt: ")
    except (EOFError, KeyboardInterrupt):
        # user pressed ctrl-D (under linux)
        #  or ctrl-C --> KeyboardInterrupt
        print # end in newline
        break


In case ctrl-C will allways trow TypeError (and isn't dependend of the
content of the clipboard), you found your solution and only have to
silence the Exception.


Michael

> >>>
> Type a string:asdfjk;l
> Type a string:asdfj;
> Type a string:asdfj
>
> Traceback (most recent call last):
>   File "C:\Documents and Settings\Christstopher
> Spears\My Documents\python\unit7question2.py", line 4,
> in -toplevel-
>     s = raw_input ('Type a string:')
> TypeError: object.readline() returned non-string
> >>>
>
> Ok, so the script works, but what is the EOF signal in
> IDLE?  Reading the docs, I seemed to gather that when
> reading a file, Python sees an empty string as the
> EOF.  Am I wrong?  Is there some variable that can be
> used to signal EOF to Python?  I have already tried
> eof.
>
> -Chris
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From michel.belanger at seidel.ca  Thu Jan 29 09:45:30 2004
From: michel.belanger at seidel.ca (=?ISO-8859-1?Q?Michel_B=E9langer?=)
Date: Thu Jan 29 09:45:56 2004
Subject: [Tutor] help with re.split use
Message-ID: <40191C8A.6040100@seidel.ca>

Hi,

I  use the re.split function to parse Fisrt and Last name from a contact 
field.  I use the following command:    

# -*- coding: cp1252 -*-
import csv
import re
row = "Genevieve Camir?"
contact = re.split(' ',row)
print row, contact, len(contact)

This generate the following results:
Genevieve Camir? ['Genevieve', 'Camir\xe9'] 2


question1:  When I first ran the code, I had and I/O warning message 
which  ended up with the addition of the first line of code  # -*- 
coding: cp1252 -*-  What is it for?

question2:  Why the word 'Camir?' got changed to 'Camir\xe9'

question3: Some of the row from my contacts list contain only one word 
which result with contact been a list of length 1.  Is it possible to 
add an argument to the split function so that it generates an empty 
string for the second item in contact list: i.e.

row = "Belanger"
after split function is applied to row
contact = ['Belanger','']

Thanks



From Ralf.Steckel at AtosOrigin.com  Thu Jan 29 09:47:00 2004
From: Ralf.Steckel at AtosOrigin.com (Steckel, Ralf)
Date: Thu Jan 29 09:47:07 2004
Subject: [Tutor] Tkinter problem with withdraw() by upgrdaing from Python
	2.2.2 to 2.2.3
Message-ID: <42BF8717D22EB1409F03483C993F46A70DE7FF@DEACX002.ikossvan.de>

Dear Tutor,

I have a problem with the withdraw() method for the root window Tk from
Tkinter. I use an application with dialogs derived from the dialog example
by Fredrik Lundh's 'An Introduction to Tkinter'. In my application the
dialog has buttons, which modify the layout of the dialog itself and
therefore, after pressing each button the dialog is closed and opened again
in an infinite loop until a certain result is returned.

To hide the root window of Tkinter and to show only the dialog I use the
withdraw method of Tk as suggested by earlier e-mails of this list. This
works fine on Suse Linux 7.2, Python 2.2.2, Tcl/Tk 8.3.3-23. But on Suse
Linux 8.2, Python 2.2.3, Tcl/Tk 8.4.2 there is just a short flickering of
the root and of the dialog window and none of both windows are visible.

Do I something wrong or results the withdrawing of the parent window in
newer Tkinter versions in hiding the child window too? (The same effect is
on Windows XP SP 1 with Python 2.2.3 for Windows)

Please find reduced source code below.

Thanks and best wishes,

Ralf

#! /usr/bin/env python
#
# dialog basis class
#
import time
from Tkinter import *

class rstDialog(Toplevel):

   def __init__(self, parent, title = None):
      self.result = None

      self.top = Toplevel.__init__(self, parent)
      self.transient(parent)

      if title:
         self.title(title)

      self.parent = parent

      body = Frame(self)
      self.initial_focus = self.body(body)
      body.pack(padx = 5, pady = 5)

      self.buttonbox()

      self.grab_set()

      if not self.initial_focus:
         self.initial_focus = self

      self.protocol('WM_DELETE_WINDOW', self.cancel)

      print 'parent x/y', self.parent.winfo_rootx(),
self.parent.winfo_rooty()

      #self.geometry('+%d+%d' % (50 ,  50 ) )

      self.geometry('+%d+%d' % (self.parent.winfo_rootx() + 50,
                              self.parent.winfo_rooty() + 50))

      self.initial_focus.focus_set()

      self.wait_window(self)

      #
      # construction hooks
      #
   def body(self, master):
      # create dialog body, return widget that should have
      # initial focus. this method should be overwritten

      #Label(master, text = 'Dialog').grid()

      pass

   def buttonbox(self):
      # add standard button box, override if you don't want the
      # standard buttons

      box = Frame(self)

      w = Button(box, text = 'Finish', width = 10,
                  command = self.ok,
                  default = ACTIVE)
      w.pack(side = LEFT, padx = 5, pady = 5)

      w = Button(box, text = 'Again', width = 10,
                  command = self.cancel)
      w.pack(side = LEFT, padx = 5, pady = 5)

      self.bind('&lt;Return>', self.ok)
      self.bind('&lt;Escape>', self.cancel)

      box.pack()

   #
   # standard buttons semantics
   #

   def ok(self, event = None):
      if not self.validate():
         # put focus back
         self.initial_focus.focus_set()
         return

      self.withdraw()
      self.update_idletasks()

      self.apply()

      self.result = 1

      self.cancel()
   def cancel(self, event = None):
      # put focus back to parent window
      self.parent.focus_set()
      self.destroy()

      return self.result

   #
   # command hooks
   #

   def validate(self):
      # override
      return 1

   def apply(self):
      # override
      pass


def run():
   root = Tk()
   root.title('Root')

   width=root.winfo_screenwidth()
   heigth=root.winfo_screenheight()

   root_width = 200
   root_height = 100

   root.geometry('%dx%d+%d+%d' % ( root_width, root_height, \
      (width-root_width)/2, (heigth-root_height)/2 ) )

   root.initial_focus = root
   root.initial_focus.focus_set()
   root.update()
   # this 'withdraw' works only with Python 2.2.2 Tcl/Tk 8.3.3-23
   # this 'withdraw' doesn't work with Python 2.2.3 Tcl/Tk 8.4.2
   root.withdraw()

   while 1:
      dlg = rstDialog(root, 'Dialog')
      if None <> dlg.result:
         return

run()

From python at keep-trying.com  Thu Jan 29 09:46:52 2004
From: python at keep-trying.com (richard)
Date: Thu Jan 29 09:48:05 2004
Subject: [Tutor] Calling Dialog Box from a Class - Still Problems
In-Reply-To: <6.0.0.22.0.20040128200323.020366d0@192.168.5.1>
References: <6.0.0.22.0.20040128200323.020366d0@192.168.5.1>
Message-ID: <6.0.0.22.0.20040129143947.01ffb9b0@192.168.5.1>

Greetings,

Following my earlier email I found that I was not on quite right.
By amending the code as follows:

def OnButton1Button(self, event):
         test = tester()
         test.Info('message','caption')

class tester:
      def Info(self,message,caption):
          dlg = wxMessageDialog(self,message, caption, wxOK | 
wxICON_INFORMATION)
          dlg.ShowModal()
          dlg.Destroy()

I now expected to finally get my dialog box, however instead it gives the
following error:

Traceback (most recent call last):
   File "D:\pythonwork\tesguis\mainmenu.py", line 66, in OnButton1Button
     test.Info('message','caption')
   File "D:\pythonwork\tesguis\mainmenu.py", line 70, in Info
     dlg = wxMessageDialog(self,message, caption, wxOK | wxICON_INFORMATION)
   File "C:\Python23\Lib\site-packages\wxPython\cmndlgs.py", line 368, in 
__init__
     self.this = cmndlgsc.new_wxMessageDialog(*_args,**_kwargs)
TypeError: Type error in argument 1 of new_wxMessageDialog. Expected 
_wxWindow_p.

Searching previous posts appears to be a result of me calling a
method rather than an instance.But I am calling the instance
'Info' so why is it not working?

Richard


From mhansen at cso.atmel.com  Thu Jan 29 10:00:00 2004
From: mhansen at cso.atmel.com (Mike Hansen)
Date: Thu Jan 29 10:00:42 2004
Subject: [Tutor] parsing email
In-Reply-To: <Pine.A41.4.56.0401291223050.204744@hermes-22.rz.uni-frankfurt.de>
References: <4017D3F8.8030504@cso.atmel.com>
	<Pine.A41.4.56.0401281732530.47532@hermes-22.rz.uni-frankfurt.de>
	<4017EF76.3040004@cso.atmel.com>
	<Pine.A41.4.56.0401291223050.204744@hermes-22.rz.uni-frankfurt.de>
Message-ID: <40191FF0.5080706@cso.atmel.com>

In the case of MyDoom, the virus hit before our virus scanner software 
even had an update to scan for MyDoom.

Mike

Michael Janssen wrote:

>On Wed, 28 Jan 2004, Mike Hansen wrote:
>
>  
>
>>Thanks for the reply. I'm told they are text files with each message
>>having its own text file.
>>    
>>
>
>when each eMail is on a single file - why not just run a virus scanner
>about them? The virus scanner can savely delete all virus mails.
>
>
>Michael
>
>
>  
>

From littledanehren at yahoo.com  Thu Jan 29 10:22:20 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Thu Jan 29 10:22:24 2004
Subject: [Tutor] help with re.split use
In-Reply-To: <40191C8A.6040100@seidel.ca>
Message-ID: <20040129152220.23296.qmail@web41801.mail.yahoo.com>

Michel_Bélanger wrote:
> Hi,
> 
> I  use the re.split function to parse Fisrt and Last
> name from a contact 
> field.  I use the following command:    
> 
> # -*- coding: cp1252 -*-
> import csv
> import re
> row = "Genevieve Camiré"
> contact = re.split(' ',row)
> print row, contact, len(contact)
> 
> This generate the following results:
> Genevieve Camiré ['Genevieve', 'Camir\xe9'] 2
> 
> 
> question1:  When I first ran the code, I had and I/O
> warning message 
> which  ended up with the addition of the first line
> of code  # -*- 
> coding: cp1252 -*-  What is it for?
> 
> question2:  Why the word 'Camiré' got changed to
> 'Camir\xe9'
> 
> question3: Some of the row from my contacts list
> contain only one word 
> which result with contact been a list of length 1. 
> Is it possible to 
> add an argument to the split function so that it
> generates an empty 
> string for the second item in contact list: i.e.
> 
> row = "Belanger"
> after split function is applied to row
> contact = ['Belanger','']
> 
> Thanks

Don't use re.split(' ', somestring), use
' '.split(somestring). That fixes your problem. Only
use the re module when you're not just matching a
string.

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Yahoo! SiteBuilder - Free web site building tool. Try it!
http://webhosting.yahoo.com/ps/sb/

From pythontutor at venix.com  Thu Jan 29 10:50:45 2004
From: pythontutor at venix.com (Lloyd Kvam)
Date: Thu Jan 29 10:50:51 2004
Subject: [Tutor] help with re.split use
In-Reply-To: <20040129152220.23296.qmail@web41801.mail.yahoo.com>
References: <20040129152220.23296.qmail@web41801.mail.yahoo.com>
Message-ID: <40192BD5.1040102@venix.com>

Think you meant:
	somestring.split(' ')
Actually split defaults to ALL whitspace characters  so you can probably omit ' '
and still get what you want.

Daniel Ehrenberg wrote:
> Michel_B?langer wrote:
> 
>>Hi,
>>
>>I  use the re.split function to parse Fisrt and Last
>>name from a contact 
>>field.  I use the following command:    
>>
>># -*- coding: cp1252 -*-
>>import csv
>>import re
>>row = "Genevieve Camir?"
>>contact = re.split(' ',row)
>>print row, contact, len(contact)
>>
>>This generate the following results:
>>Genevieve Camir? ['Genevieve', 'Camir\xe9'] 2
>>
>>
>>question1:  When I first ran the code, I had and I/O
>>warning message 
>>which  ended up with the addition of the first line
>>of code  # -*- 
>>coding: cp1252 -*-  What is it for?
>>
>>question2:  Why the word 'Camir?' got changed to
>>'Camir\xe9'
>>
>>question3: Some of the row from my contacts list
>>contain only one word 
>>which result with contact been a list of length 1. 
>>Is it possible to 
>>add an argument to the split function so that it
>>generates an empty 
>>string for the second item in contact list: i.e.
>>
>>row = "Belanger"
>>after split function is applied to row
>>contact = ['Belanger','']
>>
>>Thanks
> 
> 
> Don't use re.split(' ', somestring), use
> ' '.split(somestring). That fixes your problem. Only
> use the re module when you're not just matching a
> string.
> 
> Daniel Ehrenberg
> 
> __________________________________
> Do you Yahoo!?
> Yahoo! SiteBuilder - Free web site building tool. Try it!
> http://webhosting.yahoo.com/ps/sb/
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582


From michel.belanger at seidel.ca  Thu Jan 29 10:59:43 2004
From: michel.belanger at seidel.ca (=?ISO-8859-1?Q?Michel_B=E9langer?=)
Date: Thu Jan 29 10:59:49 2004
Subject: [Tutor] help with re.split use
Message-ID: <40192DEF.8010701@seidel.ca>

Daniel Ehrenberg wrote:

Don't use re.split(' ', somestring), use
' '.split(somestring). That fixes your problem. Only
use the re module when you're not just matching a
string.


Here is the code I tried:

# -*- coding: cp1252 -*-
row = "Genevieve Camir?e"
contact = ' '.split(row)
print row, contact

I get an empty string:

Genevieve Camir?e [' ']





From michel.belanger at seidel.ca  Thu Jan 29 11:06:07 2004
From: michel.belanger at seidel.ca (=?ISO-8859-1?Q?Michel_B=E9langer?=)
Date: Thu Jan 29 11:06:11 2004
Subject: [Tutor] help with re.split use
In-Reply-To: <40192BD5.1040102@venix.com>
References: <20040129152220.23296.qmail@web41801.mail.yahoo.com>
	<40192BD5.1040102@venix.com>
Message-ID: <40192F6F.3050808@seidel.ca>

Yes, it did work.

Now When I run the following code I get:

# -*- coding: cp1252 -*-
row = "Genevieve Camir?e"
contact = row.split()
print row, contact

Genevieve Camir?e ['Genevieve', 'Camir\xe9e']

Do you have any idea about the '?' why it get modify to '\xe9e' in the 
process?

Lloyd Kvam wrote:

> Think you meant:
>     somestring.split(' ')
> Actually split defaults to ALL whitspace characters  so you can 
> probably omit ' '
> and still get what you want.
>
> Daniel Ehrenberg wrote:
>
>> Michel_B?langer wrote:
>>
>>> Hi,
>>>
>>> I  use the re.split function to parse Fisrt and Last
>>> name from a contact field.  I use the following command:   
>>> # -*- coding: cp1252 -*-
>>> import csv
>>> import re
>>> row = "Genevieve Camir?"
>>> contact = re.split(' ',row)
>>> print row, contact, len(contact)
>>>
>>> This generate the following results:
>>> Genevieve Camir? ['Genevieve', 'Camir\xe9'] 2
>>>
>>>
>>> question1:  When I first ran the code, I had and I/O
>>> warning message which  ended up with the addition of the first line
>>> of code  # -*- coding: cp1252 -*-  What is it for?
>>>
>>> question2:  Why the word 'Camir?' got changed to
>>> 'Camir\xe9'
>>>
>>> question3: Some of the row from my contacts list
>>> contain only one word which result with contact been a list of 
>>> length 1. Is it possible to add an argument to the split function so 
>>> that it
>>> generates an empty string for the second item in contact list: i.e.
>>>
>>> row = "Belanger"
>>> after split function is applied to row
>>> contact = ['Belanger','']
>>>
>>> Thanks
>>
>>
>>
>> Don't use re.split(' ', somestring), use
>> ' '.split(somestring). That fixes your problem. Only
>> use the re module when you're not just matching a
>> string.
>>
>> Daniel Ehrenberg
>>
>> __________________________________
>> Do you Yahoo!?
>> Yahoo! SiteBuilder - Free web site building tool. Try it!
>> http://webhosting.yahoo.com/ps/sb/
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor@python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
>



From sigurd at 12move.de  Thu Jan 29 11:08:36 2004
From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=)
Date: Thu Jan 29 11:10:43 2004
Subject: [Tutor] parsing email
In-Reply-To: <Pine.A41.4.56.0401291223050.204744@hermes-22.rz.uni-frankfurt.de>
	(Michael
	Janssen's message of "Thu, 29 Jan 2004 12:26:19 +0100 (CET)")
References: <4017D3F8.8030504@cso.atmel.com>
	<Pine.A41.4.56.0401281732530.47532@hermes-22.rz.uni-frankfurt.de>
	<4017EF76.3040004@cso.atmel.com>
	<Pine.A41.4.56.0401291223050.204744@hermes-22.rz.uni-frankfurt.de>
Message-ID: <m3fzdylp6g.fsf@hamster.pflaesterer.de>

On 29 Jan 2004, Michael Janssen <- Janssen@rz.uni-frankfurt.de wrote:

> On Wed, 28 Jan 2004, Mike Hansen wrote:

>> Thanks for the reply. I'm told they are text files with each message
>> having its own text file.

> when each eMail is on a single file - why not just run a virus scanner
> about them? The virus scanner can savely delete all virus mails.

A virus scanner can easily be broken by unfriendly senders; e.g. if you
send an e-mail with a zip attachment the scanner has to unpack the
attachment.  If you zipped a bigggggg file (some GB) of only zeros you
have a small and nice zip file which if unzipped stops your machine (to
make it perfekt you need a hex editor to change the header of the zip
file so the real size can't be seen).  Or use bzip2.  Google for 42.zip.
Furthermore a virus scanner has to know the pattern of the virus.  So a
virus scanner gives you a false feeling of security.  And you might not
only want to search for virus files but for every sort of UCE or UBE.



   Karl
-- 
Please do *not* send copies of replies to me.
I read the list


From mlong at datalong.com  Thu Jan 29 13:17:41 2004
From: mlong at datalong.com (Michael Long)
Date: Thu Jan 29 13:17:49 2004
Subject: [Tutor] (no subject)
Message-ID: <.161.88.255.139.1075400261.squirrel@datalong.com>

Hi,

I cannot see the flaw in the logic of my code. I would appreciate it if someone
could explain the results I am seeing.

### the code
print '----newKeyRS'
newKeyRS = []
for newRecord in newRS:
	newPk = ''
	for nKey in newKeys:
		newPk = newPk + str(newRecord[nKey]).strip()
	newKeyRS.append((newPk, newRecord))
	if newPk[:5]=='15000': print (newPk, newRecord)

print '        ----'
for newRecord in newKeyRS:
	if newRecord[0][:5]=='15000': print newRecord

### the results
----newKeyRS
('150002', {'GroupCode': 50002, 'LanguageId': 1})
('150003', {'GroupCode': 50003, 'LanguageId': 1})
('150004', {'GroupCode': 50004, 'LanguageId': 1})
('150005', {'GroupCode': 50005, 'LanguageId': 1})
('150006', {'GroupCode': 50006, 'LanguageId': 1})
('150007', {'GroupCode': 50007, 'LanguageId': 1})
('150008', {'GroupCode': 50008, 'LanguageId': 1})
('150009', {'GroupCode': 50009, 'LanguageId': 1})
        ----
('150002', {'GroupCode': 50002, 'LanguageId': 1})
('150004', {'GroupCode': 50004, 'LanguageId': 1})
('150006', {'GroupCode': 50006, 'LanguageId': 1})
('150008', {'GroupCode': 50008, 'LanguageId': 1})

Thanks,
Mike

From mlong at datalong.com  Thu Jan 29 13:20:14 2004
From: mlong at datalong.com (Michael Long)
Date: Thu Jan 29 13:20:20 2004
Subject: [Tutor] Unexpected results with list
Message-ID: <.161.88.255.139.1075400414.squirrel@datalong.com>

Hi,

I cannot see the flaw in the logic of my code. I would appreciate it if someone
could explain the results I am seeing.

### the code
print '----newKeyRS'
newKeyRS = []
for newRecord in newRS:
        newPk = ''
        for nKey in newKeys:
                newPk = newPk + str(newRecord[nKey]).strip()
        newKeyRS.append((newPk, newRecord))
        if newPk[:5]=='15000': print (newPk, newRecord)

print '        ----'
for newRecord in newKeyRS:
        if newRecord[0][:5]=='15000': print newRecord

### the results
----newKeyRS
('150002', {'GroupCode': 50002, 'LanguageId': 1})
('150003', {'GroupCode': 50003, 'LanguageId': 1})
('150004', {'GroupCode': 50004, 'LanguageId': 1})
('150005', {'GroupCode': 50005, 'LanguageId': 1})
('150006', {'GroupCode': 50006, 'LanguageId': 1})
('150007', {'GroupCode': 50007, 'LanguageId': 1})
('150008', {'GroupCode': 50008, 'LanguageId': 1})
('150009', {'GroupCode': 50009, 'LanguageId': 1})
        ----
('150002', {'GroupCode': 50002, 'LanguageId': 1})
('150004', {'GroupCode': 50004, 'LanguageId': 1})
('150006', {'GroupCode': 50006, 'LanguageId': 1})
('150008', {'GroupCode': 50008, 'LanguageId': 1})

Thanks,
Mike



From orbitz at ezabel.com  Thu Jan 29 13:26:24 2004
From: orbitz at ezabel.com (orbitz@ezabel.com)
Date: Thu Jan 29 13:26:57 2004
Subject: [Tutor] help with re.split use
In-Reply-To: <40192F6F.3050808@seidel.ca>
References: <20040129152220.23296.qmail@web41801.mail.yahoo.com>
	<40192BD5.1040102@venix.com> <40192F6F.3050808@seidel.ca>
Message-ID: <20040129132624.7ff52172.orbitz@ezabel.com>

It isn't regular character and neds to be represented using an esacpe
code. if you do: print contact[1] it sohuld print Camir?e.


On Thu, 29 Jan 2004 11:06:07 -0500
Michel B?langer <michel.belanger@seidel.ca> wrote:

> Yes, it did work.
> 
> Now When I run the following code I get:
> 
> # -*- coding: cp1252 -*-
> row = "Genevieve Camir?e"
> contact = row.split()
> print row, contact
> 
> Genevieve Camir?e ['Genevieve', 'Camir\xe9e']
> 
> Do you have any idea about the '?' why it get modify to '\xe9e' in the
> 
> process?
> 
> Lloyd Kvam wrote:
> 
> > Think you meant:
> >     somestring.split(' ')
> > Actually split defaults to ALL whitspace characters  so you can 
> > probably omit ' '
> > and still get what you want.
> >
> > Daniel Ehrenberg wrote:
> >
> >> Michel_B?langer wrote:
> >>
> >>> Hi,
> >>>
> >>> I  use the re.split function to parse Fisrt and Last
> >>> name from a contact field.  I use the following command:   
> >>> # -*- coding: cp1252 -*-
> >>> import csv
> >>> import re
> >>> row = "Genevieve Camir?"
> >>> contact = re.split(' ',row)
> >>> print row, contact, len(contact)
> >>>
> >>> This generate the following results:
> >>> Genevieve Camir? ['Genevieve', 'Camir\xe9'] 2
> >>>
> >>>
> >>> question1:  When I first ran the code, I had and I/O
> >>> warning message which  ended up with the addition of the first
> >line>> of code  # -*- coding: cp1252 -*-  What is it for?
> >>>
> >>> question2:  Why the word 'Camir?' got changed to
> >>> 'Camir\xe9'
> >>>
> >>> question3: Some of the row from my contacts list
> >>> contain only one word which result with contact been a list of 
> >>> length 1. Is it possible to add an argument to the split function
> >so >> that it
> >>> generates an empty string for the second item in contact list:
> >i.e.>>
> >>> row = "Belanger"
> >>> after split function is applied to row
> >>> contact = ['Belanger','']
> >>>
> >>> Thanks
> >>
> >>
> >>
> >> Don't use re.split(' ', somestring), use
> >> ' '.split(somestring). That fixes your problem. Only
> >> use the re module when you're not just matching a
> >> string.
> >>
> >> Daniel Ehrenberg
> >>
> >> __________________________________
> >> Do you Yahoo!?
> >> Yahoo! SiteBuilder - Free web site building tool. Try it!
> >> http://webhosting.yahoo.com/ps/sb/
> >>
> >> _______________________________________________
> >> Tutor maillist  -  Tutor@python.org
> >> http://mail.python.org/mailman/listinfo/tutor
> >>
> >
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

From pythontutor at venix.com  Thu Jan 29 14:06:01 2004
From: pythontutor at venix.com (Lloyd Kvam)
Date: Thu Jan 29 14:06:05 2004
Subject: [Tutor] help with re.split use
In-Reply-To: <40191C8A.6040100@seidel.ca>
References: <40191C8A.6040100@seidel.ca>
Message-ID: <40195999.6030703@venix.com>

belatedly answerin all of the questions.

Michel B?langer wrote:

> Hi,
> 
> I  use the re.split function to parse Fisrt and Last name from a contact 
> field.  I use the following command:   
> # -*- coding: cp1252 -*-
> import csv
> import re
> row = "Genevieve Camir?"
> contact = re.split(' ',row)
> print row, contact, len(contact)
> 
> This generate the following results:
> Genevieve Camir? ['Genevieve', 'Camir\xe9'] 2
> 
> 
> question1:  When I first ran the code, I had and I/O warning message 
> which  ended up with the addition of the first line of code  # -*- 
> coding: cp1252 -*-  What is it for?
Each string character has a range of 256 possible values.  0 - 127 have a very standard
definition between byte values and character representation, so 48 represents zero '0'.
The values from 128 - 255 vary depending upon the "code page".  cp1252 provides a
convenient mapping between byte values and characters needed in Western European
languages.  The "standard" ASCII mapping leaves 128-255 undefined.

\xe9 provides the hex value (e9) of the accented e character.  The decimal value would be
(14 * 16) + 9

http://www.joelonsoftware.com/articles/Unicode.html
readable description of unicode issues.
> 
> question2:  Why the word 'Camir?' got changed to 'Camir\xe9'
see above

> 
> question3: Some of the row from my contacts list contain only one word 
> which result with contact been a list of length 1.  Is it possible to 
> add an argument to the split function so that it generates an empty 
> string for the second item in contact list: i.e.
> 
> row = "Belanger"
> after split function is applied to row
> contact = ['Belanger','']

row.split(' ',1) would limit the length to two items.  I think you are stuck with
checking for lengths of 1 and appending '' for those cases in your code.

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

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582


From python at cairnlin.co.uk  Thu Jan 29 14:14:23 2004
From: python at cairnlin.co.uk (Iain)
Date: Thu Jan 29 14:15:11 2004
Subject: [Tutor] Converting string or list to sum 
Message-ID: <200401291914.23909.python@cairnlin.co.uk>

If I have a sum as a string (e.g. '2+3') or in a list (e.g. [2,'+',3]), how 
can I get the result of the sum?

Thanks

Iain.


From dyoo at hkn.eecs.berkeley.edu  Thu Jan 29 14:41:42 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Jan 29 14:41:50 2004
Subject: [Tutor] Converting string or list to sum 
In-Reply-To: <200401291914.23909.python@cairnlin.co.uk>
Message-ID: <Pine.LNX.4.44.0401291138180.20840-100000@hkn.eecs.berkeley.edu>



On Thu, 29 Jan 2004, Iain wrote:

> If I have a sum as a string (e.g. '2+3') or in a list (e.g. [2,'+',3]),
> how can I get the result of the sum?


Hi Iain,



If we had a function that takes three arguments:

    calculate(left_hand_side, operator, right_hand_side)


then we might be able to say something like:

###
>>> calculate(2, '+', 3)
5
>>> calculate(42, '-', 43)
-1
###


Is this the sort of thing that you're asking?



Talk to you later!


From orbitz at ezabel.com  Thu Jan 29 14:47:18 2004
From: orbitz at ezabel.com (orbitz@ezabel.com)
Date: Thu Jan 29 14:47:51 2004
Subject: [Tutor] Converting string or list to sum
In-Reply-To: <200401291914.23909.python@cairnlin.co.uk>
References: <200401291914.23909.python@cairnlin.co.uk>
Message-ID: <20040129144718.177ba6af.orbitz@ezabel.com>

The easiest way out is probably to use eval.

>>> eval('2+1')
3


if you have a list, however, you will just create a list using that.


On Thu, 29 Jan 2004 19:14:23 +0000
Iain <python@cairnlin.co.uk> wrote:

> If I have a sum as a string (e.g. '2+3') or in a list (e.g. [2,'+',3]), how 
> can I get the result of the sum?
> 
> Thanks
> 
> Iain.
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

From python at cairnlin.co.uk  Thu Jan 29 15:02:37 2004
From: python at cairnlin.co.uk (Iain)
Date: Thu Jan 29 15:03:12 2004
Subject: [Tutor] Converting string or list to sum
In-Reply-To: <Pine.LNX.4.44.0401291138180.20840-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0401291138180.20840-100000@hkn.eecs.berkeley.edu>
Message-ID: <200401292002.37262.python@cairnlin.co.uk>

On Thursday 29 January 2004 19:41, Danny Yoo wrote:
> On Thu, 29 Jan 2004, Iain wrote:
> > If I have a sum as a string (e.g. '2+3') or in a list (e.g. [2,'+',3]),
> > how can I get the result of the sum?
>
> Hi Iain,
>
>
>
> If we had a function that takes three arguments:
>
>     calculate(left_hand_side, operator, right_hand_side)
>
>
> then we might be able to say something like:
>
> ###
>
> >>> calculate(2, '+', 3)
>
> 5
>
> >>> calculate(42, '-', 43)
>
> -1
> ###
>
>
> Is this the sort of thing that you're asking?
>
>
>
> Talk to you later!

Hi Danny,

I was hoping for something more generic, but that might do the trick with a 
bit of effort.

I'm trying to learn Tk and writing a little GUI calculator - doubtless very 
badly but never mind.  I've got it doing everything except the calculation.  
At the moment, the  buttons pressed go into a list, so if I want 22 + 10 I'll 
have a list that looks like [2,2,'+',1,0].  I want to get from that to the 
answer of 32, and have it generic enough to cope with any basic arithmetic 
calculation.

Of course, if this is just a terrible way to do it, perhaps someone can 
suggest a better one.

Iain.

 


From WRSimoni at MAPLLC.com  Thu Jan 29 15:29:46 2004
From: WRSimoni at MAPLLC.com (Simoni, Bill)
Date: Thu Jan 29 15:29:42 2004
Subject: [Tutor] Converting string or list to sum
Message-ID: <DD0F81089B11A54A83A3270D9E1125E8646AC3@FDYEXC213.mgroupnet.com>

Iain
Something like this may work. I've only tested as far as you see below.

>>> eq=[2,2,'+',1,0]
>>> eval(''.join([str(x) for x in eq]))
32

It also appears to work if parenthesis get involved.

>>> eq = ['(',1,'+',2,')','*',3]
>>> eval(''.join([str(x) for x in eq]))
9

The list comprehension takes care of .join not working on integers.

Bill


-----Original Message-----
From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On
Behalf Of Iain
Sent: Thursday, January 29, 2004 3:03 PM
To: Danny Yoo
Cc: tutor@python.org
Subject: Re: [Tutor] Converting string or list to sum


On Thursday 29 January 2004 19:41, Danny Yoo wrote:
> On Thu, 29 Jan 2004, Iain wrote:
> > If I have a sum as a string (e.g. '2+3') or in a list (e.g. [2,'+',3]),
> > how can I get the result of the sum?
>
> Hi Iain,
>
>
>
> If we had a function that takes three arguments:
>
>     calculate(left_hand_side, operator, right_hand_side)
>
>
> then we might be able to say something like:
>
> ###
>
> >>> calculate(2, '+', 3)
>
> 5
>
> >>> calculate(42, '-', 43)
>
> -1
> ###
>
>
> Is this the sort of thing that you're asking?
>
>
>
> Talk to you later!

Hi Danny,

I was hoping for something more generic, but that might do the trick with a 
bit of effort.

I'm trying to learn Tk and writing a little GUI calculator - doubtless very 
badly but never mind.  I've got it doing everything except the calculation.  
At the moment, the  buttons pressed go into a list, so if I want 22 + 10 I'll 
have a list that looks like [2,2,'+',1,0].  I want to get from that to the 
answer of 32, and have it generic enough to cope with any basic arithmetic 
calculation.

Of course, if this is just a terrible way to do it, perhaps someone can 
suggest a better one.

Iain.

 


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


From bigsteve127 at hotmail.com  Thu Jan 29 15:38:26 2004
From: bigsteve127 at hotmail.com (big steve)
Date: Thu Jan 29 15:38:27 2004
Subject: [Tutor] vb6.0
Message-ID: <BAY8-DAV66XAPtJoXOy0001135e@hotmail.com>

  I guess I am not the "sharpest pencil in the drawer", cause I spent $1000.00 for a on line course for vb6.0 and I am not a programmer yet!  I did learn a lot about all the tools but if I had to write anything more than "Hello, World" I would be in trouble. 
       Well that is a little extreme, but I sure did not get all I thought I would out of this course. Now, am I just not made to program?  Or do you think I could enhance my programming by studying Python. I do have the will. I think my biggest problem is I have no Idea of what I want to program.  I have downloaded the latest Python so I am ready!  I guess I am asking for words of encouragement, got any?  
Thanks  Steve Hulett
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20040129/6f9b1cb3/attachment-0001.html
From python at cairnlin.co.uk  Thu Jan 29 15:47:03 2004
From: python at cairnlin.co.uk (Iain)
Date: Thu Jan 29 15:47:18 2004
Subject: [Tutor] Converting string or list to sum
In-Reply-To: <200401292021.38242.iain@cairnlin.co.uk>
References: <200401291914.23909.python@cairnlin.co.uk>
	<20040129144718.177ba6af.orbitz@ezabel.com>
	<200401292021.38242.iain@cairnlin.co.uk>
Message-ID: <200401292047.03492.python@cairnlin.co.uk>

Thanks,

 I think I can put two ideas together to solve it for lists :
 >>> a=[2, 3, '+', 4]
 >>> d=""
 >>> for item in range(len(a)):

 ...     d=d+str(a[item])
 ...

 >>> d
 '23+4'

 >>> eval(d)
 27

 I didn't realise eval did that - very handy.

 Iain.

> On Thursday 29 January 2004 19:47, orbitz@ezabel.com wrote:
> > The easiest way out is probably to use eval.
> >
> > >>> eval('2+1')
> >
> > 3
> >
> >
> > if you have a list, however, you will just create a list using that.
> >
> >
> > On Thu, 29 Jan 2004 19:14:23 +0000
> >
> > Iain <python@cairnlin.co.uk> wrote:
> > > If I have a sum as a string (e.g. '2+3') or in a list (e.g. [2,'+',3]),
> > > how can I get the result of the sum?
> > >
> > > Thanks
> > >
> > > Iain.
> > >
> > >
> > > _______________________________________________
> > > Tutor maillist  -  Tutor@python.org
> > > http://mail.python.org/mailman/listinfo/tutor
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor


From brian at coolnamehere.com  Thu Jan 29 16:15:27 2004
From: brian at coolnamehere.com (Brian Wisti)
Date: Thu Jan 29 16:15:33 2004
Subject: [Tutor] vb6.0
In-Reply-To: <BAY8-DAV66XAPtJoXOy0001135e@hotmail.com>
References: <BAY8-DAV66XAPtJoXOy0001135e@hotmail.com>
Message-ID: <401977EF.6070803@coolnamehere.com>

If you have the will, then definitely give it a shot. There are a 
tremendous number of resources out there for learning Python, and most 
of them cost much much less than $1000. Learning Python will increase 
your understanding of programming in the same way that learning a new 
musical instrument will increase your understanding of music. I am more 
than a little biased, but I happen to think you will enjoy Python more 
and create more ambitious applications with Python, because it is so 
easy to get started - and stays right with you as your projects get more 
complex.

Python is free, the tutorials are plentiful and free, and the community 
is enthusiastic. Come on in, the water's fine :-)

Kind Regards,
Brian Wisti
http://coolnamehere.com/

big steve wrote:

> *  I guess I am not the "sharpest pencil in the drawer", cause I spent 
> $1000.00 for a on line course for vb6.0 and I am not a programmer 
> yet!  I did learn a lot about all the tools but if I had to write 
> anything more than "Hello, World" I would be in trouble. *
> *       Well that is a little extreme, but I sure did not get all I 
> thought I would out of this course. Now, am I just not made to 
> program?  Or do you think I could enhance my programming by studying 
> Python. I do have the will. I think my biggest problem is I have no 
> Idea of what I want to program.  I have downloaded the latest Python 
> so I am ready!  I guess I am asking for words of encouragement, got 
> any?  *
> *Thanks  Steve Hulett*
>
>------------------------------------------------------------------------
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
>  
>



From dyoo at hkn.eecs.berkeley.edu  Thu Jan 29 16:28:45 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Jan 29 16:28:58 2004
Subject: [Tutor] Converting string or list to sum [just be careful about
	eval()]
In-Reply-To: <200401292047.03492.python@cairnlin.co.uk>
Message-ID: <Pine.LNX.4.44.0401291302470.5358-100000@hkn.eecs.berkeley.edu>



On Thu, 29 Jan 2004, Iain wrote:

>  I think I can put two ideas together to solve it for lists :
>  >>> a=[2, 3, '+', 4]
>  >>> d=""
>  >>> for item in range(len(a)):
>
>  ...     d=d+str(a[item])
>  ...
>
>  >>> d
>  '23+4'
>
>  >>> eval(d)
>  27
>
>  I didn't realise eval did that - very handy.


Hello!


eval() is very handy, but just be very careful with who you let type into
it.  Since you're using it for learning Tkinter, it's fine to use it, but
if you were to do that in production code, you have to take more
responsible precautions.  Simply put: eval() can be dangerous in the wrong
hands.



eval() exposes Python itself to the outside world, so not only will the
person doing input be able to do arithmetic, but they can do even more
interesting things, like

###
>>> eval("__import__('math').sqrt(42)")
6.4807406984078604
###



By default, every library module is exposed to the outside world, and
anyone can use the __import__() built-in to get at things.  And it's even
possible to get the system to go into RuntimeErrors with some lambda
trickery:

###
>>> eval("(lambda f: f(f))(lambda g: g(g))")
  File "<string>", line 1, in <lambda>
  File "<string>", line 1, in <lambda>
  File "<string>", line 1, in <lambda>
  File "<string>", line 1, in <lambda>
[... lot of errors later]
RuntimeError: maximum recursion depth exceeded
###


(Don't worry too much about what in the world that lambda expression is
doing: it's just a disguised version of:

###
def f(): f()
###

in lambda expression form.)


And these are just harmless expressions, compared to the really evil ones
that one could construct, given enough malicious imagination.


So be careful about eval(): It's not just giving access to simple
arithmetic, but to the whole Python system.



Hope this helps!


From dyoo at hkn.eecs.berkeley.edu  Thu Jan 29 16:49:04 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Jan 29 16:49:08 2004
Subject: [Tutor] vb6.0
In-Reply-To: <Pine.LNX.4.44.0401291333070.5358-100000@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.44.0401291347140.5358-100000@hkn.eecs.berkeley.edu>



On Thu, 29 Jan 2004, Danny Yoo wrote:

> Small note: can you turn on HTML email in your mail client?  You may not
                           ^^


Errr... doh.  That was silly of me.


Can you turn _off_ HTML email in your mail client?


*grin*


From littledanehren at yahoo.com  Thu Jan 29 16:58:19 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Thu Jan 29 16:58:25 2004
Subject: [Tutor] what? (late nite entertainment) (*)
In-Reply-To: <5.1.0.14.0.20040129104059.0395f220@192.168.1.1>
Message-ID: <20040129215819.20915.qmail@web41804.mail.yahoo.com>

>         if x[z]: x[z*z:n:z]=y[z*z:n:z]
> 
> (At least it doesn't work on my machine with Python
> 2.2)

Python 2.2 doesn't support extended list slicing,
which that piece of code uses. Switch to 2.3.

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Yahoo! SiteBuilder - Free web site building tool. Try it!
http://webhosting.yahoo.com/ps/sb/

From littledanehren at yahoo.com  Thu Jan 29 17:02:58 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Thu Jan 29 17:03:04 2004
Subject: [Tutor] vb6.0
In-Reply-To: <BAY8-DAV66XAPtJoXOy0001135e@hotmail.com>
Message-ID: <20040129220258.68057.qmail@web41812.mail.yahoo.com>

big steve wrote:
>   I guess I am not the "sharpest pencil in the
> drawer", cause I spent $1000.00 for a on line course
> for vb6.0 and I am not a programmer yet!  I did
> learn a lot about all the tools but if I had to
> write anything more than "Hello, World" I would be
> in trouble. 
>        Well that is a little extreme, but I sure did
> not get all I thought I would out of this course.
> Now, am I just not made to program?  Or do you think
> I could enhance my programming by studying Python. I
> do have the will. I think my biggest problem is I
> have no Idea of what I want to program.  I have
> downloaded the latest Python so I am ready!  I guess
> I am asking for words of encouragement, got any?  
> Thanks  Steve Hulett

Python is, for many people, easier than Visual Basic.
If you're having trouble understanding what's
happening, try How to Think like a Computer Scientist,
which focuses heavily on understanding how things
work. It's at http://www.ibiblio.org/obp/thinkCSpy/

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Yahoo! SiteBuilder - Free web site building tool. Try it!
http://webhosting.yahoo.com/ps/sb/

From missive at hotmail.com  Thu Jan 29 17:11:31 2004
From: missive at hotmail.com (Lee Harr)
Date: Thu Jan 29 17:11:37 2004
Subject: [Tutor] Re: Unexpected results with list
Message-ID: <BAY2-F114yyhfHACKOH0005eef6@hotmail.com>

>I cannot see the flaw in the logic of my code. I would appreciate it if 
>someone
>could explain the results I am seeing.
>
>### the code
>print '----newKeyRS'
>newKeyRS = []
>for newRecord in newRS:
>         newPk = ''
>         for nKey in newKeys:
>                 newPk = newPk + str(newRecord[nKey]).strip()
>         newKeyRS.append((newPk, newRecord))
>         if newPk[:5]=='15000': print (newPk, newRecord)


I think I might write this as newPk.startswith('15000')

>
>print '        ----'
>for newRecord in newKeyRS:
>         if newRecord[0][:5]=='15000': print newRecord


How about changing this to ...

for newPk, newRecord in newKeyRS:
    if newPk.startswith('15000'):
        print (newPk, newRecord)
    else:
        print '---->', newRecord


>### the results
>----newKeyRS
>('150002', {'GroupCode': 50002, 'LanguageId': 1})
>('150003', {'GroupCode': 50003, 'LanguageId': 1})
>('150004', {'GroupCode': 50004, 'LanguageId': 1})
>('150005', {'GroupCode': 50005, 'LanguageId': 1})
>('150006', {'GroupCode': 50006, 'LanguageId': 1})
>('150007', {'GroupCode': 50007, 'LanguageId': 1})
>('150008', {'GroupCode': 50008, 'LanguageId': 1})
>('150009', {'GroupCode': 50009, 'LanguageId': 1})
>         ----
>('150002', {'GroupCode': 50002, 'LanguageId': 1})
>('150004', {'GroupCode': 50004, 'LanguageId': 1})
>('150006', {'GroupCode': 50006, 'LanguageId': 1})
>('150008', {'GroupCode': 50008, 'LanguageId': 1})


It would be very helpful to have a full working example to
play with...

_________________________________________________________________
STOP MORE SPAM with the new MSN 8 and get 2 months FREE* 
http://join.msn.com/?page=features/junkmail


From dyoo at hkn.eecs.berkeley.edu  Thu Jan 29 16:45:53 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Jan 29 17:15:39 2004
Subject: [Tutor] vb6.0
In-Reply-To: <BAY8-DAV66XAPtJoXOy0001135e@hotmail.com>
Message-ID: <Pine.LNX.4.44.0401291333070.5358-100000@hkn.eecs.berkeley.edu>



Hi Steve,


Small note: can you turn on HTML email in your mail client?  You may not
know this, but your email has embedded HTML tags, and some folks may have
difficulty reading your message because of those tags.


See "Configuring Mail Clients to Send Plain ASCII Text":

    http://www.expita.com/nomime.html

for details on how to turn off HTML email for the common email clients.



> Or do you think I could enhance my programming by studying Python.

Most any kind of programming language will probably help you, and Python
is a good language to start off.  Take a look at:

    http://www.python.org/topics/learn/non-prog.html


But avoid just studying the language syntax alone --- a language is
associated with a living literature, with applications that affect people.
It sounds like your class in Visual Basic focused a bit too much on the
syntax, and not on what kinds of things can be said in that language.


What sort of things are you interested in?


There's a lot of interesting programs in Useless Python:

    http://uselesspython.com/

They show the sort of things that people here can program with a little
bit of code.



Good luck to you!


From alan.gauld at blueyonder.co.uk  Thu Jan 29 19:17:26 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Thu Jan 29 19:17:00 2004
Subject: [Tutor] Calling Dialog Box from a Class - Still Problems
References: <6.0.0.22.0.20040128200323.020366d0@192.168.5.1>
	<6.0.0.22.0.20040129143947.01ffb9b0@192.168.5.1>
Message-ID: <007501c3e6c6$71163620$6401a8c0@xp>

There doesn't seem to be any other replies so I'll hazard
a guess - since I'm not an expert in wxPython which seems
to be what you are using. If this doesn't work I suggest
you try the wxPython mailing list, they are supposed to
be quite supportive of beginners...

> def OnButton1Button(self, event):
>          test = tester()
>          test.Info('message','caption')
>
> class tester:
>       def Info(self,message,caption):
>           dlg = wxMessageDialog(self,message, caption, ...

> Traceback (most recent call last):
>    File "D:\pythonwork\tesguis\mainmenu.py", line 66, in
OnButton1Button
>      test.Info('message','caption')
...
> TypeError: Type error in argument 1 of new_wxMessageDialog. Expected
> _wxWindow_p.

Going by the error message it looks like self is supposed to
be a wxWindow object but you are passing a tester. Maybe if
you made tester a subclass of wxWindow(or whatever its called)
it would work?

> Searching previous posts appears to be a result of me calling a
> method rather than an instance.But I am calling the instance
> 'Info' so why is it not working?

You seem confused by OOP terminology. You are calling the "Info"
method of the "test" instance of the "tester" class.

That seems to be the right thibng to do here but you need to pass
the right type of argument to the wxMessageDialog function.

Thats my guess,

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


From alan.gauld at blueyonder.co.uk  Thu Jan 29 19:30:37 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Thu Jan 29 19:30:56 2004
Subject: [Tutor] (no subject)
References: <.161.88.255.139.1075400261.squirrel@datalong.com>
Message-ID: <009201c3e6c8$486bae10$6401a8c0@xp>

> I cannot see the flaw in the logic of my code. I would 
> appreciate it if someone could explain the results I am seeing.


First, the indentation is all gone, pleae make sure you 
post using plain text so that indentation is preserved. 
I know thats not always esy depending on the mail tool 
but it helps a lot with Python!

> ### the code
> print '----newKeyRS'
> newKeyRS = []
> for newRecord in newRS:

newRS isn't defined yet...

> newPk = ''
> for nKey in newKeys:

Neither is newKeys...

    > newPk = newPk + str(newRecord[nKey]).strip()

Without any idea of what newRecord or newKeys looks like its 
hard to know if this is right or not, assuming it is...

    > newKeyRS.append((newPk, newRecord))
    > if newPk[:5]=='15000': 
         print (newPk, newRecord)
 
> print '        ----'

Is this supposed to be inside the if?
Or even inside the loop?


> for newRecord in newKeyRS:
     > if newRecord[0][:5]=='15000': 
           print newRecord

> ### the results
> ----newKeyRS
> ('150002', {'GroupCode': 50002, 'LanguageId': 1})
> ('150003', {'GroupCode': 50003, 'LanguageId': 1})
> ('150004', {'GroupCode': 50004, 'LanguageId': 1})
> ('150005', {'GroupCode': 50005, 'LanguageId': 1})
> ('150006', {'GroupCode': 50006, 'LanguageId': 1})
> ('150007', {'GroupCode': 50007, 'LanguageId': 1})
> ('150008', {'GroupCode': 50008, 'LanguageId': 1})
> ('150009', {'GroupCode': 50009, 'LanguageId': 1})
>         ----
> ('150002', {'GroupCode': 50002, 'LanguageId': 1})
> ('150004', {'GroupCode': 50004, 'LanguageId': 1})
> ('150006', {'GroupCode': 50006, 'LanguageId': 1})
> ('150008', {'GroupCode': 50008, 'LanguageId': 1})

So what did you expect? What came out looks like what 
you put in assuming that the dictionary is what 
newRecord looked like originally.

What exactly do you perceive to be the problem? I 
assume its the fact that only the even numbers 
are printing in the second set? I don;t know why 
thats happening because I'm not exactly sure whats 
happening in the section above.


Alan G.

From delza at blastradius.com  Wed Jan 28 23:57:20 2004
From: delza at blastradius.com (Dethe Elza)
Date: Thu Jan 29 19:39:38 2004
Subject: [Tutor] Re: [Edu-sig] what? (late nite entertainment) (*)
In-Reply-To: <401838D7.2000000@aon.at>
References: <401838D7.2000000@aon.at>
Message-ID: <9E967B83-5217-11D8-A1EA-0003939B59E8@blastradius.com>

Well, it seems to generate primes less than n, but breaks if n < 2 
(perhaps it should return an empty list?)

Another entry for obfuscated python... %-)

--Dethe

On 28-Jan-04, at 2:33 PM, Gregor Lingl wrote:

> def what(n):
>    x,y = range(n), [0]*n
>    x[1]= 0
>    z = 0
>    while z*z <= n:
>        z+=1
>        if x[z]: x[z*z:n:z]=y[z*z:n:z]
>    return [z for z in x if z]
>
This past week, everyday when I opened my Wall Street Journal, I was 
met with a full page ad from Microsoft. This ad was dominated by three 
simple words "Protect your PC." This strikes me as something akin to 
the Saudi government running ads in the New York Times in mid-September 
of 2001 saying "Protect your Tall Buildings." --Russ McGuire
-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/pkcs7-signature
Size: 2371 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20040128/518b2ced/smime.bin
From stephen at abr.com.au  Thu Jan 29 00:22:37 2004
From: stephen at abr.com.au (Stephen Thorne)
Date: Thu Jan 29 19:39:43 2004
Subject: [Tutor] Re: [Edu-sig] what? (late nite entertainment) (*)
In-Reply-To: <9E967B83-5217-11D8-A1EA-0003939B59E8@blastradius.com>
References: <401838D7.2000000@aon.at>
	<9E967B83-5217-11D8-A1EA-0003939B59E8@blastradius.com>
Message-ID: <4018989D.8030808@abr.com.au>

More correctly, it generates a list of numbers less than n, then removes 
all numbers from that list that aren't prime. Also, it breaks if n < 3.

Its definately an interesting implementation. I'm not sure I like the 
'y' variable.

Stephen.

Dethe Elza wrote:

> Well, it seems to generate primes less than n, but breaks if n < 2 
> (perhaps it should return an empty list?)
>
> Another entry for obfuscated python... %-)
>
> --Dethe
>
> On 28-Jan-04, at 2:33 PM, Gregor Lingl wrote:
>
>> def what(n):
>>    x,y = range(n), [0]*n
>>    x[1]= 0
>>    z = 0
>>    while z*z <= n:
>>        z+=1
>>        if x[z]: x[z*z:n:z]=y[z*z:n:z]
>>    return [z for z in x if z]
>>
> This past week, everyday when I opened my Wall Street Journal, I was 
> met with a full page ad from Microsoft. This ad was dominated by three 
> simple words "Protect your PC." This strikes me as something akin to 
> the Saudi government running ads in the New York Times in 
> mid-September of 2001 saying "Protect your Tall Buildings." --Russ 
> McGuire
>
>------------------------------------------------------------------------
>
>_______________________________________________
>Edu-sig mailing list
>Edu-sig@python.org
>http://mail.python.org/mailman/listinfo/edu-sig
>  
>



From urnerk at qwest.net  Thu Jan 29 03:51:00 2004
From: urnerk at qwest.net (Kirby Urner)
Date: Thu Jan 29 19:39:49 2004
Subject: [Edu-sig] Re: [Tutor] what? (late nite entertainment) (*)
In-Reply-To: <4018A3A2.6080103@aon.at>
Message-ID: <E1Am7ss-0004gF-HO@mail.python.org>

> def primes(n):
>     sieve, zeros = range(n), [0]*n
>     sieve[:2]= 0,0
>     i = 1
>     while i*i < n:
>         if sieve[i]: sieve[i*i:n:i]=zeros[i*i:n:i]
>         i += 1
>     return [p for p in sieve if p]
> 
> Regards,
> Gregor

Very nice.

Here's a slight variation:

def primes(n):
    sieve = [1]*n
    sieve[:2]= 0,0
    i = 1
    while i*i < n:
        if sieve[i]:  sieve[i*i:n:i] = len(sieve[i*i:n:i]) * [0]
        i += 1
    return [p for p in range(n) if sieve[p]]

Kirby



From rruvolo at kent.edu  Thu Jan 29 16:42:38 2004
From: rruvolo at kent.edu (rruvolo)
Date: Thu Jan 29 19:39:55 2004
Subject: [Tutor] flip coin
Message-ID: <4021326A@webmail.kent.edu>

I have no idea how to do the flip a coin 100 times problem. Can someone please 
post the right code for it. Thanks


From thomi at thomi.imail.net.nz  Thu Jan 29 19:33:23 2004
From: thomi at thomi.imail.net.nz (Thomas Clive Richards)
Date: Thu Jan 29 19:40:00 2004
Subject: [Tutor] special call for deleted objects?
Message-ID: <200401301333.23303.thomi@thomi.imail.net.nz>


Hi Guys,


I've got a list of class instances, and under certain conditions, I want to 
replace them with None. However, these instances should do some cleanup 
before they dissapear. I *could* create a cleanup method, and call it 
specifically every time I want to delete the instance, and then replace it 
with None, but I thought there might be a special method that automatically 
gets called when an object is deleted.


Am I on the right track? I took a browse through the docs, and couldn't see 
any mention of such a method, but maybe it's hidden away for a reason...

Is following this train of thought more trouble than it's worth? (probably I'm 
guessing)...


Thanks...

-- 

Thomi Richards,
thomi@once.net.nz


From alan.gauld at blueyonder.co.uk  Thu Jan 29 19:41:36 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Thu Jan 29 19:42:22 2004
Subject: [Tutor] Unexpected results with list
References: <.161.88.255.139.1075400414.squirrel@datalong.com>
Message-ID: <009701c3e6c9$d0eeed00$6401a8c0@xp>

OK, Thats better, I can see the structure this time, 
although I still don't see the missing data definitions...

> ### the code
> print '----newKeyRS'
> newKeyRS = []
> for newRecord in newRS:
>         newPk = ''
>         for nKey in newKeys:
>                 newPk = newPk + str(newRecord[nKey]).strip()

This strikes me as strange since you just keep appending to newPk.
You never reset it. Presumably newKeys is a list of numbers?
But then every time through the newRecord loop you get the same 
newPk value since you never change newKeys?

>         newKeyRS.append((newPk, newRecord))

But from the output below you are patently getting different 
newPk values... hmm.

>         if newPk[:5]=='15000': print (newPk, newRecord)

And since the original record is the second element we must 
assume that the nKey loop extracts the GroupCode value from 
the dictionary by treating the dictionary as a string? 
But how does it prepend the 1 that we see in the newPk 
values?

I think I'm missing something somewhere?

> print '        ----'
> for newRecord in newKeyRS:
>         if newRecord[0][:5]=='15000': print newRecord


> 
> ### the results
> ----newKeyRS
> ('150002', {'GroupCode': 50002, 'LanguageId': 1})
> ('150003', {'GroupCode': 50003, 'LanguageId': 1})
...
>         ----
> ('150002', {'GroupCode': 50002, 'LanguageId': 1})
> ('150004', {'GroupCode': 50004, 'LanguageId': 1})

Confused,

Alan G

From alan.gauld at blueyonder.co.uk  Thu Jan 29 19:45:09 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Thu Jan 29 19:44:42 2004
Subject: [Tutor] vb6.0
References: <BAY8-DAV66XAPtJoXOy0001135e@hotmail.com>
Message-ID: <009f01c3e6ca$4ff78670$6401a8c0@xp>


>   I guess I am not the "sharpest pencil in the drawer", 
> cause I spent $1000.00 for a on line course for vb6.0 

Ouch!
Well at least there are plenty Python courses for free! :-)

> Now, am I just not made to program?  Or do you think I 
> could enhance my programming by studying Python. 

You need to study programming. Once you get it in one 
language the rest are easy. Pick one of the tutorials on 
the Python web site, maybe even the official one since 
you've done some VB.

Alternatively you could try mine as a fast conceptual 
refresher which includes comparisons with QBASIC which 
is a little like V.Basic

Give it a go, ask questions here when you get stuck.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


From shaleh at speakeasy.net  Thu Jan 29 19:49:10 2004
From: shaleh at speakeasy.net (Sean 'Shaleh' Perry)
Date: Thu Jan 29 19:49:25 2004
Subject: [Tutor] flip coin
In-Reply-To: <4021326A@webmail.kent.edu>
References: <4021326A@webmail.kent.edu>
Message-ID: <200401291649.10183.shaleh@speakeasy.net>

On Thursday 29 January 2004 13:42, rruvolo wrote:
> I have no idea how to do the flip a coin 100 times problem. Can someone
> please post the right code for it. Thanks
>

you probably won't get much in the way of a direct response to this type of 
request.  This list tries to help and prod people onto the right path, not 
ski lift them to the top.

So, let's start over.  Which part of this confuses you?  The do it 100 times 
part?  The flip a coin part?  What have you tried?


From abeidson at sbcglobal.net  Thu Jan 29 19:47:48 2004
From: abeidson at sbcglobal.net (Andrew Eidson)
Date: Thu Jan 29 19:51:34 2004
Subject: [Tutor] Re-inventing the wheel
Message-ID: <1075423668.21695.9.camel@localhost.localdomain>

Before I go and try to re-invent the wheel here.. I am in the process of
creating an application for k-12 schools to keep track of student fees..
it will need to access DB4, MS SQL, Oracle, and DB2 style databases. It
is actually going to link into a specific proprietary school database
system. If anyone knows of something like this I would appreciate
knowing..  Especially since this is why I am actually learning Python.. 

Thanks
Andy


From abeidson at sbcglobal.net  Thu Jan 29 19:47:58 2004
From: abeidson at sbcglobal.net (Andrew Eidson)
Date: Thu Jan 29 19:51:45 2004
Subject: [Tutor] vb6.0
In-Reply-To: <BAY8-DAV66XAPtJoXOy0001135e@hotmail.com>
References: <BAY8-DAV66XAPtJoXOy0001135e@hotmail.com>
Message-ID: <1075423678.21695.11.camel@localhost.localdomain>

Being new to Programming in general I can understand.. I just recently
picked up a book that is not in the list.. but has helped me
tremendously  Python Programming for the Absolute Beginner ISBN
1592000738 

the premise behind the Absolute Beginner series is to teach not only a
language but basic programming fundamentals in a way everyone likes to
learn by programming games.. I found it on Amazon. 


On Thu, 2004-01-29 at 15:38, big steve wrote:
>   I guess I am not the "sharpest pencil in the drawer", cause I spent
> $1000.00 for a on line course for vb6.0 and I am not a programmer
> yet!  I did learn a lot about all the tools but if I had to write
> anything more than "Hello, World" I would be in trouble. 
>        Well that is a little extreme, but I sure did not get all I
> thought I would out of this course. Now, am I just not made to
> program?  Or do you think I could enhance my programming by studying
> Python. I do have the will. I think my biggest problem is I have no
> Idea of what I want to program.  I have downloaded the latest Python
> so I am ready!  I guess I am asking for words of encouragement, got
> any?  
> Thanks  Steve Hulett
> 
> ______________________________________________________________________
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor


From mlong at datalong.com  Thu Jan 29 20:03:49 2004
From: mlong at datalong.com (Michael Long)
Date: Thu Jan 29 20:03:59 2004
Subject: [Tutor] Re: Unexpected results with list
Message-ID: <.161.88.255.139.1075424629.squirrel@datalong.com>

>>for newRecord in newRS:
>>         newPk = ''
>>         for nKey in newKeys:
>>                 newPk = newPk + str(newRecord[nKey]).strip()
>>         newKeyRS.append((newPk, newRecord))
>>         if newPk[:5]=='15000': print (newPk, newRecord)
>
>
> I think I might write this as newPk.startswith('15000')

That syntax is much more intuitive.

>
> It would be very helpful to have a full working example to
> play with...
>
The entire piece involves connecting to 2 diffent databases and retrieving
recordsets which are to be compared. This statement "if newPk[:5]=='15000'" is
present to filter the resultset printed for debugging purposes.

I have found the offending code but do not understand what is going on. When you
run the following snippet it only print '150003' and '150005'. I would be grateful
for an explaination of this behavior.

newKeyRS = ['150003', '150004', '150005', '150006', '15007', '15008']

for newRecord in newKeyRS:
        if newRecord.startswith('15000'): print newRecord
        newKeyRS.remove(newRecord)

From darnold02 at sprynet.com  Thu Jan 29 21:35:59 2004
From: darnold02 at sprynet.com (don arnold)
Date: Thu Jan 29 21:36:08 2004
Subject: [Tutor] Re: Unexpected results with list
References: <.161.88.255.139.1075424629.squirrel@datalong.com>
Message-ID: <078201c3e6d9$cc75f4c0$5610ba3f@don2uvsu54fwiq>


----- Original Message -----
From: "Michael Long" <mlong@datalong.com>
To: <Tutor@Python.Org>
Sent: Thursday, January 29, 2004 7:03 PM
Subject: Re: [Tutor] Re: Unexpected results with list


<snip>
>
> I have found the offending code but do not understand what is going on.
When you
> run the following snippet it only print '150003' and '150005'. I would be
grateful
> for an explaination of this behavior.
>
> newKeyRS = ['150003', '150004', '150005', '150006', '15007', '15008']
>
> for newRecord in newKeyRS:
>         if newRecord.startswith('15000'): print newRecord
>         newKeyRS.remove(newRecord)

The problem here is that you're modifying the list as you iterate over it.
That's a no-no. Iterate over a copy of the list, instead (created here
through slicing):

newKeyRS = ['150003', '150004', '150005', '150006', '15007', '15008']

for newRecord in newKeyRS[:]:     ## using slicing to create a shallow copy
of the list
        if newRecord.startswith('15000'): print newRecord
        newKeyRS.remove(newRecord)
>>>
150003
150004
150005
150006

HTH,
Don


From mlong at datalong.com  Thu Jan 29 22:29:46 2004
From: mlong at datalong.com (Michael Long)
Date: Thu Jan 29 22:29:56 2004
Subject: [Tutor] Re: Unexpected results with list
In-Reply-To: <078201c3e6d9$cc75f4c0$5610ba3f@don2uvsu54fwiq>
References: <.161.88.255.139.1075424629.squirrel@datalong.com> 
	<078201c3e6d9$cc75f4c0$5610ba3f@don2uvsu54fwiq>
Message-ID: <.161.88.255.139.1075433386.squirrel@datalong.com>

>> I have found the offending code but do not understand what is going on.
> When you
>> run the following snippet it only print '150003' and '150005'. I would be
> grateful
>> for an explaination of this behavior.
>>
>> newKeyRS = ['150003', '150004', '150005', '150006', '15007', '15008']
>>
>> for newRecord in newKeyRS:
>>         if newRecord.startswith('15000'): print newRecord
>>         newKeyRS.remove(newRecord)
>
> The problem here is that you're modifying the list as you iterate over it.
> That's a no-no. Iterate over a copy of the list, instead (created here
> through slicing):
>
> newKeyRS = ['150003', '150004', '150005', '150006', '15007', '15008']
>
> for newRecord in newKeyRS[:]:     ## using slicing to create a shallow copy
> of the list
>         if newRecord.startswith('15000'): print newRecord
>         newKeyRS.remove(newRecord)
>>>>
> 150003
> 150004
> 150005
> 150006

This explains a lot of my frustration. Next time I will try to boil my question
down before posting it to the list. I realized after sending the first posting that
it really didn't make sense to anyone who had not been staring at my screen for a
number of hours. Actually it was Alan's reply that made the ambiquity of the
question clear :)

Cheers,
Mike


From stella at solarenergenex.com  Fri Jan 30 01:08:36 2004
From: stella at solarenergenex.com (Stella Rockford)
Date: Fri Jan 30 01:08:28 2004
Subject: [Tutor] splice a string object based on embedded html tag...
Message-ID: <BDB98766-52EA-11D8-8665-003065C79E7A@solarenergenex.com>

I am parsing some html apart with sgmllib
the end result is to feed an RSS with info scraped with pycurl
and whatever...

when I run sgmllib.py on the html file object
I am returned an extremely long list of "pieces"

this is good, however,

there is a lot of data I have no use for and it slows the parser down
I have studied the HTML code and found that the info I need
is, naturally, nested in a table with a unique id for CSS

I am assuming that removing everything but this table
before it gets parsed will allow sgmllib to function faster...

I would like to SPLICE everything before and after this table off of 
the file object
this would be the first operation on the object,  but when I looked up 
string's methods
I couldn't quite find what i am looking for to do this.

  indexing and splicing of a string seems only responds to integers

Any advice would be well received

thanks in advance,

Stella


From carroll at tjc.com  Fri Jan 30 01:15:21 2004
From: carroll at tjc.com (Terry Carroll)
Date: Fri Jan 30 01:15:27 2004
Subject: [Tutor] special call for deleted objects?
In-Reply-To: <200401301333.23303.thomi@thomi.imail.net.nz>
Message-ID: <Pine.LNX.4.44.0401292211460.12657-100000@violet.rahul.net>

On Fri, 30 Jan 2004, Thomas Clive Richards wrote:

> replace them with None. However, these instances should do some cleanup 
> before they dissapear. I *could* create a cleanup method, and call it 
> specifically every time I want to delete the instance, and then replace it 
> with None, but I thought there might be a special method that automatically 
> gets called when an object is deleted.

That's __del__, but I don't think you have much control over when the
object gets deleted.  When you del an object, its reference count gets
decremented, and when it hits zero, it's eligible to be deleted by garbage
collection, whenever garbage collection occurs.  *That's* when __del__ 
will get called on that object.

In fact "It is not guaranteed that __del__() methods are called for 
objects that still exist when the interpreter exits."

If you want a specific cleanup to be coded, I'd make it explicit.
  


From alan.gauld at blueyonder.co.uk  Fri Jan 30 03:25:42 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Fri Jan 30 03:25:10 2004
Subject: [Tutor] Converting string or list to sum
References: <200401291914.23909.python@cairnlin.co.uk><20040129144718.177ba6af.orbitz@ezabel.com><200401292021.38242.iain@cairnlin.co.uk>
	<200401292047.03492.python@cairnlin.co.uk>
Message-ID: <00bc01c3e70a$a69f41d0$6401a8c0@xp>

>  I think I can put two ideas together to solve it for lists :
>  >>> a=[2, 3, '+', 4]
>  >>> d=""
>  >>> for item in range(len(a)):
>  ...     d=d+str(a[item])
>  ...

Or even easier:

for item in a: 
    d = d + str(item)

No need for indexing etc,

Alan G.

From alan.gauld at blueyonder.co.uk  Fri Jan 30 03:31:00 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Fri Jan 30 03:30:27 2004
Subject: [Tutor] special call for deleted objects?
References: <200401301333.23303.thomi@thomi.imail.net.nz>
Message-ID: <00f201c3e70b$63fa7240$6401a8c0@xp>

> I've got a list of class instances, and under certain conditions, I
want to
> replace them with None. However, these instances should do some
cleanup
> before they dissapear.

I seem to recall there is a __del__ method you can add to your class.

It doesn't get called until the class is actually garbage collected
however so the behaviour is a little unpredictable.

Alan G.


From alan.gauld at blueyonder.co.uk  Fri Jan 30 03:33:38 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Fri Jan 30 03:33:05 2004
Subject: [Tutor] flip coin
References: <4021326A@webmail.kent.edu>
Message-ID: <00f901c3e70b$c2349bb0$6401a8c0@xp>


> I have no idea how to do the flip a coin 100 times problem. Can
someone please
> post the right code for it. Thanks

Why don't you tell us what the poblem is first?
Then tell us how you think you wouyld approach it,
maybe showing us some code that doesn't work.
Then we can help you make it work :-)

If you are completely stuck think how you would
do it mentally, maybe using pencil and paper.

Programming is about breaking a problem into
smaller and smaller steps.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


From alan.gauld at blueyonder.co.uk  Fri Jan 30 03:38:32 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Fri Jan 30 03:38:00 2004
Subject: [Tutor] Re-inventing the wheel
References: <1075423668.21695.9.camel@localhost.localdomain>
Message-ID: <010401c3e70c$71a13540$6401a8c0@xp>


> Before I go and try to re-invent the wheel here.. I am in the
process of
> creating an application for k-12 schools to keep track of student
fees..
> it will need to access DB4, MS SQL, Oracle, and DB2 style databases.

Take a look at the Database special interest area on python.org.
I suspect you will need the ODBC drivers to talk to DB4 (which
I assume is actually DBaseIV?) and I think there are specific
drivers for the others. THe module will hide most of that diversity
from you.

Do you know SQL? That is going to be pretty essential.

> system. If anyone knows of something like this I would appreciate
> knowing..  Especially since this is why I am actually learning
Python..

Sorry, without knowing what you are trying to do its hard to say,
but I'd guess its unlikely given the variety of dsata sources.
Potentially quite a challenging project.

Alan G.


From alan.gauld at blueyonder.co.uk  Fri Jan 30 03:50:41 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Fri Jan 30 03:50:17 2004
Subject: [Tutor] Re: Unexpected results with list
References: <.161.88.255.139.1075424629.squirrel@datalong.com>
Message-ID: <010b01c3e70e$23fac020$6401a8c0@xp>

> newKeyRS = ['150003', '150004', '150005', '150006', '15007',
'15008']
>
> for newRecord in newKeyRS:
>         if newRecord.startswith('15000'): print newRecord
>         newKeyRS.remove(newRecord)

When you remove an item everything shuffles up, in effect.
Thus when the for loop pulls out the next item it effectively
misses one out!

BUT You are deleting every record! I assume you really only
want to remove the ones you filter?  ie the remove should be
inside the loop?

For this kind of thing you could use a while
loop with index:

index = 0
while index < len(newKeyRS):
         if newRecord.startswith('15000'): print newRecord
             newKeyRS.remove(newRecord)  # don't incr index
         else: index += 1

Or better still use the filter function to remove the unwanted
ones:

newKeyRS = filter(lambda x: not x.startswith('15000'), newKeyRS)

Or if you prefer, a list comprehension:

newKeyRS = [ item for item in newKeyRS if not
item.startswith('15000')]

Personally I'd use filter for this because its more self
explanatory, but if its a big list a comprehensuon will
probably be faster.

Alan G.






From dyoo at hkn.eecs.berkeley.edu  Fri Jan 30 05:29:55 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri Jan 30 05:30:23 2004
Subject: [Tutor] Converting string or list to sum
In-Reply-To: <00bc01c3e70a$a69f41d0$6401a8c0@xp>
Message-ID: <Pine.LNX.4.44.0401300227260.27785-100000@hkn.eecs.berkeley.edu>



On Fri, 30 Jan 2004, Alan Gauld wrote:

> >  I think I can put two ideas together to solve it for lists :
> >  >>> a=[2, 3, '+', 4]
> >  >>> d=""
> >  >>> for item in range(len(a)):
> >  ...     d=d+str(a[item])
> >  ...
>
> Or even easier:
>
> for item in a:
>     d = d + str(item)
>
> No need for indexing etc,


By the way, strings also support an explicit 'join()' method that can take
a list as an argument:

    http://www.python.org/doc/lib/string-methods.html#l2h-188

So there's actually no need for the loop either.  *grin*


Talk to you later!


From Janssen at rz.uni-frankfurt.de  Fri Jan 30 05:56:15 2004
From: Janssen at rz.uni-frankfurt.de (Michael Janssen)
Date: Fri Jan 30 05:56:27 2004
Subject: [Tutor] parsing email
In-Reply-To: <m3fzdylp6g.fsf@hamster.pflaesterer.de>
References: <4017D3F8.8030504@cso.atmel.com>
	<Pine.A41.4.56.0401281732530.47532@hermes-22.rz.uni-frankfurt.de>
	<4017EF76.3040004@cso.atmel.com>
	<Pine.A41.4.56.0401291223050.204744@hermes-22.rz.uni-frankfurt.de>
	<m3fzdylp6g.fsf@hamster.pflaesterer.de>
Message-ID: <Pine.A41.4.56.0401301107500.204746@hermes-22.rz.uni-frankfurt.de>

On Thu, 29 Jan 2004, Karl Pfl?sterer wrote:

> On 29 Jan 2004, Michael Janssen <- Janssen@rz.uni-frankfurt.de wrote:
>
> > when each eMail is on a single file - why not just run a virus scanner
> > about them? The virus scanner can savely delete all virus mails.
>
> A virus scanner can easily be broken by unfriendly senders; e.g. if you
> send an e-mail with a zip attachment the scanner has to unpack the
> attachment.  If you zipped a bigggggg file (some GB) of only zeros you
> have a small and nice zip file which if unzipped stops your machine (to
> make it perfekt you need a hex editor to change the header of the zip
> file so the real size can't be seen).  Or use bzip2.  Google for 42.zip.
> Furthermore a virus scanner has to know the pattern of the virus.  So a
> virus scanner gives you a false feeling of security.  And you might not
> only want to search for virus files but for every sort of UCE or UBE.

still it works for us and we are scanning 100t mail per day :-) And
seems much less worse than deleting mails by Subjects like "hello" as
used by MyDoom.

It's a pitty but both OpenSource project out there to scan mail on
server (MailScanner and amavis-new) are perl code. Would be nice to have
a python solution in the race, but it would be also a lot of work
(MailScanner has 25t lines of code and years of experience).

Simply blocking executeable Attachments could be a way to do it with
python and a reasonable amount of affort. You probably can't stop all
virus (since you can't block .doc or .zip entirely) but you can stop
many of them. You would need some kind of a ruleset with allow and deny
rules, first allowing all attachments that are Ok or can't be blocked
without angry users. Then denying executables and other nasty things
(the hard thing is to determine the complete list of nasty
filenname-extensions for Windows). Perhaps special rules with complete
filenames, when it's known that a new virus uses them.

Scanning for attachment names is a lot better then scanning Subjects,
because you wont delete legitimate mails, that doesn't even contain an
attachment (but leaves the door open for threatening html and script
code).

You probably want to delete only the attachments instead of the whole
mail and put a message in it (which should be easily done with
email.Parser and email.Generator).


Beside scanning/ blocking attachments a facility to block known virus
subjects/ bodies/ headers would be fine. But only works *after* the
admin has realized the thread and setup appropiate rules. "Rules" is the
keyword: the application need's to be rule-driffen or it would be an
endless pain to adapt it to the next viruses.

All these would be a nice not-too-big project but the problem occurs how
to do it *before* the user get their hands on the mails, ie *before* the
mails are stored in System-Inbox. On linux you can do it (inefficiently)
with procmail when you've got no better idea. I don't know how to solve
it with NT.


Michael


From dyoo at hkn.eecs.berkeley.edu  Fri Jan 30 05:58:12 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri Jan 30 05:58:18 2004
Subject: [Tutor] splice a string object based on embedded html tag...
In-Reply-To: <BDB98766-52EA-11D8-8665-003065C79E7A@solarenergenex.com>
Message-ID: <Pine.LNX.4.44.0401300232580.27785-100000@hkn.eecs.berkeley.edu>



On Fri, 30 Jan 2004, Stella Rockford wrote:

> I am parsing some html apart with sgmllib the end result is to feed an
> RSS with info scraped with pycurl and whatever...
>
> when I run sgmllib.py on the html file object I am returned an extremely
> long list of "pieces"
>
> this is good, however,
>
> there is a lot of data I have no use for and it slows the parser down


Hi Stella,

Before trying to optimize things further: have you already looked into
PyXML?

    http://pyxml.sourceforge.net/

According to the web site, the PyXML project includes a module called
'sgmlop' that accelerates sgmllib by about a factor of 5.  Installing
pyxml adds a module called 'xml.parsers.sgmllib', and it should ideally be
a drop-in for the one in the Standard Library.

So before going further, try seeing if using that enhanced version of
sgmllib will fix your performance problems.  Once you have PyXML
installed, it should just be a matter of replacing the original import:

    import sgmllib

with the replacement from the PyXML project:

    from xml.parsers import sgmllib


Give it a whirl and tell us if it helps.  Also, how are you using sgmllib?
Are you keeping an intermediate list of chunks, or keeping state as you
scan across the file?  Computers are pretty darn fast today, and I can't
imagine parsing HTML being that slow, unless the file is tremendous.
*grin*



> I would like to SPLICE everything before and after this table off of the
> file object this would be the first operation on the object, but when I
> looked up string's methods I couldn't quite find what i am looking for
> to do this.

String splicing should be functional, though I'm not sure if it will apply
easily to your problem.  If you want to do string splicing, you'll need to
find the index positions where the target table begins and ends.


Strings support a 'find()' method that, given a string to search for,
tries to find the right position:

###
>>> s = "hello world"
>>> s.find('world')
6
>>> s.find('not here')
-1
###

Note that when find() can't find, it returns -1.

So you may be able to localize the table with some string searching.
More sophisticated string searching may involve something like the
"regular expression" library:

    http://www.amk.ca/python/howto/regex/

and if you are fairly sure what the table looks like, perhaps you can use
regexes to yank it out.


Anyway, I hope this helps.  Good luck to you!


From abli at freemail.hu  Fri Jan 30 07:46:06 2004
From: abli at freemail.hu (Abel Daniel)
Date: Fri Jan 30 07:46:10 2004
Subject: [Tutor] Re: special call for deleted objects?
In-Reply-To: <200401301333.23303.thomi@thomi.imail.net.nz> (Thomas Clive
	Richards's message of "Fri, 30 Jan 2004 13:33:23 +1300")
References: <200401301333.23303.thomi@thomi.imail.net.nz>
Message-ID: <E1AmY2A-0000TA-00@hooloovoo>

Thomas Clive Richards writes:
> I've got a list of class instances, and under certain conditions, I want to 
> replace them with None.

How are you going to replace them?
>>> a=5
>>> b=a
>>> a=6
>>> b
5

Assigning to a didn't change b.

-- 
Abel Daniel

From abeidson at sbcglobal.net  Fri Jan 30 07:43:19 2004
From: abeidson at sbcglobal.net (Andrew Eidson)
Date: Fri Jan 30 07:47:18 2004
Subject: [Tutor] Re-inventing the wheel
In-Reply-To: <010401c3e70c$71a13540$6401a8c0@xp>
References: <1075423668.21695.9.camel@localhost.localdomain>
	<010401c3e70c$71a13540$6401a8c0@xp>
Message-ID: <1075466599.22577.3.camel@localhost.localdomain>

Thanks.. I have been looking over the ODBC information and yes I do know
SQL (probably not as well as I will after this project). I 'm sure you
will hear about my progress seeing this is the first thing I will
actually program on my own in any language.. just wanted to make sure
that there was not something similar out there.. though if there is some
sort of financial package written in Python that may provide a good
frame of reference.. I may start looking that way to see what I find. 


From abli at freemail.hu  Fri Jan 30 07:56:01 2004
From: abli at freemail.hu (Abel Daniel)
Date: Fri Jan 30 07:56:05 2004
Subject: [Tutor] Re: When was interned strings dropped (and why)?
In-Reply-To: <20040127202947.91777.qmail@web41807.mail.yahoo.com> (Daniel
	Ehrenberg's message of "Tue, 27 Jan 2004 12:29:46 -0800 (PST)")
References: <20040127202947.91777.qmail@web41807.mail.yahoo.com>
Message-ID: <E1AmYBl-0000U1-00@hooloovoo>

Daniel Ehrenberg writes:

> Switch to 2.3. That's what I'm using and I don't have
> that bug. Even identical tuples have the same id.

Are you sure?

Python 2.3.3 (#2, Dec 19 2003, 11:28:07) 
[GCC 3.3.3 20031203 (prerelease) (Debian)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> t=(1,2)
>>> tt=(1,2)
>>> t is tt
False
>>> t == tt
True
>>> id(t)
1075955500
>>> id(tt)
1075798540
>>> ttt=t
>>> id(ttt)
1075955500
>>> 

Of course, if you define 'identical' as 'having the same id' then 'identical
tuples have the same id', but you won't really be able to use this fact.

-- 
Abel Daniel

From michel.belanger at seidel.ca  Fri Jan 30 09:50:16 2004
From: michel.belanger at seidel.ca (=?ISO-8859-1?Q?Michel_B=E9langer?=)
Date: Fri Jan 30 09:50:29 2004
Subject: [Tutor] How to close a file opened with csv.write
Message-ID: <401A6F27.5050302@seidel.ca>

Hi,

how do I close a file that has been opened by csv.writer (with the 
command below)? or how do you released the file from IDLE because it 
cannot be deleted or moved until IDLE gets closed.

fileout = csv.writer(file("contact_mod1.csv", "w"))

Regards
Michel Belanger


From gerrit at nl.linux.org  Fri Jan 30 11:38:43 2004
From: gerrit at nl.linux.org (Gerrit Holl)
Date: Fri Jan 30 11:41:45 2004
Subject: [Tutor] How to close a file opened with csv.write
In-Reply-To: <401A6F27.5050302@seidel.ca>
References: <401A6F27.5050302@seidel.ca>
Message-ID: <20040130163843.GA5009@nl.linux.org>

Michel B=E9langer wrote:
> how do I close a file that has been opened by csv.writer (with the=20
> command below)? or how do you released the file from IDLE because it=20
> cannot be deleted or moved until IDLE gets closed.
>=20
> fileout =3D csv.writer(file("contact_mod1.csv", "w"))

Instead of passing the file constructor like this, store it locally
first: fp =3D file("foo", "w") and then csv.writer(fp). You can then
simply fp.close() it.

Gerrit.

--=20
231. If it kill a slave of the owner, then he shall pay slave for slave
to the owner of the house.
          -- 1780 BC, Hammurabi, Code of Law
--=20
PrePEP: Builtin path type
    http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html
Asperger's Syndrome - a personal approach:
	http://people.nl.linux.org/~gerrit/english/

From littledanehren at yahoo.com  Fri Jan 30 12:13:31 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Fri Jan 30 12:13:36 2004
Subject: [Tutor] Converting string or list to sum
In-Reply-To: <00bc01c3e70a$a69f41d0$6401a8c0@xp>
Message-ID: <20040130171331.52763.qmail@web41803.mail.yahoo.com>


--- Alan Gauld <alan.gauld@blueyonder.co.uk> wrote:
> >  I think I can put two ideas together to solve it
> for lists :
> >  >>> a=[2, 3, '+', 4]
> >  >>> d=""
> >  >>> for item in range(len(a)):
> >  ...     d=d+str(a[item])
> >  ...
> 
> Or even easier:
> 
> for item in a: 
>     d = d + str(item)
> 
> No need for indexing etc,
> 
> Alan G.

In that case, is there any reason not to just do

for item in a:
    d += str(item)

__________________________________
Do you Yahoo!?
Yahoo! SiteBuilder - Free web site building tool. Try it!
http://webhosting.yahoo.com/ps/sb/

From kalle at lysator.liu.se  Fri Jan 30 12:36:32 2004
From: kalle at lysator.liu.se (Kalle Svensson)
Date: Fri Jan 30 12:36:38 2004
Subject: [Tutor] Converting string or list to sum
In-Reply-To: <20040130171331.52763.qmail@web41803.mail.yahoo.com>
References: <00bc01c3e70a$a69f41d0$6401a8c0@xp>
	<20040130171331.52763.qmail@web41803.mail.yahoo.com>
Message-ID: <20040130173632.GB4889@i92.ryd.student.liu.se>

[Daniel Ehrenberg]
> 
> > >  I think I can put two ideas together to solve it
> > for lists :
> > >  >>> a=[2, 3, '+', 4]
> > >  >>> d=""
> > >  >>> for item in range(len(a)):
> > >  ...     d=d+str(a[item])
> > >  ...
> > 
> > Or even easier:
> > 
> > for item in a: 
> >     d = d + str(item)
> > 
> > No need for indexing etc,
> > 
> > Alan G.
> 
> In that case, is there any reason not to just do
> 
> for item in a:
>     d += str(item)

I'd write

  d = ''.join(map(str, a))

since that's probably much faster for large lists.

Peace,
  Kalle
-- 
Kalle Svensson, http://www.juckapan.org/~kalle/
Student, root and saint in the Church of Emacs.

From isrgish at fusemail.com  Fri Jan 30 14:35:43 2004
From: isrgish at fusemail.com (Isr Gish)
Date: Fri Jan 30 14:35:45 2004
Subject: [Tutor] splice a string object based on embedded html tag...
Message-ID: <E1AmeQO-0002N0-03@fuse1.fusemail.net>

Stella Rockford wrote:

    >there is a lot of data I have no use for and it slows the parser down
   >I have studied the HTML code and found that the info I need
   >is, naturally, nested in a table with a unique id for CSS
   >
   >I am assuming that removing everything but this table
   >before it gets parsed will allow sgmllib to function faster...
   >
   >I would like to SPLICE everything before and after this table off of 
   >the file object
   >this would be the first operation on the object,  but when I looked up 
   >string's methods
   >I couldn't quite find what i am looking for to do this.
   >
   >  indexing and splicing of a string seems only responds to integers

I don't know HTML, bt to search for the ID you would do something like this.
>>> import string
>>> ID = '<1234>' #sub string to look for in big string
>>> str = 'This is first part of string. <1234> This is after the ID.'
>>> indx = string.find(str, ID) # this finds the index in the string of the firs acurrance of ID
>>> newstr = str[indx:] # this gives you the slice from after the indx
>>> print newstr
<1234> This is after the ID.

If you want it without the ID then add to indx the length of ID like this
>>> newindx = indx + len(ID)

Good luck
Isr


From thomi at imail.net.nz  Fri Jan 30 17:24:22 2004
From: thomi at imail.net.nz (Thomas Clive Richards)
Date: Fri Jan 30 17:24:31 2004
Subject: [Tutor] Re: special call for deleted objects?
In-Reply-To: <E1AmY2A-0000TA-00@hooloovoo>
References: <200401301333.23303.thomi@thomi.imail.net.nz>
	<E1AmY2A-0000TA-00@hooloovoo>
Message-ID: <200401311124.22795.thomi@imail.net.nz>

On Saturday 31 January 2004 01:46, Abel Daniel wrote:
>
> How are you going to replace them?
>
> >>> a=5
> >>> b=a
> >>> a=6
> >>> b
>
> 5
>
> Assigning to a didn't change b.


well.. sort of like this:

a = []
for i in range(50):
	a.append(SomeClass())

a[5] = None		#<---right here...


But it's OK now, I'm calling my own cleanup method right before I insert a 
none into the list...


THanks all the same ;)


-- 

Thomi Richards,
thomi@once.net.nz


From isrgish at fusemail.com  Fri Jan 30 17:26:22 2004
From: isrgish at fusemail.com (Isr Gish)
Date: Fri Jan 30 17:26:23 2004
Subject: =?utf-8?Q?Re:_=5BTutor=5D_Converting_string_or?=
	=?utf-8?Q?_list_to_sum?=
Message-ID: <E1Amh5U-0002Rt-Fm@fuse1.fusemail.net>



Kalle Svensson Wrote:
     >[Daniel Ehrenberg]
   >> 
   >> > >  I think I can put two ideas together to solve it
   >> > for lists :
   >> > >  >>> a=[2, 3, '+', 4]
   >> > >  >>> d=""
   >> > >  >>> for item in range(len(a)):
   >> > >  ...     d=d+str(a[item])
   >> > >  ...
   >> > 
   >> > Or even easier:
   >> > 
   >> > for item in a: 
   >> >     d = d + str(item)
   >> > 
   >> > No need for indexing etc,
   >> > 
   >> > Alan G.
   >> 
   >> In that case, is there any reason not to just do
   >> 
   >> for item in a:
   >>     d += str(item)
   >
   >I'd write
   >
   >  d = ''.join(map(str, a))
   >
   >since that's probably much faster for large lists.
   >
 
I think that should be:
import __builtin__
d = ''.join(map(__builtin__.str, a))

Good luck
Isr


From isrgish at fusemail.com  Fri Jan 30 17:26:25 2004
From: isrgish at fusemail.com (Isr Gish)
Date: Fri Jan 30 17:26:32 2004
Subject: [Tutor] Re: When was interned strings dropped (and why)?
Message-ID: <E1Amh5X-0002Rt-W4@fuse1.fusemail.net>

I find that only int's and string's have the same id when they are identical.
But list's, tuple's and dictionary's have different id's even if theybare identical.

P.s I'm using Python 2.3.2


-----Original Message-----
   >From: "Abel Daniel"<abli@freemail.hu>
   >Sent: 1/30/04 7:56:01 AM
   >To: "Daniel Ehrenberg"<littledanehren@yahoo.com>
   >Cc: "pytutor"<tutor@python.org>
   >Subject: [Tutor] Re: When was interned strings dropped (and why)?
     >Daniel Ehrenberg writes:
   >
   >> Switch to 2.3. That's what I'm using and I don't have
   >> that bug. Even identical tuples have the same id.
   >
   >Are you sure?
   >
   >Python 2.3.3 (#2, Dec 19 2003, 11:28:07) 
   >[GCC 3.3.3 20031203 (prerelease) (Debian)] on linux2
   >Type "help", "copyright", "credits" or "license" for more information.
   >>>> t=(1,2)
   >>>> tt=(1,2)
   >>>> t is tt
   >False
   >>>> t == tt
   >True
   >>>> id(t)
   >1075955500
   >>>> id(tt)
   >1075798540
   >>>> ttt=t
   >>>> id(ttt)
   >1075955500
   >>>> 
   >
   >Of course, if you define 'identical' as 'having the same id' then 'identical
   >tuples have the same id', but you won't really be able to use this fact.
   >
   >-- 
   >Abel Daniel
   >
   
Good luck
Isr


From kalle at lysator.liu.se  Fri Jan 30 17:30:15 2004
From: kalle at lysator.liu.se (Kalle Svensson)
Date: Fri Jan 30 17:30:37 2004
Subject: [Tutor] Converting string or list to sum
In-Reply-To: <E1Amh5U-0002Rt-Fm@fuse1.fusemail.net>
References: <E1Amh5U-0002Rt-Fm@fuse1.fusemail.net>
Message-ID: <20040130223015.GA9280@i92.ryd.student.liu.se>

[Isr Gish]
> Kalle Svensson Wrote:
>    >I'd write
>    >
>    >  d = ''.join(map(str, a))
>    >
>    >since that's probably much faster for large lists.
>  
> I think that should be:
> import __builtin__
> d = ''.join(map(__builtin__.str, a))

Why?

(There's no need to CC me on replies, I read the list.)

Peace,
  Kalle
-- 
Kalle Svensson, http://www.juckapan.org/~kalle/
Student, root and saint in the Church of Emacs.

From hcohen2 at comcast.net  Fri Jan 30 18:55:27 2004
From: hcohen2 at comcast.net (hcohen2)
Date: Fri Jan 30 18:58:03 2004
Subject: [Tutor] Re: When was interned strings dropped (and why)?
In-Reply-To: <E1Amh5X-0002Rt-W4@fuse1.fusemail.net>
References: <E1Amh5X-0002Rt-W4@fuse1.fusemail.net>
Message-ID: <401AEEEF.8050203@comcast.net>

Isr Gish wrote:

>I find that only int's and string's have the same id when they are identical.
>But list's, tuple's and dictionary's have different id's even if theybare identical.
>
>P.s I'm using Python 2.3.2
>
>
>-----Original Message-----
>   >From: "Abel Daniel"<abli@freemail.hu>
>   >Sent: 1/30/04 7:56:01 AM
>   >To: "Daniel Ehrenberg"<littledanehren@yahoo.com>
>   >Cc: "pytutor"<tutor@python.org>
>   >Subject: [Tutor] Re: When was interned strings dropped (and why)?
>     >Daniel Ehrenberg writes:
>   >
>   >> Switch to 2.3. That's what I'm using and I don't have
>   >> that bug. Even identical tuples have the same id.
>   >
>   >Are you sure?
>   >
>   >Python 2.3.3 (#2, Dec 19 2003, 11:28:07) 
>   >[GCC 3.3.3 20031203 (prerelease) (Debian)] on linux2
>   >Type "help", "copyright", "credits" or "license" for more information.
>   >>>> t=(1,2)
>   >>>> tt=(1,2)
>   >>>> t is tt
>   >False
>   >>>> t == tt
>   >True
>   >>>> id(t)
>   >1075955500
>   >>>> id(tt)
>   >1075798540
>   >>>> ttt=t
>   >>>> id(ttt)
>   >1075955500
>   >>>> 
>   >
>   >Of course, if you define 'identical' as 'having the same id' then 'identical
>   >tuples have the same id', but you won't really be able to use this fact.
>   >
>   >-- 
>   >Abel Daniel
>   >
>   
>Good luck
>Isr
>
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>  
>
Isr,

You say it, but on an earlier (buggier?) version it is not quite so clear.

 >>> sL = [12, 'abc', 'ghj']
 >>> aL = sL
 >>> id(sL)
134923940
 >>> id(aL)
134923940
 >>> id([12, 'abc', 'ghj'])
134939756
 >>> aL == sL
1
 >>> aL == [12, 'abc', 'ghj']
1

The lists 'aL' and 'sL' are stored in the exactly the same location,  
There actual value: [12, 'abc', 'ghj'] is found elsewhere.  However, 
both aL and sL are the same as the former though it resides elsewhere.

Try that and see what you get.

Herschel




From dyoo at hkn.eecs.berkeley.edu  Fri Jan 30 20:44:02 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri Jan 30 20:44:08 2004
Subject: [Tutor] Re: When was interned strings dropped (and why)?
In-Reply-To: <E1Amh5X-0002Rt-W4@fuse1.fusemail.net>
Message-ID: <Pine.LNX.4.44.0401301649130.25379-100000@hkn.eecs.berkeley.edu>



On Fri, 30 Jan 2004, Isr Gish wrote:

> I find that only int's and string's have the same id when they are
> identical. But list's, tuple's and dictionary's have different id's even
> if theybare identical.


Hi everyone,


[Warning: somewhat fuzzy discussion about identity/equality/intern
follows.  Ask questions if it gets confusing.]


I think people are getting confused between "identity" and "equality".
"Identity" is a much more strict definition than "equality".  Equality
means that two things look the same when we repr() them out.

In Python, when we talk about "identity" between two objects, we mean that
those two objects live in the same place in memory.


Let's say that we have two strings:

###
>>> s1 = "hello world"
>>> s2 = "hello" + " " + "world"
###


Now it's very true that s1 and s2 look the same, so we'd consider them
"equal":

###
>>> s1
'hello world'
>>> s2
'hello world'
>>> s1 == s2
1
###


Despite this, they live in different locations in our computer's memory.

###
>>> id(s1)
135629440
>>> id(s2)
135629920
###


And because of this, 's1' and 's2' are not "identical", even though they
are "equal".  We can use the 'is' operator to check this strict notion of
'identity'.

###
>>> s1 is s2
0
###


[Note: if you have Java experience, be careful not to get Java and Python
confused.  Python's '==' operation is equivalent to the
java.lang.Object.equals() method, and Python's 'is' operator is equivalent
to Java's '==' operator.  So the concepts are the same, but the syntax
used in the two languages is slightly flipped.  *grin*]



So when is it possible for two things to be 'identical'?  One way is to
make a binding to an existing thing.  For example, we can make another
binding to the thing that s1 is pointed to:

###
>>> s1_rebound = s1
>>> id(s1_rebound)
135629440
###



Let's look at this as a picture with names and arrows:


                       s1_rebound

                           |
                           |
                           V

     s1 -----------> "hello world" (at location #135629440)



     s2 -----------> "hello world" (at location #135629920)



Here, 's1' and 's1_rebound' are directed at the same thing, so they are
both 'equal' and 'identical'.

###
>>> s1_rebound is s1
1
###


(If two things are identical, they have to be equal.  This point is
important a few paragraphs below.)



So that's one way to get two names to point to the same thing.  A
variation on this is to keep a table of existing objects in some
container.  Whenever we're about to make a new thing, we can check our
container, and see if it's already been made before.  What this allows us
to do is to squash any duplicates.


Here's an example that shows the technique:

###
>>> cache = {}
>>> def my_intern(s):
...     if s not in cache:
...         cache[s] = s
...     return cache[s]
...
>>> s1_interned = my_intern(s1)
>>> s2_interned = my_intern(s2)
>>> s1_interned, s2_interned
('hello world', 'hello world')
>>> s1_interned is s2_interned
1
###

This is a homebrewed version of what intern() does for us: it keeps a
global cache of strings that it has already seen, so that we can collapse
duplicate strings away by calling intern() on any string that comes at us.



But why do we care about doing intern() on strings at all?  One strong
reason is because if two strings are identical, that implies that they are
equal.  And comparing two objects for 'identity' is very cheap: we just
look at where the two objects live.

###
>>> id(s1_interned)
135629440
>>> id(s2_interned)
135629440
###

If they are in the same physical space, they have to be equal.  And if
they're not in the same physical space, they might be equal... But if we
guarantee that all strings have passed through intern(), then equality
checking is very cheap.



"Equality" checking, on the other hand, might be expensive.  Think of what
happens if we give Python two strings:

###
>>> "abracadabra" == "abracadabru"
0
###

Of course we know that these strings aren't equal, but how does Python
know this?  If Python sees something like:

    "abracadabra" == "abracadabru"

then what does it need to do to check this?  It might actually need to
do more work than we'd expect, something like:

    ('a' == 'a' and
     'b' == 'b' and
     'r' == 'r' and
     'a' == 'a' and
     'c' == 'c' and
     'a' == 'a' and
     'd' == 'd' and
     'a' == 'a' and
     'b' == 'b' and
     'r' == 'r' and
     'a' == 'u')
###

And that's one reason why people will sometimes embrace all this
complexity of identity vs equality and intern(): for the sake of making
equality comparison fast, to avoid the character-by-character comparisons.



This being said, I've seldom done anything with intern().  *grin* intern()
adds enough complexity to a program that it's often not worth worrying
about it unless we know that we need it.  In the casual case, string
comparison isn't that expensive.

And it's all too easy to mess things up by intern()ing every string we
see: remember that intern() has to keep a container of every unique string
that it has ever seen.  There are a heck of a lot of unique strings out
there.  *grin*



Hope this helps!


From nick at javacat.f2s.com  Fri Jan 30 20:39:41 2004
From: nick at javacat.f2s.com (Nick Lunt)
Date: Fri Jan 30 20:46:52 2004
Subject: [Tutor] Cannot fix OSError
Message-ID: <20040131013941.590a3503@phatbox.local>

Hi Folks,

this is my first posting to the list, although I have been snooping for
a couple of weeks ;)

I've recently started to learn Python and so far I'm having great fun.

Anyway, here's my problem, first off here's the program:

# code
import tarfile, sys, os

if len(sys.argv) <= 2:
        print 'Error:', sys.argv[0], ' <tarfile.tar> <list of files>
        sys.exit(1)

tfile = sys.argv[1]

totar = []
for f in sys.argv[2:]:
        if os.access(f, os.R_OK): # NOTE1
                totar.append(f)
        else:
                print 'Could not access', f, 'to tar'


tf = tarfile.TarFile(tfile, 'w')
for f in totar:
        tf.add(f)

tf.close

# end code

This works fine until it encounters a file that I am not allowed to access, in which case it gives me this error:

# error
Traceback (most recent call last):
  File "./tar.py", line 31, in ?
    tf.add(f)
  File "/usr/lib/python2.3/tarfile.py", line 1220, in add
    self.add(os.path.join(name, f), os.path.join(arcname, f))
  File "/usr/lib/python2.3/tarfile.py", line 1220, in add
    self.add(os.path.join(name, f), os.path.join(arcname, f))
  File "/usr/lib/python2.3/tarfile.py", line 1219, in add
    for f in os.listdir(name):
OSError: [Errno 13] Permission denied: '/etc/skel/tmp'

# end error

I could trap it in a try/except OSError block, but I'd like to know why the line NOTE1 does not simply cause the program to skip the unreadable file and continue ?

>From the python interpreter 'os.access('/file/i/cant/read', os.R_OK)' returns False so I expected my 'if' on line NOTE1 to sort that out.

If someone could just explain to me where I'm going wrong I'd be extremely greatful.

Many thanks
Nick.


From dyoo at hkn.eecs.berkeley.edu  Fri Jan 30 21:26:10 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri Jan 30 21:26:24 2004
Subject: [Tutor] Cannot fix OSError
In-Reply-To: <20040131013941.590a3503@phatbox.local>
Message-ID: <Pine.LNX.4.44.0401301800260.25379-100000@hkn.eecs.berkeley.edu>



On Sat, 31 Jan 2004, Nick Lunt wrote:

> Hi Folks,
>
> this is my first posting to the list, although I have been snooping for
> a couple of weeks ;)
>
> I've recently started to learn Python and so far I'm having great fun.
>
> Anyway, here's my problem, first off here's the program:
>
> # code
> import tarfile, sys, os
>
> if len(sys.argv) <= 2:
>         print 'Error:', sys.argv[0], ' <tarfile.tar> <list of files>
>         sys.exit(1)
>
> tfile = sys.argv[1]
>
> totar = []
> for f in sys.argv[2:]:
>         if os.access(f, os.R_OK): # NOTE1
>                 totar.append(f)
>         else:
>                 print 'Could not access', f, 'to tar'
>
>
> tf = tarfile.TarFile(tfile, 'w')
> for f in totar:
>         tf.add(f)
>
> tf.close
>
> # end code



Hmmm... there are a few lines that need to be fixed, but I don't see yet
how they would contribute to the bug.  *grin*


The last statement:

> tf.close

needs to include the open and close parens: functions fire off only in the
presence of parentheses.




> I could trap it in a try/except OSError block, but I'd like to know why
> the line NOTE1 does not simply cause the program to skip the unreadable
> file and continue ?
>
> From the python interpreter 'os.access('/file/i/cant/read', os.R_OK)'
> returns False so I expected my 'if' on line NOTE1 to sort that out.


Agreed; from the code, I don't see anything else wrong with it...


Oh!  Here is one possibility: the files listed in sys.argv[2:] may be
directories.  It's possible that tarfile.TarFile.add() can take in either
directories or filenames.  That is, the directory

    /etc

might be listed in sys.argv[2:], and technically speaking, '/etc' is
completely readable.  But if tarfile recursively dives into a directory,
it might run into:

    /etc/skel/tmp

and run into problems tarring that file.  The test for readability in the
code you've written only looks at the files explicitely listed on the
command line.


The documentation of tarfile.TarFile.add() in:

    http://www.python.org/doc/lib/module-tarfile.html

does imply that it will recursively dive into directories.  Does this make
sense?



Here's a slightly revised version of the code, where the
readability-filtering is doing in a separate function:


###
import tarfile, sys, os

def main():
    if len(sys.argv) <= 2:
        print 'Error:', sys.argv[0], ' <tarfile.tar> <list of files>
        sys.exit(1)
    tfile = sys.argv[1]
    totar = filter_for_readables(sys.argv[2:])

    tf = tarfile.TarFile(tfile, 'w')
    for f in totar:
        tf.add(f)
    tf.close()


def filter_for_readables(files):
    filtered_files = []
    for f in files:
        if os.access(f, os.R_OK):
            filtered_files.append(f)
        else:
            print 'Could not access', f, 'to tar'
    return filtered_files


if __name__ == '__main__':
    main()
###



The function reorganization here isn't just for show, but should make it
easier to test and experiment with the code, since you'll be able to do
things like:

###
>>> import tar
>>> tar.filter_for_readables(some_file)
###

from the interactive interpreter.


Anyway, to fix the bug, you may need to take some precautions and expand
out every directory name in sys.argv[2:] to the actual files that you want
to tar up.  That is, you may need to process sys.argv[2:] so that tarfile
doesn't dive into directories on its own.

The os.walk() function may be helpful for you:

    http://www.python.org/doc/lib/module-tarfile.html


If you have more questions, please feel free to ask.  Good luck!


From dyoo at hkn.eecs.berkeley.edu  Fri Jan 30 21:28:06 2004
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri Jan 30 21:28:13 2004
Subject: [Tutor] Cannot fix OSError
In-Reply-To: <Pine.LNX.4.44.0401301800260.25379-100000@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.44.0401301827261.25379-100000@hkn.eecs.berkeley.edu>

> The os.walk() function may be helpful for you:
>
>     http://www.python.org/doc/lib/module-tarfile.html


Doh.  Stupid cut-and-paste.

    http://www.python.org/doc/lib/os-file-dir.html#l2h-1465

There, that's better.  *grin*


Hope this helps!


From jb at riseup.net  Fri Jan 30 22:44:49 2004
From: jb at riseup.net (jb)
Date: Fri Jan 30 22:44:56 2004
Subject: [Tutor] Cannot fix OSError
In-Reply-To: <20040131013941.590a3503@phatbox.local>
References: <20040131013941.590a3503@phatbox.local>
Message-ID: <20040131034449.GB13417@fried.sakeos.net>

On Sat, Jan 31, 2004 at 01:39:41AM +0000, Nick Lunt wrote:
> Hi Folks,
> 
> this is my first posting to the list, although I have been snooping for
> a couple of weeks ;)
> 
> I've recently started to learn Python and so far I'm having great fun.

you're not alone :p
 
> Anyway, here's my problem, first off here's the program:
> 
> # code
> import tarfile, sys, os
> 
> if len(sys.argv) <= 2:
>         print 'Error:', sys.argv[0], ' <tarfile.tar> <list of files>
>         sys.exit(1)
> 
> tfile = sys.argv[1]
> 
> totar = []
> for f in sys.argv[2:]:
>         if os.access(f, os.R_OK): # NOTE1
>                 totar.append(f)
>         else:
>                 print 'Could not access', f, 'to tar'
> 
> 
> tf = tarfile.TarFile(tfile, 'w')
> for f in totar:
>         tf.add(f)
> 
> tf.close
> 
> # end code
> 
> This works fine until it encounters a file that I am not allowed to access, in which case it gives me this error:
> 
> # error
> Traceback (most recent call last):
>   File "./tar.py", line 31, in ?
>     tf.add(f)
>   File "/usr/lib/python2.3/tarfile.py", line 1220, in add
>     self.add(os.path.join(name, f), os.path.join(arcname, f))
>   File "/usr/lib/python2.3/tarfile.py", line 1220, in add
>     self.add(os.path.join(name, f), os.path.join(arcname, f))
>   File "/usr/lib/python2.3/tarfile.py", line 1219, in add
>     for f in os.listdir(name):
> OSError: [Errno 13] Permission denied: '/etc/skel/tmp'
> 
> # end error
> 
> I could trap it in a try/except OSError block, but I'd like to know why the line NOTE1 does not simply cause the program to skip the unreadable file and continue ?
> 
> >From the python interpreter 'os.access('/file/i/cant/read', os.R_OK)' 
returns False so I expected my 'if' on line NOTE1 to sort that out.

check out the man page for chmod: permission things are a bit different 
for files and directory - to do what you want, you have to be able to read
the directory (you check os.R_OK for that) AND you have to be able to
enter and pass through it - os.X_OK is to be checked for that.  

basically you can't tar a directory that doesnt have r and x fields set 
for you.

i hope this helps
jb



From idiot1 at netzero.net  Fri Jan 30 23:11:16 2004
From: idiot1 at netzero.net (Kirk Bailey)
Date: Fri Jan 30 23:13:28 2004
Subject: [Tutor] do pythons like coffee?
Message-ID: <401B2AE4.5090107@netzero.net>

I am studying JavaScript of late. And it occurs to me that a script 
pumping out a webpage might use a little javascript in it for assorted 
nefarious purposes. Anyone familiar with the friendlyness of these two 
unlikely bedfellows?

EGODS, the thought of a python STOKED on caffene...

-- 


end


   think   http://www.tinylist.org/ - $FREE$ software for liberty
+-------+ http://www.pinellasintergroupsociety.org/ - In Her Service
|  BOX  | http://www.listville.net/ - $FREE$ list hosting services
+-------+ http://www.howlermonkey.net/ - $FREE$ email service
   kniht   http://www.sacredelectron.org/ - My personal SCREED pit
          (C)2004 Kirk D Bailey, all rights reserved- but ask!







From shaleh at speakeasy.net  Sat Jan 31 00:59:19 2004
From: shaleh at speakeasy.net (Sean 'Shaleh' Perry)
Date: Sat Jan 31 00:59:35 2004
Subject: [Tutor] do pythons like coffee?
In-Reply-To: <401B2AE4.5090107@netzero.net>
References: <401B2AE4.5090107@netzero.net>
Message-ID: <200401302159.19748.shaleh@speakeasy.net>

On Friday 30 January 2004 20:11, Kirk Bailey wrote:
> I am studying JavaScript of late. And it occurs to me that a script
> pumping out a webpage might use a little javascript in it for assorted
> nefarious purposes. Anyone familiar with the friendlyness of these two
> unlikely bedfellows?
>
> EGODS, the thought of a python STOKED on caffene...

javascript is not Java.  The name was purely a marketing decision on the part 
of netscape.

You basically can't write a full featured website these days without it.

BTW, the "real" name for it is emcascript.


From glingl at aon.at  Sat Jan 31 01:47:38 2004
From: glingl at aon.at (Gregor Lingl)
Date: Sat Jan 31 01:46:42 2004
Subject: [Tutor] "=" invalid syntax ?
In-Reply-To: <401DE84C.8030707@netscape.net>
References: <401DE84C.8030707@netscape.net>
Message-ID: <401B4F8A.6090408@aon.at>

Hi Xuer!

> ...

 

> while (line=fi.readline()):
>        print line
> -----------------------------------------------
> then run it
>
> $./test.py
>  File "./test.py", line 8
>    while (line=fi.readline()):
>               ^
> SyntaxError: invalid syntax
>
> what's the problem?

The problem is, that in Python the assigmnment statement
doesn't return anything. Instead you may use a a more
Pythonic idiom like e.g.

fi = open("pascal.py","r")
for line in fi:
    print line

or, if you use a version < 2.3 :

fi = open("pascal.py","r")
lines = fi.readlines()  # constructs list of lines in fi
for line in lines:
    print line

HTH, Gregor


>
> thanks and regards :)
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>

From alan.gauld at blueyonder.co.uk  Sat Jan 31 03:51:34 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Sat Jan 31 03:50:45 2004
Subject: [Tutor] Converting string or list to sum
References: <E1Amh5U-0002Rt-Fm@fuse1.fusemail.net>
Message-ID: <006a01c3e7d7$6e3ad480$6401a8c0@xp>

>    >  d = ''.join(map(str, a))
>    >
>    >since that's probably much faster for large lists.
>    >
>  
> I think that should be:
> import __builtin__
> d = ''.join(map(__builtin__.str, a))

Why?

Builtins are, as the name says built in, you dont 
need to import them! And you don't need to prefix 
with the module name. Why did you think you'd 
need to do that? Do you habitually import __builtins__?
Have you had problems using builtin functions?

Alan G.


From alan.gauld at blueyonder.co.uk  Sat Jan 31 04:01:38 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Sat Jan 31 04:00:48 2004
Subject: [Tutor] Cannot fix OSError
References: <20040131013941.590a3503@phatbox.local>
Message-ID: <007501c3e7d8$d612e2e0$6401a8c0@xp>

As per Danny's post I can't se anytthing obvious
although his tar explanation sounds good to me!
However...

> # code
> import tarfile, sys, os
>
> if len(sys.argv) <= 2:
>         print 'Error:', sys.argv[0], ' <tarfile.tar> <list of files>
>         sys.exit(1)
>
> tfile = sys.argv[1]
>
> totar = []
> for f in sys.argv[2:]:
>         if os.access(f, os.R_OK): # NOTE1
>                 totar.append(f)
>         else:
>                 print 'Could not access', f, 'to tar'
>
>
> tf = tarfile.TarFile(tfile, 'w')
> for f in totar:
>         tf.add(f)

> I could trap it in a try/except OSError block, but I'd
> like to know why the line NOTE1 does not simply cause
> the program to skip the unreadable file and continue ?

What's wrong with a try/except approach:

for f in sys.argv[2:]:
    try: tf.add(f)
    except OSERror: print 'Could not access', f, 'to tar'

Do you have any reason not to use the simpler approach?
- Like maybe you just wanted to try out the os access!... :-)

In general try/except leads to simpler code than explicit
tests. Only if the error is going to do significant and
unrecoverable damage do you need to test in advance.
This is why nearly all modern languages, from ADA
onwards use try/except style error processing.

Just a thought,

Alan G.


From Janssen at rz.uni-frankfurt.de  Sat Jan 31 04:12:33 2004
From: Janssen at rz.uni-frankfurt.de (Michael Janssen)
Date: Sat Jan 31 04:12:47 2004
Subject: [Tutor] raw_input function
In-Reply-To: <014a01c3e5f2$81d852b0$6401a8c0@xp>
References: <20040128185316.42182.qmail@web12401.mail.yahoo.com>
	<m31xpjsx5s.fsf@hamster.pflaesterer.de>
	<014a01c3e5f2$81d852b0$6401a8c0@xp>
Message-ID: <Pine.A41.4.56.0401311008130.260766@hermes-22.rz.uni-frankfurt.de>

On Wed, 28 Jan 2004, Alan Gauld wrote:

> def raw_input(prompt):
>    print prompt,
>    return sys.stdin.readline()
>
> Its actually a wee bit cleverer than that I think, but so far as
> we the users go its pretty close.

one thing the builtin raw_input does cleverer is readline support. You
only need to do a "import readline" first and many keybinding including
the cursor keys are working then.

Does anybody know how to get this with sys.stdin ?

Michael

From nick at javacat.f2s.com  Sat Jan 31 10:11:50 2004
From: nick at javacat.f2s.com (Nick Lunt)
Date: Sat Jan 31 10:18:58 2004
Subject: [Tutor] Cannot fix OSError
Message-ID: <20040131151150.4fdfd86e@phatbox.local>

Many thanks for your responses.

On Fri, 30 Jan 2004 18:26:10 -0800 (PST)
Danny Yoo <dyoo@hkn.eecs.berkeley.edu> wrote:

> Oh!  Here is one possibility: the files listed in sys.argv[2:] may be
> directories.  It's possible that tarfile.TarFile.add() can take in either
> directories or filenames.  That is, the directory
> 
>     /etc
> 
> might be listed in sys.argv[2:], and technically speaking, '/etc' is
> completely readable.  But if tarfile recursively dives into a directory,
> it might run into:
> 
>     /etc/skel/tmp
> 
> and run into problems tarring that file.  The test for readability in the
> code you've written only looks at the files explicitely listed on the
> command line.

I think my main error is as Danny Voo states, the fact that I sent in /etc which can be read fine, but some files beneath it can't. Thanks for that Danny, now I've seen how you've done it I'll try not to look at it again so I can try it myself ;) And thanks for the links too.

On Sat, 31 Jan 2004 09:01:38 -0000
"Alan Gauld" <alan.gauld@blueyonder.co.uk> wrote:

> What's wrong with a try/except approach:

Alan, I agree the try/except method would help, but I wanted to understand why my if statement wasn't working 100%, the final version of my prog will include several try/except blocks

On Sat, 31 Jan 2004 04:44:49 +0100
jb <jb@riseup.net> wrote:

> basically you can't tar a directory that doesnt have r and x fields set 

Thanks jb, I understand the unix permissions and thought my if block would filter out that problem, but obviously I didn't think about it hard enough ;)

Anyway, thanks again for all your help.

Cheers
Nick.

From missive at hotmail.com  Sat Jan 31 10:44:14 2004
From: missive at hotmail.com (Lee Harr)
Date: Sat Jan 31 10:44:19 2004
Subject: [Tutor] Re: do pythons like coffee?
Message-ID: <BAY2-F140vnRQgukfMH00061ce5@hotmail.com>

>I am studying JavaScript of late. And it occurs to me that a script
>pumping out a webpage might use a little javascript in it for assorted
>nefarious purposes. Anyone familiar with the friendlyness of these two
>unlikely bedfellows?
>


I guess my response would be ... it is no more dangerous than serving
a plain text file with a malicious javascript on it.

The nice thing about server-side scripting (and why I prefer it to the
client-side scripts) is that it's all the same to the browser. On the
server it might be pulling in pieces from all over the place -- templates,
scripts, configuration files, environment variables -- but in the end it
sends out a stream of bytes and the client just sees it as a file.

_________________________________________________________________
Protect your PC - get McAfee.com VirusScan Online 
http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963


From pythontutor at venix.com  Sat Jan 31 11:40:57 2004
From: pythontutor at venix.com (Lloyd Kvam)
Date: Sat Jan 31 11:42:42 2004
Subject: [Tutor] Cannot fix OSError (try/except)
In-Reply-To: <20040131151150.4fdfd86e@phatbox.local>
References: <20040131151150.4fdfd86e@phatbox.local>
Message-ID: <401BDA99.7000001@venix.com>

Nick Lunt wrote:

> Many thanks for your responses.
> 
> On Fri, 30 Jan 2004 18:26:10 -0800 (PST)
> Danny Yoo <dyoo@hkn.eecs.berkeley.edu> wrote:
> 
> 
>>Oh!  Here is one possibility: the files listed in sys.argv[2:] may be
>>directories.  It's possible that tarfile.TarFile.add() can take in either
>>directories or filenames.  That is, the directory
(snipped)
> "Alan Gauld" <alan.gauld@blueyonder.co.uk> wrote:
> 
> 
>>What's wrong with a try/except approach:
> 
> 
> Alan, I agree the try/except method would help, but I wanted to understand why my if statement wasn't working 100%, the final version of my prog will include several try/except blocks
> (snipped)

Is there any way a try/except at this level could complete building the tar file
while only omitting the unreadable files?  It seems to me that only a try/except
in the tarfile module could actually finish building the best possible tar archive.

Am I missing something?

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582


From pythontutor at venix.com  Sat Jan 31 11:52:28 2004
From: pythontutor at venix.com (Lloyd Kvam)
Date: Sat Jan 31 11:52:36 2004
Subject: [Tutor] Re: do pythons like coffee?
In-Reply-To: <BAY2-F140vnRQgukfMH00061ce5@hotmail.com>
References: <BAY2-F140vnRQgukfMH00061ce5@hotmail.com>
Message-ID: <401BDD4C.7010503@venix.com>

IMO Javascript is mostly useful for local user interface niceties:
	mouseover messages
	smarter keystroke / mouse handling

I use javascript most commonly for POSTs that look like hyperlinks (GETs).  The
javascript is embedded in the href attribute of the anchor tag, sets
some variables and calls the form's submit function.

In looking at web sites source HTML, it is often amazing just how much javascript
gets included.  It is also interesting to peek at the javascript console
in the browser and see the accumulated javascript errors.

Lee Harr wrote:

>> I am studying JavaScript of late. And it occurs to me that a script
>> pumping out a webpage might use a little javascript in it for assorted
>> nefarious purposes. Anyone familiar with the friendlyness of these two
>> unlikely bedfellows?
>>
> 
> 
> I guess my response would be ... it is no more dangerous than serving
> a plain text file with a malicious javascript on it.
> 
> The nice thing about server-side scripting (and why I prefer it to the
> client-side scripts) is that it's all the same to the browser. On the
> server it might be pulling in pieces from all over the place -- templates,
> scripts, configuration files, environment variables -- but in the end it
> sends out a stream of bytes and the client just sees it as a file.
> 
> _________________________________________________________________
> Protect your PC - get McAfee.com VirusScan Online 
> http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582


From tim at johnsons-web.com  Sat Jan 31 12:35:32 2004
From: tim at johnsons-web.com (Tim Johnson)
Date: Sat Jan 31 12:31:35 2004
Subject: [Tutor] "=" invalid syntax ?
In-Reply-To: <401DE84C.8030707@netscape.net>
References: <401DE84C.8030707@netscape.net>
Message-ID: <20040131173532.GI5205@johnsons-web.com>

* Xuer <linuxasking@netscape.net> [040130 21:19]:
> print all lines of a simple file
> 
> test.py
> -----------------------------------------------
> #!/usr/bin/python
> 
> try:
>        fi = open('test.py', 'r')
> except IOError:
>        print 'Can\'t open file for reading.'
>        sys.exit(0)
> while (line=fi.readline()):
>        print line
> -----------------------------------------------
> then run it
> 
> $./test.py
>  File "./test.py", line 8
>    while (line=fi.readline()):
>               ^
> SyntaxError: invalid syntax
> 
> what's the problem?
> while (line=fi.readline()):
 
    '=' is an assignment operator in python.
    '==' is the comparison operator in python.
    use '=='

    happens to me all the time ....
    tim

-- 
Tim Johnson <tim@johnsons-web.com>
      http://www.alaska-internet-solutions.com

From alan.gauld at blueyonder.co.uk  Sat Jan 31 13:27:48 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Sat Jan 31 13:28:33 2004
Subject: [Tutor] Cannot fix OSError (try/except)
References: <20040131151150.4fdfd86e@phatbox.local>
	<401BDA99.7000001@venix.com>
Message-ID: <00ad01c3e827$edba6450$6401a8c0@xp>

LLoyd,

> Is there any way a try/except at this level could complete building
the tar file
> while only omitting the unreadable files?  It seems to me that only
a try/except
> in the tarfile module could actually finish building the best
possible tar

I thought the code I posted would do that?

# open tarfile up here

for f in filelist:
   try: tarfile.TarFile.add()
   except OSERror: print 'couldn't add', f

# close tarfile down here


> Am I missing something?

Maybe, or maybe it's me that missing something?


Alan G.


From missive at hotmail.com  Sat Jan 31 13:40:43 2004
From: missive at hotmail.com (Lee Harr)
Date: Sat Jan 31 13:41:01 2004
Subject: [Tutor] Re: do pythons like coffee?
Message-ID: <BAY2-F24gTFur2iz2Mb0001b19f@hotmail.com>

>>>I am studying JavaScript of late. And it occurs to me that a script
>>>pumping out a webpage might use a little javascript in it for assorted
>>>nefarious purposes. Anyone familiar with the friendlyness of these two
>>>unlikely bedfellows?
>>>
>>
>>
>>I guess my response would be ... it is no more dangerous than serving
>>a plain text file with a malicious javascript on it.
>>
>>The nice thing about server-side scripting (and why I prefer it to the
>>client-side scripts) is that it's all the same to the browser. On the
>>server it might be pulling in pieces from all over the place -- templates,
>>scripts, configuration files, environment variables -- but in the end it
>>sends out a stream of bytes and the client just sees it as a file.
>>
>
>I use javascript most commonly for POSTs that look like hyperlinks (GETs).  
>The
>javascript is embedded in the href attribute of the anchor tag, sets
>some variables and calls the form's submit function.
>


Right. That goes to my point... On my main browser, I have javascript
completely disabled. I find it really annoying when I get to a link that
looks like a regular link, but does nothing unless javascript is
enabled.

_________________________________________________________________
Help STOP SPAM with the new MSN 8 and get 2 months FREE*  
http://join.msn.com/?page=features/junkmail


From pythontutor at venix.com  Sat Jan 31 14:00:11 2004
From: pythontutor at venix.com (Lloyd Kvam)
Date: Sat Jan 31 14:00:19 2004
Subject: [Tutor] Cannot fix OSError (try/except)
In-Reply-To: <00ad01c3e827$edba6450$6401a8c0@xp>
References: <20040131151150.4fdfd86e@phatbox.local>
	<401BDA99.7000001@venix.com> <00ad01c3e827$edba6450$6401a8c0@xp>
Message-ID: <401BFB3B.4070801@venix.com>

You can pass the name of a directory.  If it can't read a file within
the directory, it abandons the rest of the directory contents.  I just
tested that.  The except will continue to the next file/directory in YOUR
list, but you've potentially skipped readable files in the directory with
an error.

Alan Gauld wrote:

> LLoyd,
> 
> 
>>Is there any way a try/except at this level could complete building
> 
> the tar file
> 
>>while only omitting the unreadable files?  It seems to me that only
> 
> a try/except
> 
>>in the tarfile module could actually finish building the best
> 
> possible tar
> 
> I thought the code I posted would do that?
> 
> # open tarfile up here
> 
> for f in filelist:
>    try: tarfile.TarFile.add()
>    except OSERror: print 'couldn't add', f
> 
> # close tarfile down here
> 
> 
> 
>>Am I missing something?
> 
> 
> Maybe, or maybe it's me that missing something?
> 
> 
> Alan G.
> 
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582


From littledanehren at yahoo.com  Sat Jan 31 14:09:17 2004
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Sat Jan 31 14:09:21 2004
Subject: [Tutor] "=" invalid syntax ?
In-Reply-To: <401DE84C.8030707@netscape.net>
Message-ID: <20040131190917.19637.qmail@web41805.mail.yahoo.com>

Xuer wrote:
> print all lines of a simple file
> 
> test.py
> -----------------------------------------------
> #!/usr/bin/python
> 
> try:
>         fi = open('test.py', 'r')
> except IOError:
>         print 'Can\'t open file for reading.'
>         sys.exit(0)
> while (line=fi.readline()):
>         print line
> -----------------------------------------------
> then run it
> 
> $./test.py
>   File "./test.py", line 8
>     while (line=fi.readline()):
>                ^
> SyntaxError: invalid syntax
> 
> what's the problem?
> 
> thanks and regards :)

In Python, = is a statement. You can still loop
through files, however. Here's how I would write the
program instead:

#!/usr/bin/python

try:
    fi = open('test.py', 'r')
    for line in fi:
        print line
except IOError:
    print "Can't open file for reading."
finally:
    fi.close()

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Yahoo! SiteBuilder - Free web site building tool. Try it!
http://webhosting.yahoo.com/ps/sb/

From orbitz at ezabel.com  Sat Jan 31 16:27:28 2004
From: orbitz at ezabel.com (orbitz@ezabel.com)
Date: Sat Jan 31 16:28:14 2004
Subject: [Tutor] "=" invalid syntax ?
In-Reply-To: <20040131190917.19637.qmail@web41805.mail.yahoo.com>
References: <401DE84C.8030707@netscape.net>
	<20040131190917.19637.qmail@web41805.mail.yahoo.com>
Message-ID: <20040131162728.2908c5fb.orbitz@ezabel.com>

I just learned this recently, but if you say = is a statement then you
would imagine:

a = b = 2 to not work. = is actually special cased for this to work.
however
a = (b = 2) does not work.  There is some 'magic' some people might say
to =, but I think a = b = .. is the only excpetion to the = is a
statement operator rule.


On Sat, 31 Jan 2004 11:09:17 -0800 (PST)
Daniel Ehrenberg <littledanehren@yahoo.com> wrote:

> Xuer wrote:
> > print all lines of a simple file
> > 
> > test.py
> > -----------------------------------------------
> > #!/usr/bin/python
> > 
> > try:
> >         fi = open('test.py', 'r')
> > except IOError:
> >         print 'Can\'t open file for reading.'
> >         sys.exit(0)
> > while (line=fi.readline()):
> >         print line
> > -----------------------------------------------
> > then run it
> > 
> > $./test.py
> >   File "./test.py", line 8
> >     while (line=fi.readline()):
> >                ^
> > SyntaxError: invalid syntax
> > 
> > what's the problem?
> > 
> > thanks and regards :)
> 
> In Python, = is a statement. You can still loop
> through files, however. Here's how I would write the
> program instead:
> 
> #!/usr/bin/python
> 
> try:
>     fi = open('test.py', 'r')
>     for line in fi:
>         print line
> except IOError:
>     print "Can't open file for reading."
> finally:
>     fi.close()
> 
> Daniel Ehrenberg
> 
> __________________________________
> Do you Yahoo!?
> Yahoo! SiteBuilder - Free web site building tool. Try it!
> http://webhosting.yahoo.com/ps/sb/
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

From sigurd at 12move.de  Sat Jan 31 16:24:37 2004
From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=)
Date: Sat Jan 31 16:29:34 2004
Subject: [Tutor] "=" invalid syntax ?
In-Reply-To: <20040131190917.19637.qmail@web41805.mail.yahoo.com> (Daniel
	Ehrenberg's message of "Sat, 31 Jan 2004 11:09:17 -0800 (PST)")
References: <20040131190917.19637.qmail@web41805.mail.yahoo.com>
Message-ID: <m3vfmriznf.fsf@hamster.pflaesterer.de>

On 31 Jan 2004, Daniel Ehrenberg <- littledanehren@yahoo.com wrote:

> In Python, = is a statement. You can still loop
> through files, however. Here's how I would write the
> program instead:

> #!/usr/bin/python

> try:
>     fi = open('test.py', 'r')
>     for line in fi:
>         print line
> except IOError:
>     print "Can't open file for reading."
> finally:
>     fi.close()

A little nitpick (I wrote try/except some time exact like the above till
I read a posting from Alex Martelli where he wrote about `else' in that
construct); IMO the above code with `else' is clearer:

try:
    fi = open('test.py', 'r')
except IOError:
    print "Can't open file for reading."
else:
    for line in fi:
        print line
finally:
    fi.close()

Now you see at first glance what you try to do, what happens if it fails
and what happens if it succeeds.


   Karl
-- 
Please do *not* send copies of replies to me.
I read the list


From project5 at redrival.net  Sat Jan 31 16:29:18 2004
From: project5 at redrival.net (Andrei)
Date: Sat Jan 31 16:32:42 2004
Subject: [Tutor] .tar.gz in Py (was: do pythons like coffee?)
References: <401B2AE4.5090107@netzero.net>
Message-ID: <18j8mrbjmj000$.ireckbqsmp5u.dlg@40tude.net>

Hi,

I have a batch file in which I create a tar.gz file of a directory
containing nested subdirectories (and files) using the 7-zip command line,
like this:

7z.exe a -ttar ..\myfile.tar * -r
cd..
7z.exe a -tgzip myfile.tar.gz myfile.tar -r

The result then looks somewhat like this:

  - myfile.tar.gz
       |
       |- myfile.tar
             |
             |- file1.ext
             |- dir1
                   |
                   |-file2.ext

Python has a tarfile module so I was thinking I'd like to migrate that to
Python (not just by running os.system()) because I use it in building a
distro for a program. The problem is that the docs for the tarfile module
don't seem to fit my brain and I also can't find any decent sample code. 
Does anyone know any examples for using the tarfile module?

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.


From pythontutor at venix.com  Sat Jan 31 16:37:31 2004
From: pythontutor at venix.com (Lloyd Kvam)
Date: Sat Jan 31 16:40:36 2004
Subject: [Tutor] "=" invalid syntax ?
In-Reply-To: <20040131190917.19637.qmail@web41805.mail.yahoo.com>
References: <20040131190917.19637.qmail@web41805.mail.yahoo.com>
Message-ID: <401C201B.9060403@venix.com>

try/except and try/finally are two different forms.  There is no try/except/finally.

(thanks to Alex Martelli) it should look more like:

try:
     try:
         fi = open('test.py', 'r')
     except IOError:
         print "Can't open file for reading."
     else:
         for line in fi:
             print line
finally:
     fi.close()

The else is a convenient to limit the scope of the try statement.

The exceptions chapter of "Python in a Nutshell" has very lucid descriptions
of exception handling strategies.

Daniel Ehrenberg wrote:
> Xuer wrote:
> 
>>print all lines of a simple file
>>
>>test.py
>>-----------------------------------------------
>>#!/usr/bin/python
>>
>>try:
>>        fi = open('test.py', 'r')
>>except IOError:
>>        print 'Can\'t open file for reading.'
>>        sys.exit(0)
>>while (line=fi.readline()):
>>        print line
>>-----------------------------------------------
>>then run it
>>
>>$./test.py
>>  File "./test.py", line 8
>>    while (line=fi.readline()):
>>               ^
>>SyntaxError: invalid syntax
>>
>>what's the problem?
>>
>>thanks and regards :)
> 
> 
> In Python, = is a statement. You can still loop
> through files, however. Here's how I would write the
> program instead:
> 
> #!/usr/bin/python
> 
> try:
>     fi = open('test.py', 'r')
>     for line in fi:
>         print line
> except IOError:
>     print "Can't open file for reading."
> finally:
>     fi.close()
> 
> Daniel Ehrenberg
> 
> __________________________________
> Do you Yahoo!?
> Yahoo! SiteBuilder - Free web site building tool. Try it!
> http://webhosting.yahoo.com/ps/sb/
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582


From alan.gauld at blueyonder.co.uk  Sat Jan 31 16:54:42 2004
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Sat Jan 31 17:02:15 2004
Subject: [Tutor] Cannot fix OSError (try/except)
References: <20040131151150.4fdfd86e@phatbox.local>
	<401BDA99.7000001@venix.com> <00ad01c3e827$edba6450$6401a8c0@xp>
	<401BFB3B.4070801@venix.com>
Message-ID: <00b401c3e844$d5215ee0$6401a8c0@xp>

> You can pass the name of a directory.  If it can't read a file
within
> the directory, it abandons the rest of the directory contents.  I
just
> tested that.  The except will continue to the next file/directory in
YOUR
> list, but you've potentially skipped readable files in the directory
with
> an error.

But doesn't the OK check do the same? You would need to do a
tree walk to avoid that, wouldn't you?

Alan G.


From nick at javacat.f2s.com  Sat Jan 31 17:13:12 2004
From: nick at javacat.f2s.com (Nick Lunt)
Date: Sat Jan 31 17:21:00 2004
Subject: [Tutor] Cannot fix OSError (try/except)
Message-ID: <20040131221312.1cf2dfb9@phatbox.local>

With the help I've received so far I've decided (but not yet coded) that the original 'if os.access('wherever', os.R_OK):' will be able to handle files passed on the command line fine, but directories will need to be walked so that any subdirectories/files can be handled seperately.

Something along the lines of 

arglist = sys.argv[2:]
for f in arglist:
	if os.path.isdir(f): # it's a dir
		<send it off to a func for a dir walk and access check>
	if os.access(f, os.R_OK): # it's a file
		<add it to the final list of files to be tarred>

Well that makes sense to me anyway - thanks to you folks ;)

Cheers
Nick.






On Sat, 31 Jan 2004 21:54:42 -0000
"Alan Gauld" <alan.gauld@blueyonder.co.uk> wrote:

> > You can pass the name of a directory.  If it can't read a file
> within
> > the directory, it abandons the rest of the directory contents.  I
> just
> > tested that.  The except will continue to the next file/directory in
> YOUR
> > list, but you've potentially skipped readable files in the directory
> with
> > an error.
> 
> But doesn't the OK check do the same? You would need to do a
> tree walk to avoid that, wouldn't you?
> 
> Alan G.

From nick at javacat.f2s.com  Sat Jan 31 17:21:26 2004
From: nick at javacat.f2s.com (Nick Lunt)
Date: Sat Jan 31 17:28:34 2004
Subject: [Tutor] .tar.gz in Py (was: do pythons like coffee?)
In-Reply-To: <18j8mrbjmj000$.ireckbqsmp5u.dlg@40tude.net>
References: <401B2AE4.5090107@netzero.net>
	<18j8mrbjmj000$.ireckbqsmp5u.dlg@40tude.net>
Message-ID: <20040131222126.15808966@phatbox.local>

Hi Andrei,

I asked a tar question myself yesterday and included my problematic program. Here it is -

# CODE

"""
tar.py:
Usage: 
        tar.py filetocreate.tar list_of_files_to_tar

imports:
        tarfile -        to do the tarring
        sys -            to manipulate command line args        
"""

# Fails in the if block on os.access when dirs are submitted as args.
# ie the dir submitted is readable but some files below it may not be,
# which the if os.access() does not pick up.
# So create a new function to walk the dir and only return the files it can
# backup successfully, but print a list of the ones it cant.


import tarfile, sys, os

if len(sys.argv) <= 2:
        print 'Error:', sys.argv[0], ' <tarfile.tar> <list of files to tar>'
        sys.exit(1)

tfile = sys.argv[1]

totar = []
for f in sys.argv[2:]:
        if os.access(f, os.R_OK):
                totar.append(f)
        else:
                print 'Could not access', f, 'to tar'


tf = tarfile.TarFile(tfile, 'w')
for f in totar:
        tf.add(f)

tf.close()

# END CODE

As you can see from the comments in my code it is not perfect yet, but it will hopefully show you how to use the tar module, and it will create a tar file for you.

There is also a gzip module you can import to gzip the tar file, but I've not got my head round that yet as the tar part is not 100%, but that is my plans for it. Then it's going to write it to CD. Then I'd like to make a GUI for it, just to learn how to ;) Oh yeah, the final version is also gonna be OOP.

Hope that helps a bit,
Cheers
Nick.



On Sat, 31 Jan 2004 22:29:18 +0100
Andrei <project5@redrival.net> wrote:

> Hi,
> 
> I have a batch file in which I create a tar.gz file of a directory
> containing nested subdirectories (and files) using the 7-zip command line,
> like this:
> 
> 7z.exe a -ttar ..\myfile.tar * -r
> cd..
> 7z.exe a -tgzip myfile.tar.gz myfile.tar -r
> 
> The result then looks somewhat like this:
> 
>   - myfile.tar.gz
>        |
>        |- myfile.tar
>              |
>              |- file1.ext
>              |- dir1
>                    |
>                    |-file2.ext
> 
> Python has a tarfile module so I was thinking I'd like to migrate that to
> Python (not just by running os.system()) because I use it in building a
> distro for a program. The problem is that the docs for the tarfile module
> don't seem to fit my brain and I also can't find any decent sample code. 
> Does anyone know any examples for using the tarfile module?
> 
> -- 
> Yours,
> 
> Andrei
> 
> =====
> Mail address in header catches spam. Real contact info (decode with rot13):
> cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
> gur yvfg, fb gurer'f ab arrq gb PP.
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

From pythontutor at venix.com  Sat Jan 31 17:39:09 2004
From: pythontutor at venix.com (Lloyd Kvam)
Date: Sat Jan 31 17:39:15 2004
Subject: [Tutor] Cannot fix OSError (try/except)
In-Reply-To: <00b401c3e844$d5215ee0$6401a8c0@xp>
References: <20040131151150.4fdfd86e@phatbox.local>
	<401BDA99.7000001@venix.com> <00ad01c3e827$edba6450$6401a8c0@xp>
	<401BFB3B.4070801@venix.com> <00b401c3e844$d5215ee0$6401a8c0@xp>
Message-ID: <401C2E8D.6000608@venix.com>

Alan Gauld wrote:

>>You can pass the name of a directory.  If it can't read a file
> 
> within
> 
>>the directory, it abandons the rest of the directory contents.  I
> 
> just
> 
>>tested that.  The except will continue to the next file/directory in
> 
> YOUR
> 
>>list, but you've potentially skipped readable files in the directory
> 
> with
> 
>>an error.
> 
> 
> But doesn't the OK check do the same? You would need to do a
> tree walk to avoid that, wouldn't you?

Or put the try/except inside the tarfile module.  It is already doing the
tree walk.  Why duplicate that logic?  I'd be inclined to use the trace
to find where the exception is raised within tarfile.py and then figure
out a way to proceed with other files.  The worst case is a custom version.
Possibly it could lead to an improved tarfile.py.

In Nick's original email the error is:
OSError: [Errno 13] Permission denied: '/etc/skel/tmp'

Wouldn't something like:

try:
     self.add(os.path.join(name, f), os.path.join(arcname, f))
except OSError, e:
     if e.errno == 13:	# permission error
         sys.stderr.write("permission problem on %f in %f\n" % (f, name))
     else:
         raise	# an exception that we really want to see


make sense?  The real challenge would be a mechanism to provide some custom control
to this so as not to spawn lots of custom variations.

> 
> Alan G.
> 
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582


From isrgish at fusemail.com  Sat Jan 31 21:14:22 2004
From: isrgish at fusemail.com (Isr Gish)
Date: Sat Jan 31 21:14:15 2004
Subject: =?utf-8?Q?Re:_=5BTutor=5D_Converting_string_or?=
	=?utf-8?Q?_list_to_sum?=
Message-ID: <E1An77Z-0005vy-AG@fuse1.fusemail.net>


Kalle Svensson" wrote:
   >>    >I'd write
   >>    >
   >>    >  d = ''.join(map(str, a))
   >>    >
   >>    >since that's probably much faster for large lists.
   >>  
   >> I think that should be:
   >> import __builtin__
   >> d = ''.join(map(__builtin__.str, a))
   >
   >Why?
   >

When I try doing.
map(str, a)
I got a traceback 
TypeError: 'str' object is not callable
But when I do,
map(__builtin__.str, a)
It works fine.

I'm using ver. 2.3.2 on a Pocket PC.

Isr


From red_necks25 at yahoo.com  Sat Jan 31 21:35:00 2004
From: red_necks25 at yahoo.com (moore william)
Date: Sat Jan 31 21:35:05 2004
Subject: [Tutor] Buttons
Message-ID: <20040201023500.51351.qmail@web13608.mail.yahoo.com>

I have a cash program that I am trying to create
buttons for instead of a simple number menu. I
understand that I need to import the Tkinter, create
and position the widgets, and enter the main loop
(Python in a nut shell). But I am still having
problems. I have attached the code I have to this
point. 

import shelve

s = shelve.open('d:/College/numberdata')

if s.has_key('numbers'):
    numbers = s['numbers']
else:
    numbers = {}

class AccountTransaction(object):
    def __init__(self, amount, time):
        self.amount = amount
        self.time = time

    def __repr__(self):
        description = time.ctime(self.time) + ' '
        if self.amount < 0:
            description += '-'
            description += '$' + str(abs(self.amount))
            return description
    def __init__(self, initial):
         self.balance = amount
 
while 1:
    print
    print
    print 'Show Me The Money'
    print '1. Deposite'
    print '2. Withdraw'
    print '3. Getbalance'
    print '9. Quit'
    print
    choice = int(raw_input('Enter your choice: '))

#   I added the exception line so that negartive
numbers woudl not be added.

    if choice == 1:
        amount = raw_input ('Amount: ')
    elif amount < 0:
        raise ValueError, 'Deposites must be positive'
    elif self.balance - amount < 0:
        raise ValueError, 'The account only holds $' +
str(self.balance)
        self._perform_transaction(-amount) 
        date = raw_input ('Date: ')
        numbers[amount] = date

# I added the exception line so that only positive
numbers woudl eb entered for withdraws. line so that 

    elif choice == 2:
        amount = raw_input ('Amount: ')
    if amount < 0:
        raise ValueError, 'Withdrawals must be
negative'
    elif self.balance - amount < 0:
        raise ValueError, 'The account only holds $' +
str(self.balance)
        self._perform_transaction(-amount)
        date = raw_input ('Date: ')
        numbers[amount] = date
        
    elif choice == 3:
        print
        for amount, date in numbers.items():
            print '%-20s : %-14s' % (amount, date)
    elif choice == 9:
        break
                
    else:
        print_menu()
        print "Goodbye"

class Account:
     def Deposit(self, amt):
         self.balance = self.balance + amt
     def Withdraw(self,amt):
         self.balance = self.balance - amt
     def getbalance(self):
         return self.balance
        
##save numbers when done
s['numbers'] = numbers

s.close()

__________________________________
Do you Yahoo!?
Yahoo! SiteBuilder - Free web site building tool. Try it!
http://webhosting.yahoo.com/ps/sb/

From carroll at tjc.com  Sat Jan 31 21:47:23 2004
From: carroll at tjc.com (Terry Carroll)
Date: Sat Jan 31 21:47:27 2004
Subject: =?utf-8?Q?Re:_=5BTutor=5D_Converting_string_or?=
	=?utf-8?Q?_list_to_sum?=
In-Reply-To: <E1An77Z-0005vy-AG@fuse1.fusemail.net>
Message-ID: <Pine.LNX.4.44.0401311843520.12657-100000@violet.rahul.net>

On Sat, 31 Jan 2004, Isr Gish wrote:

> When I try doing.
> map(str, a)
> I got a traceback 
> TypeError: 'str' object is not callable
> But when I do,
> map(__builtin__.str, a)
> It works fine.

did you rebind the variable name str elsewhere in your program, e.g.,

>>> a=['1','2','3']
>>> a
['1', '2', '3']
>>> d=''.join(map(str,a))
>>> d
'123'
>>> str="xyz"
>>> d=''.join(map(str,a))
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: 'str' object is not callable
>>>






From dana at momerath.us  Sat Jan 31 07:35:57 2004
From: dana at momerath.us (dana@momerath.us)
Date: Tue Feb  3 12:42:27 2004
Subject: [Tutor] (no subject)
Message-ID: <3119.63.225.172.24.1075552557.squirrel@mail.zoper.com>

From: Dana Baguley <dana@momerath.us>
To: tutor@python.org
Subject: HTMLParser
Date: Sat, 31 Jan 2004 04:37:18 -0800
User-Agent: KMail/1.5.4
MIME-Version: 1.0
Content-Type: text/plain;
  charset="us-ascii"
Content-Transfer-Encoding: 7bit
Content-Disposition: inline
Message-Id: <200401310437.18353.dana@momerath.us>
Status: RO
X-Status: Q
X-KMail-EncryptionState:
X-KMail-SignatureState:


Hello,

I'm new to python and pretty new to programming in general. As a first
project, I'm trying to write a program to pull data from tables on webpages.
I'm having trouble with the HTMLParser module. Below is my code and the error
message. I'm thinking I should be using the debugger for this, but I don't
have a clue where to start so I'm emailing the list instead. Thanks in
advance. Also, this is my first email to a list like this one, so I'm
wondering if I'm observing proper social conventions. This message feels kind
of long to me. What do you think?

Dana

#r.py
import HTMLParser
import urllib
import string

def getPage(address):
  page = urllib.urlopen(address)
  page = page.readlines()
  return page

def flattenPage(page):
    returned = ''
    for line in page:
        returned +=line
        returned += ' '
    for character in string.whitespace: # probably not necessary to zap
newlines.
      returned = string.replace(returned, character, ' ')
    return returned

def getFlatPage(URL):
    page = flattenPage(getPage(URL))
    return page

class InteractiveURLParser(HTMLParser.HTMLParser):
    def open(self, URL):
        page = getPage(URL)
        page = flattenPage(page)
        self.feed(page)
    def newURL(self, URL):
        __init__(self, URL)
    def handle_starttag(self, tag, attrs):
        print "tag is %s with attributes %s." %(self, tag, attrs)
    def handle_data(self, data):
        print data
--
>>> carrie = "http://www.plu.edu/~swarthcj"
>>> r.test(carrie)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "r.py", line 37, in test
    testInstance.open(URL)
  File "r.py", line 27, in open
    self.feed(page)
  File "/usr/lib/python2.3/HTMLParser.py", line 108, in feed
    self.goahead(0)
  File "/usr/lib/python2.3/HTMLParser.py", line 148, in goahead
    k = self.parse_starttag(i)
  File "/usr/lib/python2.3/HTMLParser.py", line 281, in parse_starttag
    self.handle_starttag(tag, attrs)
  File "r.py", line 31, in handle_starttag
    print "tag is %s with attributes %s." %(self, tag, attrs)
TypeError: not all arguments converted during string formatting

From thomi at thomi.imail.net.nz  Fri Jan 30 04:40:09 2004
From: thomi at thomi.imail.net.nz (Thomas Clive Richards)
Date: Tue Feb  3 12:43:19 2004
Subject: [Tutor] special call for deleted objects?
In-Reply-To: <00f201c3e70b$63fa7240$6401a8c0@xp>
References: <200401301333.23303.thomi@thomi.imail.net.nz>
	<00f201c3e70b$63fa7240$6401a8c0@xp>
Message-ID: <200401302240.09010.thomi@thomi.imail.net.nz>

>
> I seem to recall there is a __del__ method you can add to your class.
>
> It doesn't get called until the class is actually garbage collected
> however so the behaviour is a little unpredictable.

Ahh, right.

I guess I'll go with my original plan...

BTW, where can I find this information? Am I missing some documentation 
somewhere? (I'm looking in the documentation distributed with python2.3)...

-- 

Thomi Richards,
thomi@once.net.nz