From rustynewton@comcast.net Wed Jan 1 11:32:02 2003 From: rustynewton@comcast.net (Rusty Newton) Date: Wed Jan 1 11:32:02 2003 Subject: [Tutor] ansi color coding Message-ID: <000c01c2b1c2$ac670680$6401a8c0@huntsv01.al.comcast.net> This is a multi-part message in MIME format. --Boundary_(ID_vw8OjXmBV8xbMgxxACsBww) Content-type: text/plain; charset=iso-8859-1 Content-transfer-encoding: 7BIT Hey guys! Does anyone know anything about how to implement ansi color codes in python using socket programming? Thanks, Rusty --Boundary_(ID_vw8OjXmBV8xbMgxxACsBww) Content-type: text/html; charset=iso-8859-1 Content-transfer-encoding: 7BIT
Hey guys!
 
Does anyone know anything about how to implement ansi color codes in python
using socket programming?
 
Thanks, Rusty
--Boundary_(ID_vw8OjXmBV8xbMgxxACsBww)-- From ramrom@earthling.net Wed Jan 1 13:01:01 2003 From: ramrom@earthling.net (Bob Gailer) Date: Wed Jan 1 13:01:01 2003 Subject: [Tutor] ansi color coding In-Reply-To: <000c01c2b1c2$ac670680$6401a8c0@huntsv01.al.comcast.net> Message-ID: <5.2.0.9.0.20030101105947.02c31308@66.28.54.253> --=======230059DA======= Content-Type: multipart/alternative; x-avg-checked=avg-ok-43CC47F3; boundary="=====================_13521272==.ALT" --=====================_13521272==.ALT Content-Type: text/plain; x-avg-checked=avg-ok-43CC47F3; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 10:21 AM 1/1/2003 -0800, Rusty Newton wrote: >Does anyone know anything about how to implement ansi color codes in python >using socket programming? Question is a bit vague for me. Sockets have nothing to do with colors. Can you expand on what you're trying to do? Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=====================_13521272==.ALT Content-Type: text/html; x-avg-checked=avg-ok-43CC47F3; charset=us-ascii Content-Transfer-Encoding: 8bit At 10:21 AM 1/1/2003 -0800, Rusty Newton wrote:
Does anyone know anything about how to implement ansi color codes in python
using socket programming?

Question is a bit vague for me. Sockets have nothing to do with colors. Can you expand on what you're trying to do?

Bob Gailer
mailto:ramrom@earthling.net
303 442 2625
--=====================_13521272==.ALT-- --=======230059DA======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-43CC47F3 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.431 / Virus Database: 242 - Release Date: 12/17/2002 --=======230059DA=======-- From charlie@begeistert.org Wed Jan 1 13:31:01 2003 From: charlie@begeistert.org (Charlie Clark) Date: Wed Jan 1 13:31:01 2003 Subject: [Tutor] Re: Tutor digest, Vol 1 #2152 - 10 msgs In-Reply-To: <20021231170005.1744.86884.Mailman@mail.python.org> References: <20021231170005.1744.86884.Mailman@mail.python.org> Message-ID: <20030101193340.665.1@.1041443986.fake> On 2002-12-31 at 18:00:05 [+0100], tutor@python.org wrote: > shobhan wrote:Hi Pythoners, > > Can anyone tell me how to connect to Oracle DB using Python and dump the > data from a table called "logs" into a text file in CSV format..? The > text file thus created should be of the format (2002-12-30-logs.txt). It > would be fine if anyone can show a sample script. > > Thanks in advance > Schalla Hi Schalla, Az has already basically covered this already but his pseudo-code isn't really Python. The DB-API is documented at http://www.python.org/peps/pep-0249.html but you might not find that too helpful. but http://www.amk.ca/python/writing/DB-API.html is quite good. There is a special interest group with mailing list you might want to look at http://www.python.org/sigs/db-sig/ Embedding SQL in Python is quite easy once you've got the hang of it. Before you go any further you will need the appropriate Python driver for the Oracle database or mxODBC if the database is available via ODBC. As Az said, you need to connect to the database. I've never heard of this as a URL, it's called a connection object in Python. You then use your connection object to do everything for you. Your actual code will then look a bit like this: import oracledb # change to use the real driver f_out =3D open("text_file.csv", "w") # the next line must be changed db =3D oracledb.oracledb('the_database', 'schalla', 'secret_word') cursor =3D db.cursor() cursor.execute('SELECT * from logs') while (1): =09record =3D cursor.fetchone() =09if not record: =09=09break # we must have all the records =09line =3D "|".join(record) # replace "|" with whatever symbol you want to =09f_out.write(line) f_out.close() db.commit() db.close() Hope that helps! Seasons greetings from a miserable and wet Germany Charlie From ahimsa@onetel.net.uk Wed Jan 1 15:43:01 2003 From: ahimsa@onetel.net.uk (ahimsa) Date: Wed Jan 1 15:43:01 2003 Subject: [Tutor] Tkinter and IDLE2.2 In-Reply-To: <20030101170005.29667.7092.Mailman@mail.python.org> References: <20030101170005.29667.7092.Mailman@mail.python.org> Message-ID: <1041453804.4672.75.camel@localhost.localdomain> On Wed, 2003-01-01 at 17:00, Danny and Thomas from the tutor-request@python.org wrote: > Message: 3 > Date: Tue, 31 Dec 2002 10:52:42 -0800 (PST) > From: Danny Yoo > To: ahimsa > cc: tutor@python.org > Subject: Re: [Tutor] idle or lack thereof ... > Ah, I see. It looks like you're using a locally-compiled version of > Python. You may want to check if you have a library called "Tcl/Tk" > installed on your system. The _tkinter module is an extension that makes > Tcl/Tk graphics libraries available to Python, and that error message is > saying that it can't find the graphics library. Tkinter is a graphics > toolkit library that it uses to display the windows of IDLE, so that's why > it's a prerequisite. > > > You'll want to look to see if the 'development' stuff for Tcl/Tk is > installed with your system. On a Debian Linux system, for example, the > package 'tk8.3-dev' is the one you'll want to install. Once you've found > and installed the development packages, a recompile of Python should > autodetect the graphics library. > > I'm only guessing that you're using a Linux though; what kind of Unix > distribution are you using? > > > Good luck to you! > and > Message: 9 > From: Thomas Rivas > Reply-To: trivas7@rawbw.com > To: tutor@python.org > Subject: Re: [Tutor] idle or lack thereof > Date: Tue, 31 Dec 2002 16:40:37 -0800 > > Looking at the last line in your traceback("import Error: No module named > _tkinter") I suspect you don't have the tk and tcl libraries on your system. > Under KPackage on Mandrake 9.0 tk is installed as an rpm (Red Hat Package > Manager) package under the libraries section described as "Tk GUI toolkit > for Tcl" (which is also installed in the same libraries section as tcl), and > " a X Windows widget set designed to work closely with the tcl scripting > language." IDLE comes with the Python installation; I invoke it by typing > "idle" at the command line (well, actually I use the Python-headed icon I put > on my KDE panel) Make sure you have these two libraries installed on your > system. > > Thomas Rivas Thanks to you both for attending to this. Y'know the funny - and confusing - thing for me about this is that I can invoke IDLE and it runs Python 2.2c1 and I can do that from either the command line (typing IDLE2.2) or from a launcher that I have added to my gnome panel. Reason would suggest that if I can do it once then I should be able to call it up for python2.2.2 - but that is where the problems are. I obviously have the Tkinter library(libraries), but the latest version of python doesn't recognise them. Any ideas? AmF -- ahimsa From dyoo@hkn.eecs.berkeley.edu Wed Jan 1 15:57:06 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Jan 1 15:57:06 2003 Subject: [Tutor] Tkinter and IDLE2.2 In-Reply-To: <1041453804.4672.75.camel@localhost.localdomain> Message-ID: > Thanks to you both for attending to this. Y'know the funny - and > confusing - thing for me about this is that I can invoke IDLE and it > runs Python 2.2c1 and I can do that from either the command line (typing > IDLE2.2) or from a launcher that I have added to my gnome panel. Different versions of Python try not to step on each others toes by keeping their libraries in separate directories. > Reason would suggest that if I can do it once then I should be able to > call it up for python2.2.2 - but that is where the problems are. I > obviously have the Tkinter library(libraries), Ah, but most libraries are split up into two separate parts: there's a "functional" part that actually does the work of the library, and then there's a "development" part that's used only by programmers or for people who compile their own software. Development packages typically include things like C header "include" files, if you're familiar with C. (By the way, you'll typically find development header stuff in the directory '/usr/include' on many Unix systems.) Linux distributions typically place these into separate packages for space-saving reasons. (Actually, I've noticed that the latest Red Hat Linux versions don't appear to do this anymore.) I think what's going on is that you do have the libraries, but not the development add-ons that Python needs to work with Tk. Can you tell us what Unix distribution you're using? We can probably pinpoint good instructions for setting up the development libraries, but we really need more information about your system. From ahimsa@onetel.net.uk Wed Jan 1 16:00:05 2003 From: ahimsa@onetel.net.uk (ahimsa) Date: Wed Jan 1 16:00:05 2003 Subject: [Tutor] Tkinter Message-ID: <1041454864.5082.78.camel@localhost.localdomain> Hello all I'm using Linux Redhat 8.0 on an AMDk6-2 i586 HtH -- ahimsa From dyoo@hkn.eecs.berkeley.edu Wed Jan 1 16:32:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Jan 1 16:32:01 2003 Subject: [Tutor] Subclasses? [boring languages/robocode] In-Reply-To: <000701c2b110$c6530d80$58120dd5@violante> Message-ID: > > > Guido van Rossum asked for a real use-case for inner classes. > > > > Don't know the thread and am no Java expert but aren't inner classes > > the only way to fake lambas in Java? > > I'm not a Java expert either (thank God!) and it's been a long time > since I last touched it (thank you, thank you, Lord!) but yes, that is a > way to view them. Since the inner class is automatically connected with > the outer class and can steer it you can use them to fake closures and > stuff like that. > > > Stoopid language! :-) > > No disagreements here. And boring as hell! Hello! Although Java's a bit of a submission-and-bondage language, that has not stopped people from writing interesting and fun software with it. I feel that a language can be as fun as the software that's written in it. By that measurement, Java's doing pretty well. For example: http://robocode.alphaworks.ibm.com/home/home.html http://www-106.ibm.com/developerworks/java/library/j-robocode/ provides code to learn Java by using robot battle simulations. And that's pretty impressive! I guess I'm just trying to say that the syntax and language can be deceptively superficial. I'll take the radical point of view that it's the programs and the community around a language, and not the language itself, that makes a language fun to learn and use. So let's concentrate on writing fun programs so that we can attract that good talent away from the lesser languages out there. *grin* Happy New Year! From jtk@yahoo.com Wed Jan 1 19:30:03 2003 From: jtk@yahoo.com (Jeff Kowalczyk) Date: Wed Jan 1 19:30:03 2003 Subject: [Tutor] modifying list of strings during iteration (without index)? Message-ID: I'm mortified that I don't know the answer to this: What technique is used when you want to iterate over a list of strings (or other items) and reassign/modify the iteration element in place (i.e without making a copy or new list)? I'm trying not to stray into lambda/map territory for this particular piece of code, I want to see how its done with an ordinary iteration first. li = ['SELECT string 1' ,' string2', ' string3'] >>> for item in li: ... item.strip() (or ) >>> for item in li: ... item = item.strip() For the moment, I'm just assigning to a new list... Thanks. From BranimirP@cpas.com Wed Jan 1 19:32:04 2003 From: BranimirP@cpas.com (Branimir Petrovic) Date: Wed Jan 1 19:32:04 2003 Subject: [Tutor] How to log on to web site using Python? Message-ID: <33678E78A2DD4D418396703A750048D41A6381@RIKER> """I'd really appreciate if someone could help me get this 'exercise' straightened.... I am trying to produce Python script to monitor 'health' of one internal web site. Idea is to periodically request a page and time how long it takes to get it. Should it become unacceptably long, I might want to learn about it (via automated mailing), or I might even dare to empower the script to just re-boot the server. Site in question is running Java Servlets (via ServletExec) on IIS 5. For variety of reasons, this unhappy combo (Servlets on IIS) is here to stay, therefore I must find a way to automate logging on to figure out if the site is 'still there', or it needs life restoring 'reboot slap'. Normally - site requires authentication and needs browser with cookies enabled. May be my problem has to do with cookies, may be not... Here is the critical part: """ import urllib, time logonPage = 'http://myURL/servlet/Logon' validUser = 'http://myURL/servlet/FindUser' def urlOpener(url, data=None): if isinstance(data, dict): data = urllib.urlencode(data) urlObj = urllib.urlopen(url, data) return urlObj.read() # This particular web page does not require authentication # but contains log on form: tStart = time.time() page = urlOpener(logonPage) tStop = time.time() print 'Tdld = %4.2f Sec\n\n' % (tStop - tStart) print page # Web page is fetched (as it should) and printed output looks somewhat like: """ Tdld = 0.24 Sec Logon ...

... ... """ # Now I'll try to POST log on info and this is the problematic part: tStart = time.time() page = urlOpener(validUser, {'pin': 'myUsrID', 'password': 'myPWD'}) tStop = time.time() print 'Tdld = %4.2f Sec\n\n' % (tStop - tStart) print page # Printed output always - regardless of user credential used - looks like: """ Tdld = 0.66 Sec Base """ # Should I try accessing the page *without* posting anything like: tStart = time.time() page = urlOpener(validUser) tStop = time.time() print 'Tdld = %4.2f Sec\n\n' % (tStop - tStart) print page # the output will be: """ Tdld = 0.11 Sec CQ_Base """ """ Much shorter Tdld in this case indicates log on faliure, but I'd much rather get the actual page, parse it and based on this draw my own conclusions if the log on attempt was successfull or not... Why is fetched page basically empty even when proper user ID and password combo is used? Aparently I have it all wrong, but what are my mistakes? Thanks, Branimir """ From ramrom@earthling.net Wed Jan 1 19:38:02 2003 From: ramrom@earthling.net (Bob Gailer) Date: Wed Jan 1 19:38:02 2003 Subject: [Tutor] modifying list of strings during iteration (without index)? In-Reply-To: Message-ID: <5.2.0.9.0.20030101173320.02c26fa8@66.28.54.253> --=======EEB66A1======= Content-Type: text/plain; x-avg-checked=avg-ok-43CC47F3; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 07:27 PM 1/1/2003 -0500, Jeff Kowalczyk wrote: >What technique is used when you want to iterate over a list of strings (or >other items) and reassign/modify the iteration >element in place (i.e without making a copy or new list)? > >li = ['SELECT string 1' ,' string2', ' string3'] li = [item.strip() for item in li] # the easiest, but it does create a new list. To replace in site: for i in range(len(li)): li[i] = li[i].strip() Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======EEB66A1======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-43CC47F3 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.431 / Virus Database: 242 - Release Date: 12/17/2002 --=======EEB66A1=======-- From Adam Vardy Wed Jan 1 19:41:02 2003 From: Adam Vardy (Adam Vardy) Date: Wed Jan 1 19:41:02 2003 Subject: [Tutor] Tkinter In-Reply-To: <1041454864.5082.78.camel@localhost.localdomain> References: <1041454864.5082.78.camel@localhost.localdomain> Message-ID: <1852881359.20030101211021@roadrunner.nf.net> Allan, in your GUI introduction, I came to the part about setting the Relief property. But this had no effect on the window. -- Adam Vardy From jtk@yahoo.com Wed Jan 1 20:06:12 2003 From: jtk@yahoo.com (Jeff Kowalczyk) Date: Wed Jan 1 20:06:12 2003 Subject: [Tutor] Re: modifying list of strings during iteration (without index)? References: <5.2.0.9.0.20030101173320.02c26fa8@66.28.54.253> Message-ID: "Bob Gailer" wrote: > To replace in site: > for i in range(len(li)): > li[i] = li[i].strip() [jtk] Ah, hence the enumerate function due in 2.3... Thanks. PEP 279: The enumerate() Built-in Function A new built-in function, enumerate(), will make certain loops a bit clearer. enumerate(thing), where thing is either an iterator or a sequence, returns a iterator that will return (0, thing[0]), (1, thing[1]), (2, thing[2]), and so forth. Fairly often you'll see code to change every element of a list that looks like this: for i in range(len(L)): item = L[i] # ... compute some result based on item ... L[i] = result This can be rewritten using enumerate() as: for i, item in enumerate(L): # ... compute some result based on item ... L[i] = result From max@provico.fi Thu Jan 2 01:16:01 2003 From: max@provico.fi (Max Romantschuk) Date: Thu Jan 2 01:16:01 2003 Subject: [Tutor] Implementation Help Request on Game of Life Message-ID: <1041488103.3e13d8e751a66@webmail.nma.fi> Hello everyone, I'm a programming professional, but a Python novice. Thus I've decided to implement Conway's Game of Life in Python in order to learn more. I've want to encapsulate the actual logic in a Python class called PlayField. It is the two-dimensional matrix in which the game's cells live. I'would also like the PlayField to work much like a list, so that I could fetch a cell like this: spam = PlayField(10,10) # rows, colums print spam[1][2].state # cell on row 1 column 2, 'alive' for example print spam[1][2].liveNeighbors # uses getattr to calculate the number I would have no problem doing this with a one-dimensional list, but how do I do this with a two-dimensional one? I guess it can be done, but I can't get my head around how to go about it. The thing is I'd like the PlayField class to encapsulate the 2d list of cells and all the nasty logic, so you could get data without thinking about how it works, as shown above. Thanks, Max Romantschuk http://www.mp3.com/romax/ From schalla@vasoftware.com Thu Jan 2 02:41:01 2003 From: schalla@vasoftware.com (shobhan) Date: Thu Jan 2 02:41:01 2003 Subject: [Tutor] How can i print data from CLOB field..? References: <5.2.0.9.0.20021231105230.01a0bb70@66.28.54.253> Message-ID: <3E13EBF0.40701@vasoftware.com> --------------020302090305060101000101 Content-Type: text/plain; charset=us-ascii; format=flowed Content-Transfer-Encoding: 7bit Hi Pythoners, I have some problem with the script i've written here: #!/usr/bin/python import os import sys import string dbapi = __import__('cx_Oracle') import sql_utils import commands dbh = dbapi.connect("scott/tiger@mydb") dbc = dbh.cursor() dbc.execute("SELECT entry_id, span_id, start_time, depth, severity, message_type, message, ref_message FROM log_entries") for row in dbc.fetchall(): print int(row[0]), int(row[1]), int(row[2]), int(row[3]), int(row[4]), int(row[5]), row[6], row[7] print "\n\n" dbc.close() Here the "message" and "ref_message" are of tyoe CLOB in the oracle DB. When i execute the above script its printing the data as follows: 8189 1363 1035744241 0 4 0 Can anyone tell me how to printout the data from the CLOB column..in the above script...?? Thanks in advance Schalla Bob Gailer wrote: > At 03:08 PM 12/31/2002 +0530, shobhan wrote: > >> Can anyone tell me how to connect to Oracle DB using Python and dump >> the data from a table called "logs" into a text file in CSV format..? > > > I suggest using cx_oracle (http://www.computronix.com/utilities.shtml ). > > import cx_Oracle > conn = cx_Oracle.connect(xxx/yyy@zzz) > c = conn.cursor() > c.execute('select 1,2, 3 from dual') > l = c.fetchall() > # now you have a list of tuples, one tuple per row. > > There have been several discussions on this list regarding modules for > csv files. I have not tried it, but look at > http://tratt.net/laurie/python/asv/ . "ASV is a platform independent > Python module to input, manipulate and output `simple' database > storage file formats such as CSV (Comma Seperated Value) ....". I do > not take credit for spelling here! > > Bob Gailer > mailto:ramrom@earthling.net > 303 442 2625 > > >------------------------------------------------------------------------ > > >--- >Outgoing mail is certified Virus Free. >Checked by AVG anti-virus system (http://www.grisoft.com). >Version: 6.0.431 / Virus Database: 242 - Release Date: 12/17/2002 > --------------020302090305060101000101 Content-Type: text/html; charset=us-ascii Content-Transfer-Encoding: 7bit Hi Pythoners,

I have some problem with the script i've written here:

#!/usr/bin/python
import os
import sys
import string
dbapi = __import__('cx_Oracle')
import sql_utils
import commands
dbh = dbapi.connect("scott/tiger@mydb")
dbc = dbh.cursor()


dbc.execute("SELECT entry_id, span_id, start_time, depth, severity, message_type, message, ref_message FROM log_entries")

for row in dbc.fetchall():
        print int(row[0]), int(row[1]), int(row[2]), int(row[3]), int(row[4]), int(row[5]), row[6], row[7]
        print "\n\n"
dbc.close()

Here the "message" and "ref_message" are of tyoe CLOB in the oracle DB.
When i execute the above script its printing the data as follows:

    8189 1363 1035744241 0 4 0 <ExternalLobVar object at 0x82d98c8> <ExternalLobVar object at 0x82d98e0>

Can anyone tell me how to printout the data from the CLOB column..in the above script...??

Thanks in advance
Schalla



Bob Gailer wrote:
At 03:08 PM 12/31/2002 +0530, shobhan wrote:
Can anyone tell me how to connect to Oracle DB using Python and dump the data from a table called "logs" into a text file in CSV format..?

I suggest using cx_oracle (http://www.computronix.com/utilities.shtml ).

import cx_Oracle 
conn = cx_Oracle.connect(xxx/yyy@zzz)
c = conn.cursor()
c.execute('select 1,2, 3 from dual')
l = c.fetchall()
# now you have a list of tuples, one tuple per row.

There have been several discussions on this list regarding modules for csv files. I have not tried it, but look at http://tratt.net/laurie/python/asv/ . "ASV is a platform independent Python module to input, manipulate and output `simple' database storage file formats such as CSV (Comma Seperated Value) ....". I do not take credit for spelling here!

Bob Gailer
mailto:ramrom@earthling.net
303 442 2625





---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.431 / Virus Database: 242 - Release Date: 12/17/2002


--------------020302090305060101000101-- From thomi@thomi.imail.net.nz Thu Jan 2 03:36:01 2003 From: thomi@thomi.imail.net.nz (Thomi Richards) Date: Thu Jan 2 03:36:01 2003 Subject: [Tutor] medians Message-ID: <20030102212940.22bcd5ab.thomi@thomi.imail.net.nz> I think I'm missing something in the manual, but: what's the easiest way to find the median from a list of numbers? I'm sure there is something really obvious, but I'm too tired to think right now, thanks. -- Thomi Richards thomi@imail.net.nz http://thomi.imail.net.nz/ Thomi Richards, thomi@imail.net.nz From schalla@vasoftware.com Thu Jan 2 04:25:02 2003 From: schalla@vasoftware.com (shobhan) Date: Thu Jan 2 04:25:02 2003 Subject: [Tutor] How can i print data from CLOB field..? References: <5.2.0.9.0.20021231105230.01a0bb70@66.28.54.253> <3E13EBF0.40701@vasoftware.com> Message-ID: <3E140453.1020808@vasoftware.com> Sorry guys,

I've figured out how to print the data from CLOB column in Oracle
Its dbms.lob_substr()

Schalla

shobhan wrote:
Hi Pythoners,

I have some problem with the script i've written here:

#!/usr/bin/python
import os
import sys
import string
dbapi = __import__('cx_Oracle')
import sql_utils
import commands
dbh = dbapi.connect("scott/tiger@mydb")
dbc = dbh.cursor()


dbc.execute("SELECT entry_id, span_id, start_time, depth, severity, message_type, message, ref_message FROM log_entries")

for row in dbc.fetchall():
        print int(row[0]), int(row[1]), int(row[2]), int(row[3]), int(row[4]), int(row[5]), row[6], row[7]
        print "\n\n"
dbc.close()

Here the "message" and "ref_message" are of tyoe CLOB in the oracle DB.
When i execute the above script its printing the data as follows:

    8189 1363 1035744241 0 4 0 <ExternalLobVar object at 0x82d98c8> <ExternalLobVar object at 0x82d98e0>

Can anyone tell me how to printout the data from the CLOB column..in the above script...??

Thanks in advance
Schalla



Bob Gailer wrote:
At 03:08 PM 12/31/2002 +0530, shobhan wrote:
Can anyone tell me how to connect to Oracle DB using Python and dump the data from a table called "logs" into a text file in CSV format..?

I suggest using cx_oracle (http://www.computronix.com/utilities.shtml ).

import cx_Oracle 
conn = cx_Oracle.connect(xxx/yyy@zzz)
c = conn.cursor()
c.execute('select 1,2, 3 from dual')
l = c.fetchall()
# now you have a list of tuples, one tuple per row.

There have been several discussions on this list regarding modules for csv files. I have not tried it, but look at http://tratt.net/laurie/python/asv/ . "ASV is a platform independent Python module to input, manipulate and output `simple' database storage file formats such as CSV (Comma Seperated Value) ....". I do not take credit for spelling here!

Bob Gailer
mailto:ramrom@earthling.net
303 442 2625





---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.431 / Virus Database: 242 - Release Date: 12/17/2002




From janos.juhasz@VELUX.com Thu Jan 2 05:50:01 2003 From: janos.juhasz@VELUX.com (janos.juhasz@VELUX.com) Date: Thu Jan 2 05:50:01 2003 Subject: [Tutor] pyLPD Message-ID: Dear Alan! Ok, I can redirect the LPT1: to LPT2: on this way, but where can I plac= e the filter ? With LPD i can pump the data across a filter, but how can I do it with = the MODE ? Best regards, ----------------------- Juh=E1sz J=E1nos IT department Alan wrote>> > I wanted to working with LPT1: on windows, but it seems to > bee impossible. > Simply I can't capture the stream sent to it. Have you checked the MODE command? Its DOS but works even in W2K etc...= Heres the /? output: ----------------------------------------------------- C:\>mode /? Configures system devices. Serial port: MODE COMm[:] [BAUD=3Db] [PARITY=3Dp] [DATA=3Dd] [STO= P=3Ds] [to=3Don|off] [xon=3Don|off] [odsr=3Don= |off] [octs=3Don|off] [dtr=3Don|off|hs] [rts=3Don|off|hs|tg] [idsr=3Don|off] Device Status: MODE [device] [/STATUS] Redirect printing: MODE LPTn[:]=3DCOMm[:] Select code page: MODE CON[:] CP SELECT=3Dyyy Code page status: MODE CON[:] CP [/STATUS] Display mode: MODE CON[:] [COLS=3Dc] [LINES=3Dn] Typematic rate: MODE CON[:] [RATE=3Dr DELAY=3Dd] ---------------------------------------------------- Note the bit about redirecting LPTn.... HTH, Alan g. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor = From Janssen@rz.uni-frankfurt.de Thu Jan 2 05:59:02 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Thu Jan 2 05:59:02 2003 Subject: [Tutor] Implementation Help Request on Game of Life In-Reply-To: <1041488103.3e13d8e751a66@webmail.nma.fi> Message-ID: On Thu, 2 Jan 2003, Max Romantschuk wrote: > I'would also like the PlayField to work much like a list, so that I could fetch > a cell like this: > > spam = PlayField(10,10) # rows, colums > print spam[1][2].state # cell on row 1 column 2, 'alive' for example > print spam[1][2].liveNeighbors # uses getattr to calculate the number the first [1] asks for the __getitem__ operator of the PlayField class and returns, whatever __getitem__ returns (in this case a "row": a python list). The next [2] asks for the __getitem__ operator from the previosly returned list and the list returns the value at index 2. In the terms of this game it returns a cell. state() must be a method of a cell object you need to define. a longform of print spam[1][2].state() would be: row = spam.__getitem__(1) cell = row.__getitem__(2) print cell.state() Ergo: you can't put all the logic into one class (when you want to write spam[1][2].state() instead of spam.state(1,2) ). You need a PlayField class (which contains the methods to manipulate the entire playground), a row class (which can be done with a python list) and a SingleField class with the methods of a single cell: class PlayField: def __init__(self, rows, cols): self.playfield = [[SingleField()]*cols]*rows def __getitem__(self, index): return self.playfield[index] class SingleField: def state(self): return "42" what's this Game of Life is about? Michael > > I would have no problem doing this with a one-dimensional list, but how do I do > this with a two-dimensional one? I guess it can be done, but I can't get my > head around how to go about it. The thing is I'd like the PlayField class to > encapsulate the 2d list of cells and all the nasty logic, so you could get data > without thinking about how it works, as shown above. > > > Thanks, > Max Romantschuk > http://www.mp3.com/romax/ > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From Janssen@rz.uni-frankfurt.de Thu Jan 2 06:09:01 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Thu Jan 2 06:09:01 2003 Subject: [Tutor] medians In-Reply-To: <20030102212940.22bcd5ab.thomi@thomi.imail.net.nz> Message-ID: On Thu, 2 Jan 2003, Thomi Richards wrote: > > I think I'm missing something in the manual, but: > > what's the easiest way to find the median from a list of numbers? I'm > sure there is something really obvious, but I'm too tired to think right > now, I don't believe there is a special function in the library for this little task. Well, the median is (if I remember correctly) the value of the index in the middle postion of a sorted list. list_of_numbers.sort() # sort in place.. median = list_of_numbers[(len(list_of_numbers)-1)/ 2 ] would do it. Michael > > thanks. > > -- > Thomi Richards > thomi@imail.net.nz > http://thomi.imail.net.nz/ > Thomi Richards, > thomi@imail.net.nz > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From max@provico.fi Thu Jan 2 07:50:05 2003 From: max@provico.fi (Max Romantschuk) Date: Thu Jan 2 07:50:05 2003 Subject: [Tutor] Implementation Help Request on Game of Life In-Reply-To: References: Message-ID: <1041511750.3e143546a4892@webmail.nma.fi> Quoting Michael Janssen : > You need a PlayField class (which contains the methods to manipulate the > entire playground), a row class (which can be done with a python list) and > a SingleField class with the methods of a single cell: Thanks :) Actually, I already had a PlayField containing Cells, so Rows are a logical addition... it all seems to make sense now ;) > what's this Game of Life is about? It's too vast a subject to explain here, but this looks like a good introduction: http://www.math.com/students/wonders/life/life.html Also just google and you'll find all sorts of stuff: http://www.google.com/search?sourceid=navclient&q=conway+life Thanks for the help! Max Romantschuk http://www.mp3.com/romax/ From Volker Hoffmann Thu Jan 2 10:02:04 2003 From: Volker Hoffmann (Volker Hoffmann) Date: Thu Jan 2 10:02:04 2003 Subject: Re[2]: [Tutor] Declare empty string variable? In-Reply-To: <5.2.0.9.0.20021230102656.02bf9320@66.28.54.253> References: <174475595.20021229115134@omega-fleet.dyndns.org> <5.2.0.9.0.20021230102656.02bf9320@66.28.54.253> Message-ID: <4463671785.20030102143029@omega-fleet.dyndns.org> Hi! Quote - 30.12.2002, 18:53, ramrom@earthling.net: > Observations: > this program does not reassign to deci; therefore it is an endless > loop. while deci>0: can just be while deci: There actually was an additional line that reassigned deci somewhere in the whole lot of 6 lines of code :). Thanks for the hint with >0, seems to me that Python really is interesting. > Try this: > dual = '' > deci = input("Decimal? --> ") > while deci: > deci,b = divmod(deci,2) > dual=str(b)+dual > print dual I think I got it now. Thanks very much again to you and to Gonçalo, too, of course :). On the bottom line, it all came down to str(b) that I needed. - Volker -- "When the future hinges on the next words that are said, don't let logic interfere, believe your heart instead." - Philip Robison From glingl@aon.at Thu Jan 2 10:53:01 2003 From: glingl@aon.at (Gregor Lingl) Date: Thu Jan 2 10:53:01 2003 Subject: [Tutor] Implementation Help Request on Game of Life References: <1041488103.3e13d8e751a66@webmail.nma.fi> Message-ID: <3E14604A.2080106@aon.at> Hi Max! About half a year ago I wrote a version of the game of life, the code of which you can find here: http://mail.python.org/pipermail/tutor/2002-July/015528.html The user can choose between two "playfields", a flat one (programmed with Tkinter) and one on a torus (programmed with VPython). (Then I was interested to learn how to let the lifegame-machine work on two different user-interfaces.) I had hoped, that Rob Andrews had put it on his useless site, but I couldn't find it there. :-( Unfortunatly in the above mentioned posting in the archives, the code is broken by several linebreaks. In contrast to your design, I used a dictionary with keys of the form (i,j) to acces the cells of the playfield. If you are interested, I could send you the code (off-list) as a *.py - file to try it out. (I hope I can find it on my harddisk!) Regards Gregor Max Romantschuk schrieb: >Hello everyone, > >I'm a programming professional, but a Python novice. Thus I've decided to >implement Conway's Game of Life in Python in order to learn more. > >I've want to encapsulate the actual logic in a Python class called PlayField. >It is the two-dimensional matrix in which the game's cells live. > >I'would also like the PlayField to work much like a list, so that I could fetch >a cell like this: > >spam = PlayField(10,10) # rows, colums >print spam[1][2].state # cell on row 1 column 2, 'alive' for example >print spam[1][2].liveNeighbors # uses getattr to calculate the number > >I would have no problem doing this with a one-dimensional list, but how do I do >this with a two-dimensional one? I guess it can be done, but I can't get my >head around how to go about it. The thing is I'd like the PlayField class to >encapsulate the 2d list of cells and all the nasty logic, so you could get data >without thinking about how it works, as shown above. > > > Thanks, >Max Romantschuk >http://www.mp3.com/romax/ > > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From dyoo@hkn.eecs.berkeley.edu Thu Jan 2 11:57:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Jan 2 11:57:01 2003 Subject: [Tutor] Implementation Help Request on Game of Life In-Reply-To: <1041488103.3e13d8e751a66@webmail.nma.fi> Message-ID: On Thu, 2 Jan 2003, Max Romantschuk wrote: > I'm a programming professional, but a Python novice. Thus I've decided > to implement Conway's Game of Life in Python in order to learn more. > > I've want to encapsulate the actual logic in a Python class called > PlayField. It is the two-dimensional matrix in which the game's cells > live. > > I'would also like the PlayField to work much like a list, so that I > could fetch a cell like this: > > spam = PlayField(10,10) # rows, colums > print spam[1][2].state # cell on row 1 column 2, 'alive' for example > print spam[1][2].liveNeighbors # uses getattr to calculate the number It might be good to abstract the PlayField so that it's not necessarily defined by a list of lists. That is, if you allow people to access it like this: ### spam = PlayField(10,10) print spam.state(1,2) print spam.liveNeighbors(1,2) ### where state() and liveNeighbors() are now methods of the class, then it might be easier to return a list of liveNeighbors to point 1,2 this way. The way we have it now, print spam[1][2].liveNeighbors is slightly complicated because Python will split this up into a few subexpressions, where the subexpression will need to remember something about the previous subexpression. Internally, this looks something like: t = spam[1] t2 = t[2] t3 = t2.liveNeighbors 't' will be some object that keeps track of which 'Row', we want, and 't2' keeps track of both 'Row' and 'Column'. The first two subexpressions might involve writing a __getitem__() to support indexing, and the third might involve the __getattr__(). The function approach is less complicated, since a function call like: spam.liveNeighbors(1,2) has all the information it'll need, all in the same place. But let's see how far we can go by trying it both ways. *grin* > I would have no problem doing this with a one-dimensional list, but how > do I do this with a two-dimensional one? I guess it can be done, but I > can't get my head around how to go about it. Here's one way to approach this: the following classes should allow you to do spam[1][2].state and spam[1][2].liveNeighbors... just as long as Playfield.state() and Playfield.liveNeighbors() are defined. For convenience, I've omitted their definitions. *grin* ### class Playfield: def __init__(self, rows, cols): self.rows, self.cols = rows, cols def __getitem__(self, i): """Returns a 'Row' object that allows us to do later queries where the Row is fixed.""" return Row(self, i) def state(self, i, j): """Returns the current state of the playfield at coordinate (i,j).""" return "fixme! I am state()." ## fixme def liveNeighbors(self, i, j): """Returns a list of all live neighbors to coordinate (i,j).""" return "fixme! I am liveNeighbors()." ## fixme class Row: def __init__(self, play_field, row_index): self.play_field, self.index = play_field, row_index def __getitem__(self, column_index): """Returns an 'Element' that represents a single element of the playfield.""" return Element(self.play_field, self.index, column_index) class Element: def __init__(self, play_field, row_index, column_index): self.play_field = play_field self.r, self.c = row_index, column_index def __getattr__(self, attr): ## Todo: make this "data-directed" so that we don't have to ## keep writing a bunch of if/elif statements if attr == 'state': return self.play_field.state(self.r, self.c) elif attr == 'liveNeighbors': return self.play_field.liveNeighbors(self.r, self.c) else: raise AttributeError, \ ("Element instance has no such attribute %s" % attr) ### The code is incomplete, but I hope it gives some ideas on how to approach this. I hope this helps! From Don Arnold" Message-ID: <08d901c2b27f$f3b17800$8510ba3f@defaultcomp> > On Thu, 2 Jan 2003, Thomi Richards wrote: > > > > > I think I'm missing something in the manual, but: > > > > what's the easiest way to find the median from a list of numbers? I'm > > sure there is something really obvious, but I'm too tired to think right > > now, > > I don't believe there is a special function in the library for this little > task. Well, the median is (if I remember correctly) the value of the index > in the middle postion of a sorted list. > > list_of_numbers.sort() # sort in place.. > median = list_of_numbers[(len(list_of_numbers)-1)/ 2 ] > > would do it. > Actually, this is correct if the list has an odd number of elements. If the list has an even number of elements, the median is the average of the middle two elements. def median(aList): tempList = aList[:] tempList.sort() listLen = len(tempList) middleIndex = (listLen - 1) / 2 if listLen % 2 == 1: #odd number of elements. return middle element return tempList[middleIndex] else: #even number of element. return average of middle 2 elements return (tempList[middleIndex] + tempList[middleIndex + 1]) / 2.0 if __name__ == '__main__': theList = [2,3,4,5,6] print theList print 'median = ', median(theList) theList = [1,2,6,7] print theList print 'median = ', median(theList) >>> [2, 3, 4, 5, 6] median = 4 [1, 2, 6, 7] median = 4.0 HTH, Don From max@provico.fi Thu Jan 2 12:24:01 2003 From: max@provico.fi (Max Romantschuk) Date: Thu Jan 2 12:24:01 2003 Subject: [Tutor] Implementation Help Request on Game of Life References: Message-ID: <000c01c2b283$e819cca0$1324e60a@Tor> Thanks to everyone for the ideas... I've actually ended up not looking too much at the code provided... otherwise there's not much to figure out for myself... After all, I'm reinventing the wheel on purpose here, in order to get a feel for the language :) Gregor: I'd like to have a look at your implementation, providing you can find it... no stress though, this is not a high priority project, just having some fun! Anyway, thanks again for all the help. I can post my implementation somewhere when it's done, in case someone is interrested. .: Max Romantschuk .: http://www.mp3.com/romax/ From Adam Vardy Thu Jan 2 12:31:00 2003 From: Adam Vardy (Adam Vardy) Date: Thu Jan 2 12:31:00 2003 Subject: [Tutor] Debug Message-ID: <1615745792.20030102140009@roadrunner.nf.net> I was asking this before. It's hard to follow a program unless you can go through it slowly. Programs run fast. So, I try with the last one loading it, and in File/ Debug and Step. Ok. So it should meander nicely line-by-line, through the card game. Or other simple program. But immediately it goes kinda crazy. My program has disappeared. And I'm down in the middle of some mess that goes: "def _doexec(cmd, globals, locals):" And on the left of the screen 2 new windows opened up. Can someone help clear this up? -- Adam Vardy From ramrom@earthling.net Thu Jan 2 13:34:05 2003 From: ramrom@earthling.net (Bob Gailer) Date: Thu Jan 2 13:34:05 2003 Subject: [Tutor] Debug In-Reply-To: <1615745792.20030102140009@roadrunner.nf.net> Message-ID: <5.2.0.9.0.20030102111509.02bd0da8@66.28.54.253> --=======68D059FB======= Content-Type: text/plain; x-avg-checked=avg-ok-10AD26B1; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 02:00 PM 1/2/2003 -0330, Adam Vardy wrote: >My program has disappeared. And >I'm down in the middle of some mess that goes: "def _doexec(cmd, >globals, locals):" And on the left of the screen 2 new windows opened >up. Can someone help clear this up? Sounds like you're using PythonWin, which I use also. There are behaviors that are unexpected and sometimes unpredictible. def _doexec(cmd, globals, locals): is in PyhtonWin's debugger module; why it (sometimes) shows up in single step is a mystery. Your program has not disappeared; its just hidden behind the debugger window. My way of handling it is to make the debugger window very small (NOT minimize) and at the bottom of the main window. Then set a breakpoint in your program, and hit F5 until it reaches your breakpoint. The 2 new windows on the left are debugger windows. The first is the watch window. Here you can enter variables and/or expressions to see the values of things as your program proceeds. The other is the stack view, showing which functions/methods are currently being called . There is also a breakpoint window which (in my version) floats, and shows where all the breakpoints are. Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======68D059FB======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-10AD26B1 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.431 / Virus Database: 242 - Release Date: 12/17/2002 --=======68D059FB=======-- From rustynewton@comcast.net Thu Jan 2 13:38:01 2003 From: rustynewton@comcast.net (Rusty Newton) Date: Thu Jan 2 13:38:01 2003 Subject: [Tutor] ansi color coding Message-ID: <006601c2b28b$e515bac0$6401a8c0@huntsv01.al.comcast.net> This is a multi-part message in MIME format. --Boundary_(ID_4cBVz9YHMRnpmz3OZ8WWEQ) Content-type: text/plain; charset=iso-8859-1 Content-transfer-encoding: 7BIT well im making a mud game or a multiuser online text game and i want to color the text, that i send to the users? does that explain anymore? -rusty --Boundary_(ID_4cBVz9YHMRnpmz3OZ8WWEQ) Content-type: text/html; charset=iso-8859-1 Content-transfer-encoding: 7BIT
well im making a mud game or a multiuser online text game
and i want to color the text, that i send to the users? does that explain anymore?
 
-rusty
--Boundary_(ID_4cBVz9YHMRnpmz3OZ8WWEQ)-- From Adam Vardy Thu Jan 2 14:03:01 2003 From: Adam Vardy (Adam Vardy) Date: Thu Jan 2 14:03:01 2003 Subject: [Tutor] Debug In-Reply-To: <5.2.0.9.0.20030102111509.02bd0da8@66.28.54.253> References: <5.2.0.9.0.20030102111509.02bd0da8@66.28.54.253> Message-ID: <17711241113.20030102153144@roadrunner.nf.net> Thursday, January 2, 2003, 2:55:52 PM, you wrote: >> At 02:00 PM 1/2/2003 -0330, Adam Vardy wrote: >>My program has disappeared. And >>I'm down in the middle of some mess that goes: "def _doexec(cmd, >>globals, locals):" And on the left of the screen 2 new windows opened >>up. Can someone help clear this up? >> Sounds like you're using PythonWin, which I use also. There are behaviors >> that are unexpected and sometimes unpredictible. def _doexec(cmd, globals, >> locals): is in PyhtonWin's debugger module; why it (sometimes) shows up in >> single step is a mystery. Ok, thanks. Yes, a single step. But, not random. Every time. Even if I just type a two line program and debug it. Now, if you recall BASIC, there was always a real easy way to check out program progress. You just add a command Stop. And then you could print out variables, and check things out. So how it was going. -- Adam Vardy From Janssen@rz.uni-frankfurt.de Thu Jan 2 14:30:02 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Thu Jan 2 14:30:02 2003 Subject: [Tutor] ansi color coding In-Reply-To: <006601c2b28b$e515bac0$6401a8c0@huntsv01.al.comcast.net> Message-ID: On Thu, 2 Jan 2003, Rusty Newton wrote: > well im making a mud game or a multiuser online text game and i want > to color the text, that i send to the users? does that explain > anymore? perhaps you search this: print "\033[31mHello!\033[0m" --> red \033[ starts the format-cmd 30-37m chooses colours 0m sets back to standart You can combine this with 1-7 for different styles: print "\033[31;1mHello!\033[0m" --> bold red bg-colors are in 40-47 for the fate of your users, please don't use 5 ;-) Michael PS: it's also working on (*nix-)console: echo -e "\033[31mHello\033[0m" From altis@semi-retired.com Thu Jan 2 17:15:03 2003 From: altis@semi-retired.com (Kevin Altis) Date: Thu Jan 2 17:15:03 2003 Subject: [Tutor] Re: Implementation Help Request on Game of Life Message-ID: This is a multi-part message in MIME format. ------=_NextPart_000_0052_01C2B269.BE8B36E0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 7bit Hi, I'm not normally subscribed to python-tutor, but since I just implemented Conway's life in December for PythonCard this is a fresh subject for me. Please cc me on all replies as I will probably remain subscribed to the tutor list, but disable list delivery. There is more about the PytonCard life sample program at: http://pythoncard.sourceforge.net/samples/life.html The source is at: http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/pythoncard/PythonCardPrototyp e/samples/life/ You won't be able to run it without having Python 2.2.x or higher and wxPython 2.3.3.1 or higher and checking PythonCard out of cvs http://sourceforge.net/cvs/?group_id=19015 However, it will be part of release 0.7 of PythonCard sometime later this month. I've attached a zip file with the core generation calculation along with the util.py module that can read .LIF files and LIF style patterns in the clipboard (this is the same util.py that is in cvs). The cmdLife.py script runs the rpento pattern for 1103 generations (when it stabilizes); I put it together, so Bill Bumgarner could port the code to PyObjC for Mac OS X and to use as a simple benchmark comparison. The same base could be used for a tkinter app, curses, or any other GUI; PythonCard uses wxPython. The algorithm I use is pretty elegant and is more readable (but slower) than the fastest algorithms used by some of the C++ and Java programs. They all use bit shifting and "blobbing" to calculate sections of a generation all at once. My method is real simple and doesn't put any limits on universe size except for +/-maxint since an (x, y) tuple is used as the key in the dictionary for each cell. The grid is a dictionary of each live cell and its neighbors. The values of each cell is either 1 or 0. Each generation, you simply loop through all the grid cells, sum the neighbors and apply the test if sum == 3 or (grid[cell] and sum == 2) to determine whether a given cell lives in the next generation. Then you make sure all its neighbors exist. Using get and setdefault really simplifies using the dictionary and avoids try/except blocks. I am interested in further optimizations such as used by the fastest Java and C Life programs which use bit shifting and "blobbing" to calculate areas of the grid all at once. Note that I've also implemented other cellular automata and visualizations, but not all are included as PythonCard samples. ka --- Kevin Altis altis@semi-retired.com http://radio.weblogs.com/0102677/ http://www.pythoncard.org/ ------=_NextPart_000_0052_01C2B269.BE8B36E0 Content-Type: application/x-zip-compressed; name="bill_life.zip" Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename="bill_life.zip" UEsDBBQAAAAIAAORIS5TSMYRPQkAAMcbAAAUAAAAYmlsbF9saWZlL2NtZExpZmUucHm9WG1v2zgS /m7A/4Fno7CcOjrLTnpIgHzY694WBYrdINvF4RAUBi1RNjeyKIhUHG/R/34zfJGoF3fbw90JsWOK w+G8PjPkeMQPhSgVqRTPxqPxKM6olOS3nD+zUrLb8YjAk7CUbDY852qzCSTL0rmdwAfHIc69K3kS zDsTT4wVP5b0yPMduSNL3MJxrNd0OU4JJYUoqowqlpAdkJA9lSR4WZDTnKiqyJgkqSjJEztJf9mR qz2JSEAzEH9OgGJJgoTRZK7J1Z6RZ5pVjIiUMBrvkUFHXr3bHfn8pfue5aykiou8q0YiHqr8A0+Z 1mNBpGKFvLuMfI2Oe56xvkFonhhy8hdg6tHjYyWppWrP5uw4ICo+qGnMsgzsq3l02OIjq4PRojsx zRnf7beilDBf//6IFg+Q5+Py00Izf4w+zQeWE64Il+C+LfxIKegGVhcgScZzBvaHOTDiHt/uaT7E IKZZpk1D0iqP0d59qlhkC1KKI8iIsvQJipI9P+h5pLokUZ8kZy+qIXk9RIJc3ooMd4Hvs1wakkEu vkWDwPJcOBHnCxLEnbFl6r3rc/WfhmnZYVB+z2JrkVoib1wzdO/mLgH8Z0reE1VySFlKED0wV47g a6YTL+Ham7Q8QdYVCmhiUZwwE3G2sZJO7yHm20ppUgG895DTGN9SiRKjRW9AFYVsYQcQAGJOVOqI TPVcLKQa4gm7Q8DFiDSOTSMJZueBJjZu6RY4kuvlKyIzcWTlEDuaSUEqiax2TAVzA0gUYYJWGehc FIyijoJsmeW4Wl6url/ZZBliiplimVKw7+mv7CVGA24zET+BBU6ALDSOGcA2qIOp/fpOJ/6jU+VT ny2ChJtGQ9ZaD6AFPh7bEFVz9AuyHMKBAryiyASzc2IAY2FEwp8D4tgFtRRnKUCO/hw3at/dkTVi ftDsZBDWzK3mZ3SbGrg8cvhCt2Dx0JFOGtAfXmlB2O51N5T++HyvsfGxrEPJlI2eP7G5e6ZgjVyo mgFUzg2UuXr1OSvotfjllKqjxy947unWxNc95U1du+y/96qs3apNMJ1qkoTLIqOnd/UewbxLd3wJ jy+/0pT9i7PMthGtytxj0es0pjHNn6l0dTYW0A3lLFcy3FbpL2nqkx55AtlsKSXgBoOiYAYFjSE/ +3xDWinxwNKSyX274tYUcQaQ4OvWr/veKkJLKK0loqgWB5IL4GFnMMqnS1jB8gRBA7yzhxJ3EhU5 UkghAB9rGJ9eY9yBqb1IsIKLPDuRndCgKDRGanC0XVkrITxzQAI27525Vm0FoKqLw4EZQQCuNV/J /2CuFHiFIoDg3c9b6gPs8fwJGohgTXSiYu5JzCqqy51J4z2FGUqia9hE0cwQ+XyAvrOXaxDXliMi B46jFQBIWYrKWHMAohzaZSzX0DMHyKt/+8o31uvEApbLE5EH6H2IKBQ/8D86RjblD5oq+ix4gtJp 1FPQIWtbovRMc+GqB1lAaZ0B2dhJ/wJ8rDD+Hzuw/A1tJPBt4O8MrHg69zGiIUIhQiyPeRK4TpNc eLFVt52tt/MeJtiswg77Hrl+4FIFhr9Hy7L6bOOe/6e+vpQPLFaQwU2D/Q1qL1zy63+tGKstUBrU 8ZHFIitGTSX/TstQYZG7I5MGIW/JqwRJ72s18M2EvCJBB/IXnqreHjYX/oscz2CpZ1rUfzKZjEdT PIaRKFxew+8fSXkJ8aTEgedCj38wKbYgz3wnIKMlWBewCFxVUAVpk4dIpkn/uWcGId7Rg0YmzfkI lSLlJfaSQAOKliKpYmx4NT6Q6OZvy4WBUiDVREUpCiGRRBqkQwmYVG5LTYSxB0fE2DSr0BWCWGa3 Kn/KxVEL9jN87gGeAGLDi4vxCD/hhdV8POJ4RM9B2s0G83y22RwozzebmQ1Ue84XsjUstL9arwB+ mIuoyt4DgL3dlYALKCgZqAa03LAOsN/isplMmIxLXlivGk3B2koUH1iqFgbv7/SlQwjVLJd41H+b 8WIraJncmwXB7OLiYma3s3HleE0atq15u8Ok3qs1i9tOzO5OiS0eQVLosuoDgOVLjsyALUD+DmIS e8LqsGUO+ad1xahLwsI6MRFM5jNFSga+PsEZAhkS07bXxttTRd7PDkY0Xaft+UbXf31w8J2jTQVF O2bOOs43uklYkJX+c0YBHHmcQT2UM3dON8xC86+9uPYohBopKyyl3c63pm/f50Sd2eYuJPqmbbsb R9Fy7e2tTzSlTmJHaSyMCeYy1PkLYG3LM3Bt7SBtzYwnsCOWzhj8ATFrOoTfKwjencDuCPyIpdNf 5XimeG3DdXthuxZ9EHxuwqfSXKg+kGLLUEnT0cBeCRriJ+TgrjLMro0yB/rEsLtgKN5RlE8yDMOO Sbs3a9+TWr4QgZAhkO/D36EYBjO3crYgs4f7f/z88Zfww/ufZvP/cbqhefB2aLdjeBSCvDM20bd5 PH6qfXc4QXsHkAv4uSvpQV8AAshCpjB9fo7BF8CC1q6yHV1zngDnUAReYSZiaOKwU6oLaJ5A0Jm+ CLDTtcduLc2gREASHqTNc1pPyYLFPOWxTm5kjS76IU/uveyse2l9JZAAENSa6dQ+QMxhSBUZ8MFb Tmfe5sYEvil+oO6XvAlqyAi8B7WoZfrUJgwwHvVSQC9tWN0Jw5HmG1Hkamk+53HEJAj0t0TuRZUl eGReRS2/Y/PbznTbEQ+hzp/j0texB9K+VB+hZsErLF0hfgXdpR4wAcS0gxyBBxdBX5LqvsRjgyc8 t0GP57kT6pCJrm5u/jMbNc0NVogC/EtTjHzwqYZMCG/Ilfu3SFcH0ePnGXQdHIWa3ZJgiVcGkOja kbfkURfWT/ACUxMJ1gsSzb/ACcCmsV0yHmk0MdPj0ecgwh+3ZImXijhY+YN1PVj5ZCtDFrlBQ7b2 ydY+2donu/LJrnyyK5/s2ie79mW7tmRfUIUVKvY1QetBS58rX9ClP4h8qXsq1IOGwZXPYEi5etCy wZVV4ZyT9Ya+k6FLRHQ332HP4euvOPzNgryBQT8edap/DtY3CBONFXAYtYeeIsB6fdMaemv1sLGh HrbXXnlmiNqsIssqaoZRe7hqDz1WqzarVZvVqqWRHq7aQ4/Vus1q3VZw7ViB8xqsid6ENzfXy+Vy PPIPS7oDIu3jUhS9GfSFxhSNDf8GUEsDBAoAAAAAAFOOIS4AAAAAAAAAAAAAAAATAAAAYmlsbF9s aWZlL3BhdHRlcm5zL1BLAwQUAAAACAAdW40tgG9RGqoAAAD1AAAAHQAAAGJpbGxfbGlmZS9wYXR0 ZXJucy9SUEVOVE8uTElGNc4/C8IwEAXwvdDvcNCt1NBSRBwFwUXEzTm0iQmau5A/9uubnDi8IfDL u9ddrVYwiXHfNt0Zws4rTOQsEr9PEJ18vwf42CcFynGAhZwjBC9TUgFFZUwfRiEko+AinQLSwM2b jKBtiImNxRRozYtaQZY2XGE6HsahfLOxUkY+kKdYSeQ+XqBi+p9kpCnAZuximFBOZdbvWsYX0sbD biV3mGFuG9H3bVMjSr5QSwMEFAAAAAgAdLiTLbxF7EjFBgAAcRYAABEAAABiaWxsX2xpZmUvdXRp bC5webVYbW/bNhD+HiD/4Wp/sOw6QrJiG1AsA/oKFMiSoO2HAVk+UBJtc2VIgaTieMP+++5I0Xqx 7LodpiKJfXzueHc83j3V6ckY3v3+6rfbq3dw9eE9vP9w9e70ZDQanZ6Mr8SCw0V6/iN+fguvcm2U //R5xeFBWwePYqmNrqzcwNLotVBL+Pks51J62OiBu1VluWSrEZTMOW5UCvCJc2DSavj46vXrD58/ pQi+xp9bOHsBZxenJ+kMf1L6PZvhn9ms9of+FXwRTb0VD1xZoZVNaomdvjw9AXzGsBDLynDQlQOH 3hZbLOiFl3DlBAIWQvKgI/nCwSWch29Ol80XI5ar1lqmndMPzfeFNtEnECp+tLUv3vYcSL9euZuU 2gqH3kzuG8xaFG41hxWvN9uCrfiLt4EGFyU8DwqNOEOxQ3Ew0MjFAtG/+PBaHtFTRyw7WIdYDL4H DenoWjXwa8hMDxuzZTroDNEhcT34NptZnWzuKkwkOTenfefB4LwGxiIwnBVUn+/xAOn8V83Zu5Ww kOtKFpBxyFdMLXmBpoABVqM5Q3WhUFIIE1Use0QBHh5DRYXFExYKbnMjSjoqdHAyiXDO8tX2yNdC StKyAm8EVhdT8DSHTcTqxcLyOnOxNNDY3X1HhJK//6lLz2xaKVpQ4nXJVQiyWSiYY7i0KFNKhcSI bDJt66W51JaTrHMQpHd3fp9ah5ElU3iGgTU3fdI/zHAa11rxth0qedqSUuYNXry872lSkASJG3VX 0REEUE57avSUzNqulEtSQFPMOLsWbpVMxteTKaAbPenHyXTA4hjQZPXA4Y1Wa7aB5FqbByanYCrJ rQ9H6fX3evJ2cE/Kdbt+9gRLT7fO7N2Ll/fDaaOHS8uPsPP8EkZ/qBF2hAP2hqK53ZPBjC+FUtTj qciB2jxkUudfBkOPdf2MCnuPu70Wh6EnnS44EHxLzaasxHtRxO6f5rrcJNMBJbqOTV5LKVwygckA 0O/eNPb2s+3LA2u7d3hgtd31KVKhXPI0nQP93Qx5vdXDyWq9zt19F7WnEnqKMU12YA8aDtha7BS7 sw9+z0nFxATw3uxgzV10ms2hKvjG0//qqTfwfbOjmapD3KHRH5cGTwVGma5UYUfzA8Oor0KxoALL bBLm4JlXngZR7cYZmWrtVzfZ1u2db8OdQ7LdHa0kx1iuTfOnnJft6dxr5p5UOY5Ty1U4KDOW0dAi zkWsC5LyBzI0S4mEERuDNHxM+x9TrxNZIw1dlklOE5cOBwdiQY3UIdsy6COxryWOJsvMhuCl0Tm3 NgxVmhgk9N2KZidqbzBQVlDjIUvOMCHpiy0Z6hFYKySgfgKiceZCpwJqZ9inUhoSM2DG2y2x0UUK WKfYuyyZ+lKbQCSIpdKGF944Qk1riRVFYBOeVzZHRlgGvrsA8o8Ck4yOeVTtmsYDeNCP3g/kKGpp ceULx0T/dD5tctNyyzMZzy+UdoBEppDbdVRmZslNwDGiLr4bY/Q5Q55DtigSi7pgq7LUxhGWZl1C HXFaUxMbCBXmVVnJHH8jRZlpZorbsFFCAz6OhFbAn2hoYCq2LXGYLR3Fefp8InTpmtS0Kng/qdhL KLoj3A88SqZFDkS7JZN0MofJjH7d7Ey+MR138GzoxLvQbBPzTOVJ4JyVwjEJNztWLdXK5iHTEtaE U7Dkro9yK+zgyt8CtM1ihnZhHbfCHQgjPVyCne3pdqwEXrechULpkNk+Gj3Di2xMVTq6Et1FvEtI tQ2awbpfR9KtRF5nTOC98qmIVdU34Mv7z8rSHsoxz8Ebb9B7LN8DScfC8cpU8alvELMu5Ega1qNg XcCeQbuHbrWrbUevy+7jg22ejNHOBwnK8I4k7Tncb/3x2SW0RxO71ji/3EPqvpM/jZsjPJ/D+X46 Hv83hbPKYufBJNC8BepaZijWQeJFW3wX3TqSVx3DqQ7xqR0udYBHfQOHOpI//Rfu9I286bs50//A l+JrBUVpy7Sxn6tS8iTXEl3X6+blQr03Q86EALoxUSVIbAT62Y29S2qFUxrWhpU2vGFw2lQ1rDT8 8aNeY3JxE/SmPnHFn1wjfh7FhH6DE+MSW6XsohvxFl17miS12jzuRmnJe99rGy1ZtygbI6anYA6B 60C2O7a+bw1E2XT7fk8isYvkY2lEMafAbvzN9/vFj/WZx8MxMWM3rVcu4+3dEdaP0PCShvgDErCA abOPGt26Y3lMbdtsVMtJh3R7lxzvbB7oxR5mQQ/FdtfUGF3fi12U74axxtDkV0p0aJMU/cbMskq6 JKrvdsE9U27Ay14P92XX8d2X7WWvEsnQ6cm/UEsDBAoAAAAAACORIS4AAAAAAAAAAAAAAAAKAAAA YmlsbF9saWZlL1BLAQIUABQAAAAIAAORIS5TSMYRPQkAAMcbAAAUAAAAAAAAAAEAIAC2gQAAAABi aWxsX2xpZmUvY21kTGlmZS5weVBLAQIUAAoAAAAAAFOOIS4AAAAAAAAAAAAAAAATAAAAAAAAAAAA EAD/QW8JAABiaWxsX2xpZmUvcGF0dGVybnMvUEsBAhQAFAAAAAgAHVuNLYBvURqqAAAA9QAAAB0A AAAAAAAAAQAgALaBoAkAAGJpbGxfbGlmZS9wYXR0ZXJucy9SUEVOVE8uTElGUEsBAhQAFAAAAAgA dLiTLbxF7EjFBgAAcRYAABEAAAAAAAAAAQAgALaBhQoAAGJpbGxfbGlmZS91dGlsLnB5UEsBAhQA CgAAAAAAI5EhLgAAAAAAAAAAAAAAAAoAAAAAAAAAAAAQAP9BeREAAGJpbGxfbGlmZS9QSwUGAAAA AAUABQBFAQAAoREAAAAA ------=_NextPart_000_0052_01C2B269.BE8B36E0-- From gp@pooryorick.com Fri Jan 3 01:17:01 2003 From: gp@pooryorick.com (Poor Yorick) Date: Fri Jan 3 01:17:01 2003 Subject: [Tutor] variable assignment Message-ID: <3E152B1A.9040907@pooryorick.com> In the following code, I halfway expected the final print statement to produce the same number the other three print statements produced, but it did not. Could anyone explain why? class one: def __init__(self): self.d = 'hello' def Get(self): return self.d class two: def __init__(self): self.d = {1: 'hello'} def Get(self): return self.d[1] ins1 = one() var = ins1.Get() print id(var[1]) print id(ins1.d[1]) ins2 = two() var2 = ins2.Get() print id(var2[1]) print id(ins2.d[1]) poor yorick gp@pooryorick.com From ramrom@earthling.net Fri Jan 3 01:29:06 2003 From: ramrom@earthling.net (Bob Gailer) Date: Fri Jan 3 01:29:06 2003 Subject: [Tutor] variable assignment In-Reply-To: <3E152B1A.9040907@pooryorick.com> Message-ID: <5.2.0.9.0.20030102232637.02bae760@66.28.54.253> --=======18DC78B1======= Content-Type: text/plain; x-avg-checked=avg-ok-1AB03CC0; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 11:18 PM 1/2/2003 -0700, Poor Yorick wrote: > In the following code, I halfway expected the final print statement to > produce the same number the other three print statements produced. Why? Try printing the 4 expressions inside the id() 'e' 'e' 'e' 'hello' I certainly hope that 'hello' would not have the same id as 'e'! Perhaps you want print id(ins2.d[1][0])? Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======18DC78B1======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-1AB03CC0 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.431 / Virus Database: 242 - Release Date: 12/17/2002 --=======18DC78B1=======-- From wesc@deirdre.org Fri Jan 3 02:43:03 2003 From: wesc@deirdre.org (wesc@deirdre.org) Date: Fri Jan 3 02:43:03 2003 Subject: [Tutor] ANN: Python Programming course (Silicon Valley, CA) Message-ID: <200301030728.h037S5214610@alpha.ece.ucsb.edu> "Python Programming" course UC Santa Cruz, Winter Quarter 2002 Jan 6 - Mar 17, 2003 (except Jan 20, 27 and Feb 17) Monday nights, 6:30 - 9:30pm Sunnyvale, California just a reminder that if you are in the Silicon Valley area and are interested or know people who are, that the course is scheduled to start this coming Monday, so sign up fast, or show up to the 1st course to register! http://artemis.ucsc-extension.edu/~wesc/013e44cd.htm Register online, or contact Sherry at 408-861-3765 or smirkarimi@ucsc-extension.edu to enroll. hope 2 c some of u there! -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall PTR, © 2001 http://starship.python.net/crew/wesc/cpp/ Silicon Valley-San Francisco Bay Area Python Users Group (BayPIGgies) http://www.baypiggies.net wesley.j.chun :: wesc at deirdre.org cyberweb.consulting : henderson, nv : cyberweb at rocketmail.com http://roadkill.com/~wesc/cyberweb/ From missive@hotmail.com Fri Jan 3 03:17:01 2003 From: missive@hotmail.com (Lee Harr) Date: Fri Jan 3 03:17:01 2003 Subject: [Tutor] Re: ansi color coding Message-ID: >well im making a mud game or a multiuser online text game and i want >to color the text, that i send to the users I recommend a quick trip through the Vaults of Parnassus: http://www.vex.net/parnassus/ I went there and searched for "ansi" and found: http://www.livinglogic.de/Python/ansistyle/ http://www.demonseed.net/~jp/code/ansi.py which should get you started. _________________________________________________________________ MSN 8 helps eliminate e-mail viruses. Get 2 months FREE* http://join.msn.com/?page=features/virus From johnca@ourpla.net Fri Jan 3 07:54:02 2003 From: johnca@ourpla.net (John Abbe) Date: Fri Jan 3 07:54:02 2003 Subject: [Tutor] Good reasons for 1.5.2 compatibility? Message-ID: I've started a project that i intend to make available to the public, and have been keeping it 1.5.2-compatible. Is this worth the bother? That is, do many ISPs still have 1.5.2 running? (mine did until i asked for an upgrade) Are there any factors causing reasonable people to keep 1.5.2 around? Life, John -- All you /\/\ John Abbe "If you don't like the news, need \ / CatHerder go out and make some of your own." is... \/ http://ourpla.net/john/ --Wes Nisker From op73418@mail.telepac.pt Fri Jan 3 10:17:04 2003 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Fri Jan 3 10:17:04 2003 Subject: [Tutor] ansi color coding References: <006601c2b28b$e515bac0$6401a8c0@huntsv01.al.comcast.net> Message-ID: <000f01c2b296$893278a0$34190dd5@violante> This is a multi-part message in MIME format. ------=_NextPart_000_000C_01C2B296.890F6040 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable ----- Original Message -----=20 From: Rusty Newton=20 To: tutor@python.org=20 Sent: Thursday, January 02, 2003 6:22 PM Subject: [Tutor] ansi color coding >well im making a mud game or a multiuser online text game=20 >and i want to color the text, that i send to the users? does that = explain anymore? >-rusty ANSI color codes are a kind of protocol to give colorize the text = presented to the user. A table of such codes is in http://pueblo.sourceforge.net/doc/manual/ansi_color_codes.html Basically, it is of the form escape character (ESC, ASCII value 27) = followed by the appropriate code sequence. So you have to interleave the = text you send to the user with these codes and then the client must be = able to interpret them. You may also have to make sure the client *can* interpret ANSI color = codes. Since it is a MUD, you use option negotiation over telnet? You = have to check the relevant rfc's to know what's at stake. For everything = related to the telnet protocol you can look at http://www.networksorcery.com/enp/protocol/telnet.htm With my best regards, G. Rodrigues ------=_NextPart_000_000C_01C2B296.890F6040 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
----- Original Message ----- =
From: Rusty Newton
To: tutor@python.org =
Sent: Thursday, January = 02, 2003 6:22=20 PM
Subject: [Tutor] ansi = color=20 coding
 
>well im making a mud game or a = multiuser online=20 text game
>and i want to color the text, = that i send=20 to the users? does that explain anymore?
 
>-rusty
 
ANSI color codes are a kind of protocol = to give=20 colorize the text presented to the user. A table of such codes is=20 in
 
h= ttp://pueblo.sourceforge.net/doc/manual/ansi_color_codes.html<= /DIV>
 
Basically, it is of the form escape = character=20 (ESC, = ASCII=20 value 27) followed by the appropriate code sequence. So you have to = interleave the text you send to the user with = these codes and=20 then the client must be able to interpret them.
 
You may also have to make sure the = client *can*=20 interpret ANSI color codes. Since it is a MUD, you use option = negotiation over=20 telnet? You have to check the relevant rfc's to know what's at stake. = For=20 everything related to the telnet protocol you can look at
 
http://www= .networksorcery.com/enp/protocol/telnet.htm
 
With my best regards,
G. = Rodrigues
------=_NextPart_000_000C_01C2B296.890F6040-- From ramrom@earthling.net Fri Jan 3 10:31:16 2003 From: ramrom@earthling.net (Bob Gailer) Date: Fri Jan 3 10:31:16 2003 Subject: [Tutor] variable assignment In-Reply-To: <1041593750.3e157596bb481@atlas.ucpel.tche.br> References: <5.2.0.9.0.20030102232637.02bae760@66.28.54.253> <5.2.0.9.0.20030102232637.02bae760@66.28.54.253> Message-ID: <5.2.0.9.0.20030103082917.02b91008@66.28.54.253> --=======66F26452======= Content-Type: text/plain; x-avg-checked=avg-ok-1CF2B71; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 09:35 AM 1/3/2003 -0200, amd@ucpel.tche.br wrote: >Would't be id(ins2.d[1][1]) to get the same id ? oops. you're right. Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======66F26452======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-1CF2B71 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.431 / Virus Database: 242 - Release Date: 12/17/2002 --=======66F26452=======-- From rnd@onego.ru Fri Jan 3 10:46:01 2003 From: rnd@onego.ru (Roman Suzi) Date: Fri Jan 3 10:46:01 2003 Subject: [Tutor] Good reasons for 1.5.2 compatibility? In-Reply-To: Message-ID: On Fri, 3 Jan 2003, John Abbe wrote: >I've started a project that i intend to make available to the public, >and have been keeping it 1.5.2-compatible. Is this worth the bother? >That is, do many ISPs still have 1.5.2 running? (mine did until i >asked for an upgrade) Are there any factors causing reasonable people >to keep 1.5.2 around? If nothing special (XML, Unicode, email, etc) is needed 1.5.2 is still a good choice. Also I know that 2.x has difficulties with non-latin1 texts in IDLE: so it is not possible to use Tkinter (thus build GUIs) with standard 2.x versions of Python. Personally I am using 2.2.2 for new programs but at work it's still mostly 1.5.2. As for NEW projects (public or private) I think 2.2.2 is great. Just do not use things which will change in future to be on the safe side. (i.e. 2/3, yield=404, etc) Sincerely yours, Roman Suzi -- rnd@onego.ru =\= My AI powered by Linux RedHat 7.3 From Janssen@rz.uni-frankfurt.de Fri Jan 3 11:27:16 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Fri Jan 3 11:27:16 2003 Subject: [Tutor] Good reasons for 1.5.2 compatibility? In-Reply-To: Message-ID: On Fri, 3 Jan 2003, John Abbe wrote: > Are there any factors causing reasonable people > to keep 1.5.2 around? Some people do keep 1.5.2 on their system, but it's hard to tell what's their reason (that's a "frequently not answered question" on comp.lang.python). Perhaps it's just they are lazy. RedHat remained for a long time on 1.5.2 cause they frighten incompatibilities with their system-scripts written in python, but they have skipped this position and switched to a recent version. > Life, > John > -- > All you /\/\ John Abbe "If you don't like the news, > need \ / CatHerder go out and make some of your own." > is... \/ http://ourpla.net/john/ --Wes Nisker > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From sxa@fluent.com Fri Jan 3 12:40:02 2003 From: sxa@fluent.com (Sebastien Auclair) Date: Fri Jan 3 12:40:02 2003 Subject: [Tutor] Embeding Python... (Please help !) Message-ID: <029601c2b34f$0feaa760$8ae4e9c0@sxapc> Our problem is so trivial, it's crazy that we can't find anything on the net that would help us. We are trying to use the function PyArg_Parse and others in order to simply get a correctly casted pointer to a Python Class instance. That python class is in fact a subclass of a C++ class defining an interface. Our python file knows this interface class through SIP bindings. There are some examples of how we can get simple C type values (strings, int, float...) from Python types but nothing on pointers to class... We tried to use the O& option but it doesn't work. EXAMPLE : <<<<<<< PYTHON FILE >>>>>>>>>>>>> import Interfaces # From sipping def CreateInstance (): return Server () class Server (Interfaces.interface): def __init__(self): Interfaces.interface.__init__(self) <<<<<<<<< INTERFACE .h DEFINITION FILE>>>>>>>>>>> class interface{ interface(); ~interface(); someFunction(); }; <<<<<<<< MAIN APPLICATION >>>>>>> #include "Interfaces.h" ... ........python stuff to load and compile the python file...this works fine... we tested it ! ... PyObject * m_pylib = PyImport_ExecCodeModule( const_cast("server"), code ); Py_INCREF( m_pylib ); PyObject * mdict = PyModule_GetDict(m_pylib); PyObject * func1 = PyDict_GetItemString(mdict, "CreateInstance"); PyObject * v1 = PyObject_CallObject(func1,NULL); interface * interf = (interface*) v1; // OF COURSE THIS DOESN'T WORK BUT YOU GET THE IDEA.... >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Thanks for any help ! ____________________________________________________________________________ ____________ From alan.gauld@bt.com Fri Jan 3 13:21:01 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri Jan 3 13:21:01 2003 Subject: [Tutor] Debug Message-ID: <7497DCA1C240C042B28F6657ADFD8E097022E1@i2km11-ukbr.domain1.systemhost.net> > >>I'm down in the middle of some mess that goes: "def _doexec(cmd, Use Next instead of Step. Step steps intp when you *really* want to get inside a function... > Now, if you recall BASIC, there was always a real easy way to check > out program progress. You just add a command Stop. That's what breakpoints do. I can't recall whether the python debugger(or the Pythonwin one) do watches but if they do you can set a watch event that will stop the program when a variable reaches(or exceeds etc) a specified value. Unfortunately the python debugger is fairly primitive so I'm not sure it can do that yet. Alan G From alan.gauld@bt.com Fri Jan 3 13:24:02 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri Jan 3 13:24:02 2003 Subject: [Tutor] ansi color coding Message-ID: <7497DCA1C240C042B28F6657ADFD8E097022E3@i2km11-ukbr.domain1.systemhost.net> > Since it is a MUD, you use option negotiation over telnet? > You have to check the relevant rfc's to know what's at stake. > For everything related to the telnet protocol you can look at And its worth reminding that telnet is plain text, ie unencrypted so potentially insecure... so don't set things up to send your user ID/password over it... Alan g From alan.gauld@bt.com Fri Jan 3 13:31:20 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri Jan 3 13:31:20 2003 Subject: [Tutor] variable assignment Message-ID: <7497DCA1C240C042B28F6657ADFD8E097022E2@i2km11-ukbr.domain1.systemhost.net> > ins1 = one() > var = ins1.Get() <== 'hello' > print id(var[1]) <== id('e') > print id(ins1.d[1]) <== id('e') > > ins2 = two() > var2 = ins2.Get() <== 'hello' > print id(var2[1]) <== id('e') > print id(ins2.d[1]) <== id('hello') ins2.d is the dictionary, ins2.d[1] is the string, ins2.d[1][1] is the 'e'.... Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From ramrom@earthling.net Fri Jan 3 13:40:02 2003 From: ramrom@earthling.net (Bob Gailer) Date: Fri Jan 3 13:40:02 2003 Subject: [Tutor] Debug In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E097022E1@i2km11-ukbr.domain1 .systemhost.net> Message-ID: <5.2.0.9.0.20030103113356.02b8fa68@66.28.54.253> --=======5E446756======= Content-Type: text/plain; x-avg-checked=avg-ok-1CF2B71; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 06:11 PM 1/3/2003 +0000, alan.gauld@bt.com wrote: > > >>I'm down in the middle of some mess that goes: "def _doexec(cmd, > >Use Next instead of Step. Step steps intp when you *really* want to >get inside a function... Unfortunately that does not solve the problem with the PythonWin debugger. It still halts in debugger.py. Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======5E446756======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-1CF2B71 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.431 / Virus Database: 242 - Release Date: 12/17/2002 --=======5E446756=======-- From Adam Vardy Fri Jan 3 14:46:01 2003 From: Adam Vardy (Adam Vardy) Date: Fri Jan 3 14:46:01 2003 Subject: [Tutor] Tkinter Message-ID: <1528827481.20030103161511@roadrunner.nf.net> Experimenting with TK, I came up on difficulties. Like, in one program, the window is there but whenever the pointer is over the window, there is always an hourglass. Can't see anything wrong. In another example, I have a button on the window. And a function is set to run for that. But it runs right away. And nothing happens when I hit the button! -- Adam Vardy From Adam Vardy Fri Jan 3 14:50:02 2003 From: Adam Vardy (Adam Vardy) Date: Fri Jan 3 14:50:02 2003 Subject: [Tutor] Comments Message-ID: <14429062880.20030103161907@roadrunner.nf.net> How is it you phrase comments? When I'd like to take out a block and experiment with the rest, what's the method? { code ... won't run } print "will run" -- Adam Vardy From Adam Vardy Fri Jan 3 14:50:16 2003 From: Adam Vardy (Adam Vardy) Date: Fri Jan 3 14:50:16 2003 Subject: [Tutor] Debug in PythonWin In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E097022E1@i2km11-ukbr.domain1.systemhost.net> References: <7497DCA1C240C042B28F6657ADFD8E097022E1@i2km11-ukbr.domain1.systemhost.net> Message-ID: <13827711637.20030103155636@roadrunner.nf.net> Friday, January 3, 2003, 2:41:39 PM, you wrote: >> >>I'm down in the middle of some mess that goes: "def _doexec(cmd, >> Use Next instead of Step. Step steps intp when you *really* want to >> get inside a function... There is no Next option. Says Step in/ or Step out. But Step out is greyed out! Could other folks just confirm for me please if they found the same thing? The functionality all seems to be there. It just isn't working out for me. Show of hands? And, maybe some discussion if I can get anyway towards just writing a Stop command, type thing? -- Adam Vardy From aztech1200@yahoo.com Fri Jan 3 15:07:01 2003 From: aztech1200@yahoo.com (Aztech Guy) Date: Fri Jan 3 15:07:01 2003 Subject: [Tutor] Re: returning a read-only list/dict' - update - prop. not wkg. In-Reply-To: <20021229152713.68669.qmail@web9806.mail.yahoo.com> Message-ID: <20030103200614.96903.qmail@web9801.mail.yahoo.com> --0-1725536521-1041624374=:96889 Content-Type: text/plain; charset=us-ascii > > On 26 Dec 2002 05:31:07 -0800, aztech1200@yahoo.com (Az Tech) wrote: > > > > >Hello group, > > > > > >Platform: ActivePython 2.2.1 on Windows 98 - but nothing OS-specific > > >in the code. > > >This question is about how to return a list/dictionary from a method > > >(of a class) in such a way that it stays "read-only" to the caller - > > >or any other technique that is equivalent in terms of effect. Read on > Hi people, Some had suggested using the new 'property' feature of Py 2.2 to solve this problem. I tried it out, but it does not work unless I do a copy of the self.list or self.dict before returning it. Sample code and output below. # New_2.2_deep_copy_nested_list01.py # Program to test deep copy of nested list. class BinaryFile(object): import copy def __init__(self): pass def make_list2(self): self.__a_list2 = [ [1, 2], [3, 4], [5, 6] ] def get_list2(self): t_list2 = copy.deepcopy(self.__a_list2) return t_list2 # set_list2() not defined # del_list2() not defined list2 = property(get_list2, None, None, "Two-level nested list") def main(): bf = BinaryFile() bf.make_list2() #print "bf.get_list2() = ", bf.get_list2() #1 print "bef mod, bf.list2 = ", bf.list2 #2 #bf.list2 = [] #3 bf.__a_list2 = [ [0], [1] ] print "aft mod, bf.list2 = ", bf.list2 #4 print "bf.__a_list2 = ", bf.__a_list2 if __name__ == '__main__': main() Output: >>> bef mod, bf.list2 = >>> [[1, 2], [3, 4], [5, 6]] >>> aft mod, bf.list2 = >>> [[1, 2], [3, 4], [5, 6]] >>> bf.__a_list2 = >>> [[0], [1]] >>> [Note: the last two lines of the output above show that it is still possible, though, to assign to the instance's __a_list2 member - even though this does not affect the value of the property. Is this some kind of 'shadowing' of the member variable ? (Used the same printing of id() both in the method and in the caller, and it returned the same value. ) Was able to modify the member variable using the return value of the method. The only way in which I could prevent it from being modified was by making my self.list or self.dict as 'private', using a leading double underscore, e.g. self.__list, as in the code above. Also, I can get the desired result without using property at all, simply by doing a copy (or a copy.deepcopy()) of the list/dict. I've finally settled on this approach: import copy . . . then, in the method, do hand-coded copy if the element is a 'scalar' variable (a la Perl), else, if a list/dict, do a copy.deepcopy(list/dict) and then return that copy. Just FYI. Az P.S. A partial answer to Bengt - you're right, the caller doesn't need to access the data *as* a dict - he just needs to access the individual items. I was just using a dict because I was enhancing this program from an earlier version in which I used a dict - because at that time I thought it would make it more caller-friendly (even though I was both the caller and the callee) to let the items be requested by name (e.g. file_data['file_ver'], file_data['creator'], etc.) than by indexing into the struct. That version of the app was not using classes/OO, and was a monolithic program, so there was no real need to make the return value read-only. --------------------------------- Do you Yahoo!? Yahoo! Mail Plus - Powerful. Affordable. Sign up now --0-1725536521-1041624374=:96889 Content-Type: text/html; charset=us-ascii

> > On 26 Dec 2002 05:31:07 -0800, aztech1200@yahoo.com (Az Tech) wrote:
> >
> > >Hello group,
> > >
> > >Platform: ActivePython 2.2.1 on Windows 98 - but nothing OS-specific
> > >in the code.
> > >This question is about how to return a list/dictionary from a method
> > >(of a class) in such a way that it stays "read-only" to the caller -
> > >or any other technique that is equivalent in terms of effect. Read on
>

Hi people,

Some had suggested using the new 'property' feature of Py 2.2 to solve
this problem.
I tried it out, but it does not work unless I do a copy of the self.list
or self.dict before returning it.

Sample code and output below.

 

# New_2.2_deep_copy_nested_list01.py
# Program to test deep copy of nested list.


class BinaryFile(object):

    import copy

    def __init__(self):
        pass

    def make_list2(self):
        self.__a_list2 = [ [1, 2], [3, 4], [5, 6] ]

    def get_list2(self):
        t_list2 = copy.deepcopy(self.__a_list2)
        return t_list2

    # set_list2() not defined
    # del_list2() not defined
   
    list2 = property(get_list2, None,
                    None,
                    "Two-level nested list")
 
def main():
    bf = BinaryFile()
    bf.make_list2()
    #print "bf.get_list2() = ", bf.get_list2()    #1
    print "bef mod, bf.list2 = ", bf.list2                #2
    #bf.list2 = []                                #3
    bf.__a_list2 = [ [0], [1] ]
    print "aft mod, bf.list2 = ", bf.list2                #4
    print "bf.__a_list2 = ", bf.__a_list2
   
if __name__ == '__main__':
    main()

 

Output:

>>> bef mod, bf.list2 =
>>>  [[1, 2], [3, 4], [5, 6]]
>>> aft mod, bf.list2 =
>>>  [[1, 2], [3, 4], [5, 6]]
>>> bf.__a_list2 =
>>>  [[0], [1]]
>>>

[Note: the last two lines of the output above show that it is still
possible, though, to assign to the instance's __a_list2 member - even
though this does not affect the value of the property. Is this some kind
of 'shadowing' of the member variable ?

(Used the same printing of id() both in the method and in the caller,
and it returned the same value. )

Was able to modify the member variable using the return value of the
method. The only way in which I could prevent it from being modified
was by making my self.list or self.dict as 'private', using a leading
double underscore, e.g. self.__list, as in the code above.

Also, I can get the desired result without using property at all,
simply by doing a copy (or a copy.deepcopy()) of the list/dict.

I've finally settled on this approach:

import copy

.
.
.

then, in the method, do hand-coded copy if the element is a 'scalar'
variable (a la Perl), else, if a list/dict, do a copy.deepcopy(list/dict)
and then return that copy.

Just FYI.

Az

P.S.

A partial answer to Bengt - you're right, the caller doesn't need to access the data *as* a dict - he just needs to access the individual items. I was just using a dict because I was enhancing this program from an earlier version in which I used a dict - because at that time I thought it would make it more caller-friendly (even though I was both the caller and the callee) to let the items be requested by name (e.g. file_data['file_ver'], file_data['creator'], etc.) than by indexing into the struct. That version of the app was not using classes/OO, and was a monolithic program, so there was no real need to make the return value read-only.



Do you Yahoo!?
Yahoo! Mail Plus - Powerful. Affordable. Sign up now --0-1725536521-1041624374=:96889-- From churmtom@hotmail.com Fri Jan 3 15:07:15 2003 From: churmtom@hotmail.com (Tom Churm) Date: Fri Jan 3 15:07:15 2003 Subject: [Tutor] PythonWin IDE Problem on Win2K with ActivePython Message-ID: This is a multi-part message in MIME format. ------=_NextPart_000_001D_01C2B36B.E3A6FEC0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable hi, (i don't like to cross-post, but i'd sent this message originally one = week ago to python-help@python.org and never received a response.) i just installed ActivePython-2.2.2-224 on Windows 2000 (no Service = Pack). don't think it matters, but i'm running a multi-boot system and = Python has been installed on my (win2k) partition 'H:\' instead of = 'C:\'. Python works, and Tkinter works, but not the PythonWin IDE. as soon as = i open up the PythonWin IDE i get a popup window labelled 'Traceback = when executing InitInstance handler'. the text inside this popup is as = follows: File = "H:\Python22\Lib\site-packages\Pythonwin\pywin\framework\intpyapp.py", = line 163, in InitInstance import interact File = "H:\Python22\Lib\site-packages\Pythonwin\pywin\framework\interact.py", = line 26, in ? import winout File = "H:\Python22\Lib\site-packages\Pythonwin\pywin\framework\winout.py", = line 228, in ? import pywin.scintilla.view File = "H:\Python22\Lib\site-packages\Pythonwin\pywin\scintilla\view.py", line = 16, in ? import bindings File = "H:\Python22\Lib\site-packages\Pythonwin\pywin\scintilla\bindings.py", = line 6, in ? import keycodes File = "H:\Python22\Lib\site-packages\Pythonwin\pywin\scintilla\keycodes.py", = line 25, in ? _better_names =3D [ exceptions.AttributeError: 'module' object has no attribute 'VK_RETURN' please note that i've tried starting the ActivePython installer package = and running the 'Repair' option, as well as completely uninstalling = ActivePython and then reinstalling it (including deleting all Python = registry items before reinstalling), but it just ain't workin'. i hope = noone's going to suggest that i install a Win2k Service Pack...i'd like = to avoid this. any help would be greatly appreciated...oh, yeah - i'm 99% sure my = ActivePython installer package is not damaged, 'cause it's the same = installation file i've used to successfully install ActivePython on = another Win2K computer. thanks, tom ------=_NextPart_000_001D_01C2B36B.E3A6FEC0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
hi,
 
(i don't like to cross-post, but i'd = sent this=20 message originally one week ago to python-help@python.org an= d never=20 received a response.)
 
i just installed ActivePython-2.2.2-224 = on Windows=20 2000 (no Service Pack).  don't think it matters, but i'm running a=20 multi-boot system and Python has been installed on my (win2k) partition = 'H:\'=20 instead of 'C:\'.
 
Python works, and Tkinter works, but = not the=20 PythonWin IDE.  as soon as i open up the PythonWin IDE i get a = popup window=20 labelled 'Traceback when executing InitInstance handler'.  the text = inside=20 this popup is as follows:
 
  File=20 "H:\Python22\Lib\site-packages\Pythonwin\pywin\framework\intpyapp.py", = line 163,=20 in InitInstance
    import interact
  File=20 "H:\Python22\Lib\site-packages\Pythonwin\pywin\framework\interact.py", = line 26,=20 in ?
    import winout
  File=20 "H:\Python22\Lib\site-packages\Pythonwin\pywin\framework\winout.py", = line 228,=20 in ?
    import pywin.scintilla.view
  File=20 "H:\Python22\Lib\site-packages\Pythonwin\pywin\scintilla\view.py", line = 16, in=20 ?
    import bindings
  File=20 "H:\Python22\Lib\site-packages\Pythonwin\pywin\scintilla\bindings.py", = line 6,=20 in ?
    import keycodes
  File=20 "H:\Python22\Lib\site-packages\Pythonwin\pywin\scintilla\keycodes.py", = line 25,=20 in ?
    _better_names =3D = [
exceptions.AttributeError:=20 'module' object has no attribute 'VK_RETURN'
 
please note that i've tried starting = the=20 ActivePython installer package and running the 'Repair' option, as well = as=20 completely uninstalling ActivePython and then reinstalling it (including = deleting all Python registry items before reinstalling), but it just = ain't=20 workin'.  i hope noone's going to suggest that i install a Win2k = Service=20 Pack...i'd like to avoid this.
 
any help would be greatly=20 appreciated...oh, yeah - i'm 99% sure my ActivePython installer package = is not=20 damaged, 'cause it's the same installation file i've used to = successfully=20 install ActivePython on another Win2K computer.
 
thanks,
 
tom
 
 
 
 
 

 
------=_NextPart_000_001D_01C2B36B.E3A6FEC0-- From altis@semi-retired.com Fri Jan 3 15:13:41 2003 From: altis@semi-retired.com (Kevin Altis) Date: Fri Jan 3 15:13:41 2003 Subject: [Tutor] Comments In-Reply-To: <14429062880.20030103161907@roadrunner.nf.net> Message-ID: There are a few ways. You could comment out every line # code # ... # won't run comment out the block with triple quotes """ code ... won't run """ or you could just indent the whole block and stick a test in front so it won't be executed if 0: code ... won't run The last one is probably best if what you really want is something like if DEBUG: print ... where you define DEBUG as 1 or 0 at the top of the module. ka > -----Original Message----- > From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of > Adam Vardy > Sent: Friday, January 03, 2003 11:49 AM > To: tutor@python.org > Subject: [Tutor] Comments > > > > How is it you phrase comments? When I'd like to take out a block and > experiment with the rest, what's the method? > > { > > code > ... > > won't run > > } > > print "will run" > > -- > Adam Vardy > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From aztech1200@yahoo.com Fri Jan 3 16:45:02 2003 From: aztech1200@yahoo.com (Aztech Guy) Date: Fri Jan 3 16:45:02 2003 Subject: [Tutor] Applications/examples of some advanced Py features, please ! Message-ID: <20030103214439.9023.qmail@web9801.mail.yahoo.com> --0-1059684377-1041630279=:8758 Content-Type: text/plain; charset=us-ascii Hi Python gurus, Can anyone please give some examples / applications of the use of the following advanced (advanced to me, at least :-) features of Python : 1. lambda 2. nested functions - a little info was given by Danny in reply to my earlier post on local-static variables, but I would like more. 3. Thoughts on implementing Interfaces in Py - a la Java interfaces. I am, and will be doing more, on reading the docs and googling for this, but would anyway appreciate inputs from those who know this stuff. I have a specific reason for the above questions- apart from general interest, of course -> I am planning to write a game-playing program in Py which will have features somewhat AI - ish. I don't have any background in AI; nor much in functional programming. I do understand recursion though. I suspect that some of the above 3 points will help me to write my app in a better way. though not sure, of course. Hence the request for examples. For all of the above 3 points, I'm interested in : - code examples of their use - in what way their use makes code simpler, or maybe makes code possible that could not be written otherwise ('possible' in practical terms - I'm - vaguely - aware of the fact that all languages are supposed to be theoretically 'Turing-equivalent' or some such term - but what I mean is that if something is going to take a huge amount more code in some other language, or jumping through hoops, then I don't call it practically equivalent). Thanks ! Az --------------------------------- Do you Yahoo!? Yahoo! Mail Plus - Powerful. Affordable. Sign up now --0-1059684377-1041630279=:8758 Content-Type: text/html; charset=us-ascii

 

Hi Python gurus,

Can anyone please give some examples / applications of the use of the following advanced (advanced to me, at least :-) features of Python :

1. lambda

2. nested functions - a little info was given by Danny in reply to my earlier post on local-static variables, but I would like more.

3. Thoughts on implementing Interfaces in Py - a la Java interfaces.

I am, and will be doing more, on reading the docs and googling for this, but would anyway appreciate inputs from those who know this stuff.

I have a specific reason for the above questions- apart from general interest, of course -> I am planning to write a game-playing program in Py which will have features somewhat AI - ish. I don't have any background in AI; nor much in functional programming. I do understand recursion though. I suspect that some of the above 3 points will help me to write my app in a better way. though not sure, of course. Hence the request for examples.

For all of the above 3 points, I'm interested in :

 - code examples of their use

 - in what way their use makes code simpler, or maybe makes code possible that could not be written otherwise ('possible' in practical terms - I'm - vaguely - aware of the fact that all languages are supposed to be theoretically 'Turing-equivalent' or some such term - but what I mean is that if something is going to take a huge amount more code in some other language, or jumping through hoops, then I don't call it practically equivalent).

Thanks !

Az

 



Do you Yahoo!?
Yahoo! Mail Plus - Powerful. Affordable. Sign up now --0-1059684377-1041630279=:8758-- From ramrom@earthling.net Fri Jan 3 17:40:34 2003 From: ramrom@earthling.net (Bob Gailer) Date: Fri Jan 3 17:40:34 2003 Subject: [Tutor] subclass of list In-Reply-To: <13827711637.20030103155636@roadrunner.nf.net> References: <7497DCA1C240C042B28F6657ADFD8E097022E1@i2km11-ukbr.domain1.systemhost.net> <7497DCA1C240C042B28F6657ADFD8E097022E1@i2km11-ukbr.domain1.systemhost.net> Message-ID: <5.2.0.9.0.20030103142844.02baaac8@66.28.54.253> --=======1596208D======= Content-Type: text/plain; x-avg-checked=avg-ok-1CF2B71; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit In the latest Python one can subclass types, such as list. What is the benefit? What can one do with an instance of a subclass of list? I'd like to think that, given: class MyList(list): def __init__(self, list) self.list = list x = MyList([3,4]) x[0] would then return 3? Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======1596208D======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-1CF2B71 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.431 / Virus Database: 242 - Release Date: 12/17/2002 --=======1596208D=======-- From ramrom@earthling.net Fri Jan 3 17:47:02 2003 From: ramrom@earthling.net (Bob Gailer) Date: Fri Jan 3 17:47:02 2003 Subject: [Tutor] Applications/examples of some advanced Py features, please ! In-Reply-To: <20030103214439.9023.qmail@web9801.mail.yahoo.com> Message-ID: <5.2.0.9.0.20030103154019.02ba0508@66.28.54.253> --=======41CB536C======= Content-Type: text/plain; x-avg-checked=avg-ok-1CF2B71; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit Regarding lambda, it is an abbreviated way of defining a function. The limitation is that the body of the function is one expression whose value is returned. f = lambda x, y:x+y is the same as def f(x, y): return x+y It is useful when you only need to refer to the function once, as in: filter(lambda x:x>5, some-sequence-of-numbers) That's all I have to say about lambda, except that, if you want to use it with list comprehension the syntax is a little tricky: [(lambda x:x>5)(item) for item in some-sequence-of-numbers] Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======41CB536C======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-1CF2B71 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.431 / Virus Database: 242 - Release Date: 12/17/2002 --=======41CB536C=======-- From Don Arnold" Message-ID: <0b1801c2b37a$d2632490$8510ba3f@defaultcomp> ----- Original Message ----- From: "Adam Vardy" To: Sent: Friday, January 03, 2003 1:45 PM Subject: [Tutor] Tkinter > > Experimenting with TK, I came up on difficulties. Like, in one > program, the window is there but whenever the pointer is over the > window, there is always an hourglass. Can't see anything > wrong. I don't know about this one, but does it happen when you execute the script from the command prompt? Most IDEs have their own event loop that doesn't play nice with Tkinter. > > In another example, I have a button on the window. And a function is > set to run for that. But it runs right away. And nothing happens when > I hit the button! > > -- > Adam Vardy This is a pretty common error. Make sure the callback you supply to the button constructor does _not_ include the parentheses. For example: b = Button(master, text="OK", command=self.ok) assigns the function 'self.ok' as the callback to be executed when the button is pressed. However, b = Button(master, text="OK", command=self.ok( ) ) executes self.ok( ) once when the button is istantiated and assigns the result to the button's 'command' attribute. For more info on Tkinter, you might want to check out http://www.pythonware.com/library/tkinter/introduction/index.htm . HTH, Don From dman@dman.ddts.net Fri Jan 3 18:01:01 2003 From: dman@dman.ddts.net (Derrick 'dman' Hudson) Date: Fri Jan 3 18:01:01 2003 Subject: [Tutor] Re: Embeding Python... (Please help !) In-Reply-To: <029601c2b34f$0feaa760$8ae4e9c0@sxapc> References: <029601c2b34f$0feaa760$8ae4e9c0@sxapc> Message-ID: <20030103230003.GA25215@dman.ddts.net> --G4iJoqBmSsgzjUCe Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Fri, Jan 03, 2003 at 12:39:26PM -0500, Sebastien Auclair wrote: | Our problem is so trivial, it's crazy that we can't find anything on the = net | that would help us. |=20 | We are trying to use the function PyArg_Parse and others in order to simp= ly | get a correctly casted pointer to a Python Class instance. In C or C++ the type will be known as "PyObject". | That python class is in fact a subclass of a C++ class defining an | interface. Our python file knows this interface class through SIP binding= s. |=20 | There are some examples of how we can get simple C type values (strings, | int, float...) from Python types but nothing on pointers to class... We | tried to use the O& option but it doesn't work. | PyObject * v1 =3D PyObject_CallObject(func1,NULL); |=20 | interface * interf =3D (interface*) v1; // OF COURSE THIS DOESN'T WORK B= UT | YOU GET THE IDEA.... The problem here is you want to throw python away. The python object isn't _really_ a implementation of the interface. It is just a PyObject. It just so happens that the contents of the PyObject make it behave (in python) as an implementation of the interface. You need to use the python API to interact with and extract the lower-level data from the PyObject. For example, the interafce defines a method named "update" you would call it with PyObject_CallMethod(v1, "update", NULL); // it returns Py_None Now you want to use the "getValue" method on the interface to get the (integer) value from the class instance. PyObject* presult =3D PyObject_CallObject(v1, "getValue", NULL); int result =3D (int) PyInt_AsLong( presult ) ; Py_DEREF(presult) ; presult =3D NULL ; This might seem like it is overkill and too much effort -- after all, you have the interface declared in C++, but since the object itself is a python object all of its life cycle must be managed by python. The python interpreter is needed to enforce the Python, not C++, semantics of the object. The C (or C++) code for managing python objects will always be much longer and more tedious than the equivalent python code because the C (C++) compiler doesn't provide the same runtime services for C (C++) objects that the python interpreter provides for python objects.. NOTE: In this example code and in the code you posted there is no error checking. If a python C-level function returns NULL that means an exception has occured. http://python.org/doc/current/api/exceptions.html HTH, -D --=20 Windows, hmmm, does it come with a GUI interface that works or just pretty blue screens? =20 http://dman.ddts.net/~dman/ --G4iJoqBmSsgzjUCe Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAj4WFfMACgkQO8l8XBKTpRR07gCfTZ1QD0r9kweyRyJlxijJjJoU FZsAnRUOVyrxwrw1kRB5MGSvefG/Rng6 =Yc8O -----END PGP SIGNATURE----- --G4iJoqBmSsgzjUCe-- From Janssen@rz.uni-frankfurt.de Fri Jan 3 18:48:02 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Fri Jan 3 18:48:02 2003 Subject: [Tutor] subclass of list In-Reply-To: <5.2.0.9.0.20030103142844.02baaac8@66.28.54.253> Message-ID: On Fri, 3 Jan 2003, Bob Gailer wrote: > In the latest Python one can subclass types, such as list. > What is the benefit? What can one do with an instance of a subclass of list? I made very slow processes in understanding those OOP stuff, but one of the first things I've done with it was subclassing dictionaries and strings (sorry, not lists, but it's the same: adaptation of datastructures to personal needs). As a beginnner I don't subclass dict/list/string directly but the UserDict/List/String modules: These classes reimplement the exact behaviour of dict-list-strings. When you modify (subclass) these classes you possibly don't overwrite some essential functionality (Because you can take a look at the functionality in UserDict/andsoon). If subclassed UserDict in order to provide some more methods especially for the needs of my programm: it uses an internal "data-container" which is in core a dict (i.e. was a dict in early programm-versions). I recognize that I was constantly doing the same jobs with this data containing dict and so I decided to enhance UserDict with methods for this jobs. My life was easier since then, because I needn't to paste and copy the code any more but use the new methods (which means: I needn't to think of the internal implementation any more) Some days ago I have added a "readline" methods to UserString: I was struggling with the Classes in mailbox, mimetools and multifile moduls which all want to get a filedescriptor to read from. Instantiate those Classes with strings fails because of the missing readline method. Now it *works* (Disclaimer: this was purely to learn how thoses Classes work; I have removed this "workaround-code" and go on with real filedescriptors.) For lists, it can be: You don't want to write median(AList) (1) but rather: AList.median(). Or you want to compair two list not in the implementet way (That is campaire the first values, if equally the seconds and so on) but for example by its median. therefore you simply overwrite the __cmp__ method. Or you want to get something completly different as a two dimensional array. Perhaps subclassing list or UserList is a good start point for this. In short: You can put additional methods into your own classes and forget about the implementation. You can use __operator__ methods (look in doc/lib/module-operator.html for this) to call methods "without calling them directly" (hope you understand what I mean). With these operators you can overwrite the *behaviour* of list/dict/string On a side note: I've got my first inside in what OOP is for, as someone wrotes that "OOP means to put the data and functionality together". From then on, I rewrote my script, which consists of functions to handel input and store it into datastructures and functions to retrieve the data and transform it for output. now this script consist of a modified UserDict which makes much of the work self and functions to call my UserDict instance (that's not OOP, but it's a step, I believe ;-). Therefore I'm comming from the datastructure side and go to put some functionality into data, which might be a kind of OOP; but: only one kind of ;-) Michael > I'd like to think that, given: > > class MyList(list): > def __init__(self, list) > self.list = list > x = MyList([3,4]) > > x[0] would then return 3? When you take a look into UserList.py you might find out yourself, why this isn't already working ;-) > > Bob Gailer > mailto:ramrom@earthling.net > 303 442 2625 > From dyoo@hkn.eecs.berkeley.edu Fri Jan 3 19:47:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Jan 3 19:47:01 2003 Subject: [Tutor] Applications/examples of some advanced Py features, please ! In-Reply-To: <5.2.0.9.0.20030103154019.02ba0508@66.28.54.253> Message-ID: On Fri, 3 Jan 2003, Bob Gailer wrote: > Regarding lambda, it is an abbreviated way of defining a function. The > limitation is that the body of the function is one expression whose > value is returned. > > f = lambda x, y:x+y > > is the same as > > def f(x, y): > return x+y Hi Bob, Python's lambda expressions are deliberately weakened to force people to use them only for simple stuff --- Python programs favor giving real names to functions. In contrast, in some other languages, like Scheme and Ocaml, the lambda concept is allowed more expressivity, so lambda is more prevalent in those languages. > It is useful when you only need to refer to the function once, as in: > filter(lambda x:x>5, some-sequence-of-numbers) > > That's all I have to say about lambda, except that, if you want to use > it with list comprehension the syntax is a little tricky: > > [(lambda x:x>5)(item) for item in some-sequence-of-numbers] I think you mean: [item for item in some_sequence_of_numbers if (lambda x: x>5)(item)] to do a filtering kind of operation. But yes, this is pretty darn ugly. List comprehensions and lambdas don't mix very well, but that's probably because they're not supposed to. *grin* A functional programmer would use the filter() function instead of a list comprehension: ### >>> some_sequence_of_numbers = [3,1,4,1,5,9,2,6] >>> filter(lambda x: x>5, some_sequence_of_numbers) [9, 6] ### which, if we cross our eyes funny, can scan as "Filter a list of elements out of some_sequence_of_numbers, chosen by this particular boolean function." Just to contrast with another language, let's see what this might look like in OCaml: (*** OCaml code --- the stuff with # in the beginning is what I type. ***) # let some_sequence_of_numbers = [3;1;4;1;5;9;2;6];; val some_sequence_of_numbers : int list = [3; 1; 4; 1; 5; 9; 2; 6] # List.filter (function x -> x > 5) some_sequence_of_numbers;; - : int list = [9; 6] (***) Good, at least we get a similar result. *grin* Lambda is pretty much used as a convenient way of writing quicky one-shot functions for "mapping" and "filtering". In computer science theory, they're pretty important --- in the functional-based languages, lambdas are a fundamental building block of computation --- but in Python, they play a backstage role: it's often a good thing to just define a new function using 'def'. Good luck! From beercanz@hotmail.com Fri Jan 3 21:09:02 2003 From: beercanz@hotmail.com (Guess Who? Me) Date: Fri Jan 3 21:09:02 2003 Subject: [Tutor] Help. Message-ID: This is what I've done: a=0 b=0 ###### print "Enter 2 numbers!" a=input("Give me the first number so I may munch it!") b=input("Give me the second number so I may munch it!") ###### if a+b < 100: print "That number 'aint so big!" elif a+b > 100: print "That number is huge!" else: print "That number is on the edge." The question: when I try to say, 'Sum=a+c', and plug that in for a+b in the if and elif statements, it doesn't work. I'll plug in sum for a+b and put sum=a+b at the top, and the program thinks every number 'aint so big - strange. Any help is appreciated, I hope the question was clear enough. Thanks! Travis _________________________________________________________________ MSN 8 with e-mail virus protection service: 2 months FREE* http://join.msn.com/?page=features/virus From ramrom@earthling.net Fri Jan 3 21:50:14 2003 From: ramrom@earthling.net (Bob Gailer) Date: Fri Jan 3 21:50:14 2003 Subject: [Tutor] Help. In-Reply-To: Message-ID: <5.2.0.9.0.20030103194441.02c20e18@66.28.54.253> --=======4AA0B0E======= Content-Type: text/plain; x-avg-checked=avg-ok-1CF2B71; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 02:03 AM 1/4/2003 +0000, Guess Who? Me wrote: >a=0 >b=0 >###### >print "Enter 2 numbers!" >a=input("Give me the first number so I may munch it!") >b=input("Give me the second number so I may munch it!") >###### >if a+b < 100: > print "That number 'aint so big!" >elif a+b > 100: > print "That number is huge!" >else: > print "That number is on the edge." > >The question: >when I try to say, 'Sum=a+c', and plug that in for a+b in the if and elif >statements, it doesn't work. I'll plug in sum for a+b and put sum=a+b at >the top, and the program thinks every number 'aint so big - strange. Any >help is appreciated, I hope the question was clear enough. Please provide the code that doesn't work. It's very hard to guess what it looks like. If I took you literally, I'd expect: sum a+b # at the top, as you say a=0 b=0 etc which clearly won't work. Also note that assigning a=0 and b=0 accomplishes nothing, as they are replaced by the inputs. Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======4AA0B0E======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-1CF2B71 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.431 / Virus Database: 242 - Release Date: 12/17/2002 --=======4AA0B0E=======-- From ramrom@earthling.net Fri Jan 3 22:15:01 2003 From: ramrom@earthling.net (Bob Gailer) Date: Fri Jan 3 22:15:01 2003 Subject: [Tutor] subclass of list In-Reply-To: References: <5.2.0.9.0.20030103142844.02baaac8@66.28.54.253> Message-ID: <5.2.0.9.0.20030103195708.02c31d60@66.28.54.253> --=======7F796E11======= Content-Type: text/plain; x-avg-checked=avg-ok-1CF2B71; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit Your reference to UserList helped. One thing I missed was that the internal list can be set by passing a list as the argument to the instantiation call. >>> class UL(UserList):pass >>> ul=UL([1,2,3]) >>> ul [1,2,3] >>> ul.data [1,2,3] AND (using list instead of UserList) >>> class UL(llist):pass >>> ul=UL([1,2,3]) >>> ul [1,2,3] HOWEVER: >>> ul.data AttributeError: 'UL' object has no attribute 'data' A little "thinking and experimenting" led to: instead of manipulating self.data one now manipulates self: >>> class UL(list): ... def a(self): ... self[0]+=1 >>> ul=UL([1,2,3]) >>> ul.a() >>> ul [2, 2, 3] Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======7F796E11======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-1CF2B71 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.431 / Virus Database: 242 - Release Date: 12/17/2002 --=======7F796E11=======-- From glingl@aon.at Sat Jan 4 00:37:01 2003 From: glingl@aon.at (Gregor Lingl) Date: Sat Jan 4 00:37:01 2003 Subject: [Tutor] subclass of list References: <7497DCA1C240C042B28F6657ADFD8E097022E1@i2km11-ukbr.domain1.systemhost.net> <7497DCA1C240C042B28F6657ADFD8E097022E1@i2km11-ukbr.domain1.systemhost.net> <5.2.0.9.0.20030103142844.02baaac8@66.28.54.253> Message-ID: <3E1672D4.8010202@aon.at> This is a multi-part message in MIME format. --------------030307060502060304060109 Content-Type: text/plain; charset=us-ascii; format=flowed Content-Transfer-Encoding: 7bit Bob Gailer schrieb: > In the latest Python one can subclass types, such as list. Hi Bob! If you want to subclass a built-in type, you have to calls the constructor of the parent-class in the same way as if you subclass any class. That means, as a "class"-method, which goes like this: >>> class MyList(list): ... def __init__(self, liste): ... list.__init__(self,liste) ... >>> a = MyList([3,4]) >>> a [3, 4] >>> a[0] 3 You now can use any list method with a: >>> a.append(1001) >>> a [3, 4, 1001] >>> > > What is the benefit? What can one do with an instance of a subclass of > list? For instance - as an appendix to the median-thread from two or three days ago - you may create a class of Lists, which know their own median: class mlist(list): def __init__(self, aList): list.__init__(self,aList) def median(self): # according to Don Arnolds implementation tempList = self[:] tempList.sort() listLen = len(tempList) middleIndex = (listLen - 1) // 2 if listLen % 2 == 1: #odd number of elements. return middle element return tempList[middleIndex] else: #even number of element. return average of middle 2 elements return (tempList[middleIndex] + tempList[middleIndex + 1]) / 2.0 if __name__ == '__main__': theList = mlist([2,3,4,5,6]) print theList print 'median = ', theList.median() theList = mlist([1,2,6,7]) print theList print 'median = ', theList.median() Running this program you get: [2, 3, 4, 5, 6] median = 4 [1, 2, 6, 7] median = 4.0 You may find another interesting example in the attachment. There is defined a class Turm, which means tower :-) , derived from list. Actually there the constructor list.__init__ needs not to be called, because newly constructed Turms always are empty. Regards, Gregor > > I'd like to think that, given: > > class MyList(list): > def __init__(self, list) > self.list = list > x = MyList([3,4]) > > x[0] would then return 3? > > Bob Gailer --------------030307060502060304060109 Content-Type: text/plain; name="hanoig.py" Content-Transfer-Encoding: 8bit Content-Disposition: inline; filename="hanoig.py" ### Python für Kids - Kapitel B4 ### # Autor: Gregor Lingl # Datum: 29. 9. 2002 # hanoig.py from Tkinter import Tk, Canvas from Canvas import Rectangle # from scheibe import Scheibe usingIDLE = 0 # auf 1 setzen, wenn das Programm von IDLE # aus ausgeführt wird. class Scheibe(Rectangle): "Bewegliches Rechteck auf einem Tkinter-Canvas" def __init__(self,cv,pos,laenge,hoehe): x0, y0 = pos x1, x2 = x0-laenge/2.0, x0+laenge/2.0 y1, y2 = y0-hoehe, y0 Rectangle.__init__(self,cv,x1,y1,x2,y2, fill = "red") def bewege_nach(self, x, y): from math import sqrt x1,y1,x2,y2 = self.coords() x0, y0 = (x1 + x2)/2, y2 dx, dy = x-x0, y-y0 d = sqrt(dx**2+dy**2) schritte = int(d/10) + 1 dx, dy = dx/schritte, dy/schritte for i in range(schritte): self.move(dx,dy) self.canvas.update() self.canvas.after(20) class Turm(list): def __init__(self, x, y, h): self.x = x self.y = y self.h = h def top(self): return self.x, self.y - len(self)*self.h def hanoi(n,von,nach,hilf): if n==1: move(von,nach) else: hanoi(n-1,von,hilf,nach) hanoi(1,von,nach,hilf) hanoi(n-1,hilf,nach,von) def move(von_turm, nach_turm): scheibe = von_turm.pop() x1, y1 = von_turm.top() x2, y2 = nach_turm.top() scheibe.bewege_nach(x1,20) scheibe.bewege_nach(x2,20) scheibe.bewege_nach(x2,y2) nach_turm.append(scheibe) def hanoispiel(n): """Führt ein Hanoi-Spiel mit n Scheiben aus:""" root = Tk() # ein Fenster root.title("Türme von Hanoi") # mit Titel, cv = Canvas(root,width=440,height=210) # eine Leinwand - cv.pack() # - aufspannen pflock1 = Rectangle(cv, 75, 40, 85,190,fill='blue') pflock2 = Rectangle(cv,215, 40,225,190,fill='blue') pflock3 = Rectangle(cv,355, 40,365,190,fill='blue') boden = Rectangle(cv, 5,190,435,200,fill='black') turm_a = Turm( 80, 190, 15) turm_b = Turm(220, 190, 15) turm_c = Turm(360, 190, 15) for i in range(n): # turm_a aufbauen laengen_differenz = 100 // n laenge = 120 - i * laengen_differenz s = Scheibe( cv, turm_a.top(), laenge, 13) turm_a.append(s) hanoi(n, turm_a, turm_b, turm_c) if not usingIDLE: root.mainloop() if __name__ == '__main__': hanoispiel(7) --------------030307060502060304060109-- From tony@tcapp.com Sat Jan 4 01:07:01 2003 From: tony@tcapp.com (Tony Cappellini) Date: Sat Jan 4 01:07:01 2003 Subject: [Tutor] PythonWin IDE Problem on Win2K with ActivePython Message-ID: <5.1.0.14.0.20030103221352.03f6ce10@smtp.sbcglobal.net> Tom, I am using Win2k SP3, but I'm using PythonWin32 1.50, on Python 2.2.2, I don't see this problem. What is Active Python ? From glingl@aon.at Sat Jan 4 01:12:02 2003 From: glingl@aon.at (Gregor Lingl) Date: Sat Jan 4 01:12:02 2003 Subject: [Tutor] Applications/examples of some advanced Py features, please ! References: Message-ID: <3E167961.7090302@aon.at> > > > >Lambda is pretty much used as a convenient way of writing quicky one-shot >functions for "mapping" and "filtering". In computer science theory, >they're pretty important --- in the functional-based languages, lambdas >are a fundamental building block of computation --- but in Python, they >play a backstage role: it's often a good thing to just define a new >function using 'def'. > > Just to quote Guido (from: http://www.python.org/doc/essays/ppt/regrets/PythonRegrets.pdf ) . I've never liked lambda - crippled (only one expression) - confusing (no argument list parentheses) - can use a local function instead Gregor From glingl@aon.at Sat Jan 4 02:36:09 2003 From: glingl@aon.at (Gregor Lingl) Date: Sat Jan 4 02:36:09 2003 Subject: [Tutor] subclass of list References: <7497DCA1C240C042B28F6657ADFD8E097022E1@i2km11-ukbr.domain1.systemhost.net> <7497DCA1C240C042B28F6657ADFD8E097022E1@i2km11-ukbr.domain1.systemhost.net> <5.2.0.9.0.20030103142844.02baaac8@66.28.54.253> <3E1672D4.8010202@aon.at> Message-ID: <3E168EF4.5010200@aon.at> :-( ! During preparing breakfast I suddenly recognized, that I had written some nonsense here - (perhaps I should have breakfast *before* writing emails.) Gregor Lingl schrieb: > > Hi Bob! > If you want to subclass a built-in type, you have to call the > constructor of the parent-class in the same way as if you > subclass any class. That means, as a "class"-method, which goes like > this: > > >>> class MyList(list): > ... def __init__(self, liste): > ... list.__init__(self,liste) > ... > >>> a = MyList([3,4]) > >>> a > [3, 4] > >>> a[0] > 3 This is only necessary if you additionally do something else in the constructor. Otherwise, the constructor of the parent-class is called automatically. So the following simple code also works: >>> class MyList(list): ... pass ... >>> a = MyList([3,4]) >>> a [3, 4] >>> a[1] 4 >>> Of course, MyList here is nothing more than an ordinary list. But also mlist doesn't need special initialization: >>> class mlist(list): def median(self): # according to Don Arnolds implementation tempList = self[:] tempList.sort() listLen = len(tempList) middleIndex = (listLen - 1) // 2 if listLen % 2 == 1: #odd number of elements. return middle element return tempList[middleIndex] else: #even number of element. return average of middle 2 elements return (tempList[middleIndex] + tempList[middleIndex + 1]) / 2.0 >>> >>> a = mlist([1,2,3]) >>> a.median() 2 >>> a = mlist([1,2,3,4]) >>> a.median() 2.5 Sorry for this error! As an - albeit rather useless ;-) - example for a classe derived from list, which needs the call of the constructor of the superclass ma serve the following: >>> class shortList(list): ... def __init__(self, aList, maxlen=3): ... self.maxlen = maxlen ... list.__init__(self,aList[-maxlen:]) ... def append(self, element): ... list.append(self,element) ... if len(self)>3: ... return self.pop(0) ... >>> a = shortList([2,3,5,7,11,13]) >>> a [7, 11, 13] >>> a.append(17) 7 >>> a [11, 13, 17] >>> Here the definition of append (overwriting the orginal method) also shows, how to call the append method of the superclass, which has to be done exactly in the same way as it is done with __init__. If you try to replace list.append(self,element) with self.append(element) you will see immediatly that this is definitly another append (namely the one, which is just going to be defined). Maybe this also will create some insight on why some special syntax is necessary for calling methods of the parent class. Hope, this examples + explanations are correct now, Gregor From glingl@aon.at Sat Jan 4 04:03:02 2003 From: glingl@aon.at (Gregor Lingl) Date: Sat Jan 4 04:03:02 2003 Subject: [Tutor] subclass of list - one more correction References: <7497DCA1C240C042B28F6657ADFD8E097022E1@i2km11-ukbr.domain1.systemhost.net> <7497DCA1C240C042B28F6657ADFD8E097022E1@i2km11-ukbr.domain1.systemhost.net> <5.2.0.9.0.20030103142844.02baaac8@66.28.54.253> <3E1672D4.8010202@aon.at> <3E168EF4.5010200@aon.at> Message-ID: <3E16A34C.6040101@aon.at> Gregor Lingl schrieb > > As an - albeit rather useless ;-) - example for a classe derived from > list, which needs > the call of the constructor of the superclass ma serve the following: > > >>> class shortList(list): > ... def __init__(self, aList, maxlen=3): > ... self.maxlen = maxlen > ... list.__init__(self,aList[-maxlen:]) > ... def append(self, element): > ... list.append(self,element) > ... if len(self)>3: # Should read, of course: if len(self) > self.maxlen: > > ... return self.pop(0) > ... > Sorry. (No more comment, Gregor) From gp@pooryorick.com Sat Jan 4 09:22:01 2003 From: gp@pooryorick.com (Poor Yorick) Date: Sat Jan 4 09:22:01 2003 Subject: [Tutor] unicode utf-16 and readlines Message-ID: <3E16EE3E.6020603@pooryorick.com> On Windows 2000, Python 2.2.1 open.readlines seems to read lines incorrectly when the file is encoded utf-16. For example: >>> fh = open('0022data2.txt') >>> a = fh.readlines() >>> print a ['\xff\xfe\xfaQ\r\x00\n', '\x00'] In this example, Python seems to have incorrectly parsed the \n\r characters at the end of the line. It's an error that one can work around by slicing off the last three characters of every other list element, but it makes working with utf-16 files non-intuitive, especially for beginners. Or am I missing something? Poor Yorick gp@pooryorick.com From skitzomonkey@hotmail.com Sat Jan 4 09:46:01 2003 From: skitzomonkey@hotmail.com (mike O) Date: Sat Jan 4 09:46:01 2003 Subject: [Tutor] pausing and layout Message-ID: I guess I have three questions, the first being: Is there a python command to pause until the user does something? Also, how do you get python (when you don't run it in DOS Prompt) to not auto-exit? I have made a few simple programs, but as soon as it shows the answer, it exits. last, I was wondering how you do visual stuff, or make a program run in a window, instead of in the command prompt screen? Thanks, Mike _________________________________________________________________ STOP MORE SPAM with the new MSN 8 and get 2 months FREE* http://join.msn.com/?page=features/junkmail From op73418@mail.telepac.pt Sat Jan 4 10:07:02 2003 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Sat Jan 4 10:07:02 2003 Subject: [Tutor] pausing and layout References: Message-ID: <001301c2b403$c3768060$88190dd5@violante> ----- Original Message ----- From: "mike O" To: Sent: Saturday, January 04, 2003 2:45 PM Subject: [Tutor] pausing and layout > I guess I have three questions, the first being: Is there a python command > to pause until the user does something? > What do you want exactly? "until the user does something" is a very broad and general category to receive any useful and concrete answer. Is it input? Then the raw_input function is probably enough for you. Something like user_input = raw_input('Give a number, please: ') And then the program will just halt until the user has given some input and pressed newline. > Also, how do you get python (when you don't run it in DOS Prompt) to not > auto-exit? I have made a few simple programs, but as soon as it shows the > answer, it exits. > Just add a raw_input() call at the end of your program. Then, as I said earlier the program will pause giving you a chance to look at the output. > last, I was wondering how you do visual stuff, or make a program run in a > window, instead of in the command prompt screen? > This gets you in the realm of programming called GUI (graphical user interface) programming. First, you need a GUI toolkit. Python already comes with one: TKinter but there are others. The one I use is wxPython. But for an intro to TKinter you can start at: http://home.att.net/~stephen_ferg/thinking_in_tkinter/index.html > Thanks, > Mike > With my best regards, G. Rodrigues From gp@pooryorick.com Sat Jan 4 10:21:01 2003 From: gp@pooryorick.com (Poor Yorick) Date: Sat Jan 4 10:21:01 2003 Subject: Keeping DOS prompt/command window open (was [Tutor] pausing and layout) References: Message-ID: <3E16FC16.1020009@pooryorick.com> mike O wrote: > > > Also, how do you get python (when you don't run it in DOS Prompt) to > not auto-exit? I have made a few simple programs, but as soon as it > shows the answer, it exits. > > I've never seen my method of doing this posted, which is to opend python using cmd.exe /k. Here are the details for Windows 2000 (same concept should work on any version of Windows): From Windows explorer, go to Tools - Folder Options - File Types Select the ".py" extension and click "Advanced" In the "Edit File Type" window, click "New" In the action field, type in something descriptive, like "Run and remain" In the "Application used to perform action" field, add the following line: cmd.exe /k C:\Python22\python.exe "%1" %* click "OK" If you want to, set your new action as the default action. Your new action will now be available on the menu when you right-click. If it is the default action, it will trigger when you double-click on a .py file. You can also accomplish this same thing by making a shortcut to your Python executable and then adding command-line parameters to the shortcut. Poor Yorick gp@pooryorick.com From op73418@mail.telepac.pt Sat Jan 4 11:36:16 2003 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Sat Jan 4 11:36:16 2003 Subject: [Tutor] Applications/examples of some advanced Py features, please ! References: <20030103214439.9023.qmail@web9801.mail.yahoo.com> Message-ID: <001d01c2b410$49d816d0$88190dd5@violante> This is a multi-part message in MIME format. ------=_NextPart_000_001A_01C2B410.49B68510 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable I will just comment on the functional stuff and reserve my comment on = the interfaces stuff to another post. I haven't got any specific use cases for you. But one advice that I got = and that helped me a lot was just to browse the code in the Python = standard library. The code there is high quality and you are bound to = find several use cases for lambda, although much less for nested scopes = since they are a relatively recent addition to the language.=20 If you want to learn more on functional programming, David Mertz has 3 = articles about it in the IBM developer works site. Just google for them. With my best regards G. Rodrigues ----- Original Message -----=20 From: Aztech Guy=20 To: tutor@python.org=20 Sent: Friday, January 03, 2003 9:44 PM Subject: [Tutor] Applications/examples of some advanced Py features, = please ! Hi Python gurus, Can anyone please give some examples / applications of the use of the = following advanced (advanced to me, at least :-) features of Python : 1. lambda 2. nested functions - a little info was given by Danny in reply to my = earlier post on local-static variables, but I would like more. 3. Thoughts on implementing Interfaces in Py - a la Java interfaces. I am, and will be doing more, on reading the docs and googling for = this, but would anyway appreciate inputs from those who know this stuff. I have a specific reason for the above questions- apart from general = interest, of course -> I am planning to write a game-playing program in = Py which will have features somewhat AI - ish. I don't have any = background in AI; nor much in functional programming. I do understand = recursion though. I suspect that some of the above 3 points will help me = to write my app in a better way. though not sure, of course. Hence the = request for examples. For all of the above 3 points, I'm interested in : - code examples of their use - in what way their use makes code simpler, or maybe makes code = possible that could not be written otherwise ('possible' in practical = terms - I'm - vaguely - aware of the fact that all languages are = supposed to be theoretically 'Turing-equivalent' or some such term - but = what I mean is that if something is going to take a huge amount more = code in some other language, or jumping through hoops, then I don't call = it practically equivalent). Thanks ! Az ------=_NextPart_000_001A_01C2B410.49B68510 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
I will just comment on the functional stuff and reserve my comment = on the=20 interfaces stuff to another post.

I haven't got any specific use = cases=20 for you. But one advice that I got and that helped me a lot was just to = browse=20 the code in the Python standard library. The code there is high quality = and you=20 are bound to find several use cases for lambda, although much less for = nested=20 scopes since they are a relatively recent addition to the language. =

If you want to learn more on functional programming, David = Mertz has 3=20 articles about it in the IBM developer works site. Just google for=20 them.

With my best regards
G. Rodrigues
----- Original Message -----
From:=20 Aztech=20 Guy
Sent: Friday, January 03, 2003 = 9:44=20 PM
Subject: [Tutor] = Applications/examples of=20 some advanced Py features, please !

 

Hi Python gurus,

Can anyone please give some examples / applications of the use = of the=20 following advanced (advanced to me, at least :-) features of Python = :

1. lambda

2. nested functions - a little info was given by Danny in = reply to my=20 earlier post on local-static variables, but I would like = more.

3. Thoughts on implementing Interfaces in Py - a la Java=20 interfaces.

I am, and will be doing more, on reading the docs and googling for = this,=20 but would anyway appreciate inputs from those who know this stuff.

I have a specific reason for the above questions- apart from = general=20 interest, of course -> I am planning to write a game-playing = program in Py=20 which will have features somewhat AI - ish. I don't have any = background in AI;=20 nor much in functional programming. I do understand recursion though. = I=20 suspect that some of the above 3 points will help me to write my app = in a=20 better way. though not sure, of course. Hence the request for = examples.

For all of the above 3 points, I'm interested in :

 - code examples of their use

 - in what way their use makes code simpler, or maybe makes = code=20 possible that could not be written otherwise ('possible' in practical = terms -=20 I'm - vaguely - aware of the fact that all languages are supposed to = be=20 theoretically 'Turing-equivalent' or some such term - but what I mean = is that=20 if something is going to take a huge amount more code in some other = language,=20 or jumping through hoops, then I don't call it practically=20 equivalent).

Thanks !

Az

------=_NextPart_000_001A_01C2B410.49B68510-- From Janssen@rz.uni-frankfurt.de Sat Jan 4 12:48:02 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Sat Jan 4 12:48:02 2003 Subject: [Tutor] pausing and layout In-Reply-To: Message-ID: On Sat, 4 Jan 2003, mike O wrote: > I guess I have three questions, the first being: Is there a python comman= d > to pause until the user does something? Hello Mike In addition to Gon=E7alo's reply I want to say that raw_input() is typicall= y used in a while loop: from types import IntType ... while 1: p =3D raw_input("Choose a Number or [Q]uit: ") if p =3D=3D "Q" or p =3D=3D "q" or p =3D=3D "": # User requests the end of the game sys.exit() =09elif type(p) =3D=3D IntType: # we have checked if p is sufficient and exit while loop break else: # we've got some input, but it was the wrong: continue # with the while loop and ask the user again print "\tError: please choose a number." #NOW do something with "p" In a GUI application there is a overall loop "mainloop" which waits for any kind of user interaction (you needn't explicit programm this mainloop: in GUI programming it comes with the package) Michael > > Also, how do you get python (when you don't run it in DOS Prompt) to not > auto-exit? I have made a few simple programs, but as soon as it shows the > answer, it exits. > > last, I was wondering how you do visual stuff, or make a program run in a > window, instead of in the command prompt screen? > > Thanks, > Mike > > _________________________________________________________________ > STOP MORE SPAM with the new MSN 8 and get 2 months FREE* > http://join.msn.com/?page=3Dfeatures/junkmail > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From skitzomonkey@hotmail.com Sat Jan 4 12:54:02 2003 From: skitzomonkey@hotmail.com (mike O) Date: Sat Jan 4 12:54:02 2003 Subject: [Tutor] pausing and layout Message-ID: >From: Michael Janssen >To: mike O >CC: >Subject: Re: [Tutor] pausing and layout >Date: Sat, 4 Jan 2003 18:47:12 +0100 (CET) > >On Sat, 4 Jan 2003, mike O wrote: > > > I guess I have three questions, the first being: Is there a python >command > > to pause until the user does something? >Hello Mike > >In addition to Gonçalo's reply I want to say that raw_input() is typically >used in a while loop: > >from types import IntType > ... > > while 1: > p = raw_input("Choose a Number or [Q]uit: ") > if p == "Q" or p == "q" or p == "": > # User requests the end of the game > sys.exit() > elif type(p) == IntType: > # we have checked if p is sufficient and exit while loop > break > else: > # we've got some input, but it was the wrong: continue > # with the while loop and ask the user again > print "\tError: please choose a number." > #NOW do something with "p" > If you just wanted a number, couldn't you use input instead of raw_input? I'm not entirely sure on these two functions, other than that I thought input was for an integer, and raw_input was for a string, is that right? >In a GUI application there is a overall loop "mainloop" which waits for >any kind of user interaction (you needn't explicit programm this mainloop: >in GUI programming it comes with the package) > >Michael > > > > > Also, how do you get python (when you don't run it in DOS Prompt) to not > > auto-exit? I have made a few simple programs, but as soon as it shows >the > > answer, it exits. > > > > last, I was wondering how you do visual stuff, or make a program run in >a > > window, instead of in the command prompt screen? > > > > Thanks, > > Mike > > > > _________________________________________________________________ > > STOP MORE SPAM with the new MSN 8 and get 2 months FREE* > > http://join.msn.com/?page=features/junkmail > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ MSN 8 with e-mail virus protection service: 2 months FREE* http://join.msn.com/?page=features/virus From op73418@mail.telepac.pt Sat Jan 4 13:10:02 2003 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Sat Jan 4 13:10:02 2003 Subject: [Tutor] pausing and layout References: Message-ID: <000501c2b41d$55d32f30$88190dd5@violante> ----- Original Message ----- From: "mike O" To: Cc: Sent: Saturday, January 04, 2003 5:53 PM Subject: Re: [Tutor] pausing and layout > > > > > > > > >From: Michael Janssen > >To: mike O > >CC: > >Subject: Re: [Tutor] pausing and layout > >Date: Sat, 4 Jan 2003 18:47:12 +0100 (CET) > > > >On Sat, 4 Jan 2003, mike O wrote: > > > > > I guess I have three questions, the first being: Is there a python > >command > > > to pause until the user does something? > >Hello Mike > > > >In addition to Gonçalo's reply I want to say that raw_input() is typically > >used in a while loop: > > > >from types import IntType > > ... > > > > while 1: > > p = raw_input("Choose a Number or [Q]uit: ") > > if p == "Q" or p == "q" or p == "": > > # User requests the end of the game > > sys.exit() > > elif type(p) == IntType: > > # we have checked if p is sufficient and exit while loop > > break > > else: > > # we've got some input, but it was the wrong: continue > > # with the while loop and ask the user again > > print "\tError: please choose a number." > > #NOW do something with "p" > > > If you just wanted a number, couldn't you use input instead of raw_input? > I'm not entirely sure on these two functions, other than that I thought > input was for an integer, and raw_input was for a string, is that right? > No. input is just a call to raw_input *and then* an evaluation of the returned string via the eval function, that is, input is the same as eval(raw_input("A number, please:")) Since it does no checking whatsoever this is an absolute no-no in terms of security - the user can do *everything* that Python is capable (yes, including formatting the hard disk). If you really want/expect an integer just follow the usual Python idiom: try to convert it, handling any ensuing exceptions, e.g. something like while 1: s = raw_input("A number, please:") try: number = int(s) break except ValueError: print "Hey buster, I *want* a number" If you don't know while loop's or exception-handling I suggest you start at the newbie tutorials (go to the newbies section in www.python.org) and post any questions you might have here. All the best, G. Rodrigues From tony@tcapp.com Sat Jan 4 13:31:19 2003 From: tony@tcapp.com (Tony Cappellini) Date: Sat Jan 4 13:31:19 2003 Subject: [Tutor] re:Tutor] pausing and layout Message-ID: <5.1.0.14.0.20030104103803.023e37b8@smtp.sbcglobal.net> Mike I 've found this recently- which is the equivalent for getch(), which will effectively pause until the user presses a key. There are a version for windows & unix. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892 From Janssen@rz.uni-frankfurt.de Sat Jan 4 13:33:01 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Sat Jan 4 13:33:01 2003 Subject: [Tutor] pausing + raw_input vs input In-Reply-To: Message-ID: On Sat, 4 Jan 2003, mike O wrote: > If you just wanted a number, couldn't you use input instead of raw_input? > I'm not entirely sure on these two functions, other than that I thought > input was for an integer, and raw_input was for a string, is that right? half right ;-) raw_input(prompt) returns always strings. input(prompt) returns that type of object the expert user created at the prompt. The main difference is not string vs any-object but expert user vs nonexpert user! compare doc/lib/built-in-funcs.html#l2h-30 input([prompt]) Equivalent to eval(raw_input(prompt)). Warning: This function is not safe from user errors! It expects a valid Python expression as input; if the input is not syntactically valid, a SyntaxError will be raised. Other exceptions may be raised if there is an error during evaluation. (On the other hand, sometimes this is exactly what you need when writing a quick script for expert use.) You can take input() to get an integer, but the user need only to type a letter and your programm is down. Better use raw_input() and "try" to convert the users input with int(): while 1: user_input = raw_input("No: ") try: number = int(user_input) break # stop while-loop except ValueError: print "that was no number: " + user_input # implicite remain in while loop try-except is explained in the tutorial: doc/tut/node10.html. You will need to learn this anyway (in case not already done :-) Michael Example for input (at interactive interpreter): >>> j = input("hey, experts, give me an object! ") hey, experts, give me an object! [2, 3, 4, 5] >>> type(j) >>> j [2, 3, 4, 5] From aztech1200@yahoo.com Sat Jan 4 14:32:02 2003 From: aztech1200@yahoo.com (Aztech Guy) Date: Sat Jan 4 14:32:02 2003 Subject: [Tutor] Applications/examples of some advanced Py features, please ! In-Reply-To: <001d01c2b410$49d816d0$88190dd5@violante> Message-ID: <20030104193101.8744.qmail@web9806.mail.yahoo.com> --0-1915008729-1041708661=:8337 Content-Type: text/plain; charset=us-ascii Thanks, Goncalo, Gregor, Bob, Danny. I'll try out the ideas suggested and revert with my results. Looking forward to more replies on some of the other topics not mentioned, if anyone has any ideas about them.. Goncalo - a question - does the standard Python binary distribution (I have ActivePython 2.2.1 on Windows 98 and the Python 2.2 that comes with Red Hat 7.3 on Linux) - have all/most of the source for the std. lib. or do I have to download something else separately ? I do see a lot of .py files under the Lib directory, but since I'm new to Python, I don't know if they include all of the std. lib. - or if there is a formal concept of "std. lib." as there is in C, for instance. Anyway, I do have a lot of .py files there, and I'll read thru them for lambda examples. Thanks for the tip. Az. Gonçalo_Rodrigues wrote:I will just comment on the functional stuff and reserve my comment on the interfaces stuff to another post. I haven't got any specific use cases for you. But one advice that I got and that helped me a lot was just to browse the code in the Python standard library. The code there is high quality and you --------------------------------- Do you Yahoo!? Yahoo! Mail Plus - Powerful. Affordable. Sign up now --0-1915008729-1041708661=:8337 Content-Type: text/html; charset=us-ascii

Thanks,

Goncalo, Gregor, Bob, Danny.

I'll try out the ideas suggested and revert with my results.

Looking forward to more replies on some of the other topics not mentioned, if anyone has any ideas about them..

Goncalo - a question - does the standard Python binary distribution (I have ActivePython 2.2.1 on Windows 98 and the Python 2.2 that comes with Red Hat 7.3 on Linux) - have all/most of the source for the std. lib. or do I have to download something else separately ? I do see a lot of .py files under the Lib directory, but since I'm new to Python, I don't know if they include all of the std. lib. - or if there is a formal concept of "std. lib." as there is in C, for instance.  Anyway, I do have a lot of .py files there, and I'll read thru them for lambda examples. Thanks for the tip.

 

Az.

 

 

 Gonçalo_Rodrigues <op73418@mail.telepac.pt> wrote:

I will just comment on the functional stuff and reserve my comment on the interfaces stuff to another post.

I haven't got any specific use cases for you. But one advice that I got and that helped me a lot was just to browse the code in the Python standard library. The code there is high quality and you



Do you Yahoo!?
Yahoo! Mail Plus - Powerful. Affordable. Sign up now --0-1915008729-1041708661=:8337-- From dmandini@inet.hr Sat Jan 4 15:40:01 2003 From: dmandini@inet.hr (djuro) Date: Sat Jan 4 15:40:01 2003 Subject: [Tutor] joker signs? Message-ID: <001c01c2b47c$a2a71b00$8342cad5@hal> Hello! for instance: x = ['ben','sandy','roger','hillary','john','betty'] a = x.index('ben') print a --------- 0 How to get indexes of all names which begin with "b" (like x.index('b*') or, find all names that contain "er". Is it possible to do using some joker letters like in os prompt? Thank you Djuro From op73418@mail.telepac.pt Sat Jan 4 16:04:02 2003 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Sat Jan 4 16:04:02 2003 Subject: [Tutor] Applications/examples of some advanced Py features, please ! References: <20030104193101.8744.qmail@web9806.mail.yahoo.com> Message-ID: <001701c2b435$9cc90000$88190dd5@violante> This is a multi-part message in MIME format. ------=_NextPart_000_0014_01C2B435.9C441890 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable I use ActiveState Python distro for Windows, so what I mean by the = standard library are the py files in the Lib directory. They are present = in other distros for other platforms as far as I can tell. Also, since there probably is a lot of stuff there that does not = interest you, you could also search the vaults of parnassus for stuff = more akin to your interests. It is the closest thing there is to CPAN in = the Python world. With my best regards, G. Rodrigues P.S: I hate to be a nitpicker, but could you ditch HTML format in favour = of plain text? It makes harder for me (and others) to reply in a proper = way. ----- Original Message -----=20 From: Aztech Guy=20 To: [Python Tutor]=20 Sent: Saturday, January 04, 2003 7:31 PM Subject: Re: [Tutor] Applications/examples of some advanced Py = features, please ! Thanks,=20 Goncalo, Gregor, Bob, Danny.=20 I'll try out the ideas suggested and revert with my results.=20 Looking forward to more replies on some of the other topics not = mentioned, if anyone has any ideas about them..=20 Goncalo - a question - does the standard Python binary distribution (I = have ActivePython 2.2.1 on Windows 98 and the Python 2.2 that comes with = Red Hat 7.3 on Linux) - have all/most of the source for the std. lib. or = do I have to download something else separately ? I do see a lot of .py = files under the Lib directory, but since I'm new to Python, I don't know = if they include all of the std. lib. - or if there is a formal concept = of "std. lib." as there is in C, for instance. Anyway, I do have a lot = of .py files there, and I'll read thru them for lambda examples. Thanks = for the tip.=20 =20 Az.=20 ------=_NextPart_000_0014_01C2B435.9C441890 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
I use ActiveState Python distro for = Windows, so=20 what I mean by the standard library are the py files in the Lib = directory. They=20 are present in other distros for other platforms as far as I can=20 tell.
 
Also, since there probably is a lot of = stuff there=20 that does not interest you, you could also search the vaults of = parnassus for=20 stuff more akin to your interests. It is the closest thing there is to = CPAN in=20 the Python world.
 
With my best regards,
G. Rodrigues
 
P.S: I hate to be a nitpicker, but = could you ditch=20 HTML format in favour of plain text? It makes harder for me = (and=20 others) to reply in a proper way.
----- Original Message -----
From:=20 Aztech=20 Guy
Sent: Saturday, January 04, = 2003 7:31=20 PM
Subject: Re: [Tutor]=20 Applications/examples of some advanced Py features, please !

Thanks,=20

Goncalo, Gregor, Bob, Danny.=20

I'll try out the ideas suggested and revert with my results.=20

Looking forward to more replies on some of the other topics not = mentioned,=20 if anyone has any ideas about them..=20

Goncalo - a question - does the standard Python binary distribution = (I have=20 ActivePython 2.2.1 on Windows 98 and the Python 2.2 that comes with = Red Hat=20 7.3 on Linux) - have all/most of the source for the std. lib. or do I = have to=20 download something else separately ? I do see a lot of .py files under = the Lib=20 directory, but since I'm new to Python, I don't know if they include = all of=20 the std. lib. - or if there is a formal concept of "std. lib." as = there is in=20 C, for instance.  Anyway, I do have a lot of .py files = there, and=20 I'll read thru them for lambda examples. Thanks for the tip.=20

=20

Az.

------=_NextPart_000_0014_01C2B435.9C441890-- From op73418@mail.telepac.pt Sat Jan 4 16:06:02 2003 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Sat Jan 4 16:06:02 2003 Subject: [Tutor] My appologies References: <20030104193101.8744.qmail@web9806.mail.yahoo.com> Message-ID: <002001c2b435$f9669070$88190dd5@violante> My appologies, I request for email in text format and send out in HTML format! Sorry, once again, G. Rodrigues From Janssen@rz.uni-frankfurt.de Sat Jan 4 17:38:01 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Sat Jan 4 17:38:01 2003 Subject: [Tutor] joker signs? In-Reply-To: <001c01c2b47c$a2a71b00$8342cad5@hal> Message-ID: On Sat, 4 Jan 2003, djuro wrote: > Hello! > > for instance: > > x = ['ben','sandy','roger','hillary','john','betty'] > a = x.index('ben') > print a > --------- > 0 > > How to get indexes of all names which begin with "b" (like x.index('b*') > or, find all names that contain "er". Is it possible to do using some joker > letters like in os prompt? Hello Djuro, you're looking for the fnmatch modul. In Python 2.2 you can do: >>> fnmatch.filter(['ben','sandy','roger','hillary','john','betty'], "b*") ['ben', 'betty'] Michael > > Thank you > > Djuro > > > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From missive@hotmail.com Sat Jan 4 21:16:03 2003 From: missive@hotmail.com (Lee Harr) Date: Sat Jan 4 21:16:03 2003 Subject: [Tutor] Re: joker signs? Message-ID: >x = ['ben','sandy','roger','hillary','john','betty'] >a = x.index('ben') >print a >--------- >0 >How to get indexes of all names which begin with "b" (like > >x.index('b*') >or, find all names that contain "er". Is it possible to do using some > >joker >letters like in os prompt? How about a list comprehension? x = ['ben','sandy','roger','hillary','john','betty'] [name for name in x if name.find('b') == 0] [name for name in x if name.find('er') >= 0] _________________________________________________________________ Protect your PC - get McAfee.com VirusScan Online http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963 From dyoo@hkn.eecs.berkeley.edu Sat Jan 4 22:08:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Jan 4 22:08:01 2003 Subject: [Tutor] startswith()/endswith() string methods In-Reply-To: Message-ID: On Sun, 5 Jan 2003, Lee Harr wrote: > >x = ['ben','sandy','roger','hillary','john','betty'] > > >How to get indexes of all names which begin with "b" > > How about a list comprehension? > > x = ['ben','sandy','roger','hillary','john','betty'] > [name for name in x if name.find('b') == 0] > [name for name in x if name.find('er') >= 0] Hi Lee, By the way, strings support a 'startswith()' method, so we can replace an expression like: name.find('b') == 0 with name.startswith('b') They're equivalent, but using startswith() makes the intention of the code slightly clearer to a human reader. ### >>> names = ['ben','sandy','roger','hillary','john','betty'] >>> [i for i in range(len(names)) if names[i].startswith('b')] [0, 5] ### If we're curious, we can browse through a complete list of string methods in the Library Documentation here: http://www.python.org/doc/lib/string-methods.html Hope this helps! From dyoo@hkn.eecs.berkeley.edu Sat Jan 4 22:23:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Jan 4 22:23:01 2003 Subject: [Tutor] unicode utf-16 and readlines [using the 'codecs' unicode file reading module] In-Reply-To: <3E16EE3E.6020603@pooryorick.com> Message-ID: On Sat, 4 Jan 2003, Poor Yorick wrote: > On Windows 2000, Python 2.2.1 open.readlines seems to read lines > incorrectly when the file is encoded utf-16. For example: > > >>> fh = open('0022data2.txt') > >>> a = fh.readlines() > >>> print a > ['\xff\xfe\xfaQ\r\x00\n', '\x00'] Hi Poor Yorick, You may want to use a "codec" to decode Unicode from a file. The 'codecs' module is specifically designed for this: http://www.python.org/doc/lib/module-codecs.html For example: ### >>> import codecs >>> f = codecs.open('foo.txt', 'w', 'utf-16') >>> f.write("hello world") >>> f.close() >>> open('foo.txt').read() '\xff\xfeh\x00e\x00l\x00l\x00o\x00 \x00w\x00o\x00r\x00l\x00d\x00' >>> f2 = codecs.open('foo.txt', 'r', 'utf-16') >>> f2.readlines() [u'hello world'] ### > In this example, Python seems to have incorrectly parsed the \n\r > characters at the end of the line. If you use 'codecs' and its open() function, you should be all set. I saw a brief mention on it in a Unicode tutorial here: http://www.reportlab.com/i18n/python_unicode_tutorial.html I always wanted to know what 'codecs' did. Now I know. Cool. *grin* Thanks for the question! From dyoo@hkn.eecs.berkeley.edu Sat Jan 4 22:27:03 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Jan 4 22:27:03 2003 Subject: [Tutor] re:Tutor] pausing and layout (getch() equivalent) In-Reply-To: <5.1.0.14.0.20030104103803.023e37b8@smtp.sbcglobal.net> Message-ID: On Sat, 4 Jan 2003, Tony Cappellini wrote: > I 've found this recently- which is the equivalent for getch(), which will > effectively pause until the user presses a key. > There are a version for windows & unix. > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892 Hi Tony, But it's buggy on Windows platforms; Poor Yorick caught me on a bad day. *grin* http://mail.python.org/pipermail/tutor/2002-December/019508.html Can anyone confirm that the fix at: http://mail.python.org/pipermail/tutor/2002-December/019516.html is doing the right thing? From syrinx@simplecom.net Sun Jan 5 00:52:01 2003 From: syrinx@simplecom.net (Scott) Date: Sun Jan 5 00:52:01 2003 Subject: [Tutor] open extra xterm? Message-ID: <20030104234319.58985892.syrinx@simplecom.net> I'm working on a python program that will defintely need a GUI. I'll probably do it in Tkinter. But I want to get the guts of my program working before I start learning Tkinter. So I need at least two windows. How do I open a second xterm for output, while I use my main one as a readline terminal? I'm assuming pipes or something like that, but could someone show me a small example of spawning an xterm and writing to it. Thank you. From Don Arnold" Message-ID: <01b801c2b480$1e8436b0$6410ba3f@defaultcomp> ---- Original Message ----- From: "Michael Janssen" To: "mike O" Cc: Sent: Saturday, January 04, 2003 11:47 AM Subject: Re: [Tutor] pausing and layout On Sat, 4 Jan 2003, mike O wrote: >> I guess I have three questions, the first being: Is there a python command >> to pause until the user does something? >Hello Mike >In addition to Gonçalo's reply I want to say that raw_input() is typically >used in a while loop: >from types import IntType ... > while 1: > p = raw_input("Choose a Number or [Q]uit: ") > if p == "Q" or p == "q" or p == "": > # User requests the end of the game > sys.exit() I've come to the conclusion that I like the seemingly SQL'ish alternative to the 'if' statement above: if p in ('Q','q',''): sys.exit() It scans easily (to my eyes), and gives me fewer chances to typo. Don From Adam Vardy Sun Jan 5 01:47:03 2003 From: Adam Vardy (Adam Vardy) Date: Sun Jan 5 01:47:03 2003 Subject: [Tutor] getting input from keyboard In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E097022D1@i2km11-ukbr.domain1.systemhost.net> References: <7497DCA1C240C042B28F6657ADFD8E097022D1@i2km11-ukbr.domain1.systemhost.net> Message-ID: <15264841136.20030103062453@roadrunner.nf.net> Hi Allan, Thursday, December 26, 2002, 8:38:50 AM, you wrote: >> How do I get keyboard input in python ? >> I want to do the equivalent of this C code, in python >> x=getch() >> Assuming you are on Windows you need to import mscvrt >> and use the getch() function in there. >> If you are on Unix you use the curses(or ncurses) module >> which also has a getch() function. >> With the books that I have, there are no references in the >> index to get, keyboard input, or in the Python help file. >> My online web tutor (and book!)has a topic on event driven >> programming which includes an example of using msvcrt.getch() I could not actually find it there. Can you check if that's where it should be? -- Adam Vardy From beercanz@hotmail.com Sun Jan 5 03:15:01 2003 From: beercanz@hotmail.com (Guess Who? Me) Date: Sun Jan 5 03:15:01 2003 Subject: [Tutor] Help understanding part of the tutorial Message-ID: http://www.honors.montana.edu/~jjc/easytut/easytut/node9.html contains this function: def mult(a,b): if b == 0: return 0 rest = mult(a,b - 1) value = a + rest return value print "3*2 = ",mult(3,2) My question is that I don't get how mult(a,b-1) returns a value - can somebody please explain? And it still works properly if you make a==0 - but there is no "if a==0: return 0" statement. Any help would be appreciated. _________________________________________________________________ The new MSN 8: smart spam protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From dyoo@hkn.eecs.berkeley.edu Sun Jan 5 04:54:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Jan 5 04:54:02 2003 Subject: [Tutor] Help understanding part of the tutorial In-Reply-To: Message-ID: On Sun, 5 Jan 2003, Guess Who? Me wrote: > http://www.honors.montana.edu/~jjc/easytut/easytut/node9.html > contains this function: > > def mult(a,b): > if b == 0: > return 0 > rest = mult(a,b - 1) > value = a + rest > return value Hello! Hmmm... let's try to see why this works first; looking at this closely might make the defintion above more understandable. The Python code above is defines multiplication in terms of addition, using a funny definition: a * b = a + (a * (b-1)) The math works out: the left side and the right side are truly equal to each other. But how does this work as a process? Let's pretend that we're trying to multiply 5 and 3, using this weird definition. Ok, let's apply this transformation once. 5 * 3 = 5 + (5 * 2) But we don't stop here: we now expand that 5 * 2 using the same method: 5 * 3 = 5 + (5 * 2) = 5 + (5 + (5 * 1)) = 5 + (5 + (5 + (5 * 0))) = 5 + (5 + (5 + (5 + (5 * -1)))) = 5 + (5 + (5 + (5 + (5 + (5 * -2))))) ... Notice that we can do this expansion forever --- we can keep doing that a * b = a + (a * (b-1)) operation without end, and be perfectly correct as far as the math is concerned, but not closer to understanding multiplication. In Python, this out-of-control definition looks like: ### >>> def mult_broken(a, b): ... return a + mult_broken(a, b-1) ... >>> mult_broken(5, 3) ## lots and lots of error messages pop up at this ## point File "", line 2, in mult_broken File "", line 2, in mult_broken RuntimeError: maximum recursion depth exceeded ### The calculation gets so large that Python just stops, saying the program appears to be flailing out of control. That might make us think that this definition is completely useless. And that would be true, except that we do know that we can cut things short. As soon as we hit something like a * 0, we don't have to do any more expansion: 5 * 3 = 5 + (5 + (5 + (5 * 0))) = 5 + (5 + (5 + 0))) = 15 That is, we stop expanding as soon as b is equal to zero, since we know that anything times zero is zero. And that's where the 'if' statement comes in: we first check to see if b is equal to zero, and then go with the definition only if it doesn't: ### >>> def mult(a, b): ... if b == 0: ... return 0 ... return a + mult(a, b-1) ... >>> mult(5, 3) 15 ### Checking against b==0 might seem an arbitrary choice. And it is! *grin* We can just as easily make the cutoff when 'b' is equal to -1, since a *(-1) is just -a: 5 * 3 = 5 + (5 * 2) = 5 + (5 + (5 * 1)) = 5 + (5 + (5 + (5 * 0))) = 5 + (5 + (5 + (5 + (5 * -1)))) = 5 + (5 + (5 + (5 + -5))) = 15 In Python, this looks like: ### >>> def mult3(a, b): ... if b == -1: ... return -a ... return a + mult3(a, b-1) ... >>> mult3(5, 3) 15 ### The point is that we've got to make the cut somewhere. In technical terms, we need to tell Python how to solve the "base case" in a way that can be solved really easily. In multiplication, multiplying against zero is an easy task, so we can choose that as our "base case". > And it still works properly if you make a==0 - but there is no "if a==0: > return 0" statement. Very true, but it's still ok. mult(0, 25) ends up doing something like: 0 + (0 + (0 + ... + 0)))))))))))))))))))))))) which does a lot of work for nothing, but it's still perfectly correct as far as the math's concerned. I feel like I'm rushing things a bit though. If you have questions, please feel free to bring them to the Tutor list. Good luck to you! From dyoo@hkn.eecs.berkeley.edu Sun Jan 5 05:25:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Jan 5 05:25:02 2003 Subject: [Tutor] Applications/examples of some advanced Py features, please ! [Python and AI?] In-Reply-To: <001d01c2b410$49d816d0$88190dd5@violante> Message-ID: On Sat, 4 Jan 2003, [iso-8859-1] Gon=E7alo Rodrigues wrote: > If you want to learn more on functional programming, David Mertz has 3 > articles about it in the IBM developer works site. Just google for them. Here you go: http://www-106.ibm.com/developerworks/linux/library/l-prog.html http://www-106.ibm.com/developerworks/library/l-prog2.html > I have a specific reason for the above questions- apart from general > interest, of course -> I am planning to write a game-playing program in > Py which will have features somewhat AI - ish. I don't have any > background in AI; nor much in functional programming. Hmmm! You might find this useful: http://www.norvig.com/ Peter Norvig is one of the authors of the book "Artificial Intelligence, A Modern Approach". http://www.cs.berkeley.edu/~russell/aima.html It's an awesome book --- a bit on the heavy side, but chock full of good stuff. (Although I'm sorta biased about this, having taken the course from the other co-author of the book... *grin*) Norvig has example code in Python, including some game-playing code: http://www.norvig.com/python/python.html Hope this helps! From Janssen@rz.uni-frankfurt.de Sun Jan 5 08:10:02 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Sun Jan 5 08:10:02 2003 Subject: [Tutor] open extra xterm? In-Reply-To: <20030104234319.58985892.syrinx@simplecom.net> Message-ID: On Sat, 4 Jan 2003, Scott wrote: > I'm working on a python program that will defintely need a GUI. I'll > probably do it in Tkinter. But I want to get the guts of my program > working before I start learning Tkinter. > > So I need at least two windows. How do I open a second xterm for > output, while I use my main one as a readline terminal? I'm assuming > pipes or something like that, but could someone show me a small example > of spawning an xterm and writing to it. Thank you. Hello Scott, I can only give you some hints: writing to another terminal is easy: >>> fo = open("/dev/pts/4","w") >>> fo.write("hello") >>> fo.flush() this will print to terminal pts/4. Use ps to identify the current terminals: ps -a : gives you processes run by the terminal shells. You can use "sleep 10" on your second xterm to identify it. ps -Nx : gives you every terminal related process (including the shells) The problem is: you need to identify the pts and (more important) you need to start the xterm from outside the script. When you want to work around this, *probably* os.fork() os.forkpty() and the pty module helps you. Or you get os.system() or os.popen2() to work (they can start a xterm but this will run under the pts-device of the python interpreter. The popen2 fileobjects doesn't work [for me]). Would you drop me a line when you find a solution? Michael > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From abli@freemail.hu Sun Jan 5 09:47:01 2003 From: abli@freemail.hu (Abel Daniel) Date: Sun Jan 5 09:47:01 2003 Subject: [Tutor] open extra xterm? In-Reply-To: <20030104234319.58985892.syrinx@simplecom.net> References: <20030104234319.58985892.syrinx@simplecom.net> Message-ID: <20030105144637.GA1330@hooloovoo> On Sat, Jan 04, 2003 at 11:43:19PM -0600 Scott (syrinx@simplecom.net) wrote: > So I need at least two windows. How do I open a second xterm for > output, while I use my main one as a readline terminal? I'm assuming > pipes or something like that, but could someone show me a small example > of spawning an xterm and writing to it. Thank you. Not fully in python, but should work: 1, open xterm, excecute: mkfifo /tmp/pipe cat /tmp/pipe 2, start python program, for example: fo = open("/tmp/pipe","w") while 1: i=raw_input('>>') fo.write(i + '\n') fo.flush() Abel Daniel abli@freemail.hu From abli@freemail.hu Sun Jan 5 10:11:20 2003 From: abli@freemail.hu (Abel Daniel) Date: Sun Jan 5 10:11:20 2003 Subject: [Tutor] open extra xterm? In-Reply-To: <20030105144637.GA1330@hooloovoo> References: <20030104234319.58985892.syrinx@simplecom.net> <20030105144637.GA1330@hooloovoo> Message-ID: <20030105151056.GB1330@hooloovoo> On Sun, Jan 05, 2003 at 03:46:37PM +0100 Abel Daniel (abli@freemail.hu) wrote: > Not fully in python, but should work: [..snipped...] Ok, here is the fully python version: import os os.system('mkfifo /tmp/pipe') os.system("xterm -e cat /tmp/pipe &") fo = open("/tmp/pipe","w") while 1: #for simulating data output i=raw_input('>>') fo.write(i + '\n') fo.flush() Of course, using /tmp/pipe silently is not exactly a good idea, a safer version would find make up an obfuscated name, check if it's used in /tmp/ and make a pipe with that name, but i'm to tired to add that. Abel Daniel abli@freemail.hu From aztech1200@yahoo.com Sun Jan 5 11:03:01 2003 From: aztech1200@yahoo.com (Aztech Guy) Date: Sun Jan 5 11:03:01 2003 Subject: [Tutor] Applications/examples of some advanced Py features, please ! In-Reply-To: <001701c2b435$9cc90000$88190dd5@violante> Message-ID: <20030105160249.54435.qmail@web9802.mail.yahoo.com> --- Gonçalo_Rodrigues wrote: > the vaults of parnassus for stuff more akin to your Thanks for the info. > HTML format in favour of plain text? It makes harder > I hate to be a nitpicker ... Nothing nitpicking about it :-) Sorry about the HTML. I use browser-based Yahoo Mail, and till now no one had asked me to not send HTML, so I had left it at the default. I've set this mail to plain text mode, please let me know if it still comes as HTML for any reason, and I'll look into it. Az __________________________________________________ Do you Yahoo!? Yahoo! Mail Plus - Powerful. Affordable. Sign up now. http://mailplus.yahoo.com From aztech1200@yahoo.com Sun Jan 5 11:11:00 2003 From: aztech1200@yahoo.com (Aztech Guy) Date: Sun Jan 5 11:11:00 2003 Subject: [Tutor] Applications/examples of some advanced Py features, please ! [Python and AI?] In-Reply-To: Message-ID: <20030105161016.54847.qmail@web9802.mail.yahoo.com> --- Danny Yoo wrote: > > www.norvig.com Thanks for all the tips ! I've checked out the book, it looks good, and I bought it. Az. __________________________________________________ Do you Yahoo!? Yahoo! Mail Plus - Powerful. Affordable. Sign up now. http://mailplus.yahoo.com From magnus@thinkware.se Sun Jan 5 15:44:03 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Sun Jan 5 15:44:03 2003 Subject: [Tutor] 2nd bonehead question... In-Reply-To: <200212211619.29024.shalehperry@attbi.com> References: <5.1.0.14.0.20021221235403.02bcd400@www.thinkware.se> <5.1.0.14.0.20021221235403.02bcd400@www.thinkware.se> Message-ID: <5.1.0.14.0.20030105213142.02c4a830@www.thinkware.se> At 16:19 2002-12-21 -0800, Sean 'Shaleh' Perry wrote: > > .pyc is a .py file compiled into byte-code, a binary > > format that the python interpreter reads. These files > > are created automatically when a python module is > > imported, if there isn't already an updated .pyc file. > >taken a step further, the interpreter has some magic to use the .pyc first if >it exists otherwise it makes one from the .py file. There is logic there to >see if the pyc is older than the py and if so recreate it as well. Yes, this is good to know, since it might bite you in some cases: - You open an archive (.zip, .tar etc) with .py-files. You change a file x.py, and then run the program y.py, and x.pyc is created as you do "import x" in y.py. You see that your fix was bad, and you revert to the original x.py by extracting it from the archive file again. You do this with a command that preserves time settings for the file, and to your surprise, the bug you just backed out of is still in your program, despite the fact that it's gone from the source... - You make a change in foo.py module, and a foo.pyc is created. You then realize that you have previously changed the date in your computer to January 5, 2004 by accident. (Stupid Windows...) You correct this, and make further changes to foo.py, but they don't seem to be reflected in your program next time you try it... - You use clearcase with dynamic views for source control, and you check out an earlier version of a .py-file. In all these situations I think Python will be tricked into using an invalid .pyc-file. When in doubt...just delete your .pyc-files. -- 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@thinkware.se Sun Jan 5 18:09:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Sun Jan 5 18:09:01 2003 Subject: [Tutor] Debug In-Reply-To: <5.2.0.9.0.20030102111509.02bd0da8@66.28.54.253> References: <1615745792.20030102140009@roadrunner.nf.net> Message-ID: <5.1.0.14.0.20030106001048.02bd4e90@www.thinkware.se> At 11:25 2003-01-02 -0700, Bob Gailer wrote: >Sounds like you're using PythonWin, which I use also. There are behaviors >that are unexpected and sometimes unpredictible. def _doexec(cmd, globals, >locals): is in PyhtonWin's debugger module; why it (sometimes) shows up in >single step is a mystery. May I suggest that you use Boa Constructor for debugging instead? It has the nicest GUI debugger for Python that I have used. As an editor, I still find PythonWin better. -- 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 charlie@begeistert.org Sun Jan 5 18:13:14 2003 From: charlie@begeistert.org (Charlie Clark) Date: Sun Jan 5 18:13:14 2003 Subject: [Tutor] Assigning function keywords dynamically In-Reply-To: <20030105170005.14991.93345.Mailman@mail.python.org> References: <20030105170005.14991.93345.Mailman@mail.python.org> Message-ID: <20030106001539.1829.4@.1041771530.fake> Dear list, I remember a discussion about switch/case statements in Python (I know they= only exist in C) including my own contribution but haven't been able to find quite what I was looking for my usual sources. I have got a little report generator that generates reports for people with= different frequency (daily, weekly, monthly). What I want is a function that takes the frequency and returns the correct future date for the next run. current implementation using mx.DateTime from mx.DateTime import now(), DateTime.RelativeDateTime def new_date(interval): =09if interval =3D=3D "monatlich": =09=09return now() + RelativeDateTime(months=3D+1) =09elif interval =3D=3D "w=F6chentlich": =09=09return now() + RelativeDateTime(weeks=3D+1) =09elif interval =3D=3D "t=E4glich": =09=09return now() + RelativeDateTime(days=3D+1) =09else: =09=09return "Invalid interval" While this is fine it seems a little verbose and clumsy and not quite Python. What would be a better way of doing this? Also would it be a good idea to raise an exception in the else statement? Thanx very much Charlie From tim.one@comcast.net Sun Jan 5 18:36:21 2003 From: tim.one@comcast.net (Tim Peters) Date: Sun Jan 5 18:36:21 2003 Subject: [Tutor] Assigning function keywords dynamically In-Reply-To: <200301052313.h05NDMC07191@bright09> Message-ID: [Charlie Clark] > ... > I have got a little report generator that generates reports for > people with different frequency (daily, weekly, monthly). What I wa= nt > is a function that takes the frequency and returns the correct fut= ure > date for the next run. > > current implementation using mx.DateTime > > from mx.DateTime import now(), DateTime.RelativeDateTime > > def new_date(interval): > =09if interval =3D=3D "monatlich": > =09=09return now() + RelativeDateTime(months=3D+1) > =09elif interval =3D=3D "w=F6chentlich": > =09=09return now() + RelativeDateTime(weeks=3D+1) > =09elif interval =3D=3D "t=E4glich": > =09=09return now() + RelativeDateTime(days=3D+1) > =09else: > =09=09return "Invalid interval" > > While this is fine it seems a little verbose and clumsy and not qui= te > Python. What would be a better way of doing this? You're building a mapping from strings to durations, which screams "d= ict". Like so: _name2dur =3D {"monatlich": RelativeDateTime(months=3D+1), "w=F6chentlich": RelativeDateTime(weeks=3D+1). "t=E4glich": RelativeDateTime(days=3D+1), } def new_date(interval): dur =3D _name2dur.get(interval) if dur is None: raise ValueError("unknown interval '%s'" % interval) return now() + dur > Also would it be a good idea to raise an exception in the else > statement? Probably. The caller presumably expects to get some kind of date obj= ect back from this, not some kind of string, so when it does return a str= ing it will probably raise some kind of baffling exception later (like "can'= t add time to string"), or perhaps "Invalid interval" will get stored away somewhere and printed 3 months later. It would be hard to guess what= went wrong then. As a general rule, it's thoroughly appropriate for a fun= ction to raise an exception when a caller asks it to do something silly, an= d you're doing the caller a favor by not letting it get away with that = when it does. From missive@hotmail.com Sun Jan 5 18:59:02 2003 From: missive@hotmail.com (Lee Harr) Date: Sun Jan 5 18:59:02 2003 Subject: [Tutor] Re: Help understanding part of the tutorial Message-ID: >def mult(a,b): > if b == 0: > return 0 > rest = mult(a,b - 1) > value = a + rest > return value > >print "3*2 = ",mult(3,2) > >My question is that I don't get how mult(a,b-1) returns a value > Sometimes when debugging, or just trying to understand a piece of code, it helps to move through the code step by step thinking (or writing down) what the computer will do at each step: ok, I am going to call mult(3, 2) a = 3, b = 2 is b == 0? nope, so rest = mult(3, 1) ok, I am going to call mult(3, 1) a = 3, b = 1 is b == 0? nope, so rest = mult(3, 0) # note that rest here is different from the rest up above, # rest is "local" to this function call and is completely # independent of the rest in the mult(3, 2) call. ok, I am going to call mult(3, 0) a = 3, b = 0 is b == 0? YES, so return 0 # but, return 0 to where? who called this? # ah, yes, it was the call to mult(3, 1), so # back in the call to mult(3, 1) a = 3, b = 1, rest = 0 value = 3 + 0 return 3 # return to who? # to the mult(3, 2) call, so # back in the call to mult(3, 2) a = 3, b = 2, rest = 3 value = 3 + 3 return 6 # to who? # mult(3, 2) was the original call, so we're finished This is called a "recursive" function definition. (which means that the function calls itself in the process of calculating a final answer, and sets some kind of a condition for ending the stack of recursive calls) I am pretty sure that any recursive function can be written in a non-recursive way. For instance: def mult(a,b): total = 0 while a: total += b a -= 1 return total or, of course def mult(a, b): return a * b _________________________________________________________________ Help STOP SPAM: Try the new MSN 8 and get 2 months FREE* http://join.msn.com/?page=features/junkmail From magnus@thinkware.se Sun Jan 5 19:09:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Sun Jan 5 19:09:01 2003 Subject: [Tutor] Good reasons for 1.5.2 compatibility? In-Reply-To: References: Message-ID: <5.1.0.14.0.20030106010749.02bda648@www.thinkware.se> At 18:45 2003-01-03 +0300, Roman Suzi wrote: >Also I know that 2.x has difficulties with non-latin1 texts in IDLE: >so it is not possible to use Tkinter (thus build GUIs) with standard 2.x >versions of Python. I can't quite follow the conclusion you are making here. Why exactly isn't it possible to use Tkinter with standard 2.x versions of Python? Surely Tkinter does not depend on IDLE. Also, it might be time to consider using Unicode for implementing non-ASCII things in Python... -- 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 glingl@aon.at Sun Jan 5 19:47:11 2003 From: glingl@aon.at (Gregor Lingl) Date: Sun Jan 5 19:47:11 2003 Subject: [Tutor] Re: Help understanding part of the tutorial References: Message-ID: <3E18D212.10506@aon.at> Lee Harr schrieb: >> def mult(a,b): >> if b == 0: >> return 0 >> rest = mult(a,b - 1) >> value = a + rest >> return value >> >> print "3*2 = ",mult(3,2) >> >> My question is that I don't get how mult(a,b-1) returns a value >> > > > Sometimes when debugging, or just trying to understand a piece > of code, it helps to move through the code step by step thinking > (or writing down) what the computer will do at each step: > > > ok, I am going to call mult(3, 2) > a = 3, b = 2 > is b == 0? nope, so > rest = mult(3, 1) > > ok, I am going to call mult(3, 1) > a = 3, b = 1 > is b == 0? nope, so > rest = mult(3, 0) > # note that rest here is different from the rest up above, > # rest is "local" to this function call and is completely > # independent of the rest in the mult(3, 2) call. > > ok, I am going to call mult(3, 0) > a = 3, b = 0 > is b == 0? YES, so > return 0 > # but, return 0 to where? who called this? > # ah, yes, it was the call to mult(3, 1), so > > # back in the call to mult(3, 1) > a = 3, b = 1, rest = 0 > value = 3 + 0 > return 3 > # return to who? > # to the mult(3, 2) call, so > > # back in the call to mult(3, 2) > a = 3, b = 2, rest = 3 > value = 3 + 3 > return 6 > # to who? > # mult(3, 2) was the original call, so we're finished Additionally to this mental procedure it may be helpful to *observe* what's going on, when executing mult by using the IDLE-debugger (supposing IDLE works on your system). *) start IDLE *) write mult in a *.py file and execute it. *) In the IDLE-menu of the interactive window click Debug|Debugger The debugger window appears. Activate "source" by clicking the appropriate box. In the interactive window type mult(3,2). Then proceed by repeatedly clicking the "Step" - button in the Debug-Control-Window, This way you'll be able to observe: *) in dthe debugger-window: the sequence of active function calls, which in the case of recursive functions contain several active copies of the same function, each of them having their own... *) ... local variables, their values and how these are changing. *) and finally in the editor-window you'll find the code-line marked, which is going to be executed. At first this may be a little confusing, but since you easily can repeat this several times you'll get accustomed to it and it may well help you to verify your by-hand-execution of the code as well as to grasp the secrets of recursion. Try it out! Best wishes Gregor > > > This is called a "recursive" function definition. > (which means that the function calls itself in the process > of calculating a final answer, and sets some kind of a > condition for ending the stack of recursive calls) > > I am pretty sure that any recursive function can be written > in a non-recursive way. For instance: > > def mult(a,b): > total = 0 > while a: > total += b > a -= 1 > return total > > or, of course > > def mult(a, b): > return a * b > > > _________________________________________________________________ > Help STOP SPAM: Try the new MSN 8 and get 2 months FREE* > http://join.msn.com/?page=features/junkmail > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From shalehperry@attbi.com Sun Jan 5 21:43:01 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Sun Jan 5 21:43:01 2003 Subject: [Tutor] Good reasons for 1.5.2 compatibility? In-Reply-To: References: Message-ID: <200301051842.13981.shalehperry@attbi.com> On Friday 03 January 2003 08:26, Michael Janssen wrote: > On Fri, 3 Jan 2003, John Abbe wrote: > > Are there any factors causing reasonable people > > to keep 1.5.2 around? > > Some people do keep 1.5.2 on their system, but it's hard to tell what's > their reason (that's a "frequently not answered question" on > comp.lang.python). Perhaps it's just they are lazy. RedHat remained for= a > long time on 1.5.2 cause they frighten incompatibilities with their > system-scripts written in python, but they have skipped this position a= nd > switched to a recent version. > However there are still a lot of 1.5.2 RH systems out there. As an earlier poster commented, unless you need a feature from 2.x being = 1.5.x=20 compliant is not that hard. The two biggies are the import string -->=20 string.foo change and list comprehensions. From andy_osagie@hotmail.com Sun Jan 5 21:51:19 2003 From: andy_osagie@hotmail.com (Andy Osagie) Date: Sun Jan 5 21:51:19 2003 Subject: [Tutor] Taking a screenshot Message-ID: <000101c2b52e$48d81900$853c86ac@aeo120> This is a multi-part message in MIME format. ------=_NextPart_000_0002_01C2B504.60021100 Content-Type: text/plain; charset="us-ascii" Content-Transfer-Encoding: 7bit Hello, Is it possible to use Python to take a screenshot of the script-user's screen and then save it in some popular image format? I did some searching for an answer but couldn't find any module that would help me do it or any instructions on how to. Are there any suggestions? Thanks in advance. -- Andy ------=_NextPart_000_0002_01C2B504.60021100 Content-Type: text/html; charset="us-ascii" Content-Transfer-Encoding: quoted-printable

Hello,

Is it possible to use Python to take a screenshot of = the script-user’s screen and then save it in some popular image = format? I did some searching for an answer but couldn’t find any module that = would help me do it or any instructions on how to. Are there any suggestions? = Thanks in advance.

 

-- Andy

------=_NextPart_000_0002_01C2B504.60021100-- From tony@tcapp.com Mon Jan 6 02:31:06 2003 From: tony@tcapp.com (Tony Cappellini) Date: Mon Jan 6 02:31:06 2003 Subject: [Tutor] Python docs- makes the learning harder sometimes Message-ID: <5.1.0.14.0.20030105232139.01a768c0@smtp.sbcglobal.net> I've got a book which refers to some really useful string functions like. startswith() endswith() as in s="Hello Python" s.startswith("He") s.endswith("on",6) where each function has 2 parameters, however, I don't understand why these functions are not in the Global Module Index Arggggghh ! From janos.juhasz@VELUX.com Mon Jan 6 11:47:43 2003 From: janos.juhasz@VELUX.com (janos.juhasz@VELUX.com) Date: Mon Jan 6 11:47:43 2003 Subject: [Tutor] pyLpd Message-ID: Dear all, This would be the very base of my test lpd, but i don't know how can i = send back an 'octete of zero bits' for acknowledgement with self.wfile.write() ****** import SocketServer class pyLpd(SocketServer.StreamRequestHandler): def handle(self): lines =3D self.rfile.readlines() self.wfile.write() print lines if __name__ =3D=3D '__main__': server =3D SocketServer.TCPServer( ('', 515), pyLpd) server.serve_forever() ***** Best regards, ----------------------- Juh=E1sz J=E1nos IT department = From janos.juhasz@VELUX.com Mon Jan 6 11:51:06 2003 From: janos.juhasz@VELUX.com (janos.juhasz@VELUX.com) Date: Mon Jan 6 11:51:06 2003 Subject: [Tutor] pyLpd Message-ID: Dear all, This would be the very base of my test lpd, but i don't know how i coul= d send back an 'octete of zero bits' for acknowledgement with self.wfile.write() ****** import SocketServer class pyLpd(SocketServer.StreamRequestHandler): def handle(self): lines =3D self.rfile.readlines() self.wfile.write() print lines if __name__ =3D=3D '__main__': server =3D SocketServer.TCPServer( ('', 515), pyLpd) server.serve_forever() ***** Best regards, ----------------------- Juh=E1sz J=E1nos IT department = From francois.granger@free.fr Mon Jan 6 11:51:27 2003 From: francois.granger@free.fr (Fran=?ISO-8859-1?B?5w==?=ois Granger) Date: Mon Jan 6 11:51:27 2003 Subject: [Tutor] Python docs- makes the learning harder sometimes In-Reply-To: <5.1.0.14.0.20030105232139.01a768c0@smtp.sbcglobal.net> Message-ID: on 6/01/03 8:24, Tony Cappellini at tony@tcapp.com wrote: > startswith() > endswith() > however, I don't understand why these functions are not in the Global > Module Index They are string method and are referenced in the Python Library Reference. http://www.python.org/doc/current/lib/string-methods.html -- Le courrier est un moyen de communication. Les gens devraient se poser des questions sur les implications politiques des choix (ou non choix) de leurs outils et technologies. Pour des courriers propres : -- From rob@uselesspython.com Mon Jan 6 11:55:11 2003 From: rob@uselesspython.com (Rob Andrews) Date: Mon Jan 6 11:55:11 2003 Subject: [Tutor] Python docs- makes the learning harder sometimes In-Reply-To: <5.1.0.14.0.20030105232139.01a768c0@smtp.sbcglobal.net> Message-ID: > -----Original Message----- > I've got a book which refers to some really useful string functions like. > > startswith() > endswith() > > however, I don't understand why these functions are not in the Global > Module Index There is a reason that startswith() and endswith() are not included in the Global Module Index, and it's actually a pretty good one. They aren't part of a module that needs to be imported, but built-in string methods included in the Python Library Reference. This is a part of the documentation that comes with Python and can be found on the python.org site in the Documents area. If, for example, you are running on a Windows PC (like the one I happen to be sitting at presently), and you have Python installed at C:\Python22\, you should be able to find these methods described in "C:\Python22\Doc\lib\string-methods.html". The Python Library Reference is good enough to merit reading thoroughly and repeatedly, in my experience. Hope this helps, Rob http://uselesspython.com Got Zeus? http://www.hellenion.org From lumbricus@gmx.net Mon Jan 6 11:57:35 2003 From: lumbricus@gmx.net (lumbricus@gmx.net) Date: Mon Jan 6 11:57:35 2003 Subject: [Tutor] Python docs- makes the learning harder sometimes References: <5.1.0.14.0.20030105232139.01a768c0@smtp.sbcglobal.net> Message-ID: <3446.1041852185@www40.gmx.net> Hello! > startswith() > endswith() [ snip ] > where each function has 2 parameters, > however, I don't understand why these functions are not in the Global > Module Index Why should they? They are string methods and not related to a module: "http://www.python.org/doc/current/lib/string-methods.html" > Arggggghh ! :-) HTH, J"o! -- sigfault +++ GMX - Mail, Messaging & more http://www.gmx.net +++ NEU: Mit GMX ins Internet. Rund um die Uhr für 1 ct/ Min. surfen! From magnus@thinkware.se Mon Jan 6 12:00:23 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Jan 6 12:00:23 2003 Subject: [Tutor] Python docs- makes the learning harder sometimes In-Reply-To: <5.1.0.14.0.20030105232139.01a768c0@smtp.sbcglobal.net> Message-ID: <5.1.0.14.0.20030106124636.02bd8ec0@www.thinkware.se> At 23:24 2003-01-05 -0800, Tony Cappellini wrote: >I've got a book which refers to some really useful string functions like. > >startswith() >endswith() Those are methods of string objects. String is a builtin type. >however, I don't understand why these functions are not in the Global >Module Index That's because they have no place in a list of module names. The Global Module Index is only an alphabetical list of modules. I.e. roughly the same thing as the section names in chapters 3 to 22 in the Python Library Reference, but in a different order. In other words, if a name X is listed in the Global Module Index, you can type "import X" in your python program to load that module if you have a standard Python installation. There's no sense in doing "import startswith", right? >Arggggghh ! Now now, calm down a bit! ;) The Global Module Index is very useful for finding *modules* by their names, but the most important parts of the Library Reference is chapter 2: "Built-in Functions, Types, and Exceptions". What you look for is here: http://www.python.org/doc/current/lib/string-methods.html in 2.2.6.1. I suggest that you skim through chapter 2 now and then. Don't bother memorizing everything, but as your experience in Python progresses, you will find that new things will turn out to be useful, and you will refresh your memory about the basics in Python. -- 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@thinkware.se Mon Jan 6 12:04:33 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Jan 6 12:04:33 2003 Subject: [Tutor] Better (free) IDEs than IDLE for Linux ? In-Reply-To: <20021224145203.37898.qmail@web9806.mail.yahoo.com> References: <7497DCA1C240C042B28F6657ADFD8E0974DA78@i2km11-ukbr.domain1.systemhost.net> Message-ID: <5.1.0.14.0.20030106130722.02c5eb58@www.thinkware.se> At 06:52 2002-12-24 -0800, Aztech Guy wrote: >[Az] Yes, I have that book. It's good. One nice example is about scroll >bars - he argues that the up and down arrowheads on a scroll bar should be >adjacent, not at opposite ends of the bar, to reduce mousing. Haven't seen >that idea make its way into many apps though. Maybe it requires changes at >the toolkit level and would break compatibility in some way. Yes, it's a toolkit issue, and probably something we should not "fix" for individual applications. Doing what is expected might be better than doing what's "best". I think NeXT had this, right? So does some Linux GUI toolkits. Not only the NextStep derivates. MacOS 8/9 had both arrowheads in both ends of the scrollbar, to try to please everybody. I don't know if that kind of duplication was a good idea. I'm not sure what MacOS X does. -- 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@thinkware.se Mon Jan 6 12:04:49 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Jan 6 12:04:49 2003 Subject: [Tutor] Taking a screenshot In-Reply-To: <000101c2b52e$48d81900$853c86ac@aeo120> Message-ID: <5.1.0.14.0.20030106130623.02beabb0@www.thinkware.se> At 21:49 2003-01-05 -0500, Andy Osagie wrote: >Is it possible to use Python to take a screenshot of the script-user s >screen and then save it in some popular image format? I did some searching >for an answer but couldn t find any module that would help me do it or any >instructions on how to. Are there any suggestions? Thanks in advance. I'm sure it is, but as we discussed recently, things like this are done in different ways on different platforms. This is not a general enough thing for Python to have one standard, cross-platform way of doing it. I you are using MS Windows, I imagine there is a way of doing this through the win32 libraries in the Mark Hammonds win32all bundle. (This is included by default in ActivePython.) I doubt that there are Python specific docs for this though. You might have to wade through some Win32 docs to figure it out. Or try the python-win32 mailing list. -- 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 Don Arnold" Message-ID: <041d01c2b57d$a74ff5d0$6410ba3f@defaultcomp> ----- Original Message ----- From: "Tony Cappellini" To: Sent: Monday, January 06, 2003 1:24 AM Subject: [Tutor] Python docs- makes the learning harder sometimes > > > I've got a book which refers to some really useful string functions like. > > startswith() > endswith() > > as in > s="Hello Python" > s.startswith("He") > s.endswith("on",6) > > where each function has 2 parameters, > however, I don't understand why these functions are not in the Global > Module Index > I think you're expecting too much of the Global Module Index. It provides a llisting of Python's standard modules. What you are looking for are methods of the string class. Since this class is built into the language, there's no module associated with it to index. You'll have better luck looking for these in the Python Library Reference, where they're under section 2.2.6.1, 'String Methods'. > Arggggghh ! > I understand your frustration. Learning a language straight from the documentation (even a great language with great documentation) is tough. I think you're better off working with a book that teaches Python, such as Chun's "Core Python Programming" or Lutz's "Learning Python". HTH, Don From alan.gauld@bt.com Mon Jan 6 12:20:41 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Jan 6 12:20:41 2003 Subject: [Tutor] Debug Message-ID: <7497DCA1C240C042B28F6657ADFD8E097022E9@i2km11-ukbr.domain1.systemhost.net> > >Use Next instead of Step. Step steps intp when you *really* want to > >get inside a function... > > Unfortunately that does not solve the problem with the > PythonWin debugger. > It still halts in debugger.py. I didn't get that problem, I just set a break point, hit run then used step over/step into to go through my code. I tried the same in IDLE and found its debugger to be far bewtter since it highlighted the source code better but both debuggers step through code OK. Neither has a watch function although both display variables values dynamically. The Python standard debugger(pdb) is better than either IMHO, albeit non GUI. Alan g. From alan.gauld@bt.com Mon Jan 6 12:20:52 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Jan 6 12:20:52 2003 Subject: [Tutor] Tkinter Message-ID: <7497DCA1C240C042B28F6657ADFD8E097022EA@i2km11-ukbr.domain1.systemhost.net> > In another example, I have a button on the window. And a function is > set to run for that. But it runs right away. And nothing happens when > I hit the button! You are probably trying to assign the command to a function call rather than a function name. ie you added parentheses after the function name. You need a reference to the fiunction - like a function pointer in C/C++ Alan G. From alan.gauld@bt.com Mon Jan 6 12:21:02 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Jan 6 12:21:02 2003 Subject: [Tutor] Comments Message-ID: <7497DCA1C240C042B28F6657ADFD8E097022EB@i2km11-ukbr.domain1.systemhost.net> > How is it you phrase comments? When I'd like to take out a block and > experiment with the rest, what's the method? > > { > > code > ... > > won't run > > } > > print "will run" In IDLE Select the region and choose the Edit|Comment region menu command. Or if you prefer wrap it in an "if 0:" clause - indenting the section by 1 char or whatever... Alan g. From dyoo@hkn.eecs.berkeley.edu Mon Jan 6 12:22:13 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Jan 6 12:22:13 2003 Subject: [Tutor] Python docs- makes the learning harder sometimes In-Reply-To: <5.1.0.14.0.20030105232139.01a768c0@smtp.sbcglobal.net> Message-ID: On Sun, 5 Jan 2003, Tony Cappellini wrote: > startswith() > endswith() > > as in > s="Hello Python" > s.startswith("He") > s.endswith("on",6) > > where each function has 2 parameters, > however, I don't understand why these functions are not in the Global > Module Index Hi Tony, The index here: http://www.python.org/doc/lib/genindex.html does have entries for startswith() and endswith(): http://www.python.org/doc/lib/string-methods.html#l2h-141 http://www.python.org/doc/lib/string-methods.html#l2h-119 Hope this helps! From alan.gauld@bt.com Mon Jan 6 12:22:24 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Jan 6 12:22:24 2003 Subject: [Tutor] open extra xterm? Message-ID: <7497DCA1C240C042B28F6657ADFD8E097022EF@i2km11-ukbr.domain1.systemhost.net> > So I need at least two windows. How do I open a second xterm for > output, while I use my main one as a readline terminal? Simplest way is to redirect your output to a file then simply "tail" the file in the second xterm. $ man tail > I'm assuming pipes or something like that, Shouldn't be necessary - unless you will be generating huge amounts of output! As I said earlier unix *is* an IDE... Alan g From charlie@begeistert.org Mon Jan 6 12:25:36 2003 From: charlie@begeistert.org (Charlie Clark) Date: Mon Jan 6 12:25:36 2003 Subject: [Tutor] Assigning function keywords dynamically In-Reply-To: References: Message-ID: <20030106163824.631.1@.1041865326.fake> On 2003-01-06 at 00:34:40 [+0100], Tim Peters wrote: > You're building a mapping from strings to durations, which screams > "dict". Like so: > > _name2dur =3D {"monatlich": RelativeDateTime(months=3D+1), > "w=F6chentlich": RelativeDateTime(weeks=3D+1). > "t=E4glich": RelativeDateTime(days=3D+1), > } >dur =3D _name2dur.get(interval) mm, okay I understand the mapping thing but this doesn't seem much more efficient (in terms of typing) or sensible than the series of ifs I had; it= probably runs a lot faster though but then again that isn't important when compared with the subsequent SQL calls... But the mapping should be {"monatlich": "months"...} with an intermediary function (lambda()?, exec()?) magically inserting the keyword in a RelativeDateTime() call. ie. return now() + RelativeDateTime(magicfunction(dur)) I also have three questions: why do you use the "_" in the name? And is .get() becoming standard for dictionaries? how close is the upcoming "datetime" module to mx.DateTime. For those not already aware Python 2.3 will ship with a new datetime module which has many functions similar to the very useful eGenix's mx.DateTime. I remember you once made a remark about it has long been possible to make real digital computers as opposed to our current binary ones. Could you provide a reference? I discuss these kind of things with my dad who while regularly presenting a replica of the world's first electronic computer ("Baby" at the Museum of Science and Industry in Manchester) and going back= as far as IBM 704s, etc. doesn't seem to recall such devices. They sound fascinating and probably very useful. Can anybody point me to a reasonable reference as to why so much time, energy has been spent "developing" Linux over the last 10 years in order to= come up essentially with a new 4.4 BSD lite? My real interest in this is: why did yet another Unix clone receive such tremendous input from the academic community although it seemed essentially to be reinventing the wheel and repeating the mistakes and lessons of the previous 20 years. As only an occasional programmer what interests me primarily are the "design" and "project management" issues which are common to all open source projects. The relation to Python is that Python seems to have maintained focus and avoided feature creep to a large extent while managing to be innovative I understand and increasingly respect this but it leaves me wondering: how much innovation occurs when the commercial imperative is removed? Apply this directly to Python: how many modules which are now part= of the standard library were themselves previously commercial extensions or= are clean room implementations of such modules, ie. mx.DateTime and datetime; when can we afford to give something away? Thank you very much Charlie From alan.gauld@bt.com Mon Jan 6 12:28:48 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Jan 6 12:28:48 2003 Subject: [Tutor] 'if a==b or a==c or a==d' alternative (was: pausing a nd layout) Message-ID: <7497DCA1C240C042B28F6657ADFD8E097022F0@i2km11-ukbr.domain1.systemhost.net> > I've come to the conclusion that I like the seemingly SQL'ish > alternative to the 'if' statement above: > > if p in ('Q','q',''): > sys.exit() Or even: if p in 'Qq ': sys.exit() saves a few quote signs... Alan g. From tim.one@comcast.net Mon Jan 6 12:30:41 2003 From: tim.one@comcast.net (Tim Peters) Date: Mon Jan 6 12:30:41 2003 Subject: [Tutor] Assigning function keywords dynamically In-Reply-To: <200301061535.h06FZ9C15436@bright09> Message-ID: >> _name2dur =3D {"monatlich": RelativeDateTime(months=3D+1), >> "w=F6chentlich": RelativeDateTime(weeks=3D+1). >> "t=E4glich": RelativeDateTime(days=3D+1), >> } >> dur =3D _name2dur.get(interval) [Charlie Clark] > mm, okay I understand the mapping thing but this doesn't seem much > more efficient (in terms of typing) or sensible than the series of = ifs > I had; it probably runs a lot faster though but then again that isn= 't > important when compared with the subsequent SQL calls... It does the job in an obvious way -- that's as Pythonic as you can ge= t. dict-based code is also easier to change/maintain than masses of "if" statements, and the mapping it provides can be reused in other routin= es. > But the mapping should be {"monatlich": "months"...} with an > intermediary function (lambda()?, exec()?) magically inserting the > keyword in a RelativeDateTime() call. Why? The obvious way works the first time, and is easily understood = by anyone. If you had 10,000 phrases to map to durations, then a deeper= level of magic may be justified, but you've only got three values here. > ie. return now() + RelativeDateTime(magicfunction(dur)) Spell it return now() + RelativeDateTime(**magicfunction(dur)) and you could have magicfunction return a dict. Now you're asking "w= hat?" . That's the point: extra obscurity isn't worth it. If you t= hink there's some virtue in not typing RelativeDateTime 3 times, you can s= cratch that itch (again at the cost of greater obscurity) via, e.g., r =3D RelativeDateTime _name2dur =3D {"monatlich": r(months=3D+1), "w=F6chentlich": r(weeks=3D+1). "t=E4glich": r(days=3D+1), } > I also have three questions: why do you use the "_" in the name? That's a convention for names private to a module. It tells the read= er that _name2dur isn't part of the module's public API. If you would rather= make it public, that's fine too. > And is .get() becoming standard for dictionaries? Unclear what you're asking; dict.get() has been in Python a long time= . > how close is the upcoming "datetime" module to mx.DateTime. They're different designs. datetime is aimed more at efficient field extraction, mxDateTime more at efficient arithmetic. A detailed comp= arison would take more time than I can make. > ... > > I remember you once made a remark about it has long been possible t= o > make real digital computers as opposed to our current binary ones. Sorry, doesn't ring a bell; binary sounds pretty digital to me = . From alan.gauld@bt.com Mon Jan 6 12:32:33 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Jan 6 12:32:33 2003 Subject: [Tutor] getting input from keyboard Message-ID: <7497DCA1C240C042B28F6657ADFD8E097022E5@i2km11-ukbr.domain1.systemhost.net> > >> My online web tutor (and book!)has a topic on event driven > >> programming which includes an example of using msvcrt.getch() > > I could not actually find it there. Can you check if that's where it > should be? mea culpa! It's in the paper book not the web version. The web version uses BASIC INKEY$ for the example, the book OTOH is all in Python so uses msvcrt... sorry. Alan G. From alan.gauld@bt.com Mon Jan 6 12:34:49 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Jan 6 12:34:49 2003 Subject: [Tutor] pausing and layout Message-ID: <7497DCA1C240C042B28F6657ADFD8E097022EE@i2km11-ukbr.domain1.systemhost.net> > I guess I have three questions, the first being: Is there a > python command to pause until the user does something? Check out raw_input() > Also, how do you get python (when you don't run it in DOS > Prompt) to not auto-exit? There are several ways, the easiest is to use raw_input() - see above :-) > I was wondering how you do visual stuff, or make a > program run in a window, instead of in the command prompt screen? Try the GUI programming topic in my online tutorial: Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From sxa@fluent.com Mon Jan 6 12:35:41 2003 From: sxa@fluent.com (Sebastien Auclair) Date: Mon Jan 6 12:35:41 2003 Subject: [Tutor] What's wrong with this code ? Message-ID: <068a01c2b5a8$5f2b94a0$8ae4e9c0@sxapc> See code example below ! We are embeding python and our C++ software is trying to get an C++ pointer to an C++ object instantiated in a python module. This python Class "MyClass" is a sub-class of the C++ "An_Insterface*" class declared in library "A_Lib" that is of course accessible through SIP bindings. The few lines : <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< An_Interface* m_interface = NULL; PyObject *mdict = NULL; PyObject *func1 = NULL; PyObject * v1 = NULL; PyObject * sipClass; int bErrorOccured = 0; initlibsip(); mdict = PyModule_GetDict(m_pylib); // m_pylib is the compiled python file... this isvalid...It was tested. func1 = PyDict_GetItemString(mdict, "CreateInstance"); // The function that returns an instance of the desired class. (as a pointer) v1 = PyObject_CallObject(func1,NULL); // v1 will then contain some value other than NULL if (v1 == Py_None || sipIsSubClassInstance(v1,sipClass)){ file://Interesting !! This (if) test will always be FALSE (For both) } ///// HERE ARE THE CONVERSION ATTTEMPS !!!!!!!!!!!!!! m_interface = (An_Interface*)sipConvertToCpp (v1,sipClass, &bErrorOccured); // returns NULL with bErrorOccured == 1 m_interface = sipForceConvertTo_An_Interface(v1, &bErrorOccured); // returns NULL with bErrorOccured == 1 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Of course, the two last lines are both trying to do the same thing. It is just to show you what we tried. The python file, in short, looks like this : <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< def CreateInstance( ): return MyClass () class MyClass (A_Lib.An_Interface): def __init__(self): A_Lib.An_Interface.__init__(self) >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> From charlie@begeistert.org Mon Jan 6 12:40:17 2003 From: charlie@begeistert.org (Charlie Clark) Date: Mon Jan 6 12:40:17 2003 Subject: [Tutor] Assigning function keywords dynamically In-Reply-To: References: Message-ID: <20030106172212.1334.3@.1041865326.fake> On 2003-01-06 at 17:00:49 [+0100], Tim Peters wrote: > r =3D RelativeDateTime > _name2dur =3D {"monatlich": r(months=3D+1), > "w=F6chentlich": r(weeks=3D+1). > "t=E4glich": r(days=3D+1), > } That seems like a good compromise. Repeatedly typing "RelativeDateTime" means typos and copy + paste leads to different errors. Will see if I can amend this in the function which where I would like it - keep the mapping compact and maintain functional visibility. > > I also have three questions: why do you use the "_" in the name? > > That's a convention for names private to a module. It tells the reader > that _name2dur isn't part of the module's public API. If you would > rather make it public, that's fine too. name-mangling. I've heard of it but I've never read anything about when to use it and when not to use it. > > And is .get() becoming standard for dictionaries? > > Unclear what you're asking; dict.get() has been in Python a long time. I know that but I'm more used to dict['item']. I guess it has more to with class/functional duality and programming style in Python. Could you please explain the difference and the relevance to TOWTDT for this. > > how close is the upcoming "datetime" module to mx.DateTime. > > They're different designs. datetime is aimed more at efficient field > extraction, mxDateTime more at efficient arithmetic. A detailed > comparison would take more time than I can make. That's all I need to know. Seeing as Marc-Andr=E9 lives close to me I can ask him the next time we meet for a beer. > > ... > > > > I remember you once made a remark about it has long been possible to > > make real digital computers as opposed to our current binary ones. > > Sorry, doesn't ring a bell; binary sounds pretty digital to me . Base2 !=3D Base10 the last time I checked. It was in connection with floating point and something along the lines of "real digital computers have been possible for a long time now and would make all of this [floating point] mess unnecessary". Charlie From sxa@fluent.com Mon Jan 6 12:43:02 2003 From: sxa@fluent.com (Sebastien Auclair) Date: Mon Jan 6 12:43:02 2003 Subject: [Tutor] What's wrong with this code ? Message-ID: <06b201c2b5a9$db1a7580$8ae4e9c0@sxapc> See code example below ! We are embeding python and our C++ software is trying to get a C++ pointer to a C++ object instantiated in a python module. This python Class "MyClass" is a sub-class of the C++ "An_Insterface*" class declared in library "A_Lib" that is of course accessible through SIP bindings. The few CPP lines : <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< An_Interface* m_interface = NULL; PyObject *mdict = NULL; PyObject *func1 = NULL; PyObject * v1 = NULL; PyObject * sipClass; int bErrorOccured = 0; initlibsip(); mdict = PyModule_GetDict(m_pylib); // m_pylib is the compiled python file... this isvalid...It was tested. func1 = PyDict_GetItemString(mdict, "CreateInstance"); // The function that returns an instance of the desired class. (as a pointer) v1 = PyObject_CallObject(func1,NULL); // v1 will then contain some value other than NULL if (v1 == Py_None || sipIsSubClassInstance(v1,sipClass)){ // Interesting !! This (if) test will always be FALSE (For both) } ///// HERE ARE THE CONVERSION ATTTEMPS !!!!!!!!!!!!!! m_interface = (An_Interface*)sipConvertToCpp (v1,sipClass,&bErrorOccured); // returns NULL with bErrorOccured == 1 m_interface = sipForceConvertTo_An_Interface(v1, &bErrorOccured); // Returns NULL with bErrorOccured == 1 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Of course, the two last lines are both trying to do the same thing. It isjust to show you what we tried. The python file, in short, looks like this : <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< def CreateInstance( ): return MyClass () class MyClass (A_Lib.An_Interface): def __init__(self): A_Lib.An_Interface.__init__(self) >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> From charlie@begeistert.org Mon Jan 6 13:02:07 2003 From: charlie@begeistert.org (Charlie Clark) Date: Mon Jan 6 13:02:07 2003 Subject: [Tutor] Assigning function keywords dynamically In-Reply-To: References: Message-ID: <20030106190508.2864.10@.1041865326.fake> On 2003-01-06 at 18:44:18 [+0100], Tim Peters wrote: > > I expect you're conflating "digital" with "decimal", then. That's > unusual. Digital is usually contrasted with analog, in the sense of > discrete versus continuous. You're right I am but I think I'm etymologically correct - we have ten digits. > > It was in connection with floating point and something along the lines > > f "real digital computers have been possible for a long time now and > > would make all of this [floating point] mess unnecessary". > > Decimal arithmetic does hold fewer surprises for people than binary > floating-point, not because it's inherently better, but because people > have certain expectations derived from a lifetime of experience with > decimal arithmetic. That's where the feeling of discomfort comes from > when seeing, e.g., > > >>> .1 > 0.10000000000000001 indeed and I believe it can lead to problems. > Classes simulating decimal arithmetic in Python are available now; for > example (one close to my heart ) > > http://sourceforge.net/projects/fixedpoint/ filed for in case I ever need it! > Some very early computers did decimal arithmetic in hardware, but direct > HW support for it has been falling ever since. Here's a good link: Checking it out! IBM has impressive resources. How much difference would it make if the hardware did support it directly? Would it be possible to build more effecient hardware to counter current sledgehammer developments? I somehow have the feeling that it's application field would be wider than the cited "financial" and "scientific" applications. Thanx again Charlie From tim.one@comcast.net Mon Jan 6 13:14:22 2003 From: tim.one@comcast.net (Tim Peters) Date: Mon Jan 6 13:14:22 2003 Subject: [Tutor] Assigning function keywords dynamically In-Reply-To: <200301061619.h06GJ3G09129@bright08.icomcast.net> Message-ID: [Charlie Clark] > ... > I know that but I'm more used to dict['item']. I guess it has > more to with class/functional duality and programming style in Python. > Could you please explain the difference and the relevance to TOWTDT > for this. If you're happy to get a KeyError exception from dict[item], that's fine. If you would rather raise your own exception if a key is missing, and you know None isn't a possible dict value, result = dict.get(item) # or dict.get(item, None) if result is None; raise MyException is fine. It's not deep, it's a matter of what you want to do. >>> >>> I remember you once made a remark about it has long been possible to >>> make real digital computers as opposed to our current binary ones. >> Sorry, doesn't ring a bell; binary sounds pretty digital to me . > Base2 != Base10 the last time I checked. I expect you're conflating "digital" with "decimal", then. That's unusual. Digital is usually contrasted with analog, in the sense of discrete versus continuous. > It was in connection with floating point and something along the lines > f "real digital computers have been possible for a long time now and > would make all of this [floating point] mess unnecessary". Decimal arithmetic does hold fewer surprises for people than binary floating-point, not because it's inherently better, but because people have certain expectations derived from a lifetime of experience with decimal arithmetic. That's where the feeling of discomfort comes from when seeing, e.g., >>> .1 0.10000000000000001 >>> Classes simulating decimal arithmetic in Python are available now; for example (one close to my heart ) http://sourceforge.net/projects/fixedpoint/ Some very early computers did decimal arithmetic in hardware, but direct HW support for it has been falling ever since. Here's a good link: http://www2.hursley.ibm.com/decimal/ From emil@lysator.liu.se Mon Jan 6 13:24:06 2003 From: emil@lysator.liu.se (Emil Styrke) Date: Mon Jan 6 13:24:06 2003 Subject: [Tutor] pyLpd In-Reply-To: References: Message-ID: <3E19C64E.106@lysator.liu.se> janos.juhasz@VELUX.com wrote: > Dear all, > > This would be the very base of my test lpd, but i don't know how can i send > back an 'octete of zero bits' for acknowledgement > with self.wfile.write() That would be a byte (octet) with the value 0. You can produce one with the string "\0". (Unlike in C, where this would just result in an empty string.) /Emil > > ****** > import SocketServer > > > class pyLpd(SocketServer.StreamRequestHandler): > def handle(self): > lines = self.rfile.readlines() > self.wfile.write() > print lines > > > if __name__ == '__main__': > server = SocketServer.TCPServer( ('', 515), pyLpd) > server.serve_forever() > ***** > > Best regards, > ----------------------- > Juhász János > IT department > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From alan.gauld@bt.com Mon Jan 6 13:50:34 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Jan 6 13:50:34 2003 Subject: [Tutor] Better (free) IDEs than IDLE for Linux ? Message-ID: <7497DCA1C240C042B28F6657ADFD8E097022F7@i2km11-ukbr.domain1.systemhost.net> > MacOS 8/9 had both arrowheads in both ends of the scrollbar, to > try to please everybody. I don't know if that kind of duplication > was a good idea. I'm not sure what MacOS X does. Mac OS X lets you choose which style in the user prefeences but by default they are both at the bottom. Welcome back Magnus :-) Alan g. From Adam Vardy Mon Jan 6 13:58:02 2003 From: Adam Vardy (Adam Vardy) Date: Mon Jan 6 13:58:02 2003 Subject: [Tutor] Tkinter In-Reply-To: <0b1801c2b37a$d2632490$8510ba3f@defaultcomp> References: <1528827481.20030103161511@roadrunner.nf.net> <0b1801c2b37a$d2632490$8510ba3f@defaultcomp> Message-ID: <1233543745.20030106151911@roadrunner.nf.net> Friday, January 3, 2003, 7:22:25 PM, you wrote: >> >> Experimenting with TK, I came up on difficulties. Like, in one >> program, the window is there but whenever the pointer is over the >> window, there is always an hourglass. Can't see anything >> wrong. >> I don't know about this one, but does it happen when you execute the script >> from the command prompt? Specifically from a command prompt: ============================================================= from Tkinter import * import time,msvcrt root = Tk() c = Canvas(root) c.pack() o = c.create_text(35,35,text="Hi!") root.update() for i in range (1,10): c.move(o,8*i,0) root.update() a=msvcrt.getch() >> Most IDEs have their own event loop that doesn't >> play nice with Tkinter. >> >> This is a pretty common error. Make sure the callback you supply to the >> button constructor does _not_ include the parentheses. For example: >> b = Button(master, text="OK", command=self.ok) >> assigns the function 'self.ok' as the callback to be executed when the >> button is pressed. However, >> b = Button(master, text="OK", command=self.ok( ) ) >> executes self.ok( ) once when the button is istantiated and assigns the >> result to the button's 'command' attribute. How then do you send an argument to the function? And where was it said that you could just type the name, and no () which always seem mandatory? -- Adam Vardy From Adam Vardy Mon Jan 6 13:59:08 2003 From: Adam Vardy (Adam Vardy) Date: Mon Jan 6 13:59:08 2003 Subject: [Tutor] Debug In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E097022E9@i2km11-ukbr.domain1.systemhost.net> References: <7497DCA1C240C042B28F6657ADFD8E097022E9@i2km11-ukbr.domain1.systemhost.net> Message-ID: <1304053478.20030106152740@roadrunner.nf.net> Monday, January 6, 2003, 9:46:24 AM, you wrote: >> Unfortunately that does not solve the problem with the >> PythonWin debugger. >> It still halts in debugger.py. >> I didn't get that problem, I just set a break point, hit run then >> used step over/step into to go through my code. Ah, finally a Hand! :-) Bless you Alan. Ok, for that, maybe you could be more specific. After you hit Run, you probably got a prompt? How did you answer it? And what happened after that? -- Adam Vardy From alan.gauld@bt.com Mon Jan 6 14:28:44 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Jan 6 14:28:44 2003 Subject: [Tutor] Assigning function keywords dynamically Message-ID: <7497DCA1C240C042B28F6657ADFD8E097022F8@i2km11-ukbr.domain1.systemhost.net> > from mx.DateTime import now(), DateTime.RelativeDateTime >=20 > def new_date(interval): > if interval =3D=3D "monatlich": > return now() + RelativeDateTime(months=3D+1) > elif interval =3D=3D "w=F6chentlich": > return now() + RelativeDateTime(weeks=3D+1) > elif interval =3D=3D "t=E4glich": > return now() + RelativeDateTime(days=3D+1) > else: > return "Invalid interval" I don't know how RelativeDAteTime works but I assume it is returning=20 a fixed value. Thus I'd store them in a dictionary and do: Intervals =3D {"mon":RelativeDateTime(months=3D+1), "week":RelativeDateTime(weeks=3D+1), "day":RelativeDateTime(days=3D+1) } def new_date(interval): return now() + Intervals[interval] That will raise an exception automatically if the key doesn't exist. Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From alan.gauld@bt.com Mon Jan 6 14:41:09 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Jan 6 14:41:09 2003 Subject: [Tutor] Taking a screenshot Message-ID: <7497DCA1C240C042B28F6657ADFD8E097022F9@i2km11-ukbr.domain1.systemhost.net> This message is in MIME format. Since your mail reader does not understand this format, some or all of this message may not be legible. ------_=_NextPart_001_01C2B5B2.B36CB21F Content-Type: text/plain; charset="iso-8859-1" > Is it possible to use Python to take a screenshot of the script-user's screen > and then save it in some popular image format? That would be incredibly system dependant. Its the same problem as trying to clear the screen - how can Python know what kind of screen the user has? eg. How do you take a screen shot of a paper teletype? Or what about a server which doesn't have a screen? > I did some searching for an answer but couldn't find any module that would help me > do it or any instructions on how to. Are there any suggestions? Thanks in advance. It might be possible to set up a 3rd party tool to do so using os.system() Thats the best I can think of. Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ ------_=_NextPart_001_01C2B5B2.B36CB21F Content-Type: text/html; charset="iso-8859-1"
>  Is it possible to use Python to take a screenshot of the script-user’s screen  
>  and then save it in some popular image format?  
 
That would be incredibly system dependant. Its the same problem as trying to clear the
screen - how can Python know what kind of screen the user has? eg. How do you take a
screen shot of a paper teletype?
 
Or what about a server which doesn't have a screen?
 
>   I did some searching for an answer but couldn’t find any module that would help me  
>  do it or any instructions on how to. Are there any suggestions? Thanks in advance. 
 
It might be possible to set up a 3rd party tool to do so using os.system()
 
Thats the best I can think of.
 

Alan g.
Author of the Learn to Program website
http://www.freenetpages.co.uk/hp/alan.gauld/

------_=_NextPart_001_01C2B5B2.B36CB21F-- From abli@freemail.hu Mon Jan 6 14:49:42 2003 From: abli@freemail.hu (Abel Daniel) Date: Mon Jan 6 14:49:42 2003 Subject: [Tutor] open extra xterm? In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E097022EF@i2km11-ukbr.domain1.systemhost.net> References: <7497DCA1C240C042B28F6657ADFD8E097022EF@i2km11-ukbr.domain1.systemhost.net> Message-ID: <20030106192737.GA1476@hooloovoo> alan.gauld@bt.com (alan.gauld@bt.com) wrote: > > So I need at least two windows. How do I open a second xterm for > > output, while I use my main one as a readline terminal? > > Simplest way is to redirect your output to a file then simply > "tail" the file in the second xterm. > > $ man tail I tried this, too, with tail -f, but there was a noticable lag (1-2 secs). In the other solution i posted, which uses named pipes, there was no visible lag at all. Abel Daniel abli@freemail.hu From aztech1200@yahoo.com Mon Jan 6 17:23:14 2003 From: aztech1200@yahoo.com (Aztech Guy) Date: Mon Jan 6 17:23:14 2003 Subject: [Tutor] Better (free) IDEs than IDLE for Linux ? In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E097022F7@i2km11-ukbr.domain1.systemhost.net> Message-ID: <20030106215135.86451.qmail@web9807.mail.yahoo.com> --- alan.gauld@bt.com wrote: > Welcome back Magnus :-) I second the motion ! :-/ __________________________________________________ Do you Yahoo!? Yahoo! Mail Plus - Powerful. Affordable. Sign up now. http://mailplus.yahoo.com From dyoo@hkn.eecs.berkeley.edu Mon Jan 6 17:43:55 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Jan 6 17:43:55 2003 Subject: [Tutor] open extra xterm? In-Reply-To: <20030106192737.GA1476@hooloovoo> Message-ID: On Mon, 6 Jan 2003, Abel Daniel wrote: > alan.gauld@bt.com (alan.gauld@bt.com) wrote: > > > So I need at least two windows. How do I open a second xterm for > > > output, while I use my main one as a readline terminal? > > > > Simplest way is to redirect your output to a file then simply > > "tail" the file in the second xterm. > > > > $ man tail > I tried this, too, with tail -f, but there was a noticable lag > (1-2 secs). Hi Abel, By the way, the lag is probably due to the polling behavior of 'tail -f'. By default, tail checks the status of the file only every second. If we want to make the polling occur more frequently, we can set the "sleep interval" by using the '-s' option to something shorter. Hope this helps! From israel@lith.com Mon Jan 6 18:03:54 2003 From: israel@lith.com (Israel Evans) Date: Mon Jan 6 18:03:54 2003 Subject: [Tutor] Better (free) IDEs than IDLE for Linux ? Message-ID: Enjoying Jedit which is free and in Java. It also has a Jython Console embedded in it as well as a TON of plugins and Macros available on line. While it doesn't have a CPython inside, it is pretty darn cool. www.jedit.org is where to go. I've got it working very nicely on both my Windows and MacOSX boxes. ~Israel~ -----Original Message----- From: Aztech Guy [mailto:aztech1200@yahoo.com] Sent: 06 January 2003 1:52 PM To: tutor@python.org Subject: RE: [Tutor] Better (free) IDEs than IDLE for Linux ? --- alan.gauld@bt.com wrote: > Welcome back Magnus :-) I second the motion ! :-/ __________________________________________________ Do you Yahoo!? Yahoo! Mail Plus - Powerful. Affordable. Sign up now. http://mailplus.yahoo.com _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor _________________________________________________ Scanned for viruses on 06 Jan 2003 22:24:15 No viruses found. Virus scanning by http://erado.com From glingl@aon.at Mon Jan 6 19:00:23 2003 From: glingl@aon.at (Gregor Lingl) Date: Mon Jan 6 19:00:23 2003 Subject: [Tutor] Tkinter References: <1528827481.20030103161511@roadrunner.nf.net> <0b1801c2b37a$d2632490$8510ba3f@defaultcomp> <1233543745.20030106151911@roadrunner.nf.net> Message-ID: <3E1A117B.30006@aon.at> Hi, Adam! I will shortly first give a diagnosis about the "hour-glass", then show you an alternative way to accomplish your task and try to explain (but surely more and clearer explanations by others will follow) Adam Vardy schrieb: >Friday, January 3, 2003, 7:22:25 PM, you wrote: > > > >>>Experimenting with TK, I came up on difficulties. Like, in one >>>program, the window is there but whenever the pointer is over the >>>window, there is always an hourglass. Can't see anything >>>wrong. >>> >>> > > > >>>I don't know about this one, but does it happen when you execute the script >>>from the command prompt? >>> >>> If you run the program below from the msdos-prompt, you will observe, that the "focus" will shift from the msdos-window to the Tkinter-window. But seemingly msvcrt.getch() doesn't stop it's desire for a keypress, so your computer remains waiting for this and therefore shows its wellknown hourglass. in this situation, if you cliock on the msdos-window, thus restoring the focus on it, your program will work (approximately) as expected, but the Tkinter-window will close after executuion of the for-loop, something, which you might not have expected. >Specifically from a command prompt: > >============================================================= > >from Tkinter import * >import time,msvcrt > >root = Tk() >c = Canvas(root) >c.pack() > >o = c.create_text(35,35,text="Hi!") > >root.update() > >for i in range (1,10): > c.move(o,8*i,0) > root.update() > a=msvcrt.getch() > > > > This somewhat weird behaviour comes imo from the common use of Tkinter and msvcrt, which are not made to work together. On the contrary GUI-programs work according to an entirely different philosophy. They catch events via the operating system and perform actions according to these events (and the will of their programmer). Such events are keypresses, mouseclicks, mousemoves and more ... The programmer can bind specific actions to specific events. Then the os informs the GUI-program about the occurence of theses events (and some data connected with them via an event-object) and the GUI-program performs the action bound to the event just occuring, probably using the information, which is contained in the event-object. (Therefore the os has to deliver the event-object (the description of the event) to the action which is going to be performed. This action is defined as a function, which receives the event-object as an argument. (Thus it's definition has - in most cases - to contain a parameter, which by convention mostly is called event). So when the program is activ no programmer-defined loop is necessary, because there is .... is it? an event-loop, which catches all the occuring events. Hmmm.... it has to be there. But it has to be put there by the programmer. Now, woh can this be done: (1) determin an action: c.move(o,8,0) (2) bind it to the KeyPress-event for the root-window (3) Make the root window listen to the occuring events: It goes like this: from Tkinter import * root = Tk() c = Canvas(root) c.pack() o = c.create_text(35,35,text="Hi!") root.update() def moveHi(event): c.move(o,8,0) # (1) root.bind("", moveHi) # (2) root.mainloop() #(3) ----------------------------------------------- This extremely simple program does not use the information contained in event. But the window now can be closed by clicking the x - mark in the right upper corner (which didn't work with your earlier program). It recognizes this mouse-click-event and responds accordingly If you like to see how the information contained in event can be used, insert the following statement into the definition of moveHi before the c.move - call: c.itemconfigure(o,text=event.keysym) run the program, press several (different) keys and see the text change! One more remark to your last question below. A quick experiment in IDLE shows that there is an important difference between a function(-object) and the return-value(-object) of the function- >>> def ten(): return 10 >>> ten() 10 >>> ten >>> For our moveHi - function the return-value will be None (as there is no return-statement in the functino-definition). It would make no sense to bind None to the KeyPress-Event. What is needed is a function, i.e. something, which is callable - and which will be called with an event-object as argument, whenever an event occurs. In other words: ten() is a function call, and causes the code of the function to be executed. ten is a function - object, which *later* may be called - or even replaced. Both are Python-objects and thus can, in principle, be used as arguments. Look at the following really weird - but working - code: from Tkinter import * root = Tk() c = Canvas(root) c.pack() o = c.create_text(35,35,text="Hi!") # I don't like o root.update() def moveHi(event): root.unbind_all("") root.bind("", moveback) c.move(o,50,0) def moveback(event): root.unbind_all("") root.bind("", moveHi) c.move(o,-50,0) root.bind("", moveHi) root.mainloop() Hope, this is a first step to clearifying GUI- things. Regards, Gregor > > >>>Most IDEs have their own event loop that doesn't >>>play nice with Tkinter. >>> >>> > > > > > > >>>This is a pretty common error. Make sure the callback you supply to the >>>button constructor does _not_ include the parentheses. For example: >>> >>> > > > >>>b = Button(master, text="OK", command=self.ok) >>> >>> > > > >>>assigns the function 'self.ok' as the callback to be executed when the >>>button is pressed. However, >>> >>> > > > > >>>b = Button(master, text="OK", command=self.ok( ) ) >>> >>> > > > >>>executes self.ok( ) once when the button is istantiated and assigns the >>>result to the button's 'command' attribute. >>> >>> > >How then do you send an argument to the function? And where was it >said that you could just type the name, and no () which always seem >mandatory? > > > > From lumbricus@gmx.net Mon Jan 6 22:33:01 2003 From: lumbricus@gmx.net (lumbricus@gmx.net) Date: Mon Jan 6 22:33:01 2003 Subject: [Tutor] open extra xterm? References: Message-ID: <29890.1041895173@www40.gmx.net> Hi! > By the way, the lag is probably due to the polling behavior of 'tail -f'. > By default, tail checks the status of the file only every second. If we > want to make the polling occur more frequently, we can set the "sleep > interval" by using the '-s' option to something shorter. FYI: This feature is non standard. > Hope this helps! Dito, J"o! -- sigfault +++ GMX - Mail, Messaging & more http://www.gmx.net +++ NEU: Mit GMX ins Internet. Rund um die Uhr für 1 ct/ Min. surfen! From gp@pooryorick.com Tue Jan 7 01:01:02 2003 From: gp@pooryorick.com (Poor Yorick) Date: Tue Jan 7 01:01:02 2003 Subject: [Tutor] unicode utf-16 and readlines [using the 'codecs' unicode file reading module] References: Message-ID: <3E1A69D4.2010007@pooryorick.com> Danny Yoo wrote: > > >You may want to use a "codec" to decode Unicode from a file. The 'codecs' >module is specifically designed for this: > > http://www.python.org/doc/lib/module-codecs.html > > >For example: > >### > >>>>import codecs >>>>f = codecs.open('foo.txt', 'w', 'utf-16') >>>>f.write("hello world") >>>>f.close() >>>>open('foo.txt').read() >>>> >'\xff\xfeh\x00e\x00l\x00l\x00o\x00 \x00w\x00o\x00r\x00l\x00d\x00' > >>>>f2 = codecs.open('foo.txt', 'r', 'utf-16') >>>>f2.readlines() >>>> >[u'hello world'] >### > Thanks for the info! Using the codecs module is much better. It's interesting to note, though, that when using the codecs module on a real utf-16 text file, Python's automatic handling of new line characters seems to break down. For example: >>> import codecs >>> fh = codecs.open('0022data2.txt', 'r', 'utf-16') >>> a = fh.read() >>> a u'\u51fa\r\n' >>> print a ?? >>> a = a.strip() >>> print a ? >>> From glingl@aon.at Tue Jan 7 03:21:53 2003 From: glingl@aon.at (Gregor Lingl) Date: Tue Jan 7 03:21:53 2003 Subject: [Tutor] Tkinter - appendix Message-ID: <3E1A81EB.8080507@aon.at> Appendix: I'm not sure if this was not already posted few days ago. However, the following link not only does contain an intro to Tkinter, but also links to most - if not all - relevant documents on Tkinter: http://home.att.net/~stephen_ferg/thinking_in_tkinter/index.html Regards, Gregor From mongo57a@comcast.net Tue Jan 7 12:26:18 2003 From: mongo57a@comcast.net (andy surany) Date: Tue Jan 7 12:26:18 2003 Subject: [Tutor] Tk Listbox scrollbars Message-ID: <000e01c2b670$b9777000$2502a8c0@emily.ewndsr01.nj.comcast.net> Hello all, I wrote a program for a scrolled list containing a Y-axis scrollbar which has been working fine. At this point, my data is also overflowing the width of the box, so I have added an X-axis scrollbar. Both scrollbars appear, but the x-axis scrollbar is "vertical" (and tiny...and I press the up or down arrow to move left or right). What I want is a "slider" similar to the y scroll bar. I'm pretty sure that the error is in the way that I am packing the widget, as follows: sbar.pack(side=RIGHT, fill=Y) # This is for the Y-axis bar and it works correctly tbar.pack(side=BOTTOM) # This places the X-axis bar as described above TIA -Andy From alan.gauld@bt.com Tue Jan 7 13:03:02 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Jan 7 13:03:02 2003 Subject: [Tutor] 'if a==b or a==c or a==d' alternative (was: pausing a nd layout) Message-ID: <7497DCA1C240C042B28F6657ADFD8E0974DA82@i2km11-ukbr.domain1.systemhost.net> > > if p in 'Qq ': > > sys.exit() > > I've just looked thru the new stuff on Python 2.3, and it > seems that it will support larger subsplices, so that > > if 'ab' in 'abcdefg': > print 'found' > > will actually print 'found'. Which means that the above > example would do a sys.exit() if the user types 'Qq'. Which is probably better than raising an exception which is what it would do now... I guess the solution will be to put [0] after the test variable if you really only want to test 1 char. if 'ab'[0] in 'abcdefg':... But that's not so pretty. However it's countered by the number of folks who obviously expect 'ini' to work as it will in 2.3 - going by the number of times it crops up as a 'bug' on this list. But yes, I agree it's not entirely backward compatible and might well break some old code that relied on try/except to catch multi char input... - oddly enough I was reading the 2.3 stuff myself at the weekend and wondered about that too. Alan g. From alan.gauld@bt.com Tue Jan 7 16:11:22 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Jan 7 16:11:22 2003 Subject: [Tutor] Applications/examples of some advanced Py features, p lease ! Message-ID: <7497DCA1C240C042B28F6657ADFD8E097022ED@i2km11-ukbr.domain1.systemhost.net> This message is in MIME format. Since your mail reader does not understand this format, some or all of this message may not be legible. ------_=_NextPart_001_01C2B588.41E56D3E Content-Type: text/plain; charset="iso-8859-1" > Can anyone please give some examples / applications of the use of the following advanced > (advanced to me, at least :-) features of Python : 1. lambda I cover lambdas in my Functional Programming topic on my online tutor... 2. nested functions - a little info was given by Danny in reply to my earlier post on local-static variables, but I would like more. Its just a function defined inside another function, it can either be a helper function for the "parent" one or it can be a function that is returned by the parent in a similar way to the lambda construct (see above). This latter style of programming is powerful in a few areas and replaces lambdas in many cases. 3. Thoughts on implementing Interfaces in Py - a la Java interfaces. You can do it since an interface is just a class with empty method definitions. What Python won't do is force you to provide definitions though. However there is little or no need for interfaces in Python since it support full multiple inheritance and its dynamic nature makes the use of interfaces redundant in most cases anyway. Python effectively checks the interface of any object when it uses it. > I am planning to write a game-playing program in Py which will have features somewhat AI - ish. Thats fine, but you shlouldn't need interfaces. THe other features may be useful. > - in what way their use makes code simpler, or maybe makes code possible > that could not be written otherwise ('possible' in practical terms - I'm - vaguely - aware > of the fact that all languages are supposed to be theoretically 'Turing-equivalent' or > some such term - but what I mean is that if something is going to take a huge > amount more code in some other language, or jumping through hoops, then > I don't call it practically equivalent). Languages are practically equivalent if they can do the same jobs. There may be good reasons to write reams more code - like performance! But for most purposes each language has some things it is better at. Python is not the best AI language but its better than, say, C++ or Java. IMHO of course! :-) Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ ------_=_NextPart_001_01C2B588.41E56D3E Content-Type: text/html; charset="iso-8859-1"
>  Can anyone please give some examples / applications of the use of the following advanced  
>  (advanced to me, at least :-) features of Python :

1. lambda 

I cover lambdas in my Functional Programming topic on my online tutor...

2. nested functions - a little info was given by Danny in reply to my earlier post on local-static  
 variables, but I would like more. 

Its just a function defined inside another function, it can either be a helper function for the "parent"
one or it can be a function that is returned by the parent in a similar way to the lambda construct
(see above). This latter style of programming is powerful in a few areas and replaces lambdas
in many cases.

3. Thoughts on implementing Interfaces in Py - a la Java interfaces. 

You can do it since an interface is just a class with empty method definitions.
What Python won't do is force you to provide definitions though.

However there is little or no need for interfaces in Python since it support full multiple
inheritance and its dynamic nature makes the use of interfaces redundant in most cases anyway.

Python effectively checks the interface of any object when it uses it.

 > I am planning to write a game-playing program in Py which will have features somewhat AI - ish.  

Thats fine, but you shlouldn't need interfaces. THe other features may be useful.

>   - in what way their use makes code simpler, or maybe makes code possible  
>  
that could not be written otherwise ('possible' in practical terms - I'm - vaguely - aware  
of the fact that all languages are supposed to be theoretically 'Turing-equivalent' or  
>
 some such term - but what I mean is that if something is going to take a huge  
>
 amount more code in some other language, or jumping through hoops, then  
I don't call it practically equivalent). 

Languages are practically equivalent if they can do the same jobs. There may be good
reasons to write reams more code - like performance! But for most purposes each
language has some things it is better at. Python is not the best AI language but its
better than, say, C++ or Java.

IMHO of course! :-)

Alan g.
Author of the Learn to Program website
http://www.freenetpages.co.uk/hp/alan.gauld/

 

------_=_NextPart_001_01C2B588.41E56D3E-- From jeff@ccvcorp.com Tue Jan 7 16:17:00 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Tue Jan 7 16:17:00 2003 Subject: [Tutor] Assigning function keywords dynamically References: <20030106190508.2864.10@.1041865326.fake> Message-ID: <3E19DD98.3080407@ccvcorp.com> Charlie Clark wrote: >On 2003-01-06 at 18:44:18 [+0100], Tim Peters wrote: > > >>I expect you're conflating "digital" with "decimal", then. That's >>unusual. Digital is usually contrasted with analog, in the sense of >>discrete versus continuous. >> >> >You're right I am but I think I'm etymologically correct - we have ten >digits. > > Well, when using decimal arithmetic we use ten digits. When using binary arithmetic we use two digits, and when using hexadecimal arithmetic we use sixteen. Actually, it would be more appropriate to say that we use X number of possible values for each digit, where 0000000001 is a number with ten digits. The point here being that precision in language can be important. People are better at guessing likely meanings than computers are, but it's still important to say precisely what you mean, or someone will think you mean something else. :) Jeff Shannon Technician/Programmer Credit International From mcp.bov@insightbb.com Tue Jan 7 16:23:24 2003 From: mcp.bov@insightbb.com (Mike P) Date: Tue Jan 7 16:23:24 2003 Subject: [Tutor] Re: Help understanding part of the tutorial References: <20030106165735.4595.40268.Mailman@mail.python.org> Message-ID: <000601c2b5bf$64f16d80$1de4dc0c@ct192133a> Message: 5 From: "Lee Harr" To: tutor@python.org Date: Sun, 05 Jan 2003 23:46:30 +0000 Subject: [Tutor] Re: Help understanding part of the tutorial >def mult(a,b): > if b == 0: > return 0 > rest = mult(a,b - 1) > value = a + rest > return value > >print "3*2 = ",mult(3,2) > >My question is that I don't get how mult(a,b-1) returns a value > Sometimes when debugging, or just trying to understand a piece of code, it helps to move through the code step by step thinking (or writing down) what the computer will do at each step: ok, I am going to call mult(3, 2) a = 3, b = 2 is b == 0? nope, so rest = mult(3, 1) ok, I am going to call mult(3, 1) a = 3, b = 1 is b == 0? nope, so rest = mult(3, 0) # note that rest here is different from the rest up above, # rest is "local" to this function call and is completely # independent of the rest in the mult(3, 2) call. ok, I am going to call mult(3, 0) a = 3, b = 0 is b == 0? YES, so return 0 # but, return 0 to where? who called this? # ah, yes, it was the call to mult(3, 1), so # back in the call to mult(3, 1) a = 3, b = 1, rest = 0 value = 3 + 0 return 3 # return to who? # to the mult(3, 2) call, so # back in the call to mult(3, 2) a = 3, b = 2, rest = 3 value = 3 + 3 return 6 # to who? # mult(3, 2) was the original call, so we're finished This is called a "recursive" function definition. (which means that the function calls itself in the process of calculating a final answer, and sets some kind of a condition for ending the stack of recursive calls) I am pretty sure that any recursive function can be written in a non-recursive way. For instance: def mult(a,b): total = 0 while a: total += b a -= 1 return total or, of course def mult(a, b): return a * b ----------------------------------------- I'm still learning Python and wondered if there was a reason I'm not seeing to use: def mult(a,b): if b == 0: return 0 rest = mult(a,b - 1) value = a + rest return value Instead of: def mult(a, b): return a * b Regards, Mike P. --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.435 / Virus Database: 244 - Release Date: 12/30/2002 From ramrom@earthling.net Tue Jan 7 16:23:52 2003 From: ramrom@earthling.net (Bob Gailer) Date: Tue Jan 7 16:23:52 2003 Subject: [Tutor] Debug In-Reply-To: <1304053478.20030106152740@roadrunner.nf.net> References: <7497DCA1C240C042B28F6657ADFD8E097022E9@i2km11-ukbr.domain1.systemhost.net> <7497DCA1C240C042B28F6657ADFD8E097022E9@i2km11-ukbr.domain1.systemhost.net> Message-ID: <5.2.0.9.0.20030106131240.019fa8e8@66.28.54.253> --=======63B61ACB======= Content-Type: text/plain; x-avg-checked=avg-ok-E7844FA; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit I have just e-mailled the problem to Mark Hammond. Let's see what he has to say. Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======63B61ACB======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-E7844FA Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.431 / Virus Database: 242 - Release Date: 12/17/2002 --=======63B61ACB=======-- From mongo57a@comcast.net Tue Jan 7 16:34:35 2003 From: mongo57a@comcast.net (andy surany) Date: Tue Jan 7 16:34:35 2003 Subject: [Tutor] Tk Listbox scrollbars Message-ID: <00a001c2b5c7$4dc6f8c0$2502a8c0@emily.ewndsr01.nj.comcast.net> Hello all, I wrote a program for a scrolled list containing a Y-axis scrollbar which has been working fine. At this point, my data is also overflowing the width of the box, so I have added an X-axis scrollbar. Both scrollbars appear, but the x-axis scrollbar is "vertical" (and tiny...and I press the up or down arrow to move left or right). What I want is a "slider" similar to the y scroll bar. I'm pretty sure that the error is in the way that I am packing the widget, as follows: sbar.pack(side=RIGHT, fill=Y) # This is for the Y-axis bar and it works correctly tbar.pack(side=BOTTOM) # This places the X-axis bar as described above TIA -Andy From aztech1200@yahoo.com Tue Jan 7 16:42:48 2003 From: aztech1200@yahoo.com (Aztech Guy) Date: Tue Jan 7 16:42:48 2003 Subject: [Tutor] Applications/examples of some advanced Py features, p lease ! In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E097022ED@i2km11-ukbr.domain1.systemhost.net> Message-ID: <20030106213856.82492.qmail@web9801.mail.yahoo.com> Thanks, Alan ! Az. --- alan.gauld@bt.com wrote: > I cover lambdas in my Functional Programming topic > > 2. nested functions - a little info was given by > powerful in a few areas and > replaces lambdas > > 3. Thoughts on implementing Interfaces in Py - a la > Java interfaces. > > You can do it since an interface is just a class > However there is little or no need for interfaces in > inheritance and its dynamic nature makes the use of > interfaces redundant in > most cases anyway. > > __________________________________________________ Do you Yahoo!? Yahoo! Mail Plus - Powerful. Affordable. Sign up now. http://mailplus.yahoo.com From brad.reisfeld@colostate.edu Tue Jan 7 16:44:12 2003 From: brad.reisfeld@colostate.edu (Brad Reisfeld) Date: Tue Jan 7 16:44:12 2003 Subject: [Tutor] OO approach to solving problem? Message-ID: Hi, I have a problem that I would like to solve using Python, but am not quite sure about a good approach. I do not know much about object-oriented methods, but it seems as if this approach might make sense for my problem. As a simple example of what I am trying to do, imagine a collection of creatures that you would like to 'manage'. Each creature has a certain rate of growth, a certain probability of transforming into another creature at some point in time, and a given lifetime. You would like to keep an 'inventory' of the creatures as a function of time. In terms of programming, it seems to me that one approach might be to have each creature as an instance of a creature class with properties like type of creature, growth rate, lifetime, transformation probability, and age. These instances would be created by a 'master class' (a factory class?) that would 'create' each creature, update it as to its age, and transform it. At some point, the instance would 'alert' the master class that it is ready to die and the master class would delete it. For my problem there will be a _large_ number of 'creatures' (>100000) and 'time' steps (>10^6). Does the above approach sound reasonable? If so, I think I know how to address most of the issues. However, I am unclear as to how the creature instances can communicate with the master class. How does the instance 'know' who created it and how to pass information back to it? I'm sure this must be a common design pattern, but being an old-time Fortran programmer, I haven't acquired much OO experience. Any advice and suggestions are appreciated. -Brad From magnus@thinkware.se Tue Jan 7 16:53:10 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Jan 7 16:53:10 2003 Subject: [Tutor] Debug In-Reply-To: <5.2.0.9.0.20030106130034.02c8b820@66.28.54.253> References: <5.1.0.14.0.20030106001048.02bd4e90@www.thinkware.se> <5.2.0.9.0.20030102111509.02bd0da8@66.28.54.253> <1615745792.20030102140009@roadrunner.nf.net> Message-ID: <5.1.0.14.0.20030106234848.02c146c0@www.thinkware.se> At 13:01 2003-01-06 -0700, Bob Gailer wrote: >At 12:13 AM 1/6/2003 +0100, you wrote: >>May I suggest that you use Boa Constructor > >I downloaded it; however there's no instructions (that I can find) about >how to run it. How do you start it? First of all, you need wxPython of suitable version as described in http://boa-constructor.sourceforge.net/Download.html Once installed you double click on Boa.pyw in Windows. In other OSes I suppose you run Boa.py... -- 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 lumbricus@gmx.net Tue Jan 7 16:54:26 2003 From: lumbricus@gmx.net (lumbricus@gmx.net) Date: Tue Jan 7 16:54:26 2003 Subject: [Tutor] pyLpd References: <3E19C64E.106@lysator.liu.se> Message-ID: <9258.1041894106@www40.gmx.net> Hello! [ snip ] > That would be a byte (octet) with the value 0. You can produce one with > the string "\0". (Unlike in C, where this would just result in an empty > string.) But a string in C is per definition an array of characters _terminated by '\0'_. So the "empty string" in C you mention above (*char s = "") is really one char with value 0 (which is equivalent to '\0') - mostly but not necessarily an octet AKA byte. BTW in C: char *s = "\0"; This gives not an empty string - it is an array of two characters with value 0. > /Emil Greets, J"o! -- sigfault +++ GMX - Mail, Messaging & more http://www.gmx.net +++ NEU: Mit GMX ins Internet. Rund um die Uhr für 1 ct/ Min. surfen! From lumbricus@gmx.net Tue Jan 7 16:55:00 2003 From: lumbricus@gmx.net (lumbricus@gmx.net) Date: Tue Jan 7 16:55:00 2003 Subject: [Tutor] Taking a screenshot References: <7497DCA1C240C042B28F6657ADFD8E097022F9@i2km11-ukbr.domain1.systemhost.net> Message-ID: <23260.1041894779@www40.gmx.net> Hi! > > Is it possible to use Python to take a screenshot of the script-user's > screen > > and then save it in some popular image format? > > That would be incredibly system dependant. Its the same problem as trying > to > clear the > screen - how can Python know what kind of screen the user has? eg. How do > you take a > screen shot of a paper teletype? > > Or what about a server which doesn't have a screen? ACK > It might be possible to set up a 3rd party tool to do so using os.system() f.e.: os.system("xwd -root -out x.dump") os.system("xwud -in x.dump") works for me. > Thats the best I can think of. > > Alan g. Greets, J"o! -- sigfault +++ GMX - Mail, Messaging & more http://www.gmx.net +++ NEU: Mit GMX ins Internet. Rund um die Uhr für 1 ct/ Min. surfen! From glingl@aon.at Tue Jan 7 17:00:28 2003 From: glingl@aon.at (Gregor Lingl) Date: Tue Jan 7 17:00:28 2003 Subject: [Tutor] Tkinter References: <1528827481.20030103161511@roadrunner.nf.net> <0b1801c2b37a$d2632490$8510ba3f@defaultcomp> <1233543745.20030106151911@roadrunner.nf.net> Message-ID: <3E1A1505.1020708@aon.at> Appendix: I'm not sure if this was not already posted few days ago, nevertheless the following link not only does contain an intro to Tkinter, but also links to most - if not all - relevant documents on Tkinter: http://home.att.net/~stephen_ferg/thinking_in_tkinter/index.html Regards, Gregor Adam Vardy schrieb: >Friday, January 3, 2003, 7:22:25 PM, you wrote: > > > >>>Experimenting with TK, I came up on difficulties. Like, in one >>>program, the window is there but whenever the pointer is over the >>>window, there is always an hourglass. Can't see anything >>>wrong. >>> >>> > > > >>>I don't know about this one, but does it happen when you execute the script >>>from the command prompt? >>> >>> > >Specifically from a command prompt: > >============================================================= > >from Tkinter import * >import time,msvcrt > >root = Tk() >c = Canvas(root) >c.pack() > >o = c.create_text(35,35,text="Hi!") > >root.update() > >for i in range (1,10): > c.move(o,8*i,0) > root.update() > a=msvcrt.getch() > > > > > >>>Most IDEs have their own event loop that doesn't >>>play nice with Tkinter. >>> >>> > > > > > > >>>This is a pretty common error. Make sure the callback you supply to the >>>button constructor does _not_ include the parentheses. For example: >>> >>> > > > >>>b = Button(master, text="OK", command=self.ok) >>> >>> > > > >>>assigns the function 'self.ok' as the callback to be executed when the >>>button is pressed. However, >>> >>> > > > > >>>b = Button(master, text="OK", command=self.ok( ) ) >>> >>> > > > >>>executes self.ok( ) once when the button is istantiated and assigns the >>>result to the button's 'command' attribute. >>> >>> > >How then do you send an argument to the function? And where was it >said that you could just type the name, and no () which always seem >mandatory? > > > > From magnus@thinkware.se Tue Jan 7 17:03:21 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Jan 7 17:03:21 2003 Subject: [Tutor] Taking a screenshot In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E097022F9@i2km11-ukbr.domain1 .systemhost.net> Message-ID: <5.1.0.14.0.20030107002032.02c15a28@www.thinkware.se> At 18:37 2003-01-06 +0000, alan.gauld@bt.com wrote: >It might be possible to set up a 3rd party tool to do so using os.system() This is certainly possible. For Windows, the win32all bundle has a win32clipboard module, but the GetClipboardData function doesn't seem to handle images, only text, so that is of little help. (Maybe there is another way here.) Otherwise I guess it could have been possible to use some other function that triggered PrintScreen which would put a screenshot in the clipboard. Actually, there is one case where I think it's fairly simple to get screenshots in Python--cross platform even. Tkinter canvases can dump screenshots if I understand correctly. At least as PostScript. But that's no help if you want to get some other kind of screenshot... Hang on, isn't there support for this in PIL? Yes, if you are using Windows, it's supported in PIL from version 1.1.3. See the ImageGrab module in http://www.pythonware.com/products/pil/pil-handbook.pdf It doesn't seem to work quite as the docs suggests though... I couldn't find any ImageGrab module. Ask on comp.lang.python, and I'm pretty sure Fredrik will respond. Else, use his older, separate grabscreen from http://effbot.org/downloads/ With PIL and grabscreen, I tried this, and it worked: from PIL import Image import _grabscreen size, data = _grabscreen.grab() im = Image.fromstring("RGB", size, data, "raw", "BGR", (size[0]*3+3) & -4, -1) im.show() -- 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 fredm@smartypantsco.com Tue Jan 7 17:04:36 2003 From: fredm@smartypantsco.com (Alfred Milgrom) Date: Tue Jan 7 17:04:36 2003 Subject: [Tutor] keeping track of multiple cascading menus in Tkinter? Message-ID: <5.1.0.14.0.20030107111212.00ab0220@192.168.1.1> Hi: I wonder if anyone can help me? I am trying to create some menus dynamically, and I would like to know where a cascading menu is coming from. Since the menus are built dynamically, the final menu choices could be coming from any one of a number of parent menu choices, and I can't tell which one was chosen. The problem I have with the built-in menu types is that a menu item can be either a command type or a cascading type, but not both. I have tried to build a cascading menu with a command but no 'menu=' option, and that will execute a command to convert it to a normal cascading menu, but it closes the menu before conversion (as with normal menu choices) so this does not work for me. The relevant parts of this approach are: self.mFont.add_cascade(label='Font1', command=lambda index=1 : self.insertCascade(index)) def insertcascade(self, index): self.mFont.entryconfigure(index, menu=self.styleMenu) Not only do I want to have style options (normal, bold, italics), but also size options (10pt, 12pt, etc.) so I don't want to have to create a zillion font/style/size menus and commands. Is there a simple way to keep track of where you are in a series of cascading menus? (Hope this question makes some sense). Thanks in anticipation, Fred Milgrom Here is a simplified version of the code: from Tkinter import * class FontChooser: def __init__(self, parent=0): self.mainWindow = Frame(parent) fMenu=Frame(self.mainWindow) fMenu.pack(side=TOP,fill=X) bFont=Menubutton(fMenu, text="Font") bFont.pack(side=LEFT,anchor=W) self.mFont = Menu(bFont,tearoff=0) self.styleMenu = Menu(bFont, tearoff=0) self.styleMenu.add_command(label='Normal') self.styleMenu.add_command(label='Bold') self.styleMenu.add_command(label='Italic') self.mFont.add_command(label='Font0', command=self.font0) self.mFont.add_cascade(label='Font1', command=lambda index=1 : self.insertCascade(index)) bFont["menu"]=self.mFont self.entry = Entry(self.mainWindow) self.entry.insert(0,"Choose a font") self.entry.pack(fill=X) fOuter = Frame(self.mainWindow, border=1, relief="sunken") fButtons = Frame(fOuter, border=1, relief="raised") bClear = Button(fButtons, text="Clear", width=8, height=1, command=self.clearText) bQuit = Button(fButtons, text="Quit", width=8, height=1, command=self.mainWindow.quit) bClear.pack(side="left", padx=15, pady=1) bQuit.pack(side="right", padx=15, pady=1) fButtons.pack(fill=X) fOuter.pack(fill=X) self.mainWindow.pack() self.mainWindow.master.title("Font chooser") def clearText(self): self.entry.delete(0,END) def display (self, text) : self.clearText() self.entry.insert(END, text) def font0(self): self.display('Font 0 chosen') def insertCascade(self, index): self.display("Font 1 chosen") self.mFont.entryconfigure(index, menu=self.styleMenu) app = FontChooser() app.mainWindow.mainloop() From mongo57a@comcast.net Tue Jan 7 17:13:50 2003 From: mongo57a@comcast.net (andy surany) Date: Tue Jan 7 17:13:50 2003 Subject: [Tutor] Tk Listbox scrollbars Message-ID: <032d01c2b698$cfcb8120$2502a8c0@emily.ewndsr01.nj.comcast.net> Sorry for the multiple postings. Looks like my service provider had problems..... -----Original Message----- From: andy surany To: tutor@python.org Date: Tuesday, January 07, 2003 4:35 PM Subject: [Tutor] Tk Listbox scrollbars Hello all, I wrote a program for a scrolled list containing a Y-axis scrollbar which has been working fine. At this point, my data is also overflowing the width of the box, so I have added an X-axis scrollbar. Both scrollbars appear, but the x-axis scrollbar is "vertical" (and tiny...and I press the up or down arrow to move left or right). What I want is a "slider" similar to the y scroll bar. I'm pretty sure that the error is in the way that I am packing the widget, as follows: sbar.pack(side=RIGHT, fill=Y) # This is for the Y-axis bar and it works correctly tbar.pack(side=BOTTOM) # This places the X-axis bar as described above TIA -Andy _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From alan.gauld@bt.com Tue Jan 7 17:55:18 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Jan 7 17:55:18 2003 Subject: [Tutor] Debug Message-ID: <7497DCA1C240C042B28F6657ADFD8E0974DA7F@i2km11-ukbr.domain1.systemhost.net> > >> I didn't get that problem, I just set a break point, hit run then > >> used step over/step into to go through my code. > you hit Run, you probably got a prompt? How did you answer it? And > what happened after that? OK, Here's what I'm doing step by step: Open Python win File->Open select debug.py Select a line in my code and hit F9 - Toggle Breakpoint *Hit the "Sprinting man" icon in toolbar *Hit OK in dialog box Select View_>Toolbars->debugging In the debug toolbar hit GO (black arrow) Code runs to breakpoint Hit Step Into Code steps into my test function(see below) Hit step over, code stepsd to first line Open function/local browser to see variable values Step over thru' loop a few times Step out of to exit loop Examine variable values Step out of again to reach end of program Step over ends program with SystemExit exception displkayed in output (shell) window I don't think the lines prefixed '*' are needed.... just checked no, they aren't. HTH, Alan G. From alan.gauld@bt.com Tue Jan 7 18:00:40 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Jan 7 18:00:40 2003 Subject: [Tutor] Assigning function keywords dynamically Message-ID: <7497DCA1C240C042B28F6657ADFD8E097022FD@i2km11-ukbr.domain1.systemhost.net> I can't resist.... > > _name2dur =3D {"monatlich": RelativeDateTime(months=3D+1), > > "w=F6chentlich": RelativeDateTime(weeks=3D+1). > > "t=E4glich": RelativeDateTime(days=3D+1), > > } > >dur =3D _name2dur.get(interval) >=20 > mm, okay I understand the mapping thing but this doesn't seem=20 > much more efficient (in terms of typing)=20 It is if you have to add more entries later since you only need=20 update the dictionary, no modification and potential breaking=20 of existing function code involved. > compared with the subsequent SQL calls... But the mapping should be=20 > {"monatlich": "months"...} with an intermediary function (lambda()?,=20 > exec()?) magically inserting the keyword in a RelativeDateTime() = call. Why? Surely we are just generating a fixed period(month, week etc?)=20 Or is the call clever enough to work out the month length depending=20 on the current date? If the latter then yes a function reference would be necessary(either by lambda or def f...). But you don't need the=20 intermediate step, just put the function reference into the = dictionary...) > I also have three questions: why do you use the "_" in the=20 > name?=20 It prevents external(to the module users) seeing it. > I remember you once made a remark about it has long been=20 > possible to make real digital computers as opposed to our=20 > current binary ones.=20 An interesting distinction. What does it mean? I've seen an experimental three state computer once, and some early computers=20 did actually work in octal, but the complexity meant they=20 were slower than binary machines... > ("Baby" at the Museum of Science and Industry in Manchester)=20 Heh, I saw a film on Baby once - 1956/8 or thereabouts? :-) > Can anybody point me to a reasonable reference as to why so=20 > much time, energy has been spent "developing" Linux over=20 > the last 10 years in order to come up essentially with a=20 > new 4.4 BSD lite?=20 Have you read Neal Stephenson's history of the command line? Grep google for Stephenson command line... Initially it was just for kicks, plus the fact that Unix was=20 at the time(c1991) not free for the PC. Minix and Coherent=20 were available for about $100 each but neither was fully=20 featured. The Hurd was stagnating fast. There were some=20 tentative free BSD developments but they weren't aimed at=20 the PC market. Then people realised how good Unix on a PC was compared=20 to the alternatives and flocked to it. > wheel and repeating the mistakes and lessons of the previous=20 > 20 years.=20 But they didn't. Quite a few of the mitakes were learnt from=20 and improved upon. Linux code is/was much better than thhe early=20 Unix stuff from AT&T and even Berkely(sockets aside). It was=20 a modern Unix not an historical one - a trend that continues. And since Unix is still the best mid range OS what else should=20 they do? Pan 9 from AT&T bombed in the market(it was never=20 really expected to be huge) and BeOS seems to have died a death=20 with only niche support. > wondering: how much innovation occurs when the commercial=20 > imperative is removed?=20 Quite a lot. There are many open source type software projects=20 that are a long way ahead of any commercial competitor - X Windows=20 itself is probably the best example! Or the GNU emacs editor. Or gcc... Alan G. From scot@possum.in-berlin.de Tue Jan 7 18:31:47 2003 From: scot@possum.in-berlin.de (Scot Stevenson) Date: Tue Jan 7 18:31:47 2003 Subject: [Tutor] 'if a==b or a==c or a==d' alternative (was: pausing a nd layout) In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E097022F0@i2km11-ukbr.domain1.systemhost.net> References: <7497DCA1C240C042B28F6657ADFD8E097022F0@i2km11-ukbr.domain1.systemhost.net> Message-ID: <200301070833.36497.scot@possum.in-berlin.de> Hello Alan, > if p in 'Qq ': > sys.exit() > saves a few quote signs... I've just looked thru the new stuff on Python 2.3, and it seems that it will support larger subsplices, so that if 'ab' in 'abcdefg': print 'found' will actually print 'found'. Which means that the above example would do a sys.exit() if the user types 'Qq'. Okay, that's probably not going to ruin your party, but in other cases it might be a nasty side effect one of these days. Y, Scot -- Scot W. Stevenson -- scot@possum.in-berlin.de -- Zepernick, Germany From dyoo@hkn.eecs.berkeley.edu Tue Jan 7 18:34:17 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Jan 7 18:34:17 2003 Subject: [Tutor] unicode utf-16 and readlines [using the 'codecs' unicode file reading module] In-Reply-To: <3E1A69D4.2010007@pooryorick.com> Message-ID: > Thanks for the info! Using the codecs module is much better. It's > interesting to note, though, that when using the codecs module on a real > utf-16 text file, Python's automatic handling of new line characters > seems to break down. For example: > > >>> import codecs > >>> fh = codecs.open('0022data2.txt', 'r', 'utf-16') > >>> a = fh.read() > >>> a > u'\u51fa\r\n' > >>> print a > ?? > > > >>> a = a.strip() > >>> print a > ? Hi Poor Yorick! I have to admit I'm a bit confused; there shouldn't be any automatic handling of newlines when we use read(), since read() sucks all the text out of a file. Can you explain more what you mean by automatic newline handling? Do you mean a conversion of '\r\n' to '\n'? > >>> a > u'\u51fa\r\n' > >>> print a > ?? > > > >>> a = a.strip() > >>> print a > ? I think it's working. If we look at the actual representation of the strings, both the carriage return and the newline are being removed: ### >>> a = u"\u51fa\r\n" >>> a u'\u51fa\r\n' >>> a.strip() u'\u51fa' ### I can't actually use print or str() to look at the Unicode characters on my console, since that '\u51fa' character isn't ASCII. Best of wishes to you! From phil@xfr.co.uk Tue Jan 7 18:41:24 2003 From: phil@xfr.co.uk (Philip Kilner) Date: Tue Jan 7 18:41:24 2003 Subject: [Tutor] Assigning function keywords dynamically In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E097022FD@i2km11-ukbr.domain1.systemhost.net> References: <7497DCA1C240C042B28F6657ADFD8E097022FD@i2km11-ukbr.domain1.systemhost.net> Message-ID: Hi Alan, In article <7497DCA1C240C042B28F6657ADFD8E097022FD@i2km11-ukbr.domain1.systemhost.ne t>, wrote: > > wondering: how much innovation occurs when the commercial > > imperative is removed? > > Quite a lot. There are many open source type software projects > that are a long way ahead of any commercial competitor - X Windows > itself is probably the best example! Or the GNU emacs editor. Or gcc... > Or Python? Commercial competitors I see none... The idea that the wheel is an open source component in a proprietary market hasn't held the motor industry back too badly. Clever commercial types recognise that, just as designing next years Merc is a commercial imperative, so is *NOT* re-inventing the wheel. Where would we be if the likes of, say, Bill Gates, Monsanto or Glaxo had their hands on a patent for the wheel? Not driving around in a Mercedes, that's for sure... Regards, PhilK Tue, 07 Jan 2003 23:19 GMT @ Vaio Email: phil@xfr.co.uk / Voicemail & Facsimile: 07092 070518 Tell me and I forget. Show me and I remember. Involve me and I understand. - Chinese saying From hall@ouhep1.nhn.ou.edu Tue Jan 7 18:46:25 2003 From: hall@ouhep1.nhn.ou.edu (Isaac Hall) Date: Tue Jan 7 18:46:25 2003 Subject: [Tutor] Tk Listbox scrollbars In-Reply-To: <000e01c2b670$b9777000$2502a8c0@emily.ewndsr01.nj.comcast.net> Message-ID: Hi Andy, You are in luck. I had to write this exact thing not long ago, so I will just copy for you the code that I have written to do this. It is in the form of a class, but I you can take the important things out of it. I use grid here, but pack can be used in the same way. I should note that when I used pack, the thing looked a little different, but not by much. The only difference here in calling this instead of a listbox is that the box is class.box from Tkinter import * class ScrolledListbox(Frame): def __init__(self,parent): Frame.__init__(self,parent) self.yScroll=Scrollbar(self,orient=VERTICAL) self.xScroll=Scrollbar(self, orient=HORIZONTAL) self.box=Listbox(self,xscrollcommand=self.xScroll.set, yscrollcommand=self.yScroll.set,bg='white') self.box.grid(row=0,column=0,sticky=N+S+E+W) self.xScroll.grid(row=1,column=0,sticky=E+W) self.yScroll.grid(row=0,column=1,sticky=N+S) self.xScroll["command"]=self.box.xview self.yScroll["command"]=self.box.yview Ike On Tue, 7 Jan 2003, andy surany wrote: > Hello all, > > I wrote a program for a scrolled list containing a Y-axis scrollbar > which has been working fine. At this point, my data is also overflowing > the width of the box, so I have added an X-axis scrollbar. > > Both scrollbars appear, but the x-axis scrollbar is "vertical" (and > tiny...and I press the up or down arrow to move left or right). What I > want is a "slider" similar to the y scroll bar. I'm pretty sure that the > error is in the way that I am packing the widget, as follows: > > sbar.pack(side=RIGHT, fill=Y) # This is for the Y-axis bar and it works > correctly > tbar.pack(side=BOTTOM) # This places the X-axis bar as described above > > TIA > > -Andy > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- From malik_martin@hotmail.com Tue Jan 7 18:48:33 2003 From: malik_martin@hotmail.com (malik martin) Date: Tue Jan 7 18:48:33 2003 Subject: [Tutor] does anyone want to read chapter 5 with me? Message-ID:
hi i'm having problems with chapter five in hopw to think like a computer program and i barely made it through chapter 4. i think its cause i suck at math. does anyone think that they can help me out. anyone on a windows machine have a program sharing client like netmeeting? or any other suggestions?. i currently use pythonwin.


The new MSN 8 is here: Try it free* for 2 months From Adam Vardy Tue Jan 7 19:00:41 2003 From: Adam Vardy (Adam Vardy) Date: Tue Jan 7 19:00:41 2003 Subject: [Tutor] Debug In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E0974DA7F@i2km11-ukbr.domain1.systemhost.net> References: <7497DCA1C240C042B28F6657ADFD8E0974DA7F@i2km11-ukbr.domain1.systemhost.net> Message-ID: <10085524698.20030107140532@roadrunner.nf.net> Tuesday, January 7, 2003, 7:14:51 AM, you wrote: >> >> I didn't get that problem, I just set a break point, hit run then >> >> used step over/step into to go through my code. >> you hit Run, you probably got a prompt? How did you answer it? And >> what happened after that? >> OK, Here's what I'm doing step by step: Thanks Alan! >> Open Python win File->>Open select debug.py Don't have a 'debug.py' file. But I tried another. >> Select a line in my code and hit F9 - Toggle Breakpoint >> *Hit the "Sprinting man" icon in toolbar >> *Hit OK in dialog box Ok. Only that's the prompt I was referring to, I think. Which has 3 fields, and Browse Ok, and Cancel. How are your fields set? Select View_>>Toolbars->debugging >> In the debug toolbar hit GO (black arrow) >> Code runs to breakpoint Actually, mine went again to the same part: else: # Can't find the source file - linecache may have it? import linecache line = linecache.getline(filename, lineno) print "%s(%d): %s" % (os.path.basename(filename), lineno, string.expandtabs(line[:-1],4)) return 0 def _doexec(cmd, globals, locals): exec cmd in globals, locals -- Adam Vardy From ramrom@earthling.net Tue Jan 7 19:16:14 2003 From: ramrom@earthling.net (Bob Gailer) Date: Tue Jan 7 19:16:14 2003 Subject: [Tutor] Debug In-Reply-To: <5.2.0.9.0.20030106131240.019fa8e8@66.28.54.253> References: <1304053478.20030106152740@roadrunner.nf.net> <7497DCA1C240C042B28F6657ADFD8E097022E9@i2km11-ukbr.domain1.systemhost.net> <7497DCA1C240C042B28F6657ADFD8E097022E9@i2km11-ukbr.domain1.systemhost.net> Message-ID: <5.2.0.9.0.20030107170422.028e3978@66.28.54.253> --=======14476836======= Content-Type: text/plain; x-avg-checked=avg-ok-6F772678; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit Mark Hammond says the PythonWin debug problem is fixed in the newest version. Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======14476836======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-6F772678 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.431 / Virus Database: 242 - Release Date: 12/17/2002 --=======14476836=======-- From dyoo@hkn.eecs.berkeley.edu Tue Jan 7 19:34:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Jan 7 19:34:01 2003 Subject: [Tutor] does anyone want to read chapter 5 with me? In-Reply-To: Message-ID: On Tue, 7 Jan 2003, malik martin wrote: > hi i'm having problems with chapter five in hopw to think like a > computer program and i barely made it through chapter 4. Hi Malik, Don't worry about it. One thing that I've noticed is that, for an author that knows a subject too well, communicating ideas can be a hard thing... *grin* I know that a few of us here on Tutor are working on the same examples from HOPW, so you have a sympathetic audience. Can you point out a particular example from Chapter Four or Five that you'd like to talk about? We can all pitch in to tease it, pull it, and pick it apart here on the Tutor mailing list. Best of wishes to you! From gp@pooryorick.com Tue Jan 7 19:39:05 2003 From: gp@pooryorick.com (Poor Yorick) Date: Tue Jan 7 19:39:05 2003 Subject: [Tutor] unicode utf-16 and readlines [using the 'codecs' unicode file reading module] References: Message-ID: <3E1B7357.5050701@pooryorick.com> Danny Yoo wrote: > > > >I have to admit I'm a bit confused; there shouldn't be any automatic >handling of newlines when we use read(), since read() sucks all the text >out of a file. > >Can you explain more what you mean by automatic newline handling? Do you >mean a conversion of '\r\n' to '\n'? > > > As you mentioned, strip works correctly with the list items returned by codec.readlines(), so my problem is entirely resolved. Yes, I meant that codecs.readlines returns '\r\n' where a standard file object returns just '\n': >>> import codecs >>> fh = codecs.open('0022data2.txt', 'r', 'utf-16') >>> a = fh.readlines() >>> a [u'\u51fa\r\n'] >>> fh = open('test1.txt', 'r') >>> a = fh.readlines() >>> a ['hello\n', 'goodbye\n', 'where\n', 'how\n', 'when'] >>> Perhaps you could tell me if this inconsistency poses any implications for the Python programmer. Poor Yorick gp@pooryorick.com From ramrom@earthling.net Tue Jan 7 19:50:03 2003 From: ramrom@earthling.net (Bob Gailer) Date: Tue Jan 7 19:50:03 2003 Subject: [Tutor] OO approach to solving problem? In-Reply-To: Message-ID: <5.2.0.9.0.20030107171040.02aa3280@66.28.54.253> --=======39424E94======= Content-Type: text/plain; x-avg-checked=avg-ok-6F772678; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 02:32 PM 1/7/2003 -0700, Brad Reisfeld wrote: >As a simple example of what I am trying to do, imagine a collection of >creatures that you would like to 'manage'. Each creature has a certain rate >of growth, a certain probability of transforming into another creature at >some point in time, and a given lifetime. You would like to keep an >'inventory' of the creatures as a function of time. > >In terms of programming, it seems to me that one approach might be to have >each creature as an instance of a creature class with properties like type >of creature, growth rate, lifetime, transformation probability, and age. >These instances would be created by a 'master class' (a factory class?) that >would 'create' each creature, update it as to its age, and transform it. At >some point, the instance would 'alert' the master class that it is ready to >die and the master class would delete it. Whoa. Classes don't do things. Module statements run the show, and they in turn can call functions, create instances of classes, and invoke instance methods. Statements in functions and methods continue to run the show. Potential solution outline: class Creature: def __init__(self, ctype, growth_rate, probability, lifetime): self.ctype = ctype self.growth_rate = growth_rate self.probability = probability self.lifetime = lifetime self.age = 0 self.alive = 1 def grow(self): self.age += 1 self.alive = self.lifetime > self.age if self.alive: # transform ?? return self.alive if __name__ == '__main__': collection = [] for creature_number in range(100000): # create the creature collection # determine ctype, growth_rate, probability, lifetime for next creature collection.append(Creature(ctype, growth_rate, probability, lifetime)) for timestep in range(1000000): collection = [creature in collection for creature.grow()] # age each creature and retain just those that still live On a 1 Ghz Win2K 512 K Ram machine with collection size = 4 and 10*6 cycles last loop required about 30 seconds. For about 100 creatures and 10*5 cycles about same time. YMMV. Other approaches that might be faster would involve just some arrays of data and no instance objects. HTH Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======39424E94======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-6F772678 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.431 / Virus Database: 242 - Release Date: 12/17/2002 --=======39424E94=======-- From jeff@ccvcorp.com Tue Jan 7 20:30:09 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Tue Jan 7 20:30:09 2003 Subject: [Tutor] OO approach to solving problem? References: <5.2.0.9.0.20030107171040.02aa3280@66.28.54.253> Message-ID: <3E1B7EB1.1090705@ccvcorp.com> Bob Gailer wrote: > At 02:32 PM 1/7/2003 -0700, Brad Reisfeld wrote: > >> As a simple example of what I am trying to do, imagine a collection of >> creatures that you would like to 'manage'. Each creature has a >> certain rate >> of growth, a certain probability of transforming into another >> creature at >> some point in time, and a given lifetime. You would like to keep an >> 'inventory' of the creatures as a function of time. > > > Potential solution outline: Hrm, did you actually test your results? :) > class Creature: .... > def grow(self): > self.age += 1 > self.alive = self.lifetime > self.age > if self.alive: > # transform ?? > return self.alive .... > collection = [creature in collection for creature.grow()] # age > each creature and retain just those that still live Proper list comprehension syntax would be [creature.grow() for creature in collection], rather than what you've got here. But this is the least of the problems, because creature.grow(), as you've shown it, returns a boolean value. So your first iteration of this list comprehension will convert your list of creature instances into a list of integers (or bools if using a sufficiently recent version of Python). The second iteration would therefore result in a (series of) AttributeErrors, as integers have no grow() method. (Which makes me wonder just how you got your timing statistics....) Something along these lines *could* be made to work by having creature.grow() return self instead of self.alive, though, and the general idea is pretty much correct. However, it would not be at all out of line to have a class that manages the list of creatures -- a CreatureCollection class. (Perhaps a Menagerie class?) The collection class could then initialize all of the creatures, guide each through it's grow() step, cull the dead ones, track statistics, etc. Jeff Shannon Technician/Programmer Credit International From dyoo@hkn.eecs.berkeley.edu Tue Jan 7 20:49:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Jan 7 20:49:02 2003 Subject: [Tutor] Composing codecs using codecs.EncodedFile / UTF-16 DOS format converted to Unix ASCII In-Reply-To: <3E1B7357.5050701@pooryorick.com> Message-ID: On Tue, 7 Jan 2003, Poor Yorick wrote: > >I have to admit I'm a bit confused; there shouldn't be any automatic > >handling of newlines when we use read(), since read() sucks all the > >text out of a file. > > > >Can you explain more what you mean by automatic newline handling? Do > >you mean a conversion of '\r\n' to '\n'? > > > > > > > As you mentioned, strip works correctly with the list items returned by > codec.readlines(), so my problem is entirely resolved. Yes, I meant > that codecs.readlines returns '\r\n' where a standard file object > returns just '\n': Ah, I see what you mean now. No, as far as I understand, Python doesn't do this automatic conversion of newlines. However, Python 2.3's "Universal Newline" support is probably what you're looking for. Till then, it's still possible to tie in a "\r\n" --> "\n" sort of scheme, using the mechanism of 'codecs'. It's not documented too well, but Python does support a scheme similar to the nested Readers that Java uses. Here is a module I cooked up called 'u_newlines.py' that provides such a codec for newline conversions: ### """A small demonstration of codec-writing. Transparently converts "\r\n" into "\n" Danny Yoo (dyoo@hkn.eecs.berkeley.edu) """ import codecs class Codec(codecs.Codec): def encode(self, input, errors="strict"): return input.replace("\r\n", "\n"), len(input) def decode(self, input, errors="strict"): return input.replace("\r\n", "\n"), len(input) class StreamWriter(Codec, codecs.StreamWriter): pass class StreamReader(Codec, codecs.StreamWriter): pass def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) codecs.register(getregentry) ### Let's see this in action. Let's say that we had a sample file in UTF-16 format: ### >>> sample_file = open("foo.txt", 'w') >>> sample_file.write("hello world\r\nThis is a test\r\n".encode("utf-16")) >>> sample_file.close() >>> open("foo.txt").read() '\xff\xfeh\x00e\x00l\x00l\x00o\x00 \x00w\x00o\x00r\x00l\x00d\x00\r\x00\n\x00T\x00h\x00i\x00s\x00 \x00i\x00s\x00 \x00a\x00 \x00t\x00e\x00s\x00t\x00\r\x00\n\x00' ### 'foo.txt' now contains two lines of UTF-16 encoded text. Notice that a normal read() on this file isn't working too well now, since Python doesn't know that it's reading from a UTF-16 source. However, we can fix this by introducing a codecs.EncodedFile() wrapper around the object: ### >>> import codecs >>> import u_newlines >>> f = codecs.EncodedFile(open("foo.txt"), 'ascii', 'utf-16') >>> f.read() 'hello world\r\nThis is a test\r\n' ### This EncodedFile wraps around our original file, and converts our ASCII'ish file using a UTF-16 converter. Here's the kicker: these EncodedFiles can be "composed": we can combine the effects of several codecs, including that of u_newlines.py above, by doing a double wrapping of our input file! ### >>> f = codecs.EncodedFile(open("foo.txt"), 'ascii', 'utf-16') >>> f2 = codecs.EncodedFile(f, 'u_newlines') >>> f2.read() 'hello world\nThis is a test\n' ### Muhahaha. *grin* I hope this helps! From dyoo@hkn.eecs.berkeley.edu Tue Jan 7 20:57:04 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Jan 7 20:57:04 2003 Subject: [Tutor] Re: Composing codecs using codecs.EncodedFile / UTF-16 DOS format converted to Unix ASCII In-Reply-To: Message-ID: > ### > """A small demonstration of codec-writing. Transparently converts > "\r\n" into "\n" > > Danny Yoo (dyoo@hkn.eecs.berkeley.edu) > """ > > import codecs > > class Codec(codecs.Codec): > def encode(self, input, errors="strict"): > return input.replace("\r\n", "\n"), len(input) > > def decode(self, input, errors="strict"): > return input.replace("\r\n", "\n"), len(input) > > class StreamWriter(Codec, codecs.StreamWriter): pass > class StreamReader(Codec, codecs.StreamWriter): pass > > def getregentry(): > return (Codec().encode,Codec().decode,StreamReader,StreamWriter) > > codecs.register(getregentry) > ### Small amendment: that last part of u_newlines.py is wrong; I should not have touched codecs.register. Sorry about that! The corrected code, along with a small test case, follows below: ### """A small demonstration of codec-writing. Transparently converts "\r\n" into "\n" Danny Yoo (dyoo@hkn.eecs.berkeley.edu) """ import codecs class Codec(codecs.Codec): def encode(self, input, errors="strict"): return input.replace("\r\n", "\n"), len(input) def decode(self, input, errors="strict"): return input.replace("\r\n", "\n"), len(input) class StreamWriter(Codec, codecs.StreamWriter): pass class StreamReader(Codec, codecs.StreamWriter): pass def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) def _test(): import StringIO f = codecs.EncodedFile(StringIO.StringIO("Hello\r\nWorld\r\n"), "u_newlines") assert f.readlines() == ["Hello\n", "World\n"] print "All done!" if __name__ == '__main__': _test() ### Hope this helps! From gp@pooryorick.com Tue Jan 7 21:22:34 2003 From: gp@pooryorick.com (Poor Yorick) Date: Tue Jan 7 21:22:34 2003 Subject: [Tutor] Composing codecs using codecs.EncodedFile / UTF-16 DOS format converted to Unix ASCII References: Message-ID: <3E1B8B73.2040308@pooryorick.com> Danny Yoo wrote: > >Ah, I see what you mean now. No, as far as I understand, Python doesn't >do this automatic conversion of newlines. However, Python 2.3's >"Universal Newline" support is probably what you're looking for. > Thanks for the sample code! It'll take me a while to digest.... But about newlines, I thought that '\n' was already a sort of universal newline for Python. On windows platforms, both open.read and open.readlines already transform '\r\n' into '\n' unless you use binary mode. That's why I thought it was a discrepancy for codecs.open to return '\r\n'. Poor Yorick gp@pooryorick.com From gp@pooryorick.com Tue Jan 7 21:51:03 2003 From: gp@pooryorick.com (Poor Yorick) Date: Tue Jan 7 21:51:03 2003 Subject: [Tutor] does anyone want to read chapter 5 with me? References: Message-ID: <3E1B78E9.2000703@pooryorick.com> Danny Yoo wrote: > >On Tue, 7 Jan 2003, malik martin wrote: > >>hi i'm having problems with chapter five in hopw to think like a >>computer program and i barely made it through chapter 4. >> > Pardon me if this is painfully obvious, but what is HOPW? Poor Yorick gp@pooryorick.com From ramrom@earthling.net Tue Jan 7 22:02:02 2003 From: ramrom@earthling.net (Bob Gailer) Date: Tue Jan 7 22:02:02 2003 Subject: [Tutor] OO approach to solving problem? In-Reply-To: <3E1B7EB1.1090705@ccvcorp.com> References: <5.2.0.9.0.20030107171040.02aa3280@66.28.54.253> Message-ID: <5.2.0.9.0.20030107195838.02a92e90@66.28.54.253> --=======23CC37EB======= Content-Type: text/plain; x-avg-checked=avg-ok-6F772678; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 05:28 PM 1/7/2003 -0800, Jeff Shannon wrote: Hrm, did you actually test your results? :) >> collection = [creature in collection for creature.grow()] # age each >> creature and retain just those that still live oops: I meant collection = [creature for creature in collection if creature.grow()] I was testing separately, and forgot to bring the modified code back to the e-mail. I did test the above. Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======23CC37EB======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-6F772678 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.431 / Virus Database: 242 - Release Date: 12/17/2002 --=======23CC37EB=======-- From Don Arnold" <3E1B78E9.2000703@pooryorick.com> Message-ID: <018001c2b6c2$141bebc0$2cd1b241@defaultcomp> Whew! I was afraid I was the only one who didn't know what they were talking about. Don ----- Original Message ----- From: "Poor Yorick" To: "Danny Yoo" Cc: "malik martin" ; Sent: Tuesday, January 07, 2003 7:03 PM Subject: Re: [Tutor] does anyone want to read chapter 5 with me? > > > Danny Yoo wrote: > > > > >On Tue, 7 Jan 2003, malik martin wrote: > > > >>hi i'm having problems with chapter five in hopw to think like a > >>computer program and i barely made it through chapter 4. > >> > > > Pardon me if this is painfully obvious, but what is HOPW? > > Poor Yorick > gp@pooryorick.com > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From aicolburn@yahoo.com Tue Jan 7 22:50:03 2003 From: aicolburn@yahoo.com (Alan Colburn) Date: Tue Jan 7 22:50:03 2003 Subject: [Tutor] wxPython newbie Message-ID: <20030107225231.36662.qmail@web20503.mail.yahoo.com> Having dabbled in Tkinter a bit last summer, I've now started dabbling similarly in wxPython. For all the newbies out there (like me) who wonder about wxPython vs. Tkinter, from a beginner perspective, I'd tell you not to be afraid of wxPython. I'm not finding it more difficult to understand than Tkinter and, in fact, wxPython has a logic to it that seems (to me) to be more consistent--thus easier--as my learning moves among different aspects of the module. However, I find the documentation to be pretty skimpy. Most people suggest looking at the wxPython tutorial, and then working with the wxPython demo. Doing things this way I've been able to make remarkably complex GUI designs pretty quickly -- but I don't always understand what I'm doing :-) So, first, if anyone can point me toward newbie-oriented resources to give me a more conceptual understanding, e.g., line by line, about what's happening in simply wxPython scripts, please do so! Second, what's returned when a user presses the "Yes" and "No" buttons in a dialog box whose parameters include wxYES_NO? I'd like to include code (for a dialog called d) that says: if d.ShowModal()==??what goes here??: ##do something after pressing YES Second, I get the impression there's a special dialog called wxValidate? wxValidator? for the traditional "Are you sure you want to do this?" type of message. I wasn't able to find documentation on this. Any help? As always, thank you all for your help! -- Al C. __________________________________________________ Do you Yahoo!? Yahoo! Mail Plus - Powerful. Affordable. Sign up now. http://mailplus.yahoo.com From syrinx@simplecom.net Wed Jan 8 01:14:02 2003 From: syrinx@simplecom.net (Scott) Date: Wed Jan 8 01:14:02 2003 Subject: [Tutor] pdb Message-ID: <20030108000851.71ecd5a7.syrinx@simplecom.net> Does pdb really work? Everytime I try to use it, every command gets 'EOF.' What could I be doing wrong? From johnca@ourpla.net Wed Jan 8 02:04:01 2003 From: johnca@ourpla.net (John Abbe) Date: Wed Jan 8 02:04:01 2003 Subject: [Tutor] A little security Message-ID: Aksed before, but no answer, so: I'm working on a Python CGI using passwords, which for now i've implemented in a field that gets sent with the GET method. This is obviously insecure. I'm guessing that https might be the simplest way to add security, but am very open to any suggestions. If it is to be https, i'd love to hear about any simpler ways to use it than the stuff pointed at by this news thread: http://groups.google.com/groups?frame=left&th=3ad2d5de60bb5f05 Life, John p.s. Thanks all for the answers to my 1.5.2 vs. 2.x question -- guess i'll work to retain compatibility for now at least -- All you /\/\ John Abbe "If you don't like the news, need \ / CatHerder go out and make some of your own." is... \/ http://ourpla.net/john/ --Wes Nisker From =?ISO-8859-1?B?YW50b25tdWhpbiDt4CByYW1ibGVyLnJ1?= Wed Jan 8 04:59:01 2003 From: =?ISO-8859-1?B?YW50b25tdWhpbiDt4CByYW1ibGVyLnJ1?= (=?ISO-8859-1?B?YW50b25tdWhpbiDt4CByYW1ibGVyLnJ1?=) Date: Wed Jan 8 04:59:01 2003 Subject: [Tutor] OO approach to solving problem? In-Reply-To: References: Message-ID: <471237128.20030108125756@rambler.ru> Hello Brad, Wednesday, January 8, 2003, 12:32:15 AM, you wrote: BR> Does the above approach sound reasonable? Rather reasonable. However, see several notes below. BR> If so, I think I know how to address most of the issues. However, I am BR> unclear as to how the creature instances can communicate with the master BR> class. How does the instance 'know' who created it and how to pass BR> information back to it? I'm sure this must be a common design pattern, but BR> being an old-time Fortran programmer, I haven't acquired much OO experience. There are several approaches. One of most simple may be to have a reference to the 'master' object. Something like: class BeastMaster: def isGoingToDie(self, creature): print "Creature", creature, "is going to die!" # Sure, you need something else here class BasicCreature: def __init__(self, master): self.master = master def onDie(self): self.master.isGoingToDie(self) class Moth(BasicCreature): def someMethod(self): # It's going to die... self.onDie() Actually there is kind of general pattern: Observer pattern (google for it and you'll find a lot). In some cases weak references may be more useful, though I don't think it pertains to your problem as you described it. Another thing that should be thought out is managing parallelism. As you described your problem it seems that creatures should live their life in parallel. There are several approaches to it. You may use threads and alike stuff. However, there would appear a lot of problems with locks, synchronization (though you may be much better in parallel programming than me, and it'd be really easy for you :) ). There is simpler approach that in CPython seems to be quicker too: you may use generators to dispatch process quants to creatures. If you need more info, please, write. -- Best regards, antonmuhin mailto:antonmuhin@rambler.ru From fredm@smartypantsco.com Wed Jan 8 08:17:02 2003 From: fredm@smartypantsco.com (Alfred Milgrom) Date: Wed Jan 8 08:17:02 2003 Subject: [Tutor] is this code dangerous? Message-ID: <5.1.0.14.0.20030108235804.01eccdd0@mail.milgromphoto.com> Hi: Can someone please tell me the best way to override class methods for specific instances? I want to have a general class, such as Person, with general methods. Some of the instances of the Person class may have different methods, and I want to be able to override the base method (such as the speak method for the cranky person in the example below). Do I need to define a new class for each instance where there is a different method? Is there overhead associated with having a large number of classes? Is the following code dangerous? (Obviously I could change the name of the cranky class to crankyperson, or something like that, and have a different class for each instance). What is the best way to handle this? ************************ class Person: def __init__(self, name): self.name = name def speak(self): print "%s says: my name is %s" % (self.name, self.name) hobbit = Person('Bilbo Baggins') class cranky(Person): def speak(self): print "%s says: I don't tell anyone my name" % (self.name) cranky = cranky('someone else') hobbit.speak() cranky.speak() ************************ Thanks in advance, Fred Milgrom From mfarnham@acm.org Wed Jan 8 08:24:02 2003 From: mfarnham@acm.org (Michael Farnham) Date: Wed Jan 8 08:24:02 2003 Subject: [Tutor] does anyone want to read chapter 5 with me? In-Reply-To: <3E1B78E9.2000703@pooryorick.com> References: <3E1B78E9.2000703@pooryorick.com> Message-ID: <104203287302@ispsnet.net> On Tuesday 07 January 2003 07:03 pm, you wrote: > Danny Yoo wrote: > >On Tue, 7 Jan 2003, malik martin wrote: > >>hi i'm having problems with chapter five in hopw to think like a > >>computer program and i barely made it through chapter 4. > > Pardon me if this is painfully obvious, but what is HOPW? > > Poor Yorick > gp@pooryorick.com > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor It looks like a typo to me. I think it should be how. HTH Mike -- You've got to be honest; if you can fake that, you've got it made. -- George Burns From op73418@mail.telepac.pt Wed Jan 8 10:58:01 2003 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Wed Jan 8 10:58:01 2003 Subject: [Tutor] is this code dangerous? References: <5.1.0.14.0.20030108235804.01eccdd0@mail.milgromphoto.com> Message-ID: <003f01c2b72f$4eed84d0$97190dd5@violante> ----- Original Message ----- From: "Alfred Milgrom" To: Sent: Wednesday, January 08, 2003 1:14 PM Subject: [Tutor] is this code dangerous? > Hi: > > Can someone please tell me the best way to override class methods for > specific instances? > > I want to have a general class, such as Person, with general methods. Some > of the instances of the Person class may have different methods, and I want > to be able to override the base method (such as the speak method for the > cranky person in the example below). > > Do I need to define a new class for each instance where there is a > different method? Is there overhead associated with having a large number > of classes? > Using the example you give below you can also do: >>> class Person: ... def __init__(self, name): ... self.name = name ... def speak(self): ... print "%s says: my name is %s" % (self.name, self.name) ... >>> Person >>> cranky = Person('someone else') >>> def crankyspeak(self): ... print "%s says: I don't tell anyone my name" % (self.name) ... >>> cranky.speak = crankyspeak But you have to notice though that speak is not a method but a plain function object: self is not automatically passed, e.g. >>> cranky.speak() Traceback (most recent call last): File "", line 1, in ? TypeError: crankyspeak() takes exactly 1 argument (0 given) >>> cranky.speak(cranky) someone else says: I don't tell anyone my name There are ways of course to override this - e.g. using something like the template pattern. You could code something like class Person: def speak(self): __speak = self.et('my_speak') if __speak is not None: __speak(self) else: print "%s says: my name is %s" % (self.name, self.name) This allows the user to just add a my_speak method to the instance and the speak method just looks for it first. I am sure there are other (and better) ways to do this, but it's an initial step. And do not worry about overhead unless you really have to e.g. your analysis has proved that you do need to worry - your program is not fast enough to meet the requirements - and that this place in the program is one of the bottlenecks. > Is the following code dangerous? (Obviously I could change the name of the > cranky class to crankyperson, or something like that, and have a different > class for each instance). What is the best way to handle this? > What do you mean by dangerous? > ************************ > > class Person: > def __init__(self, name): > self.name = name > > def speak(self): > print "%s says: my name is %s" % (self.name, self.name) > > hobbit = Person('Bilbo Baggins') > > class cranky(Person): > def speak(self): > print "%s says: I don't tell anyone my name" % (self.name) > > cranky = cranky('someone else') > > hobbit.speak() > cranky.speak() > > ************************ > > Thanks in advance, > Fred Milgrom > With my best regards, G. Rodrigues From aztech1200@yahoo.com Wed Jan 8 11:23:59 2003 From: aztech1200@yahoo.com (Aztech Guy) Date: Wed Jan 8 11:23:59 2003 Subject: [Tutor] is this code dangerous? In-Reply-To: <5.1.0.14.0.20030108235804.01eccdd0@mail.milgromphoto.com> Message-ID: <20030108162236.78572.qmail@web9806.mail.yahoo.com> Hi, [I'm fairly new to Python myself too, so take what I say with a grain of salt and test it out.] Answers inline in your message. Az. --- Alfred Milgrom wrote: > Hi: > > Can someone please tell me the best way to override > class methods for > specific instances? First, based on your code below, I think you may actually mean 'instane method' instead of class method. (Sorry if I'm wrong about that). [Not sure if class methods are allowed in Python or not - not got that far in the tut/docs yet :-)] Class methods are different from instance methods. They're allowed in C++ and Java. A class method is a method that is not associated with a specific instance of that class; its declaration / definition syntax is different than for instance methods. Also, a class method can be called - and typically is called - without having to instantiate even one instance of the class, whereas an instance method can only be called when you *have* an instance, using the syntax : inst.meth(args) - whereas a class method is called by syntax something like : class_name.meth(args) (don't remember now, but I think it's class_name::meth(args) in C++. So, assuming you mean 'instance method' : Not sure if it can be done in Python. I do know that it is not possible in C++ and Java but is possible in Ruby. Maybe newer versions of Python allow it. Check the docs - or wait for a reply from someone else :-) > > I want to have a general class, such as Person, with > general methods. Some > of the instances of the Person class may have > different methods, and I want > to be able to override the base method (such as the > speak method for the > cranky person in the example below). > > Do I need to define a new class for each instance > where there is a > different method? See my answers above for whether it is possible in the first place. If it is possible, then the answer to question just above is yes, since, if you don't do it, all instances will have the exact same methods. Is there overhead associated with > having a large number > of classes? Depends on what kind of overhead you mean. You'll surely have more source code overhead - as in quantity of code - when you have more classes. Also, if you have more code, it will take longer to load, and occupy more space in memory while the code is running - I would think both of these would be, roughly, directly proportional to the amount of code. This may or may not be a concern to you, depending on your hardware configuration - CPU, RAM, etc. > > Is the following code dangerous? (Obviously I could > change the name of the > cranky class to crankyperson, or something like > that, and have a different > class for each instance). What is the best way to > handle this? No, your code below is not 'dangerous'. What makes you think it might be ? Actually, for the need you've described, its the right code - if you plan to have categories - i.e. classes - of people, such as normal people (class Person) and cranky people (class cranky). If you can categorize your people instances that you need to create into a fairly small number of such classes, then you can create a separate class for each, each differing somewhat in the methods that they have. (You can in fact have different methods in each class, not just different implementations of the same method). However, if your code is going to have a really large number of individual people instances, and you want different behaviour for each of them, then it's going to be a problem for you - you'll have to type out the code for the different methods that each one has. Then this becomes something like you're attacking the problem with a wrong approach. You might then want to reconsider your design - one possible way could be to analyse your app, and try to identify a smaller number of categories of people, define classes for each (e.g. Normal, Cranky, Deaf-Mute, Anti-Social, etc.) and then parameterize the constructors so as to be able to pass different values for some argument, and within the speak method, use the different values to generate different behaviour, using a nested if/elif/..../else statement. HTH Az > > ************************ > > class Person: > def __init__(self, name): > self.name = name > > def speak(self): > print "%s says: my name is %s" % > (self.name, self.name) > > hobbit = Person('Bilbo Baggins') > > class cranky(Person): > def speak(self): > print "%s says: I don't tell anyone my > name" % (self.name) > > cranky = cranky('someone else') > > hobbit.speak() > cranky.speak() > > ************************ > > Thanks in advance, > Fred Milgrom > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor __________________________________________________ Do you Yahoo!? Yahoo! Mail Plus - Powerful. Affordable. Sign up now. http://mailplus.yahoo.com From alan.gauld@bt.com Wed Jan 8 11:39:07 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed Jan 8 11:39:07 2003 Subject: [Tutor] does anyone want to read chapter 5 with me? Message-ID: <7497DCA1C240C042B28F6657ADFD8E0970230C@i2km11-ukbr.domain1.systemhost.net> > Whew! I was afraid I was the only one who didn't know what > they were talking about. > > >>hi i'm having problems with chapter five in hopw to think like a > > >>computer program and i barely made it through chapter 4. > > Pardon me if this is painfully obvious, but what is HOPW? I believe its just a typo for "How" and the full title should be "How to think like a computer programmer" Alan g From alan.gauld@bt.com Wed Jan 8 11:43:01 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed Jan 8 11:43:01 2003 Subject: [Tutor] wxPython newbie Message-ID: <7497DCA1C240C042B28F6657ADFD8E0970230D@i2km11-ukbr.domain1.systemhost.net> > Second, what's returned when a user presses the "Yes" > and "No" buttons in a dialog box whose parameters > include wxYES_NO? When in doubt print it out is my motto. Why not just add a couple of lines: res = d.ShowModal() print res See what gets printed and substitute in your program... Alan G. From alan.gauld@bt.com Wed Jan 8 11:46:06 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed Jan 8 11:46:06 2003 Subject: [Tutor] pdb Message-ID: <7497DCA1C240C042B28F6657ADFD8E0970230E@i2km11-ukbr.domain1.systemhost.net> > Does pdb really work? Everytime I try to use it, every command gets > 'EOF.' What could I be doing wrong? Yes it works fine. If you know gdb it shouldn't cause any problems. How are you using it? Do you get as far as the pdb prompt? If you type help do you get the list of commands OK? Alan G. From marta_andrea@libero.it Wed Jan 8 11:48:02 2003 From: marta_andrea@libero.it (Andrea Valle) Date: Wed Jan 8 11:48:02 2003 Subject: R: [Tutor] wxPython newbie In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E0970230D@i2km11-ukbr.domain1.systemhost.net> Message-ID: Is there a real tutorial on wxpython (or on Tkinter)? I started learning Pythin thanks to its marvellous tutorial by Guido. But GUI semms to have not a resource like that. thanks! -a- From alan.gauld@bt.com Wed Jan 8 12:04:22 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed Jan 8 12:04:22 2003 Subject: [Tutor] is this code dangerous? Message-ID: <7497DCA1C240C042B28F6657ADFD8E0970230F@i2km11-ukbr.domain1.systemhost.net> > Can someone please tell me the best way to override class methods for > specific instances? You did it right in the example you gave. > Do I need to define a new class for each instance where there is a > different method? You should really, the definition of a class is its interface so if you change the interface you change the class! However Pythons implementation of OO is so open and flexible I'm sure there is a way to modify a method in place - there certainly is to add a new method... I just don't think its a good idea! > Is there overhead associated with having a > large number of classes? Of course - more names in the dict for a start, but not nearly as much as in having lots of instances! > (Obviously I could change the name of the cranky class to > crankyperson, or something like that... Why on earth would you want to do that? Its not necessary to include the parent classes name when subclassing. > have a different class for each instance). Thats the usual way. Diffeent behaviour is different class. BUT there is a style of programming that is designed to limit the damage. Its called mixin programming and is common in Lisp. The idea is you capture common groups of behaviour as abstract classes. Then you create the concrete classes by mutiply inheriting the mixins you need, something like this: class mute: def speak(msg): pass class shouter: def speak(msg): print msg.uppercase() class old: def age(): print "Mind your ow business!" class young: def age(): print "I'm ",self.age Now we can define some persons: class Person: def __init__(self,age): self.age = age def speak(msg): print msg def age(): pass class MutePerson(Person, mute): pass class LoudPerson(Person, Shouter): pass class Oldster(Person, Old): pass class Youngster(Person, Young) pass class OldandLoud(Person, Old, Shouter):pass And so on, if you categorize the behaviour right, the vast majority of classes have little or no code in them but just mixin the behaviour needed. You do have to be careful about things like the order of searching for methods, especially if multiple mixins implement the same metgod - say old had also implemented speak()... But it can be a useul way of reducing the complexity of your classes. Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From dyoo@hkn.eecs.berkeley.edu Wed Jan 8 13:30:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Jan 8 13:30:02 2003 Subject: [Tutor] does anyone want to read chapter 5 with me? In-Reply-To: <018001c2b6c2$141bebc0$2cd1b241@defaultcomp> Message-ID: On Tue, 7 Jan 2003, Don Arnold wrote: > Whew! I was afraid I was the only one who didn't know what they were > talking about. > > Pardon me if this is painfully obvious, but what is HOPW? My brain flubbed. I can't explain what HOPW means either. I've been trying to figure out what I was thinking as I typed that. Tracing back, I think I was mixing between "How to Think Like a Computer Scientist": http://www.ibiblio.org/obp/thinkCSpy/ and the Scheme textbook "How to Design Programs". http://www.htdp.org/ Somehow, I think the "HOw to" part got stuck in my head, and got condensed to the prefix "HO". "PW" might be a simple transposing of "Writing Programs"... but this only a guess as what kind of long-range logic bug was in my brain when I typed that acronym out. In summary: I screwed up. *grin* That'll teach me to use acronyms inapproriately. My apologies for the mixup! From dyoo@hkn.eecs.berkeley.edu Wed Jan 8 14:14:03 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Jan 8 14:14:03 2003 Subject: [Tutor] Composing codecs using codecs.EncodedFile / UTF-16 DOS format converted to Unix ASCII In-Reply-To: <3E1B8B73.2040308@pooryorick.com> Message-ID: On Tue, 7 Jan 2003, Poor Yorick wrote: > >Ah, I see what you mean now. No, as far as I understand, Python > >doesn't do this automatic conversion of newlines. However, Python > >2.3's "Universal Newline" support is probably what you're looking for. > > > > Thanks for the sample code! It'll take me a while to digest.... > > But about newlines, I thought that '\n' was already a sort of universal > newline for Python. On windows platforms, both open.read and > open.readlines already transform '\r\n' into '\n' unless you use binary > mode. That's why I thought it was a discrepancy for codecs.open to > return '\r\n'. Ah! I completely forgot about that! You're right: there's an platform-dependent automatic conversion of the line-endings. http://www.wdvl.com/Authoring/Languages/Python/Quick/python4_2.html if we open a file in "text" mode, which is what we've been doing in the past examples. However, this "\r\n"->"\n" conversion won't take its expected effect against UTF-16-encoded files because the character sequence isn't '\r\n' in the file, but rather, the four byte sequence: '\x00\r\x00\n'. That is, there's padding involved because each character now consists of two bytes each! So even when we open the file in text mode, Python file operations don't catch and do platform-dependent conversions here. Even the Universal Newlines support of Python 2.3 won't help us here, since by the time we read those four bytes, normalization will pass by without touching those strings. Or even worse, may even convert what looks like a lone "\r" into another newline since it looks like a Macintosh newline. So we may really need to open UTF-16 files in binary mode after all to be careful. Hmmm... perhaps this is a bug! Perhaps the utf-16 decoder should really do the '\r\n' normalization if it's running on a Windows platform. I haven't been able to Google other pages talking about this issue, so I have no idea what other people think about it. Maybe you might want to bring it up on the i18n-sig? http://www.python.org/sigs/i18n-sig/ It would be an interesting thing to talk about. I'm sorry I can't give a definitive answer on this one; I really don't know what the "right" thing to do is in this case. Good luck to you! From syrinx@simplecom.net Wed Jan 8 14:27:01 2003 From: syrinx@simplecom.net (Scott) Date: Wed Jan 8 14:27:01 2003 Subject: [Tutor] pdb In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E0970230E@i2km11-ukbr.domain1.systemhost.net> References: <7497DCA1C240C042B28F6657ADFD8E0970230E@i2km11-ukbr.domain1.systemhost.net> Message-ID: <20030108132202.0c290bcf.syrinx@simplecom.net> Strange. It's working now. I have no idea what I'm doing differently, but it's working. I hate when that happens. :( From magnus@thinkware.se Wed Jan 8 15:48:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Wed Jan 8 15:48:02 2003 Subject: [Tutor] 'if a==b or a==c or a==d' alternative (was: pausing a nd layout) In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E0974DA82@i2km11-ukbr.domain1 .systemhost.net> Message-ID: <5.1.0.14.0.20030108214746.02bf8268@www.thinkware.se> At 17:37 2003-01-07 +0000, alan.gauld@bt.com wrote: > > > if p in 'Qq ': > > > sys.exit() > > > > I've just looked thru the new stuff on Python 2.3, and it > > seems that it will support larger subsplices, so that > > > > if 'ab' in 'abcdefg': > > print 'found' > > > > will actually print 'found'. Which means that the above > > example would do a sys.exit() if the user types 'Qq'. > >Which is probably better than raising an exception which >is what it would do now... I guess the solution will be >to put [0] after the test variable if you really only >want to test 1 char. > >if 'ab'[0] in 'abcdefg':... > >But that's not so pretty. Another option is: "if len(p) == 1 and p in "Qq ":" or "if q in list('Qq '):" But in the case at hand, it seems likely that we know that q is one character long, for instance if it's the result of a key press. On the other hand, I fear that not even all key-presses are one character long... -- 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@thinkware.se Wed Jan 8 16:03:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Wed Jan 8 16:03:01 2003 Subject: [Tutor] wxPython newbie In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E0970230D@i2km11-ukbr.domain1 .systemhost.net> Message-ID: <5.1.0.14.0.20030108220115.02c0ab18@www.thinkware.se> At 16:41 2003-01-08 +0000, alan.gauld@bt.com wrote: >When in doubt print it out is my motto. And my motto is "When in doubt, learn the right way to do it!" ;) >Why not just add a couple of lines: > > res = d.ShowModal() > print res Because it will just be a stupid digit that doesn't mean anything to whoever reads the code. Magic numbers in the code is a no-no in my book. Who can be certain that these constants will remain the same in the next version of wxPython? (If I was wxWindows maintainer I might just shuffle them around on purpose between versions just to break such badly written code! ;) >See what gets printed and substitute in your program... Better to use wxID_YES, wxID_NO, wxID_OK or wxID_CANCEL. -- 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@thinkware.se Wed Jan 8 16:04:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Wed Jan 8 16:04:02 2003 Subject: [Tutor] wxPython newbie In-Reply-To: <20030107225231.36662.qmail@web20503.mail.yahoo.com> Message-ID: <5.1.0.14.0.20030108220658.02bfe128@www.thinkware.se> At 14:52 2003-01-07 -0800, Alan Colburn wrote: >So, first, if anyone can point me toward >newbie-oriented resources to give me a more conceptual >understanding, e.g., line by line, about what's >happening in simply wxPython scripts, please do so! Have you looked at the Wiki? Do you subscribe to the wxpython mailinglist? -- 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@thinkware.se Wed Jan 8 16:11:24 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Wed Jan 8 16:11:24 2003 Subject: [Tutor] does anyone want to read chapter 5 with me? In-Reply-To: <018001c2b6c2$141bebc0$2cd1b241@defaultcomp> References: <3E1B78E9.2000703@pooryorick.com> Message-ID: <5.1.0.14.0.20030108221059.02bfdfe0@www.thinkware.se> At 21:00 2003-01-07 -0600, Don Arnold wrote: >Whew! I was afraid I was the only one who didn't know what they were tal= king >about. It's maybe not the best tutorial for those who feel that their math skills are weak? On the other hand, trying to improve your understanding of maths is likely to make you a better programmer. Maybe something like G. P=F3lya's "How to solve it" might be helpful? --=20 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@thinkware.se Wed Jan 8 16:18:04 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Wed Jan 8 16:18:04 2003 Subject: [Tutor] pdb In-Reply-To: <20030108132202.0c290bcf.syrinx@simplecom.net> References: <7497DCA1C240C042B28F6657ADFD8E0970230E@i2km11-ukbr.domain1.systemhost.net> <7497DCA1C240C042B28F6657ADFD8E0970230E@i2km11-ukbr.domain1.systemhost.net> Message-ID: <5.1.0.14.0.20030108222005.02c73eb8@www.thinkware.se> At 13:22 2003-01-08 -0600, Scott wrote: >Strange. It's working now. I have no idea what I'm doing differently, >but it's working. I hate when that happens. :( Really? Why not just be happy instead? Life is to short to solve boring problems like "why didn't this work yesterday". Happy debugging! -- 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 jeff@ccvcorp.com Wed Jan 8 16:45:03 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Wed Jan 8 16:45:03 2003 Subject: [Tutor] does anyone want to read chapter 5 with me? References: Message-ID: <3E1C9B76.8030505@ccvcorp.com> Danny Yoo wrote: > >My brain flubbed. I can't explain what HOPW means either. > > >I've been trying to figure out what I was thinking as I typed that. > I think you expanded on a typo made by the original poster. To quote a segment of the inital message in this thread, "...chapter five in hopw to think like a computer program ..." -- it looks like you somehow conflated that typo with the name of the book, and went from there. I find that it's not all that uncommon that I will read something and the words will come up competely different in my brain -- I won't provide any examples, though, as most of them are horribly impolite. >cough< ;) Jeff Shannon Technician/Programmer Credit International From malik_martin@hotmail.com Wed Jan 8 17:40:24 2003 From: malik_martin@hotmail.com (malik martin) Date: Wed Jan 8 17:40:24 2003 Subject: [Tutor] does anyone want to read chapter 5 with me? Message-ID:

these replies came so late i wasnt sure i would get one i'll do some reading tonight and get back to you thanks alot guys

"Maybe something like G. Pólya's "How to solve it"
might be helpful? "

i'll have to check this out



>From: Danny Yoo
>To: Don Arnold
>CC: Poor Yorick , malik martin ,
>Subject: Re: [Tutor] does anyone want to read chapter 5 with me?
>Date: Wed, 8 Jan 2003 10:28:30 -0800 (PST)
>
>
>
>On Tue, 7 Jan 2003, Don Arnold wrote:
>
> > Whew! I was afraid I was the only one who didn't know what they were
> > talking about.
>
> > > Pardon me if this is painfully obvious, but what is HOPW?
>
>
>My brain flubbed. I can't explain what HOPW means either.
>
>
>I've been trying to figure out what I was thinking as I typed that.
>Tracing back, I think I was mixing between "How to Think Like a Computer
>Scientist":
>
> http://www.ibiblio.org/obp/thinkCSpy/
>
>and the Scheme textbook "How to Design Programs".
>
> http://www.htdp.org/
>
>Somehow, I think the "HOw to" part got stuck in my head, and got condensed
>to the prefix "HO". "PW" might be a simple transposing of "Writing
>Programs"... but this only a guess as what kind of long-range logic bug
>was in my brain when I typed that acronym out.
>
>
>
>In summary: I screwed up. *grin* That'll teach me to use acronyms
>inapproriately. My apologies for the mixup!
>
>
>_______________________________________________
>Tutor maillist - Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor


get 2 months FREE* From wolf_binary@hotmail.com Wed Jan 8 19:20:02 2003 From: wolf_binary@hotmail.com (Cameron Stoner) Date: Wed Jan 8 19:20:02 2003 Subject: [Tutor] OOP class declaration question Message-ID: Hi all, Recently I made a class that I found out wouldn't work properly unless all the variables were filled with something. My question is why do you have to have all the fields filled with something? Is it because you can't make an object of something without knowing what each part is soposed to be? I thought python could allow for variable declaration on the fly and you didn't have to worry about what type of data it was sopposed to hold. Thanks, -Cameron Here is the code: class mobileSuit: def __init__(self,lArm, rArm, head, lLeg, rLeg, back, maxHealth): self.leftArmHealth = lArm self.rightArmHealth = rArm self.headHealth = head self.leftLegHealth = lLeg self.rightLegHealth = rLeg self.backHealth = back self.maxHealth = maxHealth self.healthPercent self.actualHealth #request overall health def overallHealth(self, report): #determine actualHealth self.actualHealth = (self.leftArmHealth + self.rightArmHealth + self.headHealth + self.leftLegHealth + self.rightLegHealth + self.backHealth) / 6 #find percent of health self.healthPercent = (self.actualHealth / self.maxHealth) * 100 # report the status with a print else return the result if report == 1: print "The MS health is: ", self.healthPercent else: return self.healthPercent testSuit = mobileSuit(6,6,6,6,6,6,6) _________________________________________________________________ Help STOP SPAM: Try the new MSN 8 and get 2 months FREE* http://join.msn.com/?page=features/junkmail From drichardson@austincityclub.org Wed Jan 8 19:26:20 2003 From: drichardson@austincityclub.org (David Richardson) Date: Wed Jan 8 19:26:20 2003 Subject: [Tutor] weird edit menu Message-ID: This is a multi-part message in MIME format. ------=_NextPart_000_0026_01C2B742.F07E0370 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 7bit visited http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html to start toying with IDLE (python GUI) The edit menu to python 2.2.2 does not look like the images. In fact I can't find run script anywhere! Did I screw up something during install? David Richardson 512 301-4429 fax 512 301-4194 ------=_NextPart_000_0026_01C2B742.F07E0370 Content-Type: application/ms-tnef; name="winmail.dat" Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename="winmail.dat" eJ8+Ii0AAQaQCAAEAAAAAAABAAEAAQeQBgAIAAAA5AQAAAAAAADoAAEIgAcAGAAAAElQTS5NaWNy b3NvZnQgTWFpbC5Ob3RlADEIAQ2ABAACAAAAAgACAAEGgAMADgAAANMHAQAIABIAEAAAAAMACAEB A5AGAJgFAAAiAAAACwACAAEAAAALACMAAAAAAAMAJgAAAAAACwApAAAAAAADADYAAAAAAB4AcAAB AAAAEQAAAHdlaXJkIGVkaXQgbWVudSAAAAAAAgFxAAEAAAAWAAAAAcK3dFbA0WZGdBSBSHqaYlla C/pOwAAAAgEdDAEAAAAkAAAAU01UUDpEUklDSEFSRFNPTkBBVVNUSU5DSVRZQ0xVQi5PUkcACwAB DgAAAABAAAYOAKCtSXS3wgECAQoOAQAAABgAAAAAAAAA3MeoePkjvUeukSiaeHGUE8KAAAALAB8O AQAAAAIBCRABAAAAlQEAAJEBAADdAQAATFpGdfYFJeMDAAoAcmNwZzEyNRYyAPgLYG4OEDAzM08B 9wKkA+MCAGNoCsBzsGV0MCAHEwKAfQqBknYIkHdrC4BkNAxgbmMAUAsDC7UgEiAAkHQJCYAgaAJA cDovLxBoa24uCeBjcy6CYgSQa2VsZXkU8ABkdS9+ZHlvbyAvcHl0aAIgL2nqZBWgXwuAdANgFuAS gOhleC4UUG0JUAqxCoCwdG8gcwGQACAgGKAyeQuAZyAD8BagIEkgRExFICgWhCBHGFVJKRhEGERU aGWWIAmAFAAgB4BudRkhEiAaVTIuHUEgZG+ZB5FubwVACQBvax4gnmkVgBkgG9EHcGFnB5BsLiAZ 4AOgZgDQBUBJVCBjAHAnBUBmEnEgnHJ1A6AE9QBweXcb0PUJcCEfgEQW8CARBPEH0dx1cBjAA3AR MGgZYhXwjwUQGXELgBjRbGw/GwrbCvMiQGESIBQwUg3gEPEuZCNAC5AYUzUOICAzgDAxLTQ0MjkY RMkf0HggJ1cxORKgJUgLGEQR4QAqwAAAAAsAAYAIIAYAAAAAAMAAAAAAAABGAAAAAAOFAAAAAAAA AwADgAggBgAAAAAAwAAAAAAAAEYAAAAAEIUAAAAAAAADAA+ACCAGAAAAAADAAAAAAAAARgAAAAAB hQAAAAAAAAMAPYAIIAYAAAAAAMAAAAAAAABGAAAAAFKFAAA/cQEACwBKgAggBgAAAAAAwAAAAAAA AEYAAAAADoUAAAAAAAADAEyACCAGAAAAAADAAAAAAAAARgAAAAARhQAAAAAAAAMATYAIIAYAAAAA AMAAAAAAAABGAAAAABiFAAAAAAAAHgCAgAggBgAAAAAAwAAAAAAAAEYAAAAAVIUAAAEAAAAEAAAA OS4wAAsAgYAIIAYAAAAAAMAAAAAAAABGAAAAAAaFAAAAAAAACwCcgAggBgAAAAAAwAAAAAAAAEYA AAAAgoUAAAEAAAACAfgPAQAAABAAAADcx6h4+SO9R66RKJp4cZQTAgH6DwEAAAAQAAAA3MeoePkj vUeukSiaeHGUEwIB+w8BAAAAlwAAAAAAAAA4obsQBeUQGqG7CAArKlbCAABQU1RQUlguRExMAAAA AAAAAABOSVRB+b+4AQCqADfZbgAAAEM6XERvY3VtZW50cyBhbmQgU2V0dGluZ3NcT3duZXJcTG9j YWwgU2V0dGluZ3NcQXBwbGljYXRpb24gRGF0YVxNaWNyb3NvZnRcT3V0bG9va1xvdXRsb29rLnBz dAAAAwD+DwUAAAADAA00/TcAAAIBfwABAAAAPgAAADxMTkVIS09KQlBFRk5OQUFKR05EQU1FUElD RkFBLmRyaWNoYXJkc29uQGF1c3RpbmNpdHljbHViLm9yZz4AAAADAAYQHUhdvQMABxD4AAAAAwAQ EAAAAAADABEQAAAAAB4ACBABAAAAZQAAAFZJU0lURURIVFRQOi8vSEtORUVDU0JFUktFTEVZRURV L0RZT08vUFlUSE9OL0lETEVJTlRSTy9JTkRFWEhUTUxUT1NUQVJUVE9ZSU5HV0lUSElETEUoUFlU SE9OR1VJKVRIRUUAAAAAjkA= ------=_NextPart_000_0026_01C2B742.F07E0370-- From ramrom@earthling.net Wed Jan 8 20:51:02 2003 From: ramrom@earthling.net (Bob Gailer) Date: Wed Jan 8 20:51:02 2003 Subject: [Tutor] OOP class declaration question In-Reply-To: Message-ID: <5.2.0.9.0.20030108184713.02a7e270@66.28.54.253> --=======3DD346F======= Content-Type: text/plain; x-avg-checked=avg-ok-2C5849C1; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 06:15 PM 1/8/2003 -0600, Cameron Stoner wrote: >class mobileSuit: > def __init__(self,lArm, rArm, head, lLeg, rLeg, back, maxHealth): > self.leftArmHealth = lArm > self.rightArmHealth = rArm > self.headHealth = head > self.leftLegHealth = lLeg > self.rightLegHealth = rLeg > self.backHealth = back > self.maxHealth = maxHealth OK so far. > self.healthPercent > self.actualHealth These two lines will give errors, as the properties don't yet exist. Solution: either drop these two lines or change them into assignments. self.healthPercent = None self.actualHealth = None Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======3DD346F======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-2C5849C1 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.438 / Virus Database: 246 - Release Date: 1/7/2003 --=======3DD346F=======-- From carroll@tjc.com Wed Jan 8 22:51:01 2003 From: carroll@tjc.com (Terry Carroll) Date: Wed Jan 8 22:51:01 2003 Subject: R: [Tutor] wxPython newbie In-Reply-To: Message-ID: On Wed, 8 Jan 2003, Andrea Valle wrote: > Is there a real tutorial on wxpython (or on Tkinter)? A couple for Tkinter: http://home.att.net/~stephen_ferg/thinking_in_tkinter/ http://www.pythonware.com/library/tkinter/introduction/index.htm -- Terry Carroll | Santa Clara, CA | "The parties are advised to chill." carroll@tjc.com | - Mattel, Inc. v. MCA Records, Inc., Modell delendus est | no. 98-56577 (9th Cir. July 24, 2002) From carroll@tjc.com Wed Jan 8 22:53:06 2003 From: carroll@tjc.com (Terry Carroll) Date: Wed Jan 8 22:53:06 2003 Subject: R: [Tutor] wxPython newbie In-Reply-To: Message-ID: On Wed, 8 Jan 2003, Andrea Valle wrote: > Is there a real tutorial on wxpython (or on Tkinter)? I've never looked into wxpython, but http://www.wxpython.org/tutorial.php and http://wiki.wxpython.org/ look promising. -- Terry Carroll | Santa Clara, CA | "The parties are advised to chill." carroll@tjc.com | - Mattel, Inc. v. MCA Records, Inc., Modell delendus est | no. 98-56577 (9th Cir. July 24, 2002) From fredm@smartypantsco.com Wed Jan 8 23:02:01 2003 From: fredm@smartypantsco.com (Alfred Milgrom) Date: Wed Jan 8 23:02:01 2003 Subject: [Tutor] is this code dangerous? In-Reply-To: <003f01c2b72f$4eed84d0$97190dd5@violante> References: <5.1.0.14.0.20030108235804.01eccdd0@mail.milgromphoto.com> Message-ID: <5.1.0.14.0.20030109142846.00aaa130@192.168.1.1> Thanks to everyone who helped me out with this question. >What do you mean by dangerous? What I meant by 'dangerous' was that I had named the class 'cranky', and then threw away the reference by naming the instance 'cranky' as well. Anyway, I just wanted to share the solution that I think I will adopt: ************************************************** class Person: def __init__(self, name): self.name = name def speak(self, dummy): print "%s says: my name is %s" % (self.name, self.name) def crankyspeak(self): print "%s says: I don't tell anyone my name" % (self.name) hobbit = Person('Bilbo Baggins') cranky = Person('someone else') cranky.speak=Person.crankyspeak hobbit.speak(hobbit) cranky.speak(cranky) ************************************************** The benefits from my point of view are: * I don't have to create a large number of classes * all the code for the methods are in the one place (Person class) * I can easily mix and match the methods for any instance without the difficulties that Alan mentioned * the same code structure (albeit more unwieldy than usual) can be used for every instance/method combination (ie no problems with unbound methods or not passing self parameter) Thanks again for your help, Fred Milgrom From lumbricus@gmx.net Wed Jan 8 23:26:01 2003 From: lumbricus@gmx.net (lumbricus@gmx.net) Date: Wed Jan 8 23:26:01 2003 Subject: [Tutor] pyLpd References: <92CB4AC7-2312-11D7-8E1C-000393DC397E@styrke.com> Message-ID: <22005.1042086345@www32.gmx.net> Hi! > Yes, the array is two chars long, but considered as a string, it _is_ > empty (strlen() returns 0). A char s[1000] filled with '\0':s is still > > an empty string, although the array holding it is 1000 chars in size. > > What I was trying to hint at in my first message was that python, > unlike C, has a real 8 bit clean string type. I guess I could have > expressed myself clearer. And of course, when working with raw 8-bit > data in C one would not handle the data arrays as strings, for exactly > > this reason. ACK. > /Emil Greetings, J"o! -- None -- sigfault +++ GMX - Mail, Messaging & more http://www.gmx.net +++ NEU: Mit GMX ins Internet. Rund um die Uhr für 1 ct/ Min. surfen! From syrinx@simplecom.net Thu Jan 9 01:48:24 2003 From: syrinx@simplecom.net (Scott) Date: Thu Jan 9 01:48:24 2003 Subject: [Tutor] Kill A Fuction Call? Message-ID: <20030109004334.504ca019.syrinx@simplecom.net> Is it possible to call a function, and kill it if it doesn't complete in a certain amount of time? From pythonpython@hotmail.com Thu Jan 9 01:52:02 2003 From: pythonpython@hotmail.com (Hy Python) Date: Thu Jan 9 01:52:02 2003 Subject: [Tutor] Kill A Fuction Call? Message-ID: try the thread or threading module. Hy >From: Scott >To: tutor@python.org >Subject: [Tutor] Kill A Fuction Call? >Date: Thu, 9 Jan 2003 00:43:34 -0600 > >Is it possible to call a function, and kill it if it doesn't complete in >a certain amount of time? > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ MSN 8 with e-mail virus protection service: 2 months FREE* http://join.msn.com/?page=features/virus From pythonpython@hotmail.com Thu Jan 9 01:54:03 2003 From: pythonpython@hotmail.com (Hy Python) Date: Thu Jan 9 01:54:03 2003 Subject: [Tutor] How to force Tkinter scrollbar to move with the cursor without mouse/keyboard? Message-ID: Could someone please tell me: How to force Tkinter scrollbar to move with the cursor without mouse/keyboard? I mean, when I execute something like: textObject.mark_set(END, END) the cursor automatically goes to the end of the textObject in the GUI window, but the scrollbar does NOT move at all. How can I force the scrollbar to move to the end in the GUI window with the cursor? Thanks a lot for your help! Hy P.S. The ScolledText class I am using: class ScrolledText(Frame): def __init__(self,parent=None,text=""): Frame.__init__(self, parent) self.pack(expand=YES, fill=BOTH) self.makeWidgets() self.setText(text) def makeWidgets(self): sbar=Scrollbar(self) text=Text(self, relief=SUNKEN, width=60, height=15) sbar.config(command=text.yview) text.config(yscrollcommand=sbar.set) sbar.pack(side=RIGHT, fill=Y) text.pack(side=LEFT, expand=YES, fill=BOTH) self.text=text def setText(self,text): self.text.delete('1.0', END) self.text.insert('1.0', text) self.text.mark_set(INSERT, END) _________________________________________________________________ Add photos to your e-mail with MSN 8. Get 2 months FREE*. http://join.msn.com/?page=features/featuredemail From syrinx@simplecom.net Thu Jan 9 02:30:02 2003 From: syrinx@simplecom.net (Scott) Date: Thu Jan 9 02:30:02 2003 Subject: [Tutor] Kill A Fuction Call? In-Reply-To: References: Message-ID: <20030109012456.629f9da5.syrinx@simplecom.net> On Thu, 09 Jan 2003 06:49:55 +0000 "Hy Python" wrote: > try the thread or threading module. > Hy I thought of that but python doesn't allow you to kill threads, right? From pythonpython@hotmail.com Thu Jan 9 02:49:02 2003 From: pythonpython@hotmail.com (Hy Python) Date: Thu Jan 9 02:49:02 2003 Subject: [Tutor] Kill A Fuction Call? Message-ID: If all you want is to wait "a certain amount of time", you do not need to kill the thread. When your main thread terminates, all the other thread will die automatically. example: import thread,time def myFunc(): time.sleep(2) print "I am working..." time.sleep(3) print "I am killed by main thread..." def mainFunc(): thread.start_new_thread(myFunc,()) time.sleep(4) mainFunc() In this program, print "I am killed by main thread..." will never be executed. hope this helps... Hy On Thu, 09 Jan 2003 06:49:55 +0000 "Hy Python" wrote: >try the thread or threading module. >Hy I thought of that but python doesn't allow you to kill threads, right? >From: Scott >To: tutor@python.org >Subject: [Tutor] Kill A Fuction Call? >Date: Thu, 9 Jan 2003 00:43:34 -0600 > >Is it possible to call a function, and kill it if it doesn't complete in >a certain amount of time? > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ Add photos to your e-mail with MSN 8. Get 2 months FREE*. http://join.msn.com/?page=features/featuredemail From beercanz@hotmail.com Thu Jan 9 03:33:02 2003 From: beercanz@hotmail.com (Guess Who? Me) Date: Thu Jan 9 03:33:02 2003 Subject: [Tutor] help understanding part of the tutorial... Message-ID: Here is the source, which is at http://www.honors.montana.edu/~jjc/easytut/easytut/node10.html. test.py ## This program runs a test of knowledge true = 1 false = 0 # First get the test questions # Later this will be modified to use file io. def get_questions(): # notice how the data is stored as a list of lists return [["What color is the daytime sky on a clear day?","blue"],\ ["What is the answer to life, the universe and everything?","42"],\ ["What is a three letter word for mouse trap?","cat"]] # This will test a single question # it takes a single question in # it returns true if the user typed the correct answer, otherwise false def check_question(question_and_answer): #extract the question and the answer from the list question = question_and_answer[0] answer = question_and_answer[1] # give the question to the user given_answer = raw_input(question) # compare the user's answer to the testers answer if answer == given_answer: print "Correct" return true else: print "Incorrect, correct was:",answer return false # This will run through all the questions def run_test(questions): if len(questions) == 0: print "No questions were given." # the return exits the function return index = 0 right = 0 while index < len(questions): #Check the question if check_question(questions[index]): <<< I guess I found out how to do it now: textObject.yview(END) This will force the scrollbarOject.set() to push the bar to the end... If you have better ways of achieving the same thing, please let me know. Thanks. Hy >From: "Hy Python" >To: tutor@python.org >Subject: [Tutor] How to force Tkinter scrollbar to move with the cursor >without mouse/keyboard? >Date: Thu, 09 Jan 2003 06:45:44 +0000 > >Could someone please tell me: >How to force Tkinter scrollbar to move with the cursor without >mouse/keyboard? > >I mean, when I execute something like: > textObject.mark_set(END, END) >the cursor automatically goes to the end of the textObject in the GUI >window, but the scrollbar does NOT move at all. How can I force the >scrollbar to move to the end in the GUI window with the cursor? > >Thanks a lot for your help! > > >Hy >P.S. > >The ScolledText class I am using: > > >class ScrolledText(Frame): > def __init__(self,parent=None,text=""): > Frame.__init__(self, parent) > self.pack(expand=YES, fill=BOTH) > self.makeWidgets() > self.setText(text) > def makeWidgets(self): > sbar=Scrollbar(self) > text=Text(self, relief=SUNKEN, width=60, height=15) > sbar.config(command=text.yview) > text.config(yscrollcommand=sbar.set) > sbar.pack(side=RIGHT, fill=Y) > text.pack(side=LEFT, expand=YES, fill=BOTH) > self.text=text > def setText(self,text): > self.text.delete('1.0', END) > self.text.insert('1.0', text) > self.text.mark_set(INSERT, END) > > >_________________________________________________________________ >Add photos to your e-mail with MSN 8. Get 2 months FREE*. >http://join.msn.com/?page=features/featuredemail > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ MSN 8 helps eliminate e-mail viruses. Get 2 months FREE* http://join.msn.com/?page=features/virus From Janssen@rz.uni-frankfurt.de Thu Jan 9 05:00:02 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Thu Jan 9 05:00:02 2003 Subject: [Tutor] Kill A Fuction Call? In-Reply-To: Message-ID: also have look on the example for the signal module in the library: set an SIGALARM handler an then set signal.alarm to an amount of time. This *possible* also interrupts os.system or os.popen calls (havn't test it). Michael On Thu, 9 Jan 2003, Hy Python wrote: > try the thread or threading module. > > Hy > > > > >From: Scott > > > >Is it possible to call a function, and kill it if it doesn't complete in > >a certain amount of time? > > From abli@freemail.hu Thu Jan 9 06:17:01 2003 From: abli@freemail.hu (Abel Daniel) Date: Thu Jan 9 06:17:01 2003 Subject: [Tutor] How to force Tkinter scrollbar to move with the cursor without mouse/keyboard? In-Reply-To: References: Message-ID: <20030109111553.GA676@hooloovoo> Hy Python (pythonpython@hotmail.com) wrote: > I guess I found out how to do it now: > textObject.yview(END) > This will force the scrollbarOject.set() to push the bar to the end... > > If you have better ways of achieving the same thing, please let me know. I guess the see() method is for doing exactly this: 'Scroll such that the character at INDEX is visible.' abli abli@freemail.hu From magnus@thinkware.se Thu Jan 9 06:18:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Thu Jan 9 06:18:01 2003 Subject: [Tutor] weird edit menu In-Reply-To: Message-ID: <5.1.0.14.0.20030109121749.02c493c8@www.thinkware.se> At 18:22 2003-01-08 -0600, David Richardson wrote: >visited http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html >to start toying with IDLE (python GUI) > >The edit menu to python 2.2.2 does not look like the images. In fact I >can't find run script anywhere! Did I screw up something during install? No, just look further! At least in my 2.2.1, it's further down. Nine more menu items have been inserted between Select All and Check Module. As you see in the pictures, Danny's IDLE intro is made with an earlier version of Python. It's a bit sloppy that they didn't change the version number in IDLE though. (Mine is 0.8 as it is in the intro.) -- 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@thinkware.se Thu Jan 9 06:42:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Thu Jan 9 06:42:02 2003 Subject: [Tutor] OOP class declaration question In-Reply-To: Message-ID: <5.1.0.14.0.20030109115304.02c2cad8@www.thinkware.se> At 18:15 2003-01-08 -0600, Cameron Stoner wrote: >Hi all, > >Recently I made a class that I found out wouldn't work properly unless all >the variables were filled with something. A variable is ALWAYS a reference to an object. From a technical point of view you can see it as a location in a computers memory where you store an address to another location in the memory, where some data is stored. I imagine this is one more level of indirection than you thought. This is the same whether you use classes or not. It's probably more helpful if you see a variable as something that points out an existing object, rather than as something that you fill with an object. Let me explain why. a = [1,2] b = a c = b With the python code above, you have ONE list with the integers 1 and 2. There are three variables, but only one list object. If you do b.append(5), and print c, it will show [1, 2, 5]. Right? If you imagine c = b as filling the c variable with a list, you get the wrong idea, right? c = b means that you make c point to (or refer to) the same object in memory as the variable b (and a) does. Right? > My question is why do you have to have all the fields filled with > something? Is it because you can't make an object of something without > knowing what each part is soposed to be? This is really nothing particular for classes. > I thought python could allow for variable declaration on the fly and you > didn't have to worry about what type of data it was sopposed to hold. No. You don't have varable declarations at all in Python. You just define them. Compare with C etc. int i; /* declaration of i */ ... i = 5; /* definition of i */ In python this is replaced with: i = 5 # That's all folks! It's completely pointless in Python to refer to a variable before you have defined it. You have it all upside down. It's in the OTHER programming languages, the ones with static typing that allows you (well, forces you rather) to declare variables before you use them. It might feel confusing that not all attributes of the class is listed in one place as in Java or C++, but that's life in a dynamic language. You can add new attributes in runtime as you like. There is no way for the class definition to know about that. If this feels like a bad thing to you, have a look at the new style classes in Python 2.2, and slots. >Here is the code: > >class mobileSuit: > def __init__(self,lArm, rArm, head, lLeg, rLeg, back, maxHealth): > self.leftArmHealth = lArm > self.rightArmHealth = rArm > self.headHealth = head > self.leftLegHealth = lLeg > self.rightLegHealth = rLeg > self.backHealth = back > self.maxHealth = maxHealth Just skip the next two lines. They are pointless. You don't do declarations in Python. > self.healthPercent > self.actualHealth Or, optionally, you might want to set these attributes to some default value, that you use to indicate "undefined". Maybe None? > #request overall health > def overallHealth(self, report): > > #determine actualHealth > self.actualHealth = (self.leftArmHealth + self.rightArmHealth + > self.headHealth + self.leftLegHealth + self.rightLegHealth + > self.backHealth) / 6 > > > #find percent of health > self.healthPercent = (self.actualHealth / self.maxHealth) * 100 Here you define these attributes. They don't need to exist before you run this code. How ever you do this, you will run into problems if you try to access self.actualHealth or self.healthPercent before you run the overallHealth method. If you set default values, whatever code is fetching the attribute will get an irrelevant value, and must be able to distinguish that. If you don't set any default values, you will get AttributeError is you do something like... testSuit = mobileSuit(6,6,6,6,6,6,6) print testSuit.healthPercent > # report the status with a print else return the result > if report == 1: > print "The MS health is: ", self.healthPercent > else: > return self.healthPercent But if this is the only way you intend to use "self.actualHealth" and "self.healthPercent", you don't need the "self."-part, i.e. you shouldn't make them attributes of the instance. Instance attributes are only used when you want a value to persist between method calls. >testSuit = mobileSuit(6,6,6,6,6,6,6) If I understand your intent correctly, you can simply do class mobileSuit: def __init__(self,lArm, rArm, head, lLeg, rLeg, back, maxHealth): self.leftArmHealth = lArm self.rightArmHealth = rArm self.headHealth = head self.leftLegHealth = lLeg self.rightLegHealth = rLeg self.backHealth = back self.maxHealth = maxHealth #request overall health def overallHealth(self, report): #determine actualHealth actualHealth = (self.leftArmHealth + self.rightArmHealth + self.headHealth + self.leftLegHealth + self.rightLegHealth + self.backHealth) / 6.0 # Use a float unless you want to truncate. #find percent of health healthPercent = (actualHealth / self.maxHealth) * 100 # report the status with a print else return the result if report: print "The MS health is: ", healthPercent else: return healthPercent If you _do_ want the values calculated in overallHealth to persist, I suggest that you call overallHealth in __init__ unless that leads to bad performance. (Many million health records?) That way you will allways have a reasonable value in those attributes. Of course, if you change a used attribute, you need to call overallHealth again. x = mobileSuit(6,6,6,6,6,6,6) x.overallHealth(1) The MS health is: 100.0 print x.healthPercent 100.0 x.leftArmHealth = 3 print x.healthPercent 100.0 x.overallHealth(1) The MS health is: 91.6666666667 print x.healthPercent 91.666666666666657 There are ways of calling overallHealth automagically whenever an attribute in the class is changed, but that's not for today's lecture... -- 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@thinkware.se Thu Jan 9 07:11:18 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Thu Jan 9 07:11:18 2003 Subject: [Tutor] help understanding part of the tutorial... In-Reply-To: Message-ID: <5.1.0.14.0.20030109125147.02c2d548@www.thinkware.se> At 08:24 2003-01-09 +0000, Guess Who? Me wrote: >I don't understand how this if loop returns a value using true and false There is no such thing as an "if loop". The indented code block following an if statement is executed once if the value of the expression between "if" and ":" is true, and it will be skipped if the value of the expression was false. The concepts of true and false has nothing to do with any names of variables in the program. As far as Python is concerned, the fact that there is a varaible called true with the value 1, and a variable false with the value 0 is completely irrelevant. They could have been called stilton and cheddar instead. From the Language Reference Manual, section 5.10: "In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: None, numeric zero of all types, empty sequences (strings, tuples and lists), and empty mappings (dictionaries). All other values are interpreted as true." 1 and 0 are often used for true and false, but 5 and "" would also work. In this case, the function called check_question will return 1 or 0. If it returns 1 (true) the expression "right = right + 1" will be executed, if it returns 0 (false) it will be skipped, and right will remain unchanged. In other words, right is only incremented if you give the right reply to the question. > - I know that true=1 and false=0, but I don't get how right=right+1 > works out - does it mean that if the statement returns a false answer, > the rest of the if loop doesn't get carried out? The next line won't get executed. The while loop continues. ># This will run through all the questions >def run_test(questions): > if len(questions) == 0: > print "No questions were given." > # the return exits the function > return > index = 0 > right = 0 > while index < len(questions): > #Check the question > if check_question(questions[index]): <<< right = right + 1 > #go to the next question > index = index + 1 > #notice the order of the computation, first multiply, then divide > print "You got ",right*100/len(questions),"% right out of",len(questions) -- 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@thinkware.se Thu Jan 9 07:15:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Thu Jan 9 07:15:02 2003 Subject: [Tutor] Kill A Fuction Call? In-Reply-To: Message-ID: <5.1.0.14.0.20030109131643.02c22a08@www.thinkware.se> At 07:47 2003-01-09 +0000, Hy Python wrote: >If all you want is to wait "a certain amount of time", you do not need to >kill the thread. When your main thread terminates, all the other thread >will die automatically. But if you have a long running program in your main thread, you might not like to have big, CPU intensive jobs that you stopped waiting for running in another thread... For a server this might be a killer. -- 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 janos.juhasz@VELUX.com Thu Jan 9 07:16:03 2003 From: janos.juhasz@VELUX.com (janos.juhasz@VELUX.com) Date: Thu Jan 9 07:16:03 2003 Subject: [Tutor] OOP class declaration question Message-ID: Dear Magnus, You wrote: There are ways of calling overallHealth automagically whenever an attribute in the class is changed, but that's not for today's lecture... So, I am waiting the next lecture :) Best regards, ----------------------- Juh=E1sz J=E1nos IT department = From magnus@thinkware.se Thu Jan 9 07:33:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Thu Jan 9 07:33:02 2003 Subject: [Tutor] OOP class declaration question In-Reply-To: Message-ID: <5.1.0.14.0.20030109133445.02c27de0@www.thinkware.se> At 13:15 2003-01-09 +0100, janos.juhasz@VELUX.com wrote: >Dear Magnus, > >You wrote: >There are ways of calling overallHealth automagically whenever >an attribute in the class is changed, but that's not for today's >lecture... Untested... def __setattr__(self, attr, value): self.__dict__[attr] = value self.overallHealth() -- 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 VirginiaW@cortland.edu Thu Jan 9 08:16:00 2003 From: VirginiaW@cortland.edu (Virginia Wright) Date: Thu Jan 9 08:16:00 2003 Subject: [Tutor] remove me from list Message-ID: This is a multi-part message in MIME format. ------_=_NextPart_001_01C2B7E1.1CE00E79 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Please remove me from the python list. Thank you. =20 Jean ------_=_NextPart_001_01C2B7E1.1CE00E79 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Please remove me = from the=20 python list.   Thank you.
 
Jean
------_=_NextPart_001_01C2B7E1.1CE00E79-- From glingl@aon.at Thu Jan 9 08:51:25 2003 From: glingl@aon.at (Gregor Lingl) Date: Thu Jan 9 08:51:25 2003 Subject: [Tutor] help understanding part of the tutorial... References: <5.1.0.14.0.20030109125147.02c2d548@www.thinkware.se> Message-ID: <3E1D7DF3.2000409@aon.at> Magnus Lycka schrieb: > At 08:24 2003-01-09 +0000, Guess Who? Me wrote: > >> I don't understand how this if loop returns a value using true and false > > > There is no such thing as an "if loop". .... > In > other words, right is only incremented if you give the right reply to the > question. You may check this in an interactive session. After you have run the program once (from IDLE), the following is possible: >>> questions = get_questions() >>> right = 0 >>> if check_question(questions[0]): right = right + 1 What color is the daytime sky on a clear day?blue Correct >>> right 1 >>> if check_question(questions[0]): right = right + 1 What color is the daytime sky on a clear day?red Incorrect, correct was: blue >>> right 1 >>> if check_question(questions[1]): right = right + 1 What is the answer to life, the universe and everything?1 Incorrect, correct was: 42 >>> right 1 >>> if check_question(questions[1]): right = right + 1 What is the answer to life, the universe and everything?42 Correct >>> right 2 >>> Another way to get some more insight in the working of your program is to insert some additional print-statements, for instance - as you already know (from the code of the check-question-function) that the conditional statement may have an else-branch - the following: while index < len(questions): #Check the question if check_question(questions[index]): #<<<>> What color is the daytime sky on a clear day?blue Correct right incremented to 1 What is the answer to life, the universe and everything?1 Incorrect, correct was: 42 sorry, right remains 1 What is a three letter word for mouse trap?cat Correct right incremented to 2 You got 66.6666666667 % right out of 3 >>> Of course, after you have done your work and understand the code, delete or comment out those print-statements, you dindn't intend to be in the program. Regards, Gregor From Janssen@rz.uni-frankfurt.de Thu Jan 9 09:13:04 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Thu Jan 9 09:13:04 2003 Subject: [Tutor] help understanding part of the tutorial... In-Reply-To: Message-ID: On Thu, 9 Jan 2003, Guess Who? Me wrote: [snip - unpythonic written tutorialcode ;-)] > if check_question(questions[index]): <<< right = right + 1 [snip - upwtc] > I don't understand how this if loop returns a value using true and false - I > know that true=1 and false=0, but I don't get how right=right+1 works out - > does it mean that if the statement returns a false answer, the rest of the > if loop doesn't get carried out? Yes, you're right (but don't call it "if loop" as Magnus has stated). > Because it seems to me right=right+1 would > give you a minimum of three right answers, because you asked three questions > - I'm obviously missing some concept, could somebody fill me in? maybe you've missed, that you can use: if 1: # no testing, this if_condition is always true ...do something... if a_variable_you_have_defined_earlier == 5: # a test ...do something... if a_function_that_returns_something(): # takes the # returnvalue of this # function as if_condition ...do something... In my opinion this code isn't very helpfull even for learning purpose because its comments simply duplicate the programm logic. It's not helpful to prevent the learner from understanding the smallest part of code on his own and instead make him read everything as comments. On the other hand this code obfusciate a bit in using "true" and "false" were a simple 0 or 1 would be enough. The while loop should be a "for elem in question" loop. The intention for both might be to write code as similar to non-programmer thinking as possibly. But I'm wondering if the author of the tutorial really want to provide a section about "using 1 and 0 for true and false in the (common) case it is completly sufficient" to lead the expierenced learners to a deeper insight what kind programming is ;-) Do not start learning with learning bad habits. Michael > > Thanks! > Travis > > > > _________________________________________________________________ > The new MSN 8 is here: Try it free* for 2 months > http://join.msn.com/?page=dept/dialup > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From aztech1200@yahoo.com Thu Jan 9 09:16:03 2003 From: aztech1200@yahoo.com (Aztech Guy) Date: Thu Jan 9 09:16:03 2003 Subject: [Tutor] Python style: if/else vs. exceptions? In-Reply-To: <20030108162236.78572.qmail@web9806.mail.yahoo.com> Message-ID: <20030109141435.92388.qmail@web9801.mail.yahoo.com> Hello list, As a matter of good coding style, what are your opinions on when to use if/elif/else sequences versus when to use exceptions, i.e. try/except/finally ? TIA Az __________________________________________________ Do you Yahoo!? Yahoo! Mail Plus - Powerful. Affordable. Sign up now. http://mailplus.yahoo.com From glingl@aon.at Thu Jan 9 12:40:50 2003 From: glingl@aon.at (Gregor Lingl) Date: Thu Jan 9 12:40:50 2003 Subject: [Tutor] OT: 42? Message-ID: <3E1D88C8.5090202@aon.at> What's so special about 42? Gregor From alan.gauld@bt.com Thu Jan 9 12:44:49 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu Jan 9 12:44:49 2003 Subject: [Tutor] wxPython newbie Message-ID: <7497DCA1C240C042B28F6657ADFD8E0974DA83@i2km11-ukbr.domain1.systemhost.net> > >When in doubt print it out is my motto. > > And my motto is "When in doubt, learn the right way > to do it!" ;) Sure but a good way to find out whats happening in Python code is via python... Its one of its strongest features that almost anything can be printed. > > res = d.ShowModal() > > print res > > Because it will just be a stupid digit that doesn't > mean anything to whoever reads the code. Well, it might be, but then again it could be a string "Yes" or "No" which is, ISTR, how TKinter dialogs respond... > >See what gets printed and substitute in your program... > Better to use wxID_YES, wxID_NO, wxID_OK or wxID_CANCEL. Absolutely. If there are defined constats then use the definitions - or at least define your own if they don't already exist. But when you don't even know what type of response youll get, print is the best solution. Alan g. From op73418@mail.telepac.pt Thu Jan 9 12:45:55 2003 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Thu Jan 9 12:45:55 2003 Subject: [Tutor] is this code dangerous? Message-ID: <004501c2b72f$8e6d2a20$97190dd5@violante> ----- Original Message ----- From: "Gonçalo Rodrigues" To: Sent: Wednesday, January 08, 2003 4:02 PM Subject: Re: [Tutor] is this code dangerous? > > ----- Original Message ----- > From: "Alfred Milgrom" > To: > Sent: Wednesday, January 08, 2003 1:14 PM > Subject: [Tutor] is this code dangerous? > > > > Hi: > > > > Can someone please tell me the best way to override class methods for > > specific instances? > > > > I want to have a general class, such as Person, with general methods. Some > > of the instances of the Person class may have different methods, and I > want > > to be able to override the base method (such as the speak method for the > > cranky person in the example below). > > > > Do I need to define a new class for each instance where there is a > > different method? Is there overhead associated with having a large number > > of classes? > > > > Using the example you give below you can also do: > > >>> class Person: > ... def __init__(self, name): > ... self.name = name > ... def speak(self): > ... print "%s says: my name is %s" % (self.name, self.name) > ... > >>> Person > > >>> cranky = Person('someone else') > >>> def crankyspeak(self): > ... print "%s says: I don't tell anyone my name" % (self.name) > ... > >>> cranky.speak = crankyspeak > > But you have to notice though that speak is not a method but a plain > function object: self is not automatically passed, e.g. > > >>> cranky.speak() > Traceback (most recent call last): > File "", line 1, in ? > TypeError: crankyspeak() takes exactly 1 argument (0 given) > >>> cranky.speak(cranky) > someone else says: I don't tell anyone my name > > There are ways of course to override this - e.g. using something like the > template pattern. You could code something like > > class Person: > > > def speak(self): > __speak = self.et('my_speak') This should read: __speak = self.__dict__.get('my_speak') [rest snipped] With my best regards, G. Rodrigues From ramrom@earthling.net Thu Jan 9 17:10:24 2003 From: ramrom@earthling.net (Bob Gailer) Date: Thu Jan 9 17:10:24 2003 Subject: [Tutor] Best way to convert a type into string Message-ID: <5.2.0.9.0.20030109145611.03c0ec28@66.28.54.253> --=======1C032CC7======= Content-Type: text/plain; x-avg-checked=avg-ok-1BA33EF8; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit >>> type(1) What's the best way to get the string "int" from this? My goal is to construct a string similar to: 'pysqlite_pragma expected_types = int,str,int,float' by applying type() to a series of values. repr(type(1))[7:-2] does it; I was hoping for something simpler. Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======1C032CC7======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-1BA33EF8 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.438 / Virus Database: 246 - Release Date: 1/7/2003 --=======1C032CC7=======-- From aztech1200@yahoo.com Thu Jan 9 17:15:05 2003 From: aztech1200@yahoo.com (Aztech Guy) Date: Thu Jan 9 17:15:05 2003 Subject: [Tutor] Python style: if/else vs. exceptions? [Thanks] In-Reply-To: <5.1.0.14.0.20030109154401.02c6b2e8@www.thinkware.se> Message-ID: <20030109164728.20516.qmail@web9807.mail.yahoo.com> Thanks a lot, Magnus. That was a good amount of useful info. Az --- Magnus Lycka wrote: > Use whatever makes the code easier to read and > maintain, in the long run... .. > assumes less about calculate... > __________________________________________________ Do you Yahoo!? Yahoo! Mail Plus - Powerful. Affordable. Sign up now. http://mailplus.yahoo.com From phil@xfr.co.uk Thu Jan 9 17:17:06 2003 From: phil@xfr.co.uk (Philip Kilner) Date: Thu Jan 9 17:17:06 2003 Subject: [Tutor] OT: 42? In-Reply-To: <3E1D88C8.5090202@aon.at> References: <3E1D88C8.5090202@aon.at> Message-ID: Hi Gregor In article <3E1D88C8.5090202@aon.at>, Gregor Lingl wrote: > What's so special about 42? > Well, it's the answer to the question of life, the universe and everything in Douglas Adams' "Hitchhikers Guide to the Galaxy" four-or-more part trilogy... Why do you ask? Regards, PhilK Thu, 09 Jan 2003 19:11 GMT @ Vaio Email: phil@xfr.co.uk / Voicemail & Facsimile: 07092 070518 Tell me and I forget. Show me and I remember. Involve me and I understand. - Chinese saying From gp@pooryorick.com Thu Jan 9 17:22:22 2003 From: gp@pooryorick.com (Poor Yorick) Date: Thu Jan 9 17:22:22 2003 Subject: [Tutor] instance variables and the instance dictionary Message-ID: <3E1DA943.9030102@pooryorick.com> In an instance, are the following statements equivalent? Are there any caveats to setting an instance variable the second way? self.var1 = 5 self.__dict__.__setitem__('var1', 5) Poor Yorick gp@pooryorick.com From dyoo@hkn.eecs.berkeley.edu Thu Jan 9 17:23:10 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Jan 9 17:23:10 2003 Subject: [Tutor] OT: 42? In-Reply-To: <3E1D88C8.5090202@aon.at> Message-ID: On Thu, 9 Jan 2003, Gregor Lingl wrote: > What's so special about 42? Hi Gregor, ### >>> def to_binary(n): ... "Given a positive integer n, returns its binary representation." ... if n == 0: return "" ... return to_binary(n/2) + str(n%2) ... >>> to_binary(42) '101010' ### So it's quite a symmetric number. There's a nice web site that summarizes sightings of the number 42 throughout history: http://www.empirenet.com/~dljones/ Hope this helps! From dyoo@hkn.eecs.berkeley.edu Thu Jan 9 17:23:19 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Jan 9 17:23:19 2003 Subject: [Tutor] help understanding part of the tutorial... In-Reply-To: Message-ID: On Thu, 9 Jan 2003, Guess Who? Me wrote: > # This will run through all the questions > def run_test(questions): > if len(questions) == 0: > print "No questions were given." > return > index = 0 > right = 0 > while index < len(questions): > if check_question(questions[index]): > right = right + 1 > index = index + 1 > print "You got ",right*100/len(questions),"% right out > of",len(questions) Hi Travis Hmmm... this code can be improved. There are a few things we can do: 1. Use a for loop instead of a while loop. As far as I can tell, there's no need for a separate "index" variable if we use a 'for' loop here. Since we're "iterating" or going through a list of questions, it's much more natural to use a "for" loop. 2. Yank our the question asking section into a separate function: this might help us better understand the flow of the program if the body of each function is tiny. 3. Rename "check_question()" to something more obvious like "is_question_answered_correctly()". check_question() does not give much clue as to what will be returned if a question is answered correctly or not: what are we "checking" for? If we rename the function to "is_question_answered_correctly()", that makes it more clear that we'll get a true value if the user is hitting the right buttons. *grin* Programs are not chisled into stone: they can be revised, just like essays or creative writing. We shouldn't be afraid to break up the code into pieces. We may find that doing a "refactoring" can often help to make the code less inscrutable. *grin* Here's one way we can revise that run_test() function: ### # (assume that check_question() has been renamed to # is_question_answered_correctly()) def run_test(questions): """Asks all questions of a test, and tallies up a percentage of correct answers.""" if len(questions) == 0: print "No questions were given." return right = count_right_answers(questions) print "You got ", right*100/len(questions), print "% right out of",len(questions) def count_right_answers(questions): """Given a list of questions, asks each question in turn, and returns the number of correctly answered questions.""" number_correct = 0 for question in questions: if is_question_answered_correctly(question): number_correct = number_correct + 1 return number_correct ### Is this easier to understand? From dyoo@hkn.eecs.berkeley.edu Thu Jan 9 17:23:32 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Jan 9 17:23:32 2003 Subject: [Tutor] remove me from list In-Reply-To: Message-ID: On Thu, 9 Jan 2003, Virginia Wright wrote: > Please remove me from the python list. Thank you. > > Jean Hi Jean, You can unsubscribe yourself by visiting that mailing list page that you used to subscribe to Tutor: http://mail.python.org/mailman/listinfo/tutor If you go down to the bottom of that page, you should see something about "Edit Options", which you can use. The unsubscription button is linked up from your Options page. If you run into other problems while unsubscribing, please feel free to email the administrative address "tutor-admin@python.org". That way, you can instantly get in touch with the list admins. Hope this helps! From dyoo@hkn.eecs.berkeley.edu Thu Jan 9 17:23:47 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Jan 9 17:23:47 2003 Subject: [Tutor] weird edit menu In-Reply-To: <5.1.0.14.0.20030109121749.02c493c8@www.thinkware.se> Message-ID: On Thu, 9 Jan 2003, Magnus Lycka wrote: > At 18:22 2003-01-08 -0600, David Richardson wrote: > >visited http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html > >to start toying with IDLE (python GUI) > > > >The edit menu to python 2.2.2 does not look like the images. In fact I > >can't find run script anywhere! Did I screw up something during install? > > No, just look further! > > At least in my 2.2.1, it's further down. Nine more menu items have been > inserted between Select All and Check Module. Hmmm! David, if you see any other significant changes in 2.2's IDLE and the one on the IDLE intro, please feel free to email me about them; I'll try to update those images when I get back home. From ramrom@earthling.net Thu Jan 9 17:26:07 2003 From: ramrom@earthling.net (Bob Gailer) Date: Thu Jan 9 17:26:07 2003 Subject: [Tutor] OT: 42? In-Reply-To: <3E1D88C8.5090202@aon.at> Message-ID: <5.2.0.9.0.20030109120753.03bb2d58@66.28.54.253> --=======97119F5======= Content-Type: text/plain; x-avg-checked=avg-ok-1BA33EF8; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 03:35 PM 1/9/2003 +0100, Gregor Lingl wrote: >What's so special about 42? >Gregor It's the ONLY integer whose prime factors are 2*3*7! Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======97119F5======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-1BA33EF8 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.438 / Virus Database: 246 - Release Date: 1/7/2003 --=======97119F5=======-- From joney@clara.co.uk Thu Jan 9 17:30:03 2003 From: joney@clara.co.uk (john gennard) Date: Thu Jan 9 17:30:03 2003 Subject: [Tutor] comments in python Message-ID: <20030109181310.GA318@Leary> I've had to suspend my learning for a while - health problems. Now I'm back and have decided that, for me personally, the best way to learn may be to 'take apart' some programs and study the syntax that way (I do know they work, so the 'problem' is why do they?). Now, I find that what must be 'narrative' appears in three ways:- a. #blah blah blah This of course is no problem, but then I've seen:- b. """ blah blah blah """ and also:- c. ''' blah blah blah ''' b. and c. only seem to be used in the 'meat' of the programs, usually after the exhortation 'do not alter below here' I can find in O'Reilly reference to the use of triple quotes under 'strings' but what I see in the programs appears to be quite different to this. Will someone say if I'm just being thick? Perhaps I don't understand what a 'string' is in plain language! Any help will be much appreciated. Regards, John. From op73418@mail.telepac.pt Thu Jan 9 17:33:10 2003 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Thu Jan 9 17:33:10 2003 Subject: [Tutor] OT: 42? References: <3E1D88C8.5090202@aon.at> Message-ID: <000701c2b817$e0b126e0$b31a0dd5@violante> ----- Original Message ----- From: "Gregor Lingl" To: Sent: Thursday, January 09, 2003 2:35 PM Subject: [Tutor] OT: 42? > What's so special about 42? Hitchiker's guide to the galaxy. There is a computer built especially to spit out the answer to the question, what is the meaning of life? After a straining and stressing time it answers 42. > Gregor > With my best regards, G. Rodrigues From carroll@tjc.com Thu Jan 9 17:34:02 2003 From: carroll@tjc.com (Terry Carroll) Date: Thu Jan 9 17:34:02 2003 Subject: [Tutor] OT: 42? In-Reply-To: <3E1D88C8.5090202@aon.at> Message-ID: On Thu, 9 Jan 2003, Gregor Lingl wrote: > What's so special about 42? http://www.42webdesign.com/why42.html -- Terry Carroll | Santa Clara, CA | "The parties are advised to chill." carroll@tjc.com | - Mattel, Inc. v. MCA Records, Inc., Modell delendus est | no. 98-56577 (9th Cir. July 24, 2002) From jeff@ccvcorp.com Thu Jan 9 17:56:03 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu Jan 9 17:56:03 2003 Subject: [Tutor] OT: 42? References: <3E1D88C8.5090202@aon.at> Message-ID: <3E1DCEF4.9080605@ccvcorp.com> Gregor Lingl wrote: > What's so special about 42? It's the Answer to the Ultimate Question about Life, the Universe, and Everything. Of course, it's still not clear just how that answer was reached, or what it means, or (most importantly) just what that Ultimate Question *is*, but at least we know the Answer, right? At least, so saith Douglas Adams, in The Hitchhiker's Guide to the Galaxy. Jeff Shannon Technician/Programmer Credit International From jeff@ccvcorp.com Thu Jan 9 17:56:12 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu Jan 9 17:56:12 2003 Subject: [Tutor] Kill A Fuction Call? References: <20030109004334.504ca019.syrinx@simplecom.net> Message-ID: <3E1DD0E8.5000703@ccvcorp.com> Scott wrote: >Is it possible to call a function, and kill it if it doesn't complete in >a certain amount of time? > > Sort of, but not easily, and the method of doing so depends on whether you're writing the function yourself. If you *are*, then the simplest way is to have the function code periodically check a timer and abort itself if it's taken too long. (This can be combined with threads -- have the function's worker thread check a simple 'abort' flag, and have a timer or other function set that flag as needed.) If you do not have control over the function, then this is a very difficult thing. Threads won't work, because Python won't let you kill threads from outside, as you already know. You *can* run the function in a separate process, using standard IPC mechanisms like pipes, because processes (unlike threads) can be killed -- but processes are also rather heavier and more awkward to use. Depending on just what it is that you're doing, there may be some way around the limitations, too -- if you're waiting on a socket connection, say, there's a timeoutsocket module available that will do this for you. Jeff Shannon Technician/Programmer Credit International From magnus@thinkware.se Thu Jan 9 17:56:24 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Thu Jan 9 17:56:24 2003 Subject: [Tutor] OT: 42? In-Reply-To: <3E1D88C8.5090202@aon.at> Message-ID: <5.1.0.14.0.20030109235713.02c29bb0@www.thinkware.se> At 15:35 2003-01-09 +0100, Gregor Lingl wrote: >What's so special about 42? It's the answer to Life, the Universe and Everything. -- 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 op73418@mail.telepac.pt Thu Jan 9 18:04:01 2003 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Thu Jan 9 18:04:01 2003 Subject: [Tutor] instance variables and the instance dictionary References: <3E1DA943.9030102@pooryorick.com> Message-ID: <004a01c2b834$395d6f30$54180dd5@violante> ----- Original Message ----- From: "Poor Yorick" To: Sent: Thursday, January 09, 2003 4:54 PM Subject: [Tutor] instance variables and the instance dictionary > In an instance, are the following statements equivalent? Are there any > caveats to setting an instance variable the second way? > > self.var1 = 5 > > self.__dict__.__setitem__('var1', 5) Or, more elegantly: self.__dict__['var1'] = 5 > Let me answer with another question: why do you need this second alternative? The statement self.var1 = 5 may trigger some method calls (via __setattr__, via properties, etc.) so, by using self.__dict__ you may be breaking encapsulation and, in general, making a mess of instance data. > Poor Yorick > gp@pooryorick.com > All the best, G. Rodrigues From emil@lysator.liu.se Thu Jan 9 18:06:21 2003 From: emil@lysator.liu.se (Emil Styrke) Date: Thu Jan 9 18:06:21 2003 Subject: [Tutor] OT: 42? In-Reply-To: <3E1D88C8.5090202@aon.at> Message-ID: <24B62353-2419-11D7-BEC3-000393DC397E@lysator.liu.se> It's the answer to the meaning of life, the universe and everything, according to Douglas Adams (Hitchiker's Guide to the Galaxy). /Emil torsdagen den 9 januari 2003 kl 15.35 skrev Gregor Lingl: > What's so special about 42? > Gregor > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From wolf_binary@hotmail.com Thu Jan 9 18:10:06 2003 From: wolf_binary@hotmail.com (Cameron Stoner) Date: Thu Jan 9 18:10:06 2003 Subject: [Tutor] OOP class declaration question Message-ID: First off thanks everyone, What I really wanted to do is create classes that had high reusability for a game idea of mine. I also wanted to use them for future game additions possibly so I wanted to be able to use them with future ideas in mind already. I know you can just modify the code, but it was an idea I got from the way Microsoft designed the DirectX stuff. There are loads of attributes that you don't necessarily use, but they have defaults. I'm kinda using Python to test ideas for classes later to be built in C++. Thanks again everyone, Cameron >>Recently I made a class that I found out wouldn't work properly unless all >>the variables were filled with something. > >A variable is ALWAYS a reference to an object. From >a technical point of view you can see it as a location >in a computers memory where you store an address to >another location in the memory, where some data is stored. >I imagine this is one more level of indirection than you >thought. This is the same whether you use classes or not. > >It's probably more helpful if you see a variable as something >that points out an existing object, rather than as something >that you fill with an object. Let me explain why. > >a = [1,2] >b = a >c = b > >With the python code above, you have ONE list with the integers >1 and 2. There are three variables, but only one list object. >If you do b.append(5), and print c, it will show [1, 2, 5]. Right? > >If you imagine c = b as filling the c variable with a list, you >get the wrong idea, right? c = b means that you make c point to >(or refer to) the same object in memory as the variable b (and a) >does. Right? > >> My question is why do you have to have all the fields filled with >>something? Is it because you can't make an object of something without >>knowing what each part is soposed to be? > >This is really nothing particular for classes. > >> I thought python could allow for variable declaration on the fly and you >>didn't have to worry about what type of data it was sopposed to hold. > >No. You don't have varable declarations at all in >Python. You just define them. Compare with C etc. > >int i; /* declaration of i */ >... >i = 5; /* definition of i */ > >In python this is replaced with: > >i = 5 # That's all folks! > >It's completely pointless in Python to refer to a variable >before you have defined it. You have it all upside down. It's >in the OTHER programming languages, the ones with static >typing that allows you (well, forces you rather) to declare >variables before you use them. > >It might feel confusing that not all attributes of the class >is listed in one place as in Java or C++, but that's life in >a dynamic language. You can add new attributes in runtime as >you like. There is no way for the class definition to know >about that. If this feels like a bad thing to you, have a look >at the new style classes in Python 2.2, and slots. > >>Here is the code: >> >>class mobileSuit: >> def __init__(self,lArm, rArm, head, lLeg, rLeg, back, maxHealth): >> self.leftArmHealth = lArm >> self.rightArmHealth = rArm >> self.headHealth = head >> self.leftLegHealth = lLeg >> self.rightLegHealth = rLeg >> self.backHealth = back >> self.maxHealth = maxHealth > >Just skip the next two lines. They are pointless. You don't >do declarations in Python. > >> self.healthPercent >> self.actualHealth > >Or, optionally, you might want to set these attributes to >some default value, that you use to indicate "undefined". >Maybe None? > >> #request overall health >> def overallHealth(self, report): >> >> #determine actualHealth >> self.actualHealth = (self.leftArmHealth + self.rightArmHealth + >> self.headHealth + self.leftLegHealth + self.rightLegHealth + >> self.backHealth) / 6 >> >> >> #find percent of health >> self.healthPercent = (self.actualHealth / self.maxHealth) * 100 > >Here you define these attributes. They don't need to exist >before you run this code. > >How ever you do this, you will run into problems if you try >to access self.actualHealth or self.healthPercent before you >run the overallHealth method. If you set default values, whatever >code is fetching the attribute will get an irrelevant value, and >must be able to distinguish that. If you don't set any default >values, you will get AttributeError is you do something like... > >testSuit = mobileSuit(6,6,6,6,6,6,6) >print testSuit.healthPercent > >> # report the status with a print else return the result >> if report == 1: >> print "The MS health is: ", self.healthPercent >> else: >> return self.healthPercent > >But if this is the only way you intend to use "self.actualHealth" >and "self.healthPercent", you don't need the "self."-part, i.e. >you shouldn't make them attributes of the instance. Instance >attributes are only used when you want a value to persist between >method calls. > >>testSuit = mobileSuit(6,6,6,6,6,6,6) > >If I understand your intent correctly, you can simply do > >class mobileSuit: > def __init__(self,lArm, rArm, head, lLeg, rLeg, back, maxHealth): > self.leftArmHealth = lArm > self.rightArmHealth = rArm > self.headHealth = head > self.leftLegHealth = lLeg > self.rightLegHealth = rLeg > self.backHealth = back > self.maxHealth = maxHealth > > #request overall health > def overallHealth(self, report): > > #determine actualHealth > actualHealth = (self.leftArmHealth + self.rightArmHealth + > self.headHealth + self.leftLegHealth + self.rightLegHealth + > self.backHealth) / 6.0 # Use a float unless you want to truncate. > > #find percent of health > healthPercent = (actualHealth / self.maxHealth) * 100 > > # report the status with a print else return the result > if report: > print "The MS health is: ", healthPercent > else: > return healthPercent > >If you _do_ want the values calculated in overallHealth to persist, >I suggest that you call overallHealth in __init__ unless that leads >to bad performance. (Many million health records?) That way you will >allways have a reasonable value in those attributes. > >Of course, if you change a used attribute, you need to call >overallHealth again. > >x = mobileSuit(6,6,6,6,6,6,6) > >x.overallHealth(1) >The MS health is: 100.0 > >print x.healthPercent >100.0 > >x.leftArmHealth = 3 > >print x.healthPercent >100.0 > >x.overallHealth(1) >The MS health is: 91.6666666667 > >print x.healthPercent >91.666666666666657 > >There are ways of calling overallHealth automagically whenever >an attribute in the class is changed, but that's not for today's >lecture... > > >-- >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 _________________________________________________________________ STOP MORE SPAM with the new MSN 8 and get 2 months FREE* http://join.msn.com/?page=features/junkmail From ramrom@earthling.net Thu Jan 9 18:14:02 2003 From: ramrom@earthling.net (Bob Gailer) Date: Thu Jan 9 18:14:02 2003 Subject: [Tutor] instance variables and the instance dictionary In-Reply-To: <3E1DA943.9030102@pooryorick.com> Message-ID: <5.2.0.9.0.20030109154045.03c10988@66.28.54.253> --=======4D4E42BF======= Content-Type: text/plain; x-avg-checked=avg-ok-1BA33EF8; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 09:54 AM 1/9/2003 -0700, Poor Yorick wrote: >In an instance, are the following statements equivalent? >Are there any caveats to setting an instance variable the second way? >self.var1 = 5 >self.__dict__.__setitem__('var1', 5) Not to mention: self.__dict__['var1'] = 5 All equivalent *unless* there's a class method __setattr__ in which case self.var1 = 5 will call __setattr__ which in turn must use one of the __dict__ assignments to actually get the data in. Also note that forms 2 and 3 can use keys other than strings that represent identifiers, as in self.__dict__['313'] = 5 in which case the value can only be accessed thru the dictionary (self.313 being invalid). Even worse, if you're using PythonWin, and you enter "self.__dict__[313] = 5", then enter "self.", that raises an exception TypeError: sequence item 0: expected string, int found which sure gets in the way of using that IDE. Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======4D4E42BF======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-1BA33EF8 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.438 / Virus Database: 246 - Release Date: 1/7/2003 --=======4D4E42BF=======-- From glingl@aon.at Thu Jan 9 18:18:02 2003 From: glingl@aon.at (Gregor Lingl) Date: Thu Jan 9 18:18:02 2003 Subject: [Tutor] help understanding part of the tutorial... References: Message-ID: <3E1D87C7.5050102@aon.at> Michael Janssen schrieb: >On Thu, 9 Jan 2003, Guess Who? Me wrote: > >[snip - unpythonic written tutorialcode ;-)] > > > >> if check_question(questions[index]): <<<> right = right + 1 >> >> > >[snip - upwtc] >... > > But I'm wondering if the >author of the tutorial really want to provide a section about "using 1 and >0 for true and false in the (common) case it is completly sufficient" to >lead the expierenced learners to a deeper insight what kind programming >is ;-) > > ... and how would you comment the following code? >>> questions = [["What color is the daytime sky on a clear day?","blue"], ["What is the answer to life, the universe and everything?","42"], ["What is a three letter word for mouse trap?","cat"]] >>> def check(q_and_a): return q_and_a[1] == raw_input(q_and_a[0]) >>> for question in questions: print check(question) What color is the daytime sky on a clear day?blue True What is the answer to life, the universe and everything?1 False What is a three letter word for mouse trap?cat True >>> Gregor >Do not start learning with learning bad habits. > >Michael > > > From Janssen@rz.uni-frankfurt.de Thu Jan 9 18:26:06 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Thu Jan 9 18:26:06 2003 Subject: [Tutor] comments in python In-Reply-To: <20030109181310.GA318@Leary> Message-ID: On Thu, 9 Jan 2003, john gennard wrote: > a. #blah blah blah > This of course is no problem, but then I've seen:- > > b. """ > blah blah blah > """ > and also:- > > c. ''' blah blah blah ''' > > > b. and c. only seem to be used in the 'meat' of the programs, > usually after the exhortation 'do not alter below here' "Tripple quotes" can be used to write strings over several lines: multiline = "this is broken" multiline2 = """this not""" please take a look at section 3.1.2 of the Python Tutorial for the details of this usage of tripple quotes. Those "Tripple quotes"-Strings are also a way to provide inline documentation and are therefore called docstrings. E.g. you can use a docstrings to describe a function: def func(): """Return zero""" return 0 When you type this function into the interpreter and run the command help(func) you will get the docstring as a explanation. Docstrings doesn't do any programm-logic, but they are part of the programm: inline documentation, as already said. Docstrings are described here: http://www.python.org/doc/essays/styleguide.html Michael PS: b) and c) are functional equivalent. But nobody uses "single tripple quotes": ugly. > > I can find in O'Reilly reference to the use of triple quotes under > 'strings' but what I see in the programs appears to be quite > different to this. > > Will someone say if I'm just being thick? Perhaps I don't understand > what a 'string' is in plain language! > > Any help will be much appreciated. > > Regards, John. > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From magnus@thinkware.se Thu Jan 9 18:39:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Thu Jan 9 18:39:02 2003 Subject: [Tutor] wxPython newbie In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E0974DA83@i2km11-ukbr.domain1 .systemhost.net> Message-ID: <5.1.0.14.0.20030110002904.02c735e0@www.thinkware.se> At 15:12 2003-01-09 +0000, alan.gauld@bt.com wrote: >Sure but a good way to find out whats happening >in Python code is via python... Its one of its strongest >features that almost anything can be printed. But a problem with using an approach that you have figured out through experiments is that you can't be sure if it works by design or by accident... Will it continue to work in the next version of Python? Might it have unexpected side effects? I agree in general (of course) that experimentaion is useful, educational, and very convenient in Python. On the other hand, it's very good if we know not only how to do something, but also why etc. I guess It takes some experience to figure out when experiments are enough, and when we must consult the "scriptures"... > > Because it will just be a stupid digit that doesn't > > mean anything to whoever reads the code. > >Well, it might be, but then again it could be a string >"Yes" or "No" which is, ISTR, how TKinter dialogs respond... wxPython is just a wrapper for the C++ toolkit wxWindows, and it it uses integers for all such things, as C and C++ programs typically do. > > >See what gets printed and substitute in your program... > > Better to use wxID_YES, wxID_NO, wxID_OK or wxID_CANCEL. > >Absolutely. If there are defined constats then use the >definitions - or at least define your own if they don't >already exist. But when you don't even know what type of >response youll get, print is the best solution. Unless there is documentation... ;) For wxPython, the demo code is really useful. The answer to this question is clear from looking at the wxDialog Demo Code for instance. For more obscure parts, one might need to download the C++ version wxWindows and look at the C++ demos as well. The docs are unfortunately not always entirely up do date, and they are C++ docs with a few Python (and recently Perl) notes in them. As with Linux, odd second numbers in the version are development versions, but since 2.2 wasn't very good, everybody uses 2.3.x now, which is tracking a wxWindows development version with rapidly changing APIs etc. Hopefuly, this will get better as we approach 2.4 soon. -- 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@thinkware.se Thu Jan 9 18:43:06 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Thu Jan 9 18:43:06 2003 Subject: [Tutor] Python style: if/else vs. exceptions? In-Reply-To: <20030109141435.92388.qmail@web9801.mail.yahoo.com> References: <20030108162236.78572.qmail@web9806.mail.yahoo.com> Message-ID: <5.1.0.14.0.20030109154401.02c6b2e8@www.thinkware.se> At 06:14 2003-01-09 -0800, Aztech Guy wrote: >As a matter of good coding style, what are your >opinions on when to use if/elif/else sequences versus >when to use exceptions, i.e. try/except/finally ? Use whatever makes the code easier to read and maintain, in the long run... I think it's a good idea to use exceptions only for error handling, and if-statements for control flow. It's possible to use exceptions to implement some kind of GOTO-behaviour, but that's usually not a good thing. Using if-statements for error handling can, on the other hand, sometimes be a good thing. Exceptions are much more expensive that going to an else part of an if-statement. Since you might jump to a completely different scope, there is a lot of cleaning up to do on raise. A big advantage with try-blocks are that they can catch exceptions that occur in some very remote piece of code. This is also the problem of the matter... Since exceptions break the ordinary, structured control flow, having a lot of overlapping exception handling will lead to spaghetti code, like bad, old BASIC with GOTOs. If- statements can be nested, but not overlap like that. They retain code structure. If-statements are used if you want to handle errors before they happen, and try/raise/except is used to handle errors after they happen. For instance you could do either of: a = input('a: ') b = input('b: ') if b !=0: print "a/b =", a/b else: print "Division by zero is not possible" or a = input('a: ') b = input('b: ') try: print "a/b =", a/b except ZeroDivisionError: print "Division by zero is not possible" No big deal in this case. If a and b were read from a huge file, and b is often 0, you will get better speed with the if-version I guess. (But don't take my word for it, profile your code.) But if you have many more variables... a = input('a: ') b = input('b: ') c = input('c: ') d = input('d: ') e = input('e: ') f = input('f: ') g = input('g: ') h = input('h: ') if (b != 0 or c != 0 or d != 0 or e != 0 or f != 0 or g != 0 or h != 0): print "a/b/c/d/e/f/g/h =", a/b/c/d/e/f/g/h else: print "Division by zero is not possible" ...is certainly less convenient than... a = input('a: ') b = input('b: ') c = input('c: ') d = input('d: ') e = input('e: ') f = input('f: ') g = input('g: ') h = input('h: ') try: print "a/b/c/d/e/f/g/h =", a/b/c/d/e/f/g/h except ZeroDivisionError: print "Division by zero is not possible" ...although you could make the if statement cleaner by writing "if 0 not in [b,c,d,e,f,g,h]:", so it is still an option here. (Actually, when I wrote the previous line I included the variable "a" in the list by mistake... I could have done that in real code, and without a test that tried a as 0 (which should be allowed) I might not have have noticed my mistake... So, keeping the code as simple as possible is always a good idea. In this case that means try/except.) But what if you don't know in the place where you have your if/else or try/except what the calculation will look like? What if you evaluate a user supplied string that represents an equation? Or what if the calculation is done in a function that you call? If you do something like a = input('a: ') b = input('b: ') if b !=0: calculate(a, b) else: print "Division by zero is not possible" you are not using the code structure in a good way. The piece of the code you write here knows too much about what it expects of calculate. This means that you might run into trouble if you change the calculate function. a = input('a: ') b = input('b: ') try: calculate(a, b) except ZeroDivisionError: print "Division by zero is not possible" assumes less about calculate... -- 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@thinkware.se Thu Jan 9 18:48:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Thu Jan 9 18:48:02 2003 Subject: [Tutor] instance variables and the instance dictionary In-Reply-To: <3E1DA943.9030102@pooryorick.com> Message-ID: <5.1.0.14.0.20030110004456.02c35f68@www.thinkware.se> At 09:54 2003-01-09 -0700, Poor Yorick wrote: >In an instance, are the following statements equivalent? Are there any >caveats to setting an instance variable the second way? > >self.var1 = 5 > >self.__dict__.__setitem__('var1', 5) As others have mentioned, manipulating the __dict__ bypasses __setattr__. A consequence of this is that the code in an implementation of __setattr__ often uses __dict__ manipulation to avoid infinite recursion. A method like below would call itself until the stack breaks. def __setattr__(self, attr, val): # do some error checks ... setattr(self, attr, val) You need to do: def __setattr__(self, attr, val): # do some error checks ... self.__dict__[attr] = val instead. But note! DANGER!!! What will happen if attr is '__private' ??? -- 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 Janssen@rz.uni-frankfurt.de Thu Jan 9 18:59:42 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Thu Jan 9 18:59:42 2003 Subject: [Tutor] help understanding part of the tutorial... In-Reply-To: <3E1D87C7.5050102@aon.at> Message-ID: On Thu, 9 Jan 2003, Gregor Lingl wrote: > ... and how would you comment the following code? > > >>> questions = [["What color is the daytime sky on a clear day?","blue"], > ["What is the answer to life, the universe and > everything?","42"], > ["What is a three letter word for mouse trap?","cat"]] > > >>> def check(q_and_a): > return q_and_a[1] == raw_input(q_and_a[0]) > > >>> for question in questions: > print check(question) > That's pretty (because the code is written to do something, not to make everything step-by-step-by-step by inventing extra steps). what about: questions = [ ["What color is the daytime sky on a clear day?", "blue"], ["What is the answer to life, the universe and everything?","42"], ["What is a three letter word for mouse trap?", "cat"]] for question, answere in questions: print (raw_input(question+" ") == answere) ---- More the behavior of the former code would be: right = 0 wrong = 0 for question, answere in questions: if (raw_input(question+" ") == answere): print "this was expectet" right = right +1 else: wrong = wrong +1 print "%s! Why don't you answere '%s'?" \ % ("No"*wrong, answere) print "You got %s %% out of %s." % (right*100/len(questions),len(questions)), print "You are %s." % ["a loser", "bad", "good", "pythonic"][right] ---- A "check" function is very handy for a realistic approach, where more than one answere can be correct or misspelling should gain another result than no answere at all than something completly wrong. For a realistic approach "questions" needs to carry a history of wrong/correct attemps (to work especially on the difficult questions, or to analyze the students main problems). "questions" should be organized in levels or topics (and "higher" topics should be linked to topics, which are necessary to understand them. This way the learner can be guided back, in case s/he makes many mistakes). aah 42? Let me see. It's 6 times 7. Michael From dick.kniep@lindix.nl Thu Jan 9 19:00:09 2003 From: dick.kniep@lindix.nl (Dick Kniep) Date: Thu Jan 9 19:00:09 2003 Subject: [Tutor] Upgrading of python 2.2.2 on RedHat 8.0 Message-ID: <1042160300.3010.4.camel@kniep04.kniep> Hi there, I am facing problems with upgrading the standard installation of Python 2.2.1 of RedHat 8 to Python 2.2.2. When I install it "according to the book", it places all files in usr/local/lib, whereas RedHat expects them in usr/lib. I haven't seen any RPM's for Redhat 8 (only for older versions) I am frantically developing on this system so I need to get it right...... Please help -- Dick Kniep Lindix From glingl@aon.at Thu Jan 9 19:14:02 2003 From: glingl@aon.at (Gregor Lingl) Date: Thu Jan 9 19:14:02 2003 Subject: [Tutor] OT: 42? References: <5.1.0.14.0.20030109235713.02c29bb0@www.thinkware.se> Message-ID: <3E1E0CBC.2060407@aon.at> Magnus Lycka schrieb: > At 15:35 2003-01-09 +0100, Gregor Lingl wrote: > >> What's so special about 42? > > > It's the answer to Life, the Universe and Everything. > This I already knew, because of http://mail.python.org/pipermail/tutor/2003-January/019773.html line 16. ;-) Nevertheless thanks for that many replies to an OT-question within few hours. I must confess, that I have this novel on my bookshelve but didn't find the time to read it until now; apparently was distracted by a bunch of Python-books. (And also still have to finish 350 more pages of the "Rebels of Liang Shan Po".) But now I'll be highly motivated to read it, although it's in English. Good training! Regards, Gregor. From mongo57a@comcast.net Thu Jan 9 19:29:23 2003 From: mongo57a@comcast.net (andy surany) Date: Thu Jan 9 19:29:23 2003 Subject: [Tutor] Tk Listbox scrollbars Message-ID: <002901c2b83d$adb91920$2502a8c0@emily.ewndsr01.nj.comcast.net> Got it! The following worked for me (based on your example...): tbar=Scrollbar(self) tbar.config(command=self.makelist.xview, orient=HORIZONTAL) tbar.pack(side=BOTTOM, fill=X) Thanks so much!!! Andy -----Original Message----- From: Isaac Hall To: andy surany Cc: tutor@python.org Date: Tuesday, January 07, 2003 8:18 PM Subject: Re: [Tutor] Tk Listbox scrollbars >Hi Andy, > >You are in luck. I had to write this exact thing not long ago, so I will >just copy for you the code that I have written to do this. It is in the >form of a class, but I you can take the important things out of it. > >I use grid here, but pack can be used in the same way. >I should note that when I used pack, the thing looked a little different, >but not by much. The only difference here in calling this instead of a >listbox is that the box is class.box > > > >from Tkinter import * >class ScrolledListbox(Frame): > def __init__(self,parent): > Frame.__init__(self,parent) > self.yScroll=Scrollbar(self,orient=VERTICAL) > self.xScroll=Scrollbar(self, orient=HORIZONTAL) > self.box=Listbox(self,xscrollcommand=self.xScroll.set, > yscrollcommand=self.yScroll.set,bg='white') > self.box.grid(row=0,column=0,sticky=N+S+E+W) > self.xScroll.grid(row=1,column=0,sticky=E+W) > self.yScroll.grid(row=0,column=1,sticky=N+S) > self.xScroll["command"]=self.box.xview > self.yScroll["command"]=self.box.yview > > >Ike > >On Tue, 7 Jan 2003, andy surany wrote: > >> Hello all, >> >> I wrote a program for a scrolled list containing a Y-axis scrollbar >> which has been working fine. At this point, my data is also overflowing >> the width of the box, so I have added an X-axis scrollbar. >> >> Both scrollbars appear, but the x-axis scrollbar is "vertical" (and >> tiny...and I press the up or down arrow to move left or right). What I >> want is a "slider" similar to the y scroll bar. I'm pretty sure that the >> error is in the way that I am packing the widget, as follows: >> >> sbar.pack(side=RIGHT, fill=Y) # This is for the Y-axis bar and it works >> correctly >> tbar.pack(side=BOTTOM) # This places the X-axis bar as described above >> >> TIA >> >> -Andy >> >> >> >> _______________________________________________ >> 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 ramrom@earthling.net Thu Jan 9 20:00:05 2003 From: ramrom@earthling.net (Bob Gailer) Date: Thu Jan 9 20:00:05 2003 Subject: [Tutor] OT: 42? In-Reply-To: <3E1E0CBC.2060407@aon.at> References: <5.1.0.14.0.20030109235713.02c29bb0@www.thinkware.se> Message-ID: <5.2.0.9.0.20030109174522.03c21e98@66.28.54.253> --=======26D2D78======= Content-Type: text/plain; x-avg-checked=avg-ok-1BA33EF8; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 12:58 AM 1/10/2003 +0100, Gregor Lingl wrote: >> although it's in English. What's so special about English? Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======26D2D78======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-1BA33EF8 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.438 / Virus Database: 246 - Release Date: 1/7/2003 --=======26D2D78=======-- From fredm@smartypantsco.com Thu Jan 9 20:07:01 2003 From: fredm@smartypantsco.com (Alfred Milgrom) Date: Thu Jan 9 20:07:01 2003 Subject: [Tutor] how do you use __dict__ ? (Was: code dangerous?) In-Reply-To: <004501c2b72f$8e6d2a20$97190dd5@violante> Message-ID: <5.1.0.14.0.20030110113007.02571ec0@192.168.1.1> At 04:03 PM 8/01/03 +0000, you wrote: >This should read: > >__speak = self.__dict__.get('my_speak') > >[rest snipped] Thanks for the update - looks interesting, but I don't know anything about using __dict__, or understand what __speak means. I couldn't find any good references, so I just tried something anyway :( My attempt at implementing this code works, but seems like a heavy-handed way to use 'magic' attributes: ******************************************************** class Person: def __init__(self, name): self.name = name def speak(self): __speak = self.__dict__.get('my_speak') if __speak: eval(__speak) else: print "%s says: my name is %s" % (self.name, self.name) def crankyspeak(self): print "%s says: I don't tell anyone my name" % (self.name) hobbit = Person('Bilbo Baggins') cranky = Person('someone else') cranky.__dict__['my_speak'] = 'self.crankyspeak()' hobbit.speak() cranky.speak() ******************************************************** Can you suggest any good links or explain how I am supposed to use __dict__ and __speak ? Thanks, Fred From syrinx@simplecom.net Thu Jan 9 20:07:47 2003 From: syrinx@simplecom.net (Scott) Date: Thu Jan 9 20:07:47 2003 Subject: [Tutor] Kill A Fuction Call? In-Reply-To: <3E1DD0E8.5000703@ccvcorp.com> References: <20030109004334.504ca019.syrinx@simplecom.net> <3E1DD0E8.5000703@ccvcorp.com> Message-ID: <20030109190228.14d98d97.syrinx@simplecom.net> On Thu, 09 Jan 2003 11:43:36 -0800 "Jeff Shannon" wrote: > if you're waiting on a socket connection, say, there's a timeoutsocket > > module available that will do this for you. That is exactly what I'm doing. I will look for the timeoutsocket module. Thanks for pointing it out. From maillist@kuwest.de Thu Jan 9 20:17:10 2003 From: maillist@kuwest.de (Jens Kubieziel) Date: Thu Jan 9 20:17:10 2003 Subject: [Tutor] Calculating a math formula and finding errors Message-ID: <20030109165408.GA19944@kubieziel.de> Hi, I found a nice formula in a math magazine [1]. Though I couldn't find a proof, I'm trying to compute some values of it. If this formula is right, both sides have to be equal. But within my code, both sides are not equal. So I think that I have an error in my code. Do you see the error and maybe general mistakes I made? formula in LaTeX [2]: \sum ^{n}_{i=0} \sum ^{n-i}_{j=0}|n+1-2(i+j)| \bigl( \begin{smallmatrix} n-1\\i \end{smallmatrix} \bigr) =2 \lfloor \frac{n+2}{2} \rfloor \bigl( \begin{smallmatrix} n+1\\ \lfloor \frac{n+1}{2} \rfloor \end{smallmatrix} \bigr) - (n+1) Python code: #v+ #! /usr/bin/python import math def facul(z): if z ==1: return 1 else: return z*facul(z-1) def perm(x,y): w = 1 for i in range(y+1,x+1): w = w * i return w/facul(x-y) def MBrechts(n): b=0 for i in range(0,n): for j in range(0,n-i): betrag = n + 1 - (2*i) - (2*j) if betrag < 0: betrag = betrag * -1 prod = betrag * perm(n-i,j) b = b + prod return b def MBlinks(n): return 2 * math.floor((n+2)/2) * perm(n+1,math.floor((n+1)/2)) - n - 1 for erg in range(1,12): print "n = %d, Formel rechts = %d, Formel links = %d" % (erg,MBrechts(erg),MBlinks(erg)) #v- Thanks for your recommendations Footnotes: ========== [1] print edition of http://www.wurzel.org [2] You can find a more readable version at http://www.kuwest.de/tmp/Bencze-Formel.pdf -- Jens Kubieziel mailto:jens@kubieziel.de If you cannot in the long run tell everyone what you have been doing, your doing was worthless. -- Edwim Schrodinger From alan.gauld@bt.com Thu Jan 9 20:33:02 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu Jan 9 20:33:02 2003 Subject: [Tutor] is this code dangerous? Message-ID: <7497DCA1C240C042B28F6657ADFD8E0974DA84@i2km11-ukbr.domain1.systemhost.net> > class Person: > def __init__(self, name): > def speak(self, dummy): > def crankyspeak(self): > > hobbit = Person('Bilbo Baggins') > cranky = Person('someone else') > cranky.speak=Person.crankyspeak The problem with this approach is twofold: 1) You just lost all the advantages of polymorphism because your code has to know when it has a cranky person and whne a normal person so that it knows which version of speak() to call. This has bigger problems when you later want to add another type of speak method, you will wind up with lots of big if/elif/else chains potentially.. 2) You may wind up writing code multiple times within each speak method rather than leveraging the existing code via inheritance or delegation. > * I don't have to create a large number of classes This really shouldn't be a big problem. > * all the code for the methods are in the one place (Person class) This is not necessarily a good thing. Especially as the behaviour of your person types grows increasingly diverse. You wind up with interleaved class definitions masquerading as a single class. Thios also leads to maintenance problems later since a bug fix to any method means retesting all of your person objects not just those of the changed class. > * I can easily mix and match the methods for any instance without the > difficulties that Alan mentioned Duid I mention many difficulties? There is a downside whichever way you go but the evils of supporting many classes are IMHO much less than in supporting a single multi behaved class > * the same code structure (albeit more unwieldy than usual) > can be used for every instance/method combination (ie no problems with > unbound methods or not passing self parameter) Within the class maybe but it adds more complexity in the client code. If your application using the person objects then you are likely to wind up writing more code in total rather than less. Regards, Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From magnus@thinkware.se Thu Jan 9 21:17:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Thu Jan 9 21:17:01 2003 Subject: [Tutor] OOP class declaration question In-Reply-To: Message-ID: <5.1.0.14.0.20030110005629.02c97d48@www.thinkware.se> At 17:08 2003-01-09 -0600, Cameron Stoner wrote: >What I really wanted to do is create classes that had high reusability for >a game idea of mine. I also wanted to use them for future game additions >possibly so I wanted to be able to use them with future ideas in mind >already. I know you can just modify the code, but it was an idea I got >from the way Microsoft designed the DirectX stuff. There are loads of >attributes that you don't necessarily use, but they have defaults. I'm >kinda using Python to test ideas for classes later to be built in C++. Whether you implement in Python or in C++, I would claim that this approach is in general a bad idea. It's good to think ahead to some extent, but try to keep your code as simple as possible. Otherwise you will get a large burden of maintenance for a lot of things that you are likely to never need. None of us are godlike enough to predict what we will need in the future. Typically it's not what we thought. One of the great things with programming and software development is that we learn new things all the time. A natural consequence of that is that it's often best to scrap old ideas. If we still can... The more we have "prepared for the future" by adding features that we don't need yet, the harder it will be to change approach--both technically, psycologically and economically. See www.c2.com/cgi/wiki?YouArentGonnaNeedIt and www.c2.com/cgi/wiki?DoTheSimplestThingThatCouldPossiblyWork -- 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@thinkware.se Thu Jan 9 21:23:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Thu Jan 9 21:23:02 2003 Subject: [Tutor] how do you use __dict__ ? (Was: code dangerous?) In-Reply-To: <5.1.0.14.0.20030110113007.02571ec0@192.168.1.1> References: <004501c2b72f$8e6d2a20$97190dd5@violante> Message-ID: <5.1.0.14.0.20030110025340.02ca9d00@www.thinkware.se> At 12:06 2003-01-10 +1000, Alfred Milgrom wrote: >Can you suggest any good links or explain how I am supposed to use >__dict__ and __speak It seems a walkthrough of names in python is required. You can see from the names that __dict__ is some kind of Python magic thing that you should be able to read about in Python books or manuals. __speak, on the other hand, it just a variable name. It's nothing special in python. First of all, names in python (names for variables, functions, classes, modules etc) consists of an uninterrupted sequence of A-Z, a-z, 0-9 or '_'. In other words letters in the English alphabet, digits or underscore. They may not begin with a digit, since the could lead to confusion with numerical objects. _ or __ or __speak are allowed names for variables. There are some special rules and conventions though. Names starting AND ending with double underscores have some kind of magic function in Python. Never use double leading and trailing underscores for your own variables or other names. An example is __doc__ with identifies the documentation string as in: >>> def x(): ... "This function doesn't do anything." ... pass ... >>> print x.__doc__ This function doesn't do anything. __dict__ is another example, it contains the attributes in a class instance. __init__ is the constructor for a class. >>> class X: ... def __init__(self): ... self.x = 1 ... self._y = 2 ... self.__z = 3 ... >>> x = X() >>> print x.__dict__ {'x': 1, '_X__z': 3, '_y': 2} As you can see, __dict__ shows the values of the attributes of x. You can also see that something odd happened with self.__z. It's represented as _X__z in __dict__. See also below: >>> print x.__z Traceback (most recent call last): File "", line 1, in ? AttributeError: X instance has no attribute '__z' >>> print x._X__z 3 An attribute name starting with __ will have it's name mangled as you see. This is how private attributes are handled in Python. As you see, they aren't extremely private, you can access them if you really need, but it's not difficult to spot such violations in the code, so it's helpful to implement encapsulation without making introspection impossible. This special handling of __names only exisits in this context though. In attributes in class instance. For a local variable, __speak is no different than sp_ea_k or speak__. For the global scope, names starting with _, (single underscore is enough) will not be imported with "from XXX import *". This is the rules. There are also a few conventions. Many people emulate the protection scheme in C++ by using attribute names like this: __private _protected public __private are name-mangled like I wrote above, _protected is only protected by a gentlemens agreement, but that's enought among friends, right? Also, when you would like to use a reserved word as a name, such as if or or or in, you can use if_ or or_ or in_ instead. -- 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@thinkware.se Thu Jan 9 21:25:59 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Thu Jan 9 21:25:59 2003 Subject: [Tutor] Best way to convert a type into string In-Reply-To: <5.2.0.9.0.20030109145611.03c0ec28@66.28.54.253> Message-ID: <5.1.0.14.0.20030110032734.02c24a58@www.thinkware.se> At 15:08 2003-01-09 -0700, Bob Gailer wrote: >repr(type(1))[7:-2] does it; I was hoping for something simpler. str(type(1))[7:-2] is one character shorter. Really Bob, 17 characters in excess to the variable name. Isn't that simple? def _(x): return str(type(x))[7:-2] _(1) 'int' _('Hello') 'string' Short enough? -- 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 gp@pooryorick.com Thu Jan 9 21:29:01 2003 From: gp@pooryorick.com (Poor Yorick) Date: Thu Jan 9 21:29:01 2003 Subject: [Tutor] instance variables and the instance dictionary References: <5.2.0.9.0.20030109154045.03c10988@66.28.54.253> Message-ID: <3E1E3009.8000509@pooryorick.com> Bob Gailer wrote: > > Even worse, if you're using PythonWin, and you enter > "self.__dict__[313] = 5", then enter "self.", that raises an > exception TypeError: sequence item 0: expected string, int found which > sure gets in the way of using that IDE. > You sort of lost me here. I tried to reproduce this in Pythonwin but couldn't. Could you offer a little more sample code? Poor Yorick gp@pooryorick.com From magnus@thinkware.se Thu Jan 9 21:55:03 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Thu Jan 9 21:55:03 2003 Subject: [Tutor] OT: 42? In-Reply-To: <3E1E0CBC.2060407@aon.at> References: <5.1.0.14.0.20030109235713.02c29bb0@www.thinkware.se> Message-ID: <5.1.0.14.0.20030110011141.02c195f0@www.thinkware.se> At 00:58 2003-01-10 +0100, Gregor Lingl wrote: >I must confess, that I have this novel on my bookshelve Which of them? ;) If I remember correctly, it's one of those trilogies that consists of at least five books, right? Actually, I never read the fifth book "Mostly Harmless". Is it as good as the others? I don't know about your background, but in my circles, among electronic engineers and programmers in G=F6teborg born in the 60's or 70's, you'd have a social problem if you hadn't read Douglas Adams and watched Monty Python. In Stockholm you'd be lost if you hadn't read Terry Pratchett. (Or maybe that's a generation thing?) Hm... It seems fantasy authors manage to make trilogies trilogies, but when we get out in space, the works that are long know as trilogies tend to grow... Asimov, Herbert, Adams... --=20 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 antoneheyward@hotmail.com Fri Jan 10 00:10:02 2003 From: antoneheyward@hotmail.com (antone heyward) Date: Fri Jan 10 00:10:02 2003 Subject: [Tutor] folder dialog Message-ID: Is there a folder dialog for tkinter? wxpython has one but i want to stick with tkinter. Plus i am pretty new to programming and wxpython is a bit complex for me right now. _________________________________________________________________ The new MSN 8: smart spam protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From fredm@smartypantsco.com Fri Jan 10 00:25:01 2003 From: fredm@smartypantsco.com (Alfred Milgrom) Date: Fri Jan 10 00:25:01 2003 Subject: [Tutor] folder dialog In-Reply-To: Message-ID: <5.1.0.14.0.20030110162106.025aa300@192.168.1.1> At 05:09 AM 10/01/03 +0000, antone heyward wrote: >Is there a folder dialog for tkinter? wxpython has one but i want to stick >with tkinter. Plus i am pretty new to programming and wxpython is a bit >complex for me right now. I assume you mean is there a simple way to get the files in a folder, etc. Have a look at the example 'Text Editor' at http://www.pythonapocrypha.com/Chapter19/Chapter19.shtml HTH, Fred Milgrom From glingl@aon.at Fri Jan 10 01:59:01 2003 From: glingl@aon.at (Gregor Lingl) Date: Fri Jan 10 01:59:01 2003 Subject: [Tutor] OT: 42? References: <5.1.0.14.0.20030109235713.02c29bb0@www.thinkware.se> <5.1.0.14.0.20030110011141.02c195f0@www.thinkware.se> Message-ID: <3E1E6F23.10902@aon.at> Magnus Lycka schrieb: > At 00:58 2003-01-10 +0100, Gregor Lingl wrote: > >> I must confess, that I have this novel on my bookshelve > > > Which of them? ;) If I remember correctly, it's one of > those trilogies that consists of at least five books, > right? The (single) volume on my bookshelve seems to contain four of them. The third one being: Life, the Universe and Everything (What a shame!?) > > Actually, I never read the fifth book "Mostly Harmless". > Is it as good as the others? > > I don't know about your background, but in my circles, > among electronic engineers and programmers in Göteborg > born in the 60's or 70's, you'd have a social problem if > you hadn't read Douglas Adams and watched Monty Python. Until now this wasn't the case with me, maybe because I'm, a teacher (in a rather conservative country) and born well before this lucky period. Could one get into social problems on electronic lists? Hope not! So Long, and Thanks for All the Fish Gregor P.S: I'll leave Vienna for a 2-week-skiing-holiday tomorrow. Will be back around 26-th of January. From glingl@aon.at Fri Jan 10 02:01:01 2003 From: glingl@aon.at (Gregor Lingl) Date: Fri Jan 10 02:01:01 2003 Subject: [Tutor] OT: 42? References: <5.1.0.14.0.20030109235713.02c29bb0@www.thinkware.se> <5.2.0.9.0.20030109174522.03c21e98@66.28.54.253> Message-ID: <3E1E6F9E.50200@aon.at> Bob Gailer schrieb: > At 12:58 AM 1/10/2003 +0100, Gregor Lingl wrote: > >>> although it's in English. >> > > What's so special about English? It's not my native tongue. That's all. Gregor > > Bob Gailer > mailto:ramrom@earthling.net > 303 442 2625 > >------------------------------------------------------------------------ > > >--- >Outgoing mail is certified Virus Free. >Checked by AVG anti-virus system (http://www.grisoft.com). >Version: 6.0.438 / Virus Database: 246 - Release Date: 1/7/2003 > > From dyoo@hkn.eecs.berkeley.edu Fri Jan 10 03:24:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Jan 10 03:24:02 2003 Subject: [Tutor] Kill A Fuction Call? In-Reply-To: <20030109190228.14d98d97.syrinx@simplecom.net> Message-ID: > > if you're waiting on a socket connection, say, there's a timeoutsocket > > > > module available that will do this for you. > > That is exactly what I'm doing. I will look for the timeoutsocket > module. Thanks for pointing it out. By the way, as soon as Python 2.3 gets stable, we can look forward to it having a settimeout() method: http://python.org/doc/2.3a1/whatsnew/node15.html So the functionality of timeoutsocket will eventually become part of the core. Good luck! From aztech1200@yahoo.com Fri Jan 10 05:06:01 2003 From: aztech1200@yahoo.com (Aztech Guy) Date: Fri Jan 10 05:06:01 2003 Subject: [Tutor] Using Py 1.5.2 libs/mods with Py 2.2 ? (for PyQt) In-Reply-To: Message-ID: <20030110100441.33598.qmail@web9804.mail.yahoo.com> Hello list, 1. I have Red Hat Linux 7.3. 2. Python 1.5.2 came preinstalled with it. 3. Then, either: - I installed PyQt 3.1 OR - it was already installed along with RHL 7.2 (I don't remember which of the above, now, as it was some time back). 4. Then some days later I installed Python 2.2 from the RH apps CD. When I tried to run one of the example PyQt apps (using Py 2.2), I got an error on the 'import qt' statement - to the effect that the qt module was not found. 5. Since I knew that PyQt was installed (by doing an "rpm -q PyQt" and "rpm -q PyQt-examples", both of which showed that the respective packages were installed), I was surprised at the above error. (I had not realized at this point, that I had installed Py 2.2 after installing PyQt 3.1) 6. Doing a 'find / -name "*[Pp][Yy][Qq][Tt]*' showed the location of the PyQt files - they were installed in the Python 1.5.2 site-packages directory, not in that of Py 2.2. 7. So I switched to Py 1.5.2 and tried running the examples. Some of them worked, some partly worked and partly gave some errors. I am not sure if this is due to a version clash between Py 1.5.2 and the PyQt version which is 3.1 (and my Qt version is 3.0.3). 8. I can of course uninstall PyQt, and then re-install it in the Py 2.2 tree; I haven't tried this yet but I think I should be able to manage it. And I know that this is probably the right way to do it. 9. However, I may not want to do that just now. Generalizing the situation, this led me to wonder whether is is possible and "officially" recommended to use one version of Python with the libraries / modules installed in the site-packages directory of another version, and if so, what is the way to do it ? Setting the PYTHONPATH to include that site-packages directory ? Or some other way ? And are there any issues that may arise as a result of this ? Such as conflicts between versions of different libraries and the language, etc. ? Thanks for any advice. Az. __________________________________________________ Do you Yahoo!? Yahoo! Mail Plus - Powerful. Affordable. Sign up now. http://mailplus.yahoo.com From =?Windows-1251?B?YW50b25tdWhpbiDt4CByYW1ibGVyLnJ1?= Fri Jan 10 05:17:03 2003 From: =?Windows-1251?B?YW50b25tdWhpbiDt4CByYW1ibGVyLnJ1?= (=?Windows-1251?B?YW50b25tdWhpbiDt4CByYW1ibGVyLnJ1?=) Date: Fri Jan 10 05:17:03 2003 Subject: [Tutor] how do you use __dict__ ? (Was: code dangerous?) In-Reply-To: <5.1.0.14.0.20030110113007.02571ec0@192.168.1.1> References: <5.1.0.14.0.20030110113007.02571ec0@192.168.1.1> Message-ID: <661278969.20030110131648@rambler.ru> Hello Alfred, AM> ******************************************************** AM> class Person: AM> def __init__(self, name): AM> self.name = name AM> def speak(self): AM> __speak = self.__dict__.get('my_speak') AM> if __speak: AM> eval(__speak) AM> else: AM> print "%s says: my name is %s" % (self.name, self.name) AM> def crankyspeak(self): AM> print "%s says: I don't tell anyone my name" % (self.name) AM> hobbit = Person('Bilbo Baggins') AM> cranky = Person('someone else') AM> cranky.__dict__['my_speak'] = 'self.crankyspeak()' AM> hobbit.speak() AM> cranky.speak() AM> ******************************************************** I might be missing something, but why don't use simpler approach: class Person: def __init__(self, name): self.name = name self.speakMethod = None def speak(self): if self.speakMethod: self.speakMethod(self) else: print "%s says: my name is %s" % (self.name, self.name)" def setSpeakMethod(self, speakMethod): self.speakMethod = speakMethod def crankyspeak(person): print "%s says: I don't tell anyone my name" % (person.name) hobbit = Person('Bilbo Baggins') cranky = Person('someone else') cranky.setSpeakMethod(crankyspeak) hobbit.speak() cranky.speak() Best regards, Anton. From gerilynch@yahoo.co.uk Fri Jan 10 05:40:02 2003 From: gerilynch@yahoo.co.uk (=?iso-8859-1?q?geraldine=20lynch?=) Date: Fri Jan 10 05:40:02 2003 Subject: [Tutor] please help! Message-ID: <20030110103909.15328.qmail@web40407.mail.yahoo.com> --0-474726855-1042195149=:14991 Content-Type: text/plain; charset=iso-8859-1 Content-Transfer-Encoding: 8bit hello How do I sum all the elements of an array? I mean, is there a Capital sigma function? something like this: å yi I'm quite new to python and have to write a program before my uni term restarts so i dont have very long! thanks, Geraldine --------------------------------- With Yahoo! Mail you can get a bigger mailbox -- choose a size that fits your needs --0-474726855-1042195149=:14991 Content-Type: text/html; charset=iso-8859-1 Content-Transfer-Encoding: 8bit

hello

How do I sum all the elements of an array? I mean, is there a Capital sigma function? something like this:

å yi

I'm quite new to python and have to write a program before my uni term restarts so i dont have very long!

thanks, Geraldine



With Yahoo! Mail you can get a bigger mailbox -- choose a size that fits your needs
--0-474726855-1042195149=:14991-- From magnus@thinkware.se Fri Jan 10 05:47:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Fri Jan 10 05:47:02 2003 Subject: [Tutor] instance variables and the instance dictionary In-Reply-To: <3E1E3169.3060207@pooryorick.com> References: <5.1.0.14.0.20030110004456.02c35f68@www.thinkware.se> Message-ID: <5.1.0.14.0.20030110110056.02c9b1a0@www.thinkware.se> Please stay on the list, this is NOT off topic for Tutor. At 19:35 2003-01-09 -0700, Poor Yorick wrote: >Magnus Lycka wrote: >>A method like below would call itself until the stack breaks. >> >> def __setattr__(self, attr, val): >> # do some error checks > >I know I'm asking a lot here, but would you mind tendering a short=20 >explanation of what the stack is. I'm not just being lazy. Most of the= =20 >information on the web assumes more knowledge of computer science than I= =20 >have. I generally understand stacks, like fifo and lifo, but what is "t= he=20 >stack"? Does anyone know of a resource that explains this in a way that is understandable by people who don't already know what it's about? Is http://www.stackless.com/spcpaper.htm#_Toc470444065 helpful? This is a bit outside of my expertise. I hope someone will correct me if I'm confused about something in Python's internals. Anyway, Python has to be able to keep track of many different contexts at the same time. Let's look at some silly code: def addOne(x): return x + 1 def addTwo(y): return 1 + addOne(y) def addThree(z): return 1 + addTwo(z) def main(): a =3D 5 print addThree(a) a =3D 7 print addThree(a) main() When we run this program, Python needs to keep track of many contexts at once. First, we get into the local scope of main. There we have a local variable a with the value 5 to begin with. When we call addThree, we get into a new scope, a new context. Now the only local variable i z and we don't know about a, although z is also 5 as it's passed in with that value. addThree calls addTwo; again a new scope / context, where we only know about the variable y. Finally addTwo calls addOne and we reach a fourth scope, with the local variable x. Now addOne will reach its return statement, and we get back to addTwo. This means that we get back to our old scope, and have to remember the values of all local variables as they were before we switched scope to addOne. We will continue to revert to old scopes until we get back to main again. So, if we forgot a scope as we left it in a function call, we'll be in trouble. Eventually we will even end the main function, and we will be in the global scope of our program, but that's less of a problem. A na=EFve idea would be to solve this problem by having a storage for local variables in each function, but that won't do what we want. First of all, we might use a function again before we can drop the provious context (this is called recursion) and normally, we don't want functions to remember their state from a previous incarnation. We use classes instead when we want such memory. The normal way of solving this problem is instead to use a stack where we store these contexts. For each function call, we push a new context on the stack, and for each function return we pop it off again. If we raise an exception, we will have to pop the stack until the exception is caught. The results of all this popping is shown in the wellknown traceback... The normal C implementation of Python uses the stack which is provided for this purpose by the C runtime system. It has a limited size, which you can change as shown below. Let's look at this little example using the classical factorial function. N.B. Don't do this in a GUI python interpreter. If you like to do things that you are told not to do, make sure you don't have unsaved work. >>> import sys >>> sys.getrecursionlimit() 1000 >>> sys.setrecursionlimit(5) >>> def fact(x): ... if x < 2: ... return x ... else: ... return x * fact(x-1) ... >>> print fact(3) 6 >>> print fact(4) 24 >>> print fact(5) Traceback (most recent call last): File "", line 1, in ? File "", line 5, in fact File "", line 5, in fact File "", line 5, in fact File "", line 5, in fact RuntimeError: maximum recursion depth exceeded Here we reduced the size of the stack, and ran out of it very quickly. You see the ordinary Traceback, which will give some information about each context on the Python interpreter stack. --=20 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 glingl@aon.at Fri Jan 10 05:51:25 2003 From: glingl@aon.at (Gregor Lingl) Date: Fri Jan 10 05:51:25 2003 Subject: [Tutor] please help! References: <20030110103909.15328.qmail@web40407.mail.yahoo.com> Message-ID: <3E1EA57D.1070202@aon.at> geraldine lynch schrieb: > hello > > How do I sum all the elements of an array? I mean, is there a Capital > sigma function? something like this: > > å y_i > Yes, you can use the builtin function reduce for this ... > I'm quite new to python and have to write a program before my uni term > restarts so i dont have very long! > ... immediately: >>> from operator import add >>> reduce(add,[1,2,3,4,5,6]) 21 reduce is even more versatile than this "Capital sigma" (- which, incidentally, on my email-client appears like the å in Lyckå), for instance: >>> from operator import mul >>> reduce(mul,[1,2,3,4,5,6]) 720 Was this fast e3nough? Regards, Gregor > thanks, Geraldine > > > ------------------------------------------------------------------------ > *With Yahoo! Mail you can get a bigger mailbox -- choose a size that > fits your needs* > From magnus@thinkware.se Fri Jan 10 05:56:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Fri Jan 10 05:56:02 2003 Subject: [Tutor] folder dialog In-Reply-To: Message-ID: <5.1.0.14.0.20030110115412.02c95418@www.thinkware.se> At 05:09 2003-01-10 +0000, antone heyward wrote: >Is there a folder dialog for tkinter? wxpython has one but i want to stick >with tkinter. Plus i am pretty new to programming and wxpython is a bit >complex for me right now. import tkFileDialog x = tkFileDialog.askdirectory() # etc print "Selected folder", x help(tkFileDialog) -- 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@thinkware.se Fri Jan 10 05:59:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Fri Jan 10 05:59:01 2003 Subject: [Tutor] OT: 42? In-Reply-To: <3E1E6F23.10902@aon.at> References: <5.1.0.14.0.20030109235713.02c29bb0@www.thinkware.se> <5.1.0.14.0.20030110011141.02c195f0@www.thinkware.se> Message-ID: <5.1.0.14.0.20030110120108.02c77800@www.thinkware.se> At 07:58 2003-01-10 +0100, Gregor Lingl wrote: >Could one get into social problems on electronic lists? Hope not! By social problem I only mean things like feeling lost when everybody else knows what 42 is, or not understanding why Norwegian Blue is funny 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 glingl@aon.at Fri Jan 10 06:02:01 2003 From: glingl@aon.at (Gregor Lingl) Date: Fri Jan 10 06:02:01 2003 Subject: [Tutor] fac Message-ID: <3E1EA821.60901@aon.at> Hi people, isn't this funny, to see the factorial function coming to the tutor-list in two completely different flavours and in two comletely different contexts within one minute? Does still anyone doubt, that it is a *very* important function? :-) Gregor From magnus@thinkware.se Fri Jan 10 07:06:34 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Fri Jan 10 07:06:34 2003 Subject: [Tutor] please help! In-Reply-To: <3E1EA57D.1070202@aon.at> References: <20030110103909.15328.qmail@web40407.mail.yahoo.com> Message-ID: <5.1.0.14.0.20030110124632.02c9dcc8@www.thinkware.se> >geraldine lynch schrieb: >>How do I sum all the elements of an array? ... I'm assuming that "array" is a sequence (list or tuple) of numbers of some kind... "sum(array)" would seem like a reasonable approach, right? That's what I would do. You would have to define the sum function first, but that is fairly trivial. At 11:50 2003-01-10 +0100, Gregor Lingl wrote: >you can use the builtin function reduce for this ... But a more conventional solution would be def sum(array): s = 0 for element in array: s = s + element return s Performance is roughly the same, and you don't need to introduce any concepts that might be unknown to other programmers. Everybody who has some basic understanding of Python understands those five lines of code, and it reads more or less like English. operator.add(1,2) is probably less obvious than 1 + 2, and reduce, filter and map are confusing to many programmers. "s = s + element" can be replaced with the shorter form "s += element" if you prefer to type a little less... A sum function is certainly a reasonable thing to have in one's tool box. Like the builtins min and max, it might be a good thing if it can also handle things like "sum(1,2,3)". Let's see... >>> def sum(*args): ... sum = 0 ... for arg in args: ... if hasattr(arg, '__len__'): ... for x in arg: ... sum += x ... else: ... sum += arg ... return sum ... >>> sum(1,2,3) 6 >>> sum([1,2,3]) 6 >>> sum([1,2,3],4,(5,6)) 21 Notice that this doesn't work like the builtin min and max. They won't treat the third case like our sum does. Also note that while we can sum all elements of several sequences, we won't follow structures further. >>> sum([1,2,3],4,(5, 6, (5,6))) Traceback (most recent call last): File "", line 1, in ? File "", line 6, in sum TypeError: unsupported operand type(s) for +=: 'int' and 'tuple' -- 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 glingl@aon.at Fri Jan 10 07:19:01 2003 From: glingl@aon.at (Gregor Lingl) Date: Fri Jan 10 07:19:01 2003 Subject: [Tutor] please help! References: <20030110103909.15328.qmail@web40407.mail.yahoo.com> <5.1.0.14.0.20030110124632.02c9dcc8@www.thinkware.se> Message-ID: <3E1EBA3D.5080906@aon.at> Magnus Lycka schrieb: > >> geraldine lynch schrieb: >> >>> How do I sum all the elements of an array? ... >> > > I'm assuming that "array" is a sequence (list or tuple) > of numbers of some kind... > > "sum(array)" would seem like a reasonable approach, > right? That's what I would do. You would have to > define the sum function first, but that is fairly > trivial. > > At 11:50 2003-01-10 +0100, Gregor Lingl wrote: > >> you can use the builtin function reduce for this ... > > > But a more conventional solution would be ... > are confusing to many programmers. > if one feels, that > if hasattr(arg, '__len__'): is also confusing to many programmers, one could try if if type(arg) in (list,tuple): is intuitively a little clearer (and also excludes inappropriate strings...) ... Gregor > > > From pietro.ciuffo@nekhem.com Fri Jan 10 07:27:01 2003 From: pietro.ciuffo@nekhem.com (Pietro Ciuffo) Date: Fri Jan 10 07:27:01 2003 Subject: [Tutor] replace windows quote In-Reply-To: <017a01c26123$45270550$c009ba3f@defaultcomp> References: <20020921033729.GA8491@isis.visi.com> <017a01c26123$45270550$c009ba3f@defaultcomp> Message-ID: <20030110122536.GA1097@burma> Hi all. I have to replace - inside a text file - a quote inserted by Word X Windows with a simple plain quote. The problem is to match the 'Win' quote: if I open the file in vim, I see a '~R' blue sign, if I do cat -A, the output is a 'M-^R' sign. Anyone could help me? Thanks From op73418@mail.telepac.pt Fri Jan 10 07:33:02 2003 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Fri Jan 10 07:33:02 2003 Subject: [Tutor] Best way to convert a type into string References: <5.2.0.9.0.20030109145611.03c0ec28@66.28.54.253> Message-ID: <00bc01c2b8a5$2b0d1ef0$b9170dd5@violante> > >>> type(1) > > > What's the best way to get the string "int" from this? My goal is to > construct a string similar to: > 'pysqlite_pragma expected_types = int,str,int,float' > by applying type() to a series of values. > > repr(type(1))[7:-2] does it; I was hoping for something simpler. > Here is the simplest: >>> print type(1).__name__ int > Bob Gailer > mailto:ramrom@earthling.net > 303 442 2625 > With my best regards, G. Rodrigues From magnus@thinkware.se Fri Jan 10 07:49:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Fri Jan 10 07:49:01 2003 Subject: [Tutor] fac In-Reply-To: <3E1EA821.60901@aon.at> Message-ID: <5.1.0.14.0.20030110131405.02ca5238@www.thinkware.se> At 12:01 2003-01-10 +0100, Gregor Lingl wrote: >Hi people, >isn't this funny, to see the factorial function coming to >the tutor-list in two completely different flavours and >in two comletely different contexts within one minute? >Does still anyone doubt, that it is a *very* important >function? It probably has something to do with 42. Maybe it required 1405006117752879898543142606244511569936384000000000 operations for Deep Thought to come up with its answer? Factorial rarely comes up in contexts like this because the result it calculates is useful, but rather because it's simple to demonstrate recursion with it. I much prefer Fibonacci numbers, but implementing Fibonacci with recursion is even more stupid than implementing Factorial that way. Function calls have a cost, as the recent discussion should have revealed. The limited amount of stack space is used, and it takes time and memory to put context on the stack. So, if you need factorials in real life (who does?) it's much better to do: def fac(n): prod = 1 for i in range(1, n+1): prod *= i return prod or if you are of the other inclination... def fac(n): import operator return reduce(operator.mul, range(1,n+1)) Fibonacci numbers are much nicer, because the ratio of two adjacent fibonacci numbers get closer and closer to the Golden Ratio the higher they get. The Golden Ratio is something really important. You can ask any ancient Egyptian, landscape photographer or plastic surgeon about that. But while recursive factorials are only linearly wasteful, the function below is much worse. Think about it. >>> def fib(n): ... if n <= 1: return 1 ... else: return fib(n-2) + fib(n-1) Let's use it anyway, to show it's beauty. >>> old = 1 >>> from __future__ import division >>> for i in range(1,17): ... f = fib(i) ... print f, f / old, old / f ... old = f ... 1 1.0 1.0 2 2.0 0.5 3 1.5 0.666666666667 5 1.66666666667 0.6 8 1.6 0.625 13 1.625 0.615384615385 21 1.61538461538 0.619047619048 34 1.61904761905 0.617647058824 55 1.61764705882 0.618181818182 89 1.61818181818 0.61797752809 144 1.61797752809 0.618055555556 233 1.61805555556 0.618025751073 377 1.61802575107 0.618037135279 610 1.61803713528 0.618032786885 987 1.61803278689 0.618034447822 1597 1.61803444782 0.6180338134 -- 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@thinkware.se Fri Jan 10 08:00:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Fri Jan 10 08:00:02 2003 Subject: [Tutor] replace windows quote In-Reply-To: <20030110122536.GA1097@burma> References: <017a01c26123$45270550$c009ba3f@defaultcomp> <20020921033729.GA8491@isis.visi.com> <017a01c26123$45270550$c009ba3f@defaultcomp> Message-ID: <5.1.0.14.0.20030110135429.02ca3b08@www.thinkware.se> At 13:25 2003-01-10 +0100, Pietro Ciuffo wrote: >I have to replace - inside a text file - a quote inserted >by Word X Windows with a simple plain quote. >The problem is to match the 'Win' quote: if I open the file in vim, I >see a '~R' blue sign, if I do cat -A, the output is a 'M-^R' sign. >Anyone could help me? Open the file in Python instead. Of course! Then you have all the python tools to inspect with. It might be enough to just do: data = file('myfilename').read() print data print repr(data) If that wasn't enough, you might be helped by for x in data: print ord(x), x If the file is big, use slices "data[100:120]" to pick out the relevant piece. If you don't know how to find the right spot, use find. print data.find('some known text') -- 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 op73418@mail.telepac.pt Fri Jan 10 08:01:24 2003 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Fri Jan 10 08:01:24 2003 Subject: [Tutor] how do you use __dict__ ? (Was: code dangerous?) References: <5.1.0.14.0.20030110113007.02571ec0@192.168.1.1> Message-ID: <00d201c2b8a9$211d5730$b9170dd5@violante> ----- Original Message ----- From: "Alfred Milgrom" To: "Gonçalo Rodrigues" ; Sent: Friday, January 10, 2003 2:06 AM Subject: [Tutor] how do you use __dict__ ? (Was: code dangerous?) > At 04:03 PM 8/01/03 +0000, you wrote: > >This should read: > > > >__speak = self.__dict__.get('my_speak') > > > >[rest snipped] > > Thanks for the update - looks interesting, but I don't know anything > about using __dict__, or understand what __speak means. > I couldn't find any good references, so I just tried something anyway :( > > My attempt at implementing this code works, but seems like a heavy-handed > way to use 'magic' attributes: > Magnus Lycka has already beaten me to a very nice and informative explanation of names, special attributes and other whatnots. Let me add just a tiny wrinkle of mine: I tend to overabuse the __ name mangling (even in contexts where it doesn't make much sense, like the local __speak in the speak method). It's a (bad) habit that stuck when I moved from Java to Python. So in the speak method below just replace __speak with speakmethod, it's less confusing. > ******************************************************** > > class Person: > def __init__(self, name): > self.name = name > > def speak(self): > __speak = self.__dict__.get('my_speak') > if __speak: > eval(__speak) > else: > print "%s says: my name is %s" % (self.name, self.name) > > def crankyspeak(self): > print "%s says: I don't tell anyone my name" % (self.name) > > hobbit = Person('Bilbo Baggins') > > cranky = Person('someone else') > cranky.__dict__['my_speak'] = 'self.crankyspeak()' I have my doubts that this will work - I have not tested it anyway. It's simpler to def speak(self): #Get my_speak function object from *instance* data. speakmethod = self.__dict__.get('my_speak') #If there is a my_speak call it with apropriate arguments. if speakmethod is not None: speakmethod(self) #There is no my_speak: just do the usual stuff. else: print "%s says: my name is %s" % (self.name, self.name) And then cranky.my_speak = cranky.crankyspeak But think a minute: Is there going to be more than one cranky person? If the answer is yes, just subclass Person into CrankyPerson and override speak. The technique I showed you is mainly useful when you have a lot of different Persons that differ between them in one attribute or just one method and multiplying the classes to cover all these cases would be a real hassle. If you want a different speak for a given instance you just stick a function object in the instance data - the speak method will look there first and call it with apropriate arguments. But you should be aware that this has risks and downsides. One of them is that it makes more difficult for inheritance/overriding. Others are in Alan Gauld's post. Read it carefully, it has excellent advice. > > hobbit.speak() > cranky.speak() > > ******************************************************** > > Can you suggest any good links or explain how I am supposed to use __dict__ > and __speak ? > > Thanks, > Fred All the best, G. Rodrigues From op73418@mail.telepac.pt Fri Jan 10 08:03:02 2003 From: op73418@mail.telepac.pt (Goncalo Rodrigues) Date: Fri Jan 10 08:03:02 2003 Subject: [Tutor] how do you use __dict__ ? (Was: code dangerous?) References: <5.1.0.14.0.20030110113007.02571ec0@192.168.1.1> <661278969.20030110131648@rambler.ru> Message-ID: <00e001c2b8a9$7bd81de0$b9170dd5@violante> ----- Original Message ----- From: "antonmuhin íà rambler.ru" To: Sent: Friday, January 10, 2003 10:16 AM Subject: Re: [Tutor] how do you use __dict__ ? (Was: code dangerous?) > Hello Alfred, > > I might be missing something, but why don't use simpler approach: > > class Person: > def __init__(self, name): > self.name = name > self.speakMethod = None > > def speak(self): > if self.speakMethod: > self.speakMethod(self) > else: > print "%s says: my name is %s" % (self.name, self.name)" > > def setSpeakMethod(self, speakMethod): > self.speakMethod = speakMethod > > def crankyspeak(person): > print "%s says: I don't tell anyone my name" % (person.name) > > hobbit = Person('Bilbo Baggins') > cranky = Person('someone else') > > cranky.setSpeakMethod(crankyspeak) > > hobbit.speak() > cranky.speak() > Ah, thanks. That was exactly what was lurking in the back of my mind! Thanks for yanking it out! > Best regards, > Anton. > With my best regards, G. Rodrigues From magnus@thinkware.se Fri Jan 10 08:47:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Fri Jan 10 08:47:01 2003 Subject: [Tutor] instance variables and the instance dictionary In-Reply-To: <3E1E3009.8000509@pooryorick.com> References: <5.2.0.9.0.20030109154045.03c10988@66.28.54.253> Message-ID: <5.1.0.14.0.20030110143411.02c9d9a8@www.thinkware.se> At 19:29 2003-01-09 -0700, Poor Yorick wrote: >Bob Gailer wrote: >>Even worse, if you're using PythonWin, and you enter "self.__dict__[313] >>= 5", then enter "self.", that raises an exception TypeError: sequence >>item 0: expected string, int found which sure gets in the way of using >>that IDE. >You sort of lost me here. I tried to reproduce this in Pythonwin but >couldn't. Could you offer a little more sample code? Bob: Why ever would you like to use ints as keys in __dict__??? Yorick: Here's an example. The exception occurs when I press the '.' key as I type "x1." after having called the x() method. I'm using build 146 of PythonWin. I know Mark fixed a lot of bugs for 150, but I'm not sure about this (if he thinks it's a bug). >>> class X: ... def x(self): ... self.__dict__[313] = 5 ... >>> x1 = X() >>> x1.y = 5 >>> x1.x() >>> x1.Firing event 'KeyDot' failed. Traceback (most recent call last): File "G:\Python22\Lib\site-packages\Pythonwin\pywin\scintilla\bindings.py", line 141, in fire rc = apply(binding.handler, args) File "G:\Python22\Lib\site-packages\Pythonwin\pywin\scintilla\view.py", line 305, in KeyDotEvent self._AutoComplete() File "G:\Python22\Lib\site-packages\Pythonwin\pywin\scintilla\view.py", line 432, in _AutoComplete self.SCIAutoCShow(items) File "G:\Python22\Lib\site-packages\Pythonwin\pywin\scintilla\control.py", line 176, in SCIAutoCShow text = string.join(text) File "G:\Python22\lib\string.py", line 131, in join return sep.join(words) TypeError: sequence item 0: expected string, int found . -- 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 fredm@smartypantsco.com Fri Jan 10 09:16:35 2003 From: fredm@smartypantsco.com (Alfred Milgrom) Date: Fri Jan 10 09:16:35 2003 Subject: [Tutor] how do you use __dict__ ? (Was: code dangerous?) Message-ID: <5.1.0.14.0.20030111010828.01ed20c0@mail.milgromphoto.com> Thanks you all for helping me out, and explaining multiple inheritance,=20 __dict__, and so on. I hope I am not boring everyone, but I kept on fiddling with the code, and= =20 the following seems to be a simpler way to override the 'speak' method, and= =20 seems to work: ******************************************************** class Person: def __init__(self, name): self.name =3D name def speak(self): print "%s says: my name is %s" % (self.name, self.name) def crankyspeak(self): print "%s says: I don't tell anyone my name" % (self.name) hobbit =3D Person('Bilbo Baggins') cranky =3D Person('someone else') cranky.speak=3Dcranky.crankyspeak hobbit.speak() cranky.speak() ******************************************************** This appears to overcome the issues raised about other approaches, and the= =20 problem mentioned in Gon=E7alo Rodrigues' earlier posting about the=20 difference between a method and a plain function object. Please do let me know if I am missing something. Thanks, Fred Milgrom=20 From op73418@mail.telepac.pt Fri Jan 10 09:17:21 2003 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Fri Jan 10 09:17:21 2003 Subject: [Tutor] how do you use __dict__ ? (Was: code dangerous?) References: <5.1.0.14.0.20030111001051.01eb8c90@mail.milgromphoto.com> Message-ID: <001d01c2b8b3$ccc710d0$b9170dd5@violante> ----- Original Message ----- From: "Alfred Milgrom" To: "Gonçalo Rodrigues" ; Sent: Friday, January 10, 2003 1:19 PM Subject: Re: [Tutor] how do you use __dict__ ? (Was: code dangerous?) >Thanks you all for helping me out, and explaining multiple inheritance, >__dict__, and so on. > >I hope I am not boring everyone, but I kept on fiddling with the code, and >the following seems to be simpler and seems to work: Do not worry. I, like you, am also learning and am not bored at all. > >******************************************************** >class Person: > def __init__(self, name): > self.name = name > > def speak(self): > print "%s says: my name is %s" % (self.name, self.name) > > def crankyspeak(self): > print "%s says: I don't tell anyone my name" % (self.name) > >hobbit = Person('Bilbo Baggins') > >cranky = Person('someone else') >cranky.speak=cranky.crankyspeak > >hobbit.speak() >cranky.speak() > >******************************************************** > >This appears to overcome the problem mentioned in Gonçalo Rodrigues' >earlier posting about the difference between a method and a plain function >object. > >Please do let me know if I am missing something. Check Anton's solution. It's the best one. If you have any doubts just keep posting until between us all we have managed to kill them. >Thanks, >Fred Milgrom All the best, G. Rodrigues From Janssen@rz.uni-frankfurt.de Fri Jan 10 10:06:02 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Fri Jan 10 10:06:02 2003 Subject: [Tutor] Calculating a math formula and finding errors In-Reply-To: <20030109165408.GA19944@kubieziel.de> Message-ID: On Thu, 9 Jan 2003, Jens Kubieziel wrote: > Hi, > > I found a nice formula in a math magazine [1]. Though I couldn't find a > proof, I'm trying to compute some values of it. If this formula is right, > both sides have to be equal. But within my code, both sides are not > equal. So I think that I have an error in my code. Do you see the error > and maybe general mistakes I made? > > formula in LaTeX [2]: > \sum ^{n}_{i=0} \sum ^{n-i}_{j=0}|n+1-2(i+j)| \bigl( \begin{smallmatrix} > n-1\\i \end{smallmatrix} \bigr) =2 \lfloor \frac{n+2}{2} \rfloor \bigl( > \begin{smallmatrix} n+1\\ \lfloor \frac{n+1}{2} \rfloor \end{smallmatrix} > \bigr) - (n+1) smallmatrix is unknown to my latex. This has worked for me: \begin{displaymath} \sum ^{n}_{i=0} \sum ^{n-i}_{j=0}|n+1-2(i+j)| {n-1 \choose i} =2 \left\lfloor \frac{n+2}{2} \right\rfloor {n+1 \choose \lfloor \frac{n+1}{2} \rfloor} - (n+1) \end{displaymath} > > Python code: > #v+ > #! /usr/bin/python > > import math > > def facul(z): > if z ==1: > return 1 > else: > return z*facul(z-1) > > def perm(x,y): > w = 1 > for i in range(y+1,x+1): > w = w * i > return w/facul(x-y) > > def MBrechts(n): > b=0 > for i in range(0,n): > for j in range(0,n-i): > betrag = n + 1 - (2*i) - (2*j) > if betrag < 0: > betrag = betrag * -1 > prod = betrag * perm(n-i,j) MBrechts is the left side, isn't it? It must be perm(n-1, i) to represent latex: ${n-1 \choose i}$ (which is the binominalcoeffizient of n-1 and i) But this won't make the output equal. the "sigma-ranges" might (must? I don't know much about math notation) be range(0,n+1) and range(0,n-i+1) (both zeros aren't neccessary in python but provided for the readers convenience). (From the rest of the code I guess, you're familar with "range" so this typo needn't be explained) *This* correction (sigma-ranges) *without* the correction of perm(n-i,j) gives equal output (Disclaimer: I've both perm and facul rewritten (since i havn't understand your implementation of perm and wasn't familar with recusive-facul ;-). In case this doesn't already solve your problem, could you repost a patched version (perhaps with english var-names to give the rest of tutor-list a better chance :) and clean from rechts/links mess) so that we can restart from a coherent version? Would you give us some hints what's this formular is about? I havn't found it on the webside. What does "perm" stands for? Michael > b = b + prod > return b > > def MBlinks(n): > return 2 * math.floor((n+2)/2) * perm(n+1,math.floor((n+1)/2)) - n - 1 > > for erg in range(1,12): > print "n = %d, Formel rechts = %d, Formel links = %d" % (erg,MBrechts(erg),MBlinks(erg)) > #v- > > Thanks for your recommendations > > > Footnotes: > ========== > [1] print edition of http://www.wurzel.org > [2] You can find a more readable version at > http://www.kuwest.de/tmp/Bencze-Formel.pdf > -- > Jens Kubieziel mailto:jens@kubieziel.de > If you cannot in the long run tell everyone what you have been doing, > your doing was worthless. > -- Edwim Schrodinger > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From emil@lysator.liu.se Fri Jan 10 10:15:04 2003 From: emil@lysator.liu.se (Emil Styrke) Date: Fri Jan 10 10:15:04 2003 Subject: [Tutor] OT: 42? In-Reply-To: <5.1.0.14.0.20030110011141.02c195f0@www.thinkware.se> Message-ID: <41D8A93C-24AE-11D7-BEC3-000393DC397E@lysator.liu.se> fredagen den 10 januari 2003 kl 01.24 skrev Magnus Lycka: > At 00:58 2003-01-10 +0100, Gregor Lingl wrote: >> I must confess, that I have this novel on my bookshelve > > Which of them? ;) If I remember correctly, it's one of > those trilogies that consists of at least five books, > right? Yup. Five books, although there is also a volume with only the four=20 first books. > > Actually, I never read the fifth book "Mostly Harmless". > Is it as good as the others? In my opinion, it's one of the best. Very confusing, but good. I=20 suggest you re-read the other four first, though. /Emil > > I don't know about your background, but in my circles, > among electronic engineers and programmers in G=F6teborg > born in the 60's or 70's, you'd have a social problem if > you hadn't read Douglas Adams and watched Monty Python. > In Stockholm you'd be lost if you hadn't read Terry > Pratchett. (Or maybe that's a generation thing?) > > Hm... It seems fantasy authors manage to make trilogies > trilogies, but when we get out in space, the works that > are long know as trilogies tend to grow... Asimov, Herbert, > Adams... > > > --=20 > 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 > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From SWidney@ci.las-vegas.nv.us Fri Jan 10 10:58:03 2003 From: SWidney@ci.las-vegas.nv.us (Scott Widney) Date: Fri Jan 10 10:58:03 2003 Subject: [Tutor] is this code dangerous? Message-ID: <0E5508EBA1620743B409A2B8365DE16FDC82EE@SOVEREIGN> > > class Person: > > def __init__(self, name): > > def speak(self, dummy): > > def crankyspeak(self): > > > > hobbit = Person('Bilbo Baggins') > > cranky = Person('someone else') > > cranky.speak=Person.crankyspeak Taking a turn down a different path: make the Person's 'mood' an attribute and have the Person check his mood before speaking. >>> class Person: ... def __init__(self, name, mood=None): ... self.name = name ... self.mood = mood ... def speak(self): ... if self.mood == 'cranky': ... print "We isn't saying nothing." ... else: ... print "Hello, I'm %s." % self.name ... >>> bilbo = Person("Bilbo Baggins") >>> gollum = Person("Smeagol", 'cranky') >>> bilbo.speak() Hello, I'm Bilbo Baggins. >>> gollum.speak() We isn't saying nothing. >>> gollum.mood = 'happy' >>> gollum.speak() Hello, I'm Smeagol >>> Scott From ramrom@earthling.net Fri Jan 10 12:30:02 2003 From: ramrom@earthling.net (Bob Gailer) Date: Fri Jan 10 12:30:02 2003 Subject: [Tutor] Best way to convert a type into string In-Reply-To: <00bc01c2b8a5$2b0d1ef0$b9170dd5@violante> References: <5.2.0.9.0.20030109145611.03c0ec28@66.28.54.253> Message-ID: <5.2.0.9.0.20030110102641.01a29918@66.28.54.253> --=======1DB154BA======= Content-Type: text/plain; x-avg-checked=avg-ok-64186D05; charset=iso-8859-1; format=flowed Content-Transfer-Encoding: quoted-printable At 12:38 PM 1/10/2003 +0000, Gon=E7alo Rodrigues wrote: > > >>> type(1) > > > > > > What's the best way to get the string "int" from this? > >Here is the simplest: > > >>> print type(1).__name__ >int That's what I was looking for. Something already in the language. How does= =20 one discover things like this? Are they in the documentation? dir(type(1))= =20 reveals a lot of keys, but __name__ is not amongst them. Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======1DB154BA======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-64186D05 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.438 / Virus Database: 246 - Release Date: 1/7/2003 --=======1DB154BA=======-- From ramrom@earthling.net Fri Jan 10 12:33:02 2003 From: ramrom@earthling.net (Bob Gailer) Date: Fri Jan 10 12:33:02 2003 Subject: [Tutor] instance variables and the instance dictionary In-Reply-To: <5.1.0.14.0.20030110143411.02c9d9a8@www.thinkware.se> References: <3E1E3009.8000509@pooryorick.com> <5.2.0.9.0.20030109154045.03c10988@66.28.54.253> Message-ID: <5.2.0.9.0.20030110102959.02745b48@66.28.54.253> --=======50D05CEB======= Content-Type: text/plain; x-avg-checked=avg-ok-64186D05; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 02:51 PM 1/10/2003 +0100, Magnus Lycka wrote: >Bob: Why ever would you like to use ints as keys in __dict__??? Your question reminds me of older days when I'd call tech support with a problem, and they'd say "Why would you want to do that?" I always considered the question to be irrelevant. I did something, it caused a problem, and I wanted a solution. Same case here. It's not that I'd want to do that, but the fact is that I can do it and it creates a problem. Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======50D05CEB======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-64186D05 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.438 / Virus Database: 246 - Release Date: 1/7/2003 --=======50D05CEB=======-- From Janssen@rz.uni-frankfurt.de Fri Jan 10 12:49:01 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Fri Jan 10 12:49:01 2003 Subject: [Tutor] Best way to convert a type into string In-Reply-To: <5.2.0.9.0.20030110102641.01a29918@66.28.54.253> Message-ID: On Fri, 10 Jan 2003, Bob Gailer wrote: > At 12:38 PM 1/10/2003 +0000, Gon=E7alo Rodrigues wrote: > > > > >>> type(1) > > > > > > > > > What's the best way to get the string "int" from this? > > > >Here is the simplest: > > > > >>> print type(1).__name__ > >int > > That's what I was looking for. Something already in the language. How doe= s > one discover things like this? One way to discover something, which you don't find in the docs ist to use the rlcompleter-module: 18:37 ./janssenm> cat .pythonrc ### enables tab-completion import rlcompleter import readline readline.parse_and_bind("tab: complete") now you can type at interactive prompt: typeobject =3D type(1) typeobject.[tab][tab] and you will get the complete list of every method and variable from typeobjects. From this point you have to gess and try. Michael > Are they in the documentation? dir(type(1)) > reveals a lot of keys, but __name__ is not amongst them. > > Bob Gailer > mailto:ramrom@earthling.net > 303 442 2625 > From magnus@thinkware.se Fri Jan 10 13:25:20 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Fri Jan 10 13:25:20 2003 Subject: [Tutor] instance variables and the instance dictionary In-Reply-To: <5.2.0.9.0.20030110102959.02745b48@66.28.54.253> References: <5.1.0.14.0.20030110143411.02c9d9a8@www.thinkware.se> <3E1E3009.8000509@pooryorick.com> <5.2.0.9.0.20030109154045.03c10988@66.28.54.253> Message-ID: <5.1.0.14.0.20030110191448.02cae598@www.thinkware.se> At 10:32 2003-01-10 -0700, Bob Gailer wrote: >Same case here. It's not that I'd want to do that, but the fact is that I >can do it and it creates a problem. There are lots of things you can do with python that will create problems. I certainly don't want a set of tools that reminds me of a padded cell... And I don't think Mark should spend time fixing things in PythonWin that will never create a problem for anyone in practice. Life is too short... -- 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 ramrom@earthling.net Fri Jan 10 14:12:05 2003 From: ramrom@earthling.net (Bob Gailer) Date: Fri Jan 10 14:12:05 2003 Subject: [Tutor] instance variables and the instance dictionary In-Reply-To: <5.1.0.14.0.20030110191448.02cae598@www.thinkware.se> References: <5.2.0.9.0.20030110102959.02745b48@66.28.54.253> <5.1.0.14.0.20030110143411.02c9d9a8@www.thinkware.se> <3E1E3009.8000509@pooryorick.com> <5.2.0.9.0.20030109154045.03c10988@66.28.54.253> Message-ID: <5.2.0.9.0.20030110121009.01a18fc0@66.28.54.253> --=======56A14E20======= Content-Type: text/plain; x-avg-checked=avg-ok-64186D05; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 07:29 PM 1/10/2003 +0100, Magnus Lycka wrote: >At 10:32 2003-01-10 -0700, Bob Gailer wrote: >>Same case here. It's not that I'd want to do that, but the fact is that I >>can do it and it creates a problem. > >There are lots of things you can do with python that will >create problems. I certainly don't want a set of tools that >reminds me of a padded cell... And I don't think Mark should >spend time fixing things in PythonWin that will never create >a problem for anyone in practice. Life is too short... I'd like to end this thread. I am not asking Mark to fix that. There's enough else I want to see fixed or enhanced in PythonWin. I was just reacting to the question "why would you want to do that." Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======56A14E20======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-64186D05 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.438 / Virus Database: 246 - Release Date: 1/7/2003 --=======56A14E20=======-- From op73418@mail.telepac.pt Fri Jan 10 14:17:01 2003 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Fri Jan 10 14:17:01 2003 Subject: [Tutor] Best way to convert a type into string References: <5.2.0.9.0.20030109145611.03c0ec28@66.28.54.253> <5.2.0.9.0.20030110102641.01a29918@66.28.54.253> Message-ID: <001201c2b8dd$c156a740$b9170dd5@violante> ----- Original Message ----- From: "Bob Gailer" To: "Gonçalo Rodrigues" ; Sent: Friday, January 10, 2003 5:29 PM Subject: Re: [Tutor] Best way to convert a type into string >At 12:38 PM 1/10/2003 +0000, Gonçalo Rodrigues wrote: > >> > >>> type(1) >> > >> > >> > What's the best way to get the string "int" from this? >> >>Here is the simplest: >> >> >>> print type(1).__name__ >>int > >That's what I was looking for. Something already in the language. How does >one discover things like this? Are they in the documentation? dir(type(1)) Yes they are in the docs. Check for the description of the builtin types. dir does not catch __name__ because I believe dir only looks for instance data, first in the object then in the class and then through the whole hierarchy of super classes. That is, it goes through all the __dict__'s of these objects. It just so happens that __name__ is not in any one of them, it is hard-wired right into the C implementation. In interactive mode just use help() instead of dir. It is much better, since it lists everything. >reveals a lot of keys, but __name__ is not amongst them. > >Bob Gailer >mailto:ramrom@earthling.net >303 442 2625 All the best, G. Rodrigues From dyoo@hkn.eecs.berkeley.edu Fri Jan 10 14:20:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Jan 10 14:20:02 2003 Subject: [Tutor] factorial In-Reply-To: <5.1.0.14.0.20030110131405.02ca5238@www.thinkware.se> Message-ID: On Fri, 10 Jan 2003, Magnus Lycka wrote: > It probably has something to do with 42. Maybe it required > 1405006117752879898543142606244511569936384000000000 operations for Deep > Thought to come up with its answer? > > Factorial rarely comes up in contexts like this because the result it > calculates is useful, but rather because it's simple to demonstrate > recursion with it. I much prefer Fibonacci numbers, but implementing > Fibonacci with recursion is even more stupid than implementing Factorial > that way. > > Function calls have a cost, as the recent discussion should have > revealed. The limited amount of stack space is used, and it takes time > and memory to put context on the stack. Hi everyone, As a qualification: function calls have a cost in many languages, including Python. However, not all! There are some programming languages, particularly the functional languages, where function calls can come "for free" under certain circumstances. These circumstances come under the name "tail calls". > So, if you need factorials in real life (who does?) it's much better to > do: > > def fac(n): > prod = 1 > for i in range(1, n+1): > prod *= i > return prod > > or if you are of the other inclination... > > def fac(n): > import operator > return reduce(operator.mul, range(1,n+1)) There is a way of reformulating this so that it's still written using recursion, but it's just as efficient as a loop. For example, here's an "iterative" version in the Scheme language: ;;;;;; guile> (define (fact-iter n a) (if (= n 0) a (fact-iter (- n 1) (* n a)))) guile> (define (factorial n) (fact-iter n 1)) guile> (factorial 40) 815915283247897734345611269596115894272000000000 guile> (factorial 42) 1405006117752879898543142606244511569936384000000000 ;;;;;; This runs without any stack overhead in Scheme. There's a section in The Structure and Interpretation of Computer Programs that explains the idea of an iterative process using recursion, for those who are interested in this subject: http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-11.html#%_sec_1.2 The link above includes a neat diagram that shows intuitively why certain processes are forced to take up stack space, and why others may actually take a constant amount of space. > Fibonacci numbers are much nicer, because the ratio of two adjacent > fibonacci numbers get closer and closer to the Golden Ratio the higher > they get. The Golden Ratio is something really important. You can ask > any ancient Egyptian, landscape photographer or plastic surgeon about > that. > > But while recursive factorials are only linearly wasteful, the function > below is much worse. Think about it. > > >>> def fib(n): > ... if n <= 1: return 1 > ... else: return fib(n-2) + fib(n-1) But fib() is not expensive by necessity: we can reformulate this recursive definition as an iterative process, even with recursion: ### def fib(n): return fib_helper(n, 1, 1) def fib_helper(n, x, y): if n == 0: return x return fib_helper(n-1, y, x+y) ### And in theory, this should run without any cost related to function calling or stack usage... But unfortunately, the current implementation of Python doesn't optimize tail calls, so this runs abysmally in Python. *sigh* But it's still a good idea to be aware that function calls themselves don't have to be expensive by nature. It's only the current implementations of Python that places a cost to function calls. But if CPython and Jython does ever get tail call optimization, I will be a very happy person. *grin* From budgester@budgester.com Fri Jan 10 14:34:02 2003 From: budgester@budgester.com (Martin Stevens) Date: Fri Jan 10 14:34:02 2003 Subject: [Tutor] XML Processing In-Reply-To: References: <5.1.0.14.0.20021103193902.043b6810@www.thinkware.se> Message-ID: <20030110193204.GB23865@whos-the-daddy.budgenet> Well i have some code I'm working on with XML and Python, it's a bit hairy though. http://budgester.homeip.net/warpigs/ But if you wanna have a look at some in development XML code have a look. Budgester All usual discliamers apply On Mon, Nov 04, 2002 at 02:05:22PM -0800, Chris Rouse wrote: > Greetings, > > I was wondering if anyone knew of a good tutorial for processing XML or a > general Python XML tutorial. I have Python Bible 2.1 and have found the XML > examples some what lacking. Anyway, I am preferably looking for something on > the Web. > > Thank you > Chris Rouse > --- > Outgoing mail is certified Virus Free. > Checked by AVG anti-virus system (http://www.grisoft.com). > Version: 6.0.410 / Virus Database: 231 - Release Date: 10/31/2002 > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- "Microsoft is not the Borg. The Borg have better tech support." http://budgester.homeip.net/budge/ From gp@pooryorick.com Fri Jan 10 15:53:15 2003 From: gp@pooryorick.com (Poor Yorick) Date: Fri Jan 10 15:53:15 2003 Subject: [Tutor] instance variables and the instance dictionary References: <5.2.0.9.0.20030109154045.03c10988@66.28.54.253> <5.1.0.14.0.20030110143411.02c9d9a8@www.thinkware.se> Message-ID: <3E1F32F6.3090608@pooryorick.com> Magnus Lycka wrote: > > Yorick: Here's an example. Thank you for the example. The issue appears to be fixed in build 150. What's interesting to me about this whole thing is not the error, but the fact that using self.__dict__ you can throw an integer into self.__dict__ which is not a valid identifier. This fact by itself is pretty much useless, but as a beginning programmer in general, this sort of discussion helps me to understand the internals of the language and to think about how the gears are turning underneath the veneer. The thought leads to other ideas and questions, which is why it's worthwhile. One of the blissful things about being a beginner is that one often doesn't know what is worthwhile knowledge and what is not, and therefore has the opportunity to turn up unturned stones. Poor Yorick gp@pooryorick.com From ramrom@earthling.net Fri Jan 10 16:45:04 2003 From: ramrom@earthling.net (Bob Gailer) Date: Fri Jan 10 16:45:04 2003 Subject: [Tutor] instance variables and the instance dictionary In-Reply-To: <3E1F32F6.3090608@pooryorick.com> References: <5.2.0.9.0.20030109154045.03c10988@66.28.54.253> <5.1.0.14.0.20030110143411.02c9d9a8@www.thinkware.se> Message-ID: <5.2.0.9.0.20030110143655.034a6518@66.28.54.253> --=======4F8368B7======= Content-Type: text/plain; x-avg-checked=avg-ok-64186D05; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit Another interestng anomaly is: >>> class xx(list): ... def clear(self): ... self = [] ... >>> aa = xx([1,2,3]) >>> aa [1, 2, 3] >>> aa.clear() >>> aa [1, 2, 3] Note that self = [] does nothing, and raises no exception! BTW the proper way to do this is: self[:] = [] Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======4F8368B7======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-64186D05 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.438 / Virus Database: 246 - Release Date: 1/7/2003 --=======4F8368B7=======-- From magnus@thinkware.se Fri Jan 10 17:30:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Fri Jan 10 17:30:02 2003 Subject: [Tutor] instance variables and the instance dictionary In-Reply-To: <5.2.0.9.0.20030110143655.034a6518@66.28.54.253> References: <3E1F32F6.3090608@pooryorick.com> <5.2.0.9.0.20030109154045.03c10988@66.28.54.253> <5.1.0.14.0.20030110143411.02c9d9a8@www.thinkware.se> Message-ID: <5.1.0.14.0.20030110232436.02cb6b40@www.thinkware.se> At 14:44 2003-01-10 -0700, Bob Gailer wrote: >Note that self = [] does nothing, and raises no exception! >BTW the proper way to do this is: >self[:] = [] or del self[:] I can agree that this might seem confusing to begin with, but it's quite logical when you think about it for a while... self is a local variable. When you call your method, the variable self will be a reference to the instance object, but you are free to reassign your local variables to whatever you like. This is not different than: >>> self = "Nosir. Not a scrap. I was deliberately wasting your time, sir." >>> def x(self): ... self = "Well I'm sorry, but I'm going to have to shoot you." ... >>> print self Nosir. Not a scrap. I was deliberately wasting your time, sir. >>> x(self) >>> print self Nosir. Not a scrap. I was deliberately wasting your time, sir. -- 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@thinkware.se Fri Jan 10 19:31:26 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Fri Jan 10 19:31:26 2003 Subject: Fwd: Re: [Tutor] instance variables and the instance dictionary Message-ID: <5.1.0.14.0.20030111004141.02cc1d50@www.thinkware.se> I suppose this was meant for the list: >Date: Fri, 10 Jan 2003 16:26:46 -0700 >From: Poor Yorick >Subject: Re: [Tutor] instance variables and the instance dictionary > >Magnus Lycka wrote: >>This is not different than: >> >> >>> self = "Nosir. Not a scrap. I was deliberately wasting your time, sir." >> >>> def x(self): >>... self = "Well I'm sorry, but I'm going to have to shoot you." >>... >> >>> print self >>Nosir. Not a scrap. I was deliberately wasting your time, sir. >> >>> x(self) >> >>> print self >>Nosir. Not a scrap. I was deliberately wasting your time, sir. >Or, to illustrate it using Bob's code: > > >>> class xx(list): > def clear(self): > self = [] > print 'this is self', self > > >>> a = xx(['1','2','3']) > >>> a >['1', '2', '3'] > >>> a.clear() >this is self [] > >>> a >['1', '2', '3'] > >>> > >So I suppose that the magic is in the ".", which is what tells the >interpreter to create the identifier in a different namespace. So on a >lower level objects disappear and all you have are namespaces, >identifiers, values, functions, and virtual method tables. And out of >those things emerges object oriented programming. Is that close? Well... I don't know. The only problem with Bob's code is that he forgot that "self" is just a local variable in the method, and that assignment means that the local variable will "forget" it's previous value, and refer to a new object. There are objects everywhere. Functions, modules, integers, strings, lists. They are all objects. If you meant just instance objects, they don't disappear. They are as real inside the methods defined in the class as anywhere else. They are passed in--as you know--to all method calls in the first parameter, the one we by convention call self. But inside the method, there is no special magic for the bound instance object. Initially, self will refer to it, and we can access it and change it as we like, but if we do "self = " in the method, we have lost our reference to the instance object. Clear as the dark sky outside my window... I'd say, that there is no magic here. Everything is consistent. Let's try to analyze one of the most fundamental things in Python. The assignment statement. x = 5 What do we have here? First of all, on the Right Hand Side (RHS) we have an integer object. Python will find a place for that in memory, and store it there. Secondly, on the Left Hand Side (LHS) we have a variable name, x. From now on, until further notice (or end of scope) x will refer to the integer object 5. If x existed before this assignment, it no longer points to whatever object it pointed to before. The reference count for the object it pointed to before is decremented, and it will be garbage collected if x was the only reference to it. Let's say we continue with y = x Now the LHS is another variable, but that doesn't change any principle. The big difference is that the RHS is not an object, but a variable. So, while "x = 5" means "x should point to the integer 5 from now on", "y = x" means "y should from now on point to whatever object x is currently pointing to". For those familiar with C++, we can say that all python variables behave as references. But the LHS isn't always a variable either. For instance if we write l = [1] we have a statement of the same type as "x = 5", but we can make this more interesting by writing: l[0] = x In this case, the LHS is not a variable, but location 0 in the list object that l points to. The result will be that l will no longer be a list with a single 1 in it. It will be a list with a single 5 instead. l[:] = x would mean the same thing in this case, but it would have had a different consequence if l had contained more that one value. Lists are mutable objects, and one way of mutating lists is through assignments to slices of lists. Other ways of mutating lists, such as .append() are not assignments. As you note, we can also give a more "complete address" of a variable in a different scope. If m is a module "m.x = 5" means "The global variable x in module m should from now on point at the integer object 5". If m is a class or a function or an instance object, it would mean that "The attribute x of m should from now on point at the object 5". But there is no magic in this I think. (Can other objects than classes, instances and functions have attributes?) Your code above is not really different than writing. >>> class xx(list): pass >>> a = xx(['1','2','3']) >>> a ['1', '2', '3'] >>> b = a >>> b = [] >>> a ['1', '2', '3'] >>> Or to make it simpler. >>> a = ['1','2','3'] >>> a ['1', '2', '3'] >>> b = a >>> b = [] >>> a ['1', '2', '3'] >>> The object that a variable (local or global or an attribute of some other object) pointed to before an assignment statement is not influenced be the assignment. To make it very brief: If we write... b = a b = () ...nothing will change in the object that variable a points to, and nothing will happen to the variable a. -- 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 ramrom@earthling.net Fri Jan 10 19:41:57 2003 From: ramrom@earthling.net (Bob Gailer) Date: Fri Jan 10 19:41:57 2003 Subject: Fwd: Re: [Tutor] instance variables and the instance dictionary In-Reply-To: <5.1.0.14.0.20030111004141.02cc1d50@www.thinkware.se> Message-ID: <5.2.0.9.0.20030110173836.034b3e68@66.28.54.253> --=======4ED11B0======= Content-Type: text/plain; x-avg-checked=avg-ok-64186D05; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 01:34 AM 1/11/2003 +0100, Magnus Lycka wrote: >> >>> class xx(list): >> def clear(self): >> self = [] >> print 'this is self', self >>Well... I don't know. The only problem with Bob's code is that he forgot >that "self" is just a local variable in the method, and that assignment >means that the local variable will "forget" it's previous value, and refer >to a new object. Yep; that's it! How easy to overlook the obvious. Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======4ED11B0======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-64186D05 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.438 / Virus Database: 246 - Release Date: 1/7/2003 --=======4ED11B0=======-- From magnus@thinkware.se Fri Jan 10 20:17:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Fri Jan 10 20:17:02 2003 Subject: Fwd: Re: [Tutor] instance variables and the instance dictionary In-Reply-To: <5.2.0.9.0.20030110173836.034b3e68@66.28.54.253> References: <5.1.0.14.0.20030111004141.02cc1d50@www.thinkware.se> Message-ID: <5.1.0.14.0.20030111021209.02cb6c88@www.thinkware.se> At 17:40 2003-01-10 -0700, Bob Gailer wrote: >Yep; that's it! How easy to overlook the obvious. It's always nice when we see that the pieces fall back into the places where we expect them to be, right? I was also a bit surprised before I understood the obvious... There are those who complain loudly over the explicit self in Python. In a way it feels a little low level, that you are aware of the implementation and can peek behind the curtains. But I feel that it's reassuring that things are very consistent. And the ability to peek behind the curtains is one of Pythons best features. There is a little shortcut for instance objects that call the methods defined in its class. Instead of calling x.__class__.clear(x) we can simply call x.clear() Otherwise there is basically no magic with classes. (Well, apart from the __magic__ methods.) Classes are just holders of the method code that will be available to instances created through their __init__ methods. -- 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 =?iso-8859-1?B?cHJvZw==?=" This is a multi-part message in MIME format. --_b94281bfc1e907ae765d3914b9e82207a Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: base64 SGkgYWxsLDxiciAvPg0KPGJyIC8+DQpJJ20gbGVhcm5pbmcgdG8gdXNlIHRoZSBTaW1wbGVQYXJz ZSBtb2R1bGU6PGJyIC8+DQpodHRwOi8vbWVtYmVycy5yb2dlcnMuY29tL21jZmxldGNoL3Byb2dy YW1taW5nL3NpbXBsZXBhcnNlL3NpbXBsZXBhcnNlLmh0bWw8YnIgLz4NCjxiciAvPg0KVGhlIG9i amVjdGl2ZSBpcyB0byBwYXJzZSBzb21ldGhpbmcgbGlrZSB0aGUgc2FtcGxlIHRleHQgKGF0dGFj aGVkIGluIHRoZSBlbmQgPGJyIC8+DQpvZiB0aGlzIG1zZyBhcyAndGVzdGRhdGEnKSBpbnRvIHNl Y3Rpb25zIGxpa2U6IDxiciAvPg0KPGJyIC8+DQpbIHsgJ0FVJzogJ3h4eHgnLCAnVEknOid4eHh4 JywgJ1NPJzoneHh4eCcsICdBQic6J3h4eHgnfSw8YnIgLz4NCiAgeyAnQVUnOiAneHh4eCcsICdU SSc6J3h4eHgnLCAnU08nOid4eHh4JywgJ0FCJzoneHh4eCd9LDxiciAvPg0KICB7ICdBVSc6ICd4 eHh4JywgJ1RJJzoneHh4eCcsICdTTyc6J3h4eHgnLCAnQUInOid4eHh4J30sPGJyIC8+DQogIC4u LjxiciAvPg0KXTxiciAvPg0KPGJyIC8+DQpGb3IgdGhpcyBwdXJwb3NlIEkgd3JvdGUgYSBkZWNs YXJhdGlvbiAoZm9yIHRoZSBTaW1wbGVQYXJzZSB0byB1c2UgdG8gcGFyc2UpIGFzPGJyIC8+DQpm b2xsb3dzOjxiciAvPg0KPGJyIC8+DQpkZWNsYXJhdGlvbj1yJycnPGJyIC8+DQpwYXBlcjEgICAg ICA6PSBbXHRcbl0qLCBzZWN0aW9uKzxiciAvPg0Kc2VjdGlvbiAgICAgOj0gQVUsIFRJLCBTTywg QUI8YnIgLz4NCkFVICAgICAgICAgIDo9ICdBVSAnLCBub25hbGw8YnIgLz4NClRJICAgICAgICAg IDo9ICdUSSAnLCBub25hbGw8YnIgLz4NClNPICAgICAgICAgIDo9ICdTTyAnLCBub25hbGw8YnIg Lz4NCkFCICAgICAgICAgIDo9ICdBQiAnLCBub25hbGw8YnIgLz4NCmFsbCAgICAgICAgIDo9IGNo YXIvbnVtYmVyL3N0cmluZy9lc2NhcGVkY2hhcjxiciAvPg0Kbm9uYWxsICAgICAgOj0gLSgnQVUg Jy8nVEkgJy8nU08gJy8nQUIgJykqPGJyIC8+DQpjaGFyICAgICAgICA6PSAgLVtcMTM0JnF1b3Q7 XSs8YnIgLz4NCm51bWJlciAgICAgIDo9ICBbMC05ZUUrLi1dKzxiciAvPg0Kc3RyaW5nICAgICAg Oj0gIChjaGFyL2VzY2FwZWRjaGFyKSo8YnIgLz4NCmVzY2FwZWRjaGFyIDo9ICAnXDEzNCZxdW90 OycgLyAnXDEzNFwxMzQnPGJyIC8+DQonJyc8YnIgLz4NCjxiciAvPg0KV2l0aCB0aGUgZm9sbG93 aW5nIGxpbmVzIG9mIGNvZGU6PGJyIC8+DQo8YnIgLz4NCiM9PT09PT09PT09PT09PT09PT09PT09 PT09PT0gY29kZSBzdGFydHMgPT09PT09PGJyIC8+DQo8YnIgLz4NCmltcG9ydCBwcHJpbnQ8YnIg Lz4NCmZyb20gc2ltcGxlcGFyc2UgaW1wb3J0IGdlbmVyYXRvcjxiciAvPg0KdHJ5OjxiciAvPg0K CWZyb20gVGV4dFRvb2xzIGltcG9ydCBUZXh0VG9vbHM8YnIgLz4NCmV4Y2VwdCBJbXBvcnRFcnJv cjo8YnIgLz4NCglmcm9tIG14LlRleHRUb29scyBpbXBvcnQgVGV4dFRvb2xzPGJyIC8+DQo8YnIg Lz4NCnBhcnNlciA9IGdlbmVyYXRvci5idWlsZFBhcnNlciggZGVjbGFyYXRpb24gKS5wYXJzZXJi eW5hbWUoICdwYXBlcjEnKTxiciAvPg0KcHByaW50LnBwcmludCggVGV4dFRvb2xzLnRhZyggdGVz dGRhdGEsIHBhcnNlciApKTxiciAvPg0KPGJyIC8+DQojPT09PT09PT09PT09PT09PT09PT09PT09 PT09IGNvZGUgZW5kcyA9PT09PT09PGJyIC8+DQo8YnIgLz4NCml0IGRpZCBwYXJzZSB0aGUgdGVz dGRhdGEgdGV4dCBzdWNjZXNzZnVsbHkuIFRoZSBTaW1wbGVQYXJzZSB1c2VzPGJyIC8+DQp0aGUg ZGVmaW5pdGlvbiBpbiB0aGUgZGVjbGFyYXRpb246IEFVLCBUSSwgQUIgYW5kIFNPIHRvIGxvb2sg Zm9yIHRoZTxiciAvPg0KY29ycmVzcG9uZGluZyB0ZXh0IHRvIHBlcmZvcm0gdGhlIHBhcnNpbmcu IDxiciAvPg0KPGJyIC8+DQpOb3RpY2UgdGhhdCB0aGUgc3RyaW5nIHRvIGJlIG1hdGNoLCAnQVUn LCAnVEknLCAnQUInLCBTTycgYXJlIGluIHRoZSA8YnIgLz4NCmJlZ2lubmluZyBvZiB0aGUgbGlu ZS4gVGhpcyBpcyB0aGUgY3JpdGVyaWEgZm9yIHRoZW0gdG8gYmUgdGhlIHN0YXJ0aW5nPGJyIC8+ DQpwb2ludCBvZiBlYWNoIHN1YnNlY3Rpb24uIDxiciAvPg0KPGJyIC8+DQpJZiBhbnkgb2YgdGhl bSBhcmUgaW5zaWRlIHRleHRib2R5IGJ1dCBub3QgaW4gdGhlIGJlZ2lubmluZyBvZiBsaW5lLDxi ciAvPg0KdGhlbiB0aGV5IFNIT1VMRE4nVCBiZSBtYXRjaGVkLiBIb3dldmVyLCB0aGUgZGVjbGFy YXRpb24gdGhhdDxiciAvPg0KSSB3cm90ZSBjYW4ndCB0ZWxsIGlmIHRoZSBmb3VuZCBzdHJpbmcg aXMgaW4gdGhlIGJlZ2lubmlnIG9mIGxpbmUuPGJyIC8+DQo8YnIgLz4NClNvIHRoZSBxdWVzdGlv biBpczogaG93IHRvIHdyaXRlIGEgZGVjbGFyYXRpb24gdG8gaWRlbnRpZnkgYW5kIG1hdGNoPGJy IC8+DQpzb21lIHN0cmluZyBpbiB0aGUgYmVnaW5uaW5nIG9mIGxpbmUgYnV0IG5vdCBpbiB0aGUg dGV4dCBib2R5PzxiciAvPg0KPGJyIC8+DQpwYW48YnIgLz4NCjxiciAvPg0KPGJyIC8+DQp0ZXN0 ZGF0YT0nJyc8YnIgLz4NCkFVIENoZW4gSmlxaXU7ICBLdWhsZW5jb3JkdCBQZXRlciBKOyAgQXN0 ZXJuIEpvc2h1YTsgIEd5dXJrbyBSb2JlcnQ7ICBIdWFuZyBQYXVsPGJyIC8+DQogICBMIFthXS48 YnIgLz4NClRJIEh5cGVydGVuc2lvbiBkb2VzIG5vdCBhY2NvdW50IGZvciB0aGUgYWNjZWxlcmF0 ZWQgYXRoZXJvc2NsZXJvc2lzIGFuZDxiciAvPg0KICAgZGV2ZWxvcG1lbnQgb2YgYW5ldXJ5c21z IGluIG1hbGUgYXBvbGlwb3Byb3RlaW4gRS9lbmRvdGhlbGlhbCBuaXRyaWMgb3hpZGU8YnIgLz4N CiAgIHN5bnRoYXNlIGRvdWJsZSBrbm9ja291dCBtaWNlLjxiciAvPg0KU08gQ2lyY3VsYXRpb24u IFtwcmludF0gMTA0KDIwKS4gTm92ZW1iZXIgMTMsIDIwMDEuIDIzOTEtMjM5NC4gIDxiciAvPg0K QUIgQmFja2dyb3VuZDogQXBvbGlwb3Byb3RlaW4gRSAoYXBvRSkvZW5kb3RoZWxpYWwgbml0cmlj IG94aWRlIHN5bnRoYXNlIChlTk9TKTxiciAvPg0KICAgZG91YmxlIGtub2Nrb3V0IChES08pIG1p Y2UgPGJyIC8+DQo8YnIgLz4NCkFVIFdoaXRlIFRob21hcyBXIFthXTsgIFNlbGxpdHRvIENhdGVy aW5hOyAgUGF1bCBEYXZpZCBMOyAgR29vZGVub3VnaCBEYW5pZWw8YnIgLz4NCiAgIEEuPGJyIC8+ DQpUSSBQcmVuYXRhbCBsZW5zIGRldmVsb3BtZW50IGluIGNvbm5leGluNDMgYW5kIGNvbm5leGlu NTAgZG91YmxlIGtub2Nrb3V0PGJyIC8+DQogICBtaWNlLjxiciAvPg0KU08gSW92cy4gW3ByaW50 XSA0MigxMikuIE5vdmVtYmVyLCAyMDAxLiAyOTE2LTI5MjMuICA8YnIgLz4NCkFCIFB1cnBvc2Uu IFRvIGRldGVybWluZSB0aGUgcm9sZXMgb2YgaW50ZXJjZWxsdWxhciBjb21tdW5pY2F0aW9uIGlu IGVtYnJ5b25pYzxiciAvPg0KICAgZXllIGdyb3d0aCBhbmQgZGV2ZWxvcG1lbnQsIG1pY2Ugd2l0 aCBhIHRhcmdldGVkIGRlbGV0aW9uIG9mIHRoZSBDeDQzIGdlbmUgd2VyZTxiciAvPg0KICAgZXhh bWluZWQ8YnIgLz4NCicnJzxiciAvPg0KPGJyIC8+DQoK --_b94281bfc1e907ae765d3914b9e82207a Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: base64 PGh0bWw+CjxoZWFkPgo8bWV0YSBodHRwLWVxdWl2PSJDb250ZW50LVR5cGUiIGNvbnRlbnQ9InRl eHQvaHRtbDsgY2hhcnNldD1pc28tODg1OS0xIj4KPC9oZWFkPgo8Ym9keT4KSGkgYWxsLDxiciAv Pg0KPGJyIC8+DQpJJ20gbGVhcm5pbmcgdG8gdXNlIHRoZSBTaW1wbGVQYXJzZSBtb2R1bGU6PGJy IC8+DQpodHRwOi8vbWVtYmVycy5yb2dlcnMuY29tL21jZmxldGNoL3Byb2dyYW1taW5nL3NpbXBs ZXBhcnNlL3NpbXBsZXBhcnNlLmh0bWw8YnIgLz4NCjxiciAvPg0KVGhlIG9iamVjdGl2ZSBpcyB0 byBwYXJzZSBzb21ldGhpbmcgbGlrZSB0aGUgc2FtcGxlIHRleHQgKGF0dGFjaGVkIGluIHRoZSBl bmQgPGJyIC8+DQpvZiB0aGlzIG1zZyBhcyAndGVzdGRhdGEnKSBpbnRvIHNlY3Rpb25zIGxpa2U6 IDxiciAvPg0KPGJyIC8+DQpbIHsgJ0FVJzogJ3h4eHgnLCAnVEknOid4eHh4JywgJ1NPJzoneHh4 eCcsICdBQic6J3h4eHgnfSw8YnIgLz4NCiAgeyAnQVUnOiAneHh4eCcsICdUSSc6J3h4eHgnLCAn U08nOid4eHh4JywgJ0FCJzoneHh4eCd9LDxiciAvPg0KICB7ICdBVSc6ICd4eHh4JywgJ1RJJzon eHh4eCcsICdTTyc6J3h4eHgnLCAnQUInOid4eHh4J30sPGJyIC8+DQogIC4uLjxiciAvPg0KXTxi ciAvPg0KPGJyIC8+DQpGb3IgdGhpcyBwdXJwb3NlIEkgd3JvdGUgYSBkZWNsYXJhdGlvbiAoZm9y IHRoZSBTaW1wbGVQYXJzZSB0byB1c2UgdG8gcGFyc2UpIGFzPGJyIC8+DQpmb2xsb3dzOjxiciAv Pg0KPGJyIC8+DQpkZWNsYXJhdGlvbj1yJycnPGJyIC8+DQpwYXBlcjEgICAgICA6PSBbdG5dKiwg c2VjdGlvbis8YnIgLz4NCnNlY3Rpb24gICAgIDo9IEFVLCBUSSwgU08sIEFCPGJyIC8+DQpBVSAg ICAgICAgICA6PSAnQVUgJywgbm9uYWxsPGJyIC8+DQpUSSAgICAgICAgICA6PSAnVEkgJywgbm9u YWxsPGJyIC8+DQpTTyAgICAgICAgICA6PSAnU08gJywgbm9uYWxsPGJyIC8+DQpBQiAgICAgICAg ICA6PSAnQUIgJywgbm9uYWxsPGJyIC8+DQphbGwgICAgICAgICA6PSBjaGFyL251bWJlci9zdHJp bmcvZXNjYXBlZGNoYXI8YnIgLz4NCm5vbmFsbCAgICAgIDo9IC0oJ0FVICcvJ1RJICcvJ1NPICcv J0FCICcpKjxiciAvPg0KY2hhciAgICAgICAgOj0gIC1bMTM0JnF1b3Q7XSs8YnIgLz4NCm51bWJl ciAgICAgIDo9ICBbMC05ZUUrLi1dKzxiciAvPg0Kc3RyaW5nICAgICAgOj0gIChjaGFyL2VzY2Fw ZWRjaGFyKSo8YnIgLz4NCmVzY2FwZWRjaGFyIDo9ICAnMTM0JnF1b3Q7JyAvICcxMzQxMzQnPGJy IC8+DQonJyc8YnIgLz4NCjxiciAvPg0KV2l0aCB0aGUgZm9sbG93aW5nIGxpbmVzIG9mIGNvZGU6 PGJyIC8+DQo8YnIgLz4NCiM9PT09PT09PT09PT09PT09PT09PT09PT09PT0gY29kZSBzdGFydHMg PT09PT09PGJyIC8+DQo8YnIgLz4NCmltcG9ydCBwcHJpbnQ8YnIgLz4NCmZyb20gc2ltcGxlcGFy c2UgaW1wb3J0IGdlbmVyYXRvcjxiciAvPg0KdHJ5OjxiciAvPg0KCWZyb20gVGV4dFRvb2xzIGlt cG9ydCBUZXh0VG9vbHM8YnIgLz4NCmV4Y2VwdCBJbXBvcnRFcnJvcjo8YnIgLz4NCglmcm9tIG14 LlRleHRUb29scyBpbXBvcnQgVGV4dFRvb2xzPGJyIC8+DQo8YnIgLz4NCnBhcnNlciA9IGdlbmVy YXRvci5idWlsZFBhcnNlciggZGVjbGFyYXRpb24gKS5wYXJzZXJieW5hbWUoICdwYXBlcjEnKTxi ciAvPg0KcHByaW50LnBwcmludCggVGV4dFRvb2xzLnRhZyggdGVzdGRhdGEsIHBhcnNlciApKTxi ciAvPg0KPGJyIC8+DQojPT09PT09PT09PT09PT09PT09PT09PT09PT09IGNvZGUgZW5kcyA9PT09 PT09PGJyIC8+DQo8YnIgLz4NCml0IGRpZCBwYXJzZSB0aGUgdGVzdGRhdGEgdGV4dCBzdWNjZXNz ZnVsbHkuIFRoZSBTaW1wbGVQYXJzZSB1c2VzPGJyIC8+DQp0aGUgZGVmaW5pdGlvbiBpbiB0aGUg ZGVjbGFyYXRpb246IEFVLCBUSSwgQUIgYW5kIFNPIHRvIGxvb2sgZm9yIHRoZTxiciAvPg0KY29y cmVzcG9uZGluZyB0ZXh0IHRvIHBlcmZvcm0gdGhlIHBhcnNpbmcuIDxiciAvPg0KPGJyIC8+DQpO b3RpY2UgdGhhdCB0aGUgc3RyaW5nIHRvIGJlIG1hdGNoLCAnQVUnLCAnVEknLCAnQUInLCBTTycg YXJlIGluIHRoZSA8YnIgLz4NCmJlZ2lubmluZyBvZiB0aGUgbGluZS4gVGhpcyBpcyB0aGUgY3Jp dGVyaWEgZm9yIHRoZW0gdG8gYmUgdGhlIHN0YXJ0aW5nPGJyIC8+DQpwb2ludCBvZiBlYWNoIHN1 YnNlY3Rpb24uIDxiciAvPg0KPGJyIC8+DQpJZiBhbnkgb2YgdGhlbSBhcmUgaW5zaWRlIHRleHRi b2R5IGJ1dCBub3QgaW4gdGhlIGJlZ2lubmluZyBvZiBsaW5lLDxiciAvPg0KdGhlbiB0aGV5IFNI T1VMRE4nVCBiZSBtYXRjaGVkLiBIb3dldmVyLCB0aGUgZGVjbGFyYXRpb24gdGhhdDxiciAvPg0K SSB3cm90ZSBjYW4ndCB0ZWxsIGlmIHRoZSBmb3VuZCBzdHJpbmcgaXMgaW4gdGhlIGJlZ2lubmln IG9mIGxpbmUuPGJyIC8+DQo8YnIgLz4NClNvIHRoZSBxdWVzdGlvbiBpczogaG93IHRvIHdyaXRl IGEgZGVjbGFyYXRpb24gdG8gaWRlbnRpZnkgYW5kIG1hdGNoPGJyIC8+DQpzb21lIHN0cmluZyBp biB0aGUgYmVnaW5uaW5nIG9mIGxpbmUgYnV0IG5vdCBpbiB0aGUgdGV4dCBib2R5PzxiciAvPg0K PGJyIC8+DQpwYW48YnIgLz4NCjxiciAvPg0KPGJyIC8+DQp0ZXN0ZGF0YT0nJyc8YnIgLz4NCkFV IENoZW4gSmlxaXU7ICBLdWhsZW5jb3JkdCBQZXRlciBKOyAgQXN0ZXJuIEpvc2h1YTsgIEd5dXJr byBSb2JlcnQ7ICBIdWFuZyBQYXVsPGJyIC8+DQogICBMIFthXS48YnIgLz4NClRJIEh5cGVydGVu c2lvbiBkb2VzIG5vdCBhY2NvdW50IGZvciB0aGUgYWNjZWxlcmF0ZWQgYXRoZXJvc2NsZXJvc2lz IGFuZDxiciAvPg0KICAgZGV2ZWxvcG1lbnQgb2YgYW5ldXJ5c21zIGluIG1hbGUgYXBvbGlwb3By b3RlaW4gRS9lbmRvdGhlbGlhbCBuaXRyaWMgb3hpZGU8YnIgLz4NCiAgIHN5bnRoYXNlIGRvdWJs ZSBrbm9ja291dCBtaWNlLjxiciAvPg0KU08gQ2lyY3VsYXRpb24uIFtwcmludF0gMTA0KDIwKS4g Tm92ZW1iZXIgMTMsIDIwMDEuIDIzOTEtMjM5NC4gIDxiciAvPg0KQUIgQmFja2dyb3VuZDogQXBv bGlwb3Byb3RlaW4gRSAoYXBvRSkvZW5kb3RoZWxpYWwgbml0cmljIG94aWRlIHN5bnRoYXNlIChl Tk9TKTxiciAvPg0KICAgZG91YmxlIGtub2Nrb3V0IChES08pIG1pY2UgPGJyIC8+DQo8YnIgLz4N CkFVIFdoaXRlIFRob21hcyBXIFthXTsgIFNlbGxpdHRvIENhdGVyaW5hOyAgUGF1bCBEYXZpZCBM OyAgR29vZGVub3VnaCBEYW5pZWw8YnIgLz4NCiAgIEEuPGJyIC8+DQpUSSBQcmVuYXRhbCBsZW5z IGRldmVsb3BtZW50IGluIGNvbm5leGluNDMgYW5kIGNvbm5leGluNTAgZG91YmxlIGtub2Nrb3V0 PGJyIC8+DQogICBtaWNlLjxiciAvPg0KU08gSW92cy4gW3ByaW50XSA0MigxMikuIE5vdmVtYmVy LCAyMDAxLiAyOTE2LTI5MjMuICA8YnIgLz4NCkFCIFB1cnBvc2UuIFRvIGRldGVybWluZSB0aGUg cm9sZXMgb2YgaW50ZXJjZWxsdWxhciBjb21tdW5pY2F0aW9uIGluIGVtYnJ5b25pYzxiciAvPg0K ICAgZXllIGdyb3d0aCBhbmQgZGV2ZWxvcG1lbnQsIG1pY2Ugd2l0aCBhIHRhcmdldGVkIGRlbGV0 aW9uIG9mIHRoZSBDeDQzIGdlbmUgd2VyZTxiciAvPg0KICAgZXhhbWluZWQ8YnIgLz4NCicnJzxi ciAvPg0KPGJyIC8+DQoKPC9ib2R5PjwvaHRtbD4K --_b94281bfc1e907ae765d3914b9e82207a-- From antoneheyward@hotmail.com Fri Jan 10 22:35:01 2003 From: antoneheyward@hotmail.com (antone heyward) Date: Fri Jan 10 22:35:01 2003 Subject: [Tutor] process bar Message-ID: Is there a process\statusbar widget for tkinter? If there is where can i get some sample code on how to use it. _________________________________________________________________ Help STOP SPAM: Try the new MSN 8 and get 2 months FREE* http://join.msn.com/?page=features/junkmail From dyoo@hkn.eecs.berkeley.edu Sat Jan 11 03:07:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Jan 11 03:07:01 2003 Subject: [Tutor] please help! [tell us more about your programming experience] In-Reply-To: <20030110103909.15328.qmail@web40407.mail.yahoo.com> Message-ID: On Fri, 10 Jan 2003, [iso-8859-1] geraldine lynch wrote: > How do I sum all the elements of an array? I mean, is there a Capital > sigma function? [some text cut] > I'm quite new to python and have to write a program before my uni term > restarts so i dont have very long! Hi Geraldine, It looks like you received a few answers to your question already, so I can't add anything to it. However, when you ask a question like this, it's helpful for us on the Tutor list to know what background you already have in Python; being a "beginner" can mean several different things. With more information, we can point you toward resources that will help you learn Python more effectively. Otherwise, if we fly blind, we can end up just giving you a textbook "answer" that doesn't really get to the heart of what you really want to know or what you're having difficulty with. Since you mentioned the Sigma function, it sounds like you already have some background in math notation, and we have to assume for the moment that you've started to take some programming classes at some university. But the question that you asked is often classified as an introductory programming exercise on loops... and that's something that, honestly speaking, is a little worrying: it means that you might need some practice so you feel more comfortable with the material. What part did you get stuck on when you tried solving this summation problem? What ideas did you try? What material did you already know? If you're trying to learn Python quickly, you may find the Newcomers Page to Python useful: http://python.org/doc/Newbies.html You should be able to quickly pick up the language if you go through a few of the tutorials there. If you have particular questions on any tutorial, please feel free to ask questions on Tutor; we'll be happy to respond. Good luck to you. From dyoo@hkn.eecs.berkeley.edu Sat Jan 11 03:11:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Jan 11 03:11:01 2003 Subject: [Tutor] Upgrading of python 2.2.2 on RedHat 8.0 In-Reply-To: <1042160300.3010.4.camel@kniep04.kniep> Message-ID: On 10 Jan 2003, Dick Kniep wrote: > Hi there, > > I am facing problems with upgrading the standard installation of Python > 2.2.1 of RedHat 8 to Python 2.2.2. When I install it "according to the > book", it places all files in usr/local/lib, whereas RedHat expects them > in usr/lib. I haven't seen any RPM's for Redhat 8 (only for older > versions) Hi Dick, Yes, Python 2.2.2 is in Rawhide and the Redhat 8.1 beta, but it's not in the standard distribution of Redhat 8 yet; I think Redhat's still testing for compatibility with their own administrative scripts. However, it's perfectly ok to have Python installed in /usr/local/bin; you just have to make sure that you either explicitely type /usr/local/bin/python whenever you use Python, or that you place /usr/local/bin in your PATH with higher priority than /usr/bin. Would this work for you? Good luck to you! From dyoo@hkn.eecs.berkeley.edu Sat Jan 11 03:59:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Jan 11 03:59:02 2003 Subject: [Tutor] Calculating a math formula and finding errors In-Reply-To: Message-ID: Hi Jens, Good grief, this looks like something out of Concrete Mathematics! http://www-cs-faculty.stanford.edu/~knuth/gkp.html Wow. *grin* I've looked at the equation that you've listed. I agree with the marginal note, because otherwise it makes no sense to iterate through 'j' on the left hand side of the equation unless 'j' is being used somewhere. I don't think it's just a "possibility": i'm almost positively sure the equation is wrong. That is, if 'j' weren't being used, we could simplify the inner loop by just multiplying the whole darn expression by 'n' and be done with it, without going through the pretensions of doing an iteration. So I'll assume that someone mistyped the equation in LaTeX. *grin* The equation also doesn't quite make sense until we qualify the domain of 'n'. What happens if n=0 on the left hand side of the equation? For what values of 'n' should we be able to trust this equation? On Fri, 10 Jan 2003, Michael Janssen wrote: > > def facul(z): > > if z ==1: > > return 1 > > else: > > return z*facul(z-1) This looks like the factorial function, z!, that pops up in a lot of combinatorial math. The definition above, though, doesn't define 0!: you may want to change the base case of the recursion here so that 0! works. > > def perm(x,y): > > w = 1 > > for i in range(y+1,x+1): > > w = w * i > > return w/facul(x-y) > Would you give us some hints what's this formular is about? I havn't found > it on the webside. What does "perm" stands for? I'm not quite sure I understand the perm() function yet either... give me a moment... Let me plug in a value or two and trace the computation in my head... perm(5, 2) = 3 * 4 * 5 / (3!) = 5 * 4 / (2!) = 5! / (3! * 2!) Hmmm... Is this the choosing operation? I remember that (n choose k) = n! / (k!)(n-k)! from a math class a while back. Let me try another set of values... perm(10, 3) = 4 * 5 * 6 * 7 * 8 * 9 * 10 / (7!) = 10! / (7! * 3!) Ok, I understand now; perm(n, k) stands for the mathematical operation of how many ways we can choose k items out of a collection on n. Beware: your function is broken on perm(n,n) unless you fix facul(0). Furthermore, your choise of the name 'perm' may confuse some folks, as it suggests a "permutation of k objects out of n", which is not what the function is doing. I'd recommend renaming this function quick before it confuses anyone else. *grin* > > def MBrechts(n): > > b=0 > > for i in range(0,n): > > for j in range(0,n-i): > > betrag = n + 1 - (2*i) - (2*j) > > if betrag < 0: > > betrag = betrag * -1 > > prod = betrag * perm(n-i,j) The statements: > > betrag = n + 1 - (2*i) - (2*j) > > if betrag < 0: > > betrag = betrag * -1 can be rewritten by using the abs() absolute value function that Python provides. Let's revise MBrecths(n) to use abs(): ### def MBrechts(n): b=0 for i in range(0,n): for j in range(0,n-i): betrag = abs(n + 1 - (2*i) - (2*j)) prod = betrag * perm(n-i,j) b = b + prod return b ### The calculation of the betrag variable doesn't follow the expression that I'm reading from the PDF document. Are you sure that it's not: abs(n+1 - 2*(i+1)) instead? The PDF document you pointed us to uses '1' in place of 'i' in several places of the equation, so there's something screwy going on here. Can you clarify which is correct? Good luck! From johnca@ourpla.net Sat Jan 11 08:21:28 2003 From: johnca@ourpla.net (John Abbe) Date: Sat Jan 11 08:21:28 2003 Subject: [Tutor] A little security In-Reply-To: References: Message-ID: I've asked this twice now and gotten no replies. Am i running afoul of some rule, or just slipping through the cracks, or ... ? Thanks! Life, John At 12:59 PM +0630 on 2003-01-08, John Abbe typed: >Aksed before, but no answer, so: > >I'm working on a Python CGI using passwords, which for now i've >implemented in a field that gets sent with the GET method. This is >obviously insecure. I'm guessing that https might be the simplest >way to add security, but am very open to any suggestions. > >If it is to be https, i'd love to hear about any simpler ways to use >it than the stuff pointed at by this news thread: > >http://groups.google.com/groups?frame=left&th=3ad2d5de60bb5f05 -- All you /\/\ John Abbe "If you don't like the news, need \ / CatHerder go out and make some of your own." is... \/ http://ourpla.net/john/ --Wes Nisker From ramrom@earthling.net Sat Jan 11 10:37:01 2003 From: ramrom@earthling.net (Bob Gailer) Date: Sat Jan 11 10:37:01 2003 Subject: [Tutor] A little security In-Reply-To: References: Message-ID: <5.2.0.9.0.20030111083547.01a17600@66.28.54.253> --=======7B41588F======= Content-Type: text/plain; x-avg-checked=avg-ok-490F7F5A; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 07:18 PM 1/11/2003 +0630, John Abbe wrote: >I've asked this twice now and gotten no replies. Am i running afoul of >some rule, or just slipping through the cracks, or ... ? I, for one, have not responded, due to total lack of ability to help you. Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======7B41588F======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-490F7F5A Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.438 / Virus Database: 246 - Release Date: 1/7/2003 --=======7B41588F=======-- From Don Arnold" <5.1.0.14.0.20030110124632.02c9dcc8@www.thinkware.se> Message-ID: <060801c2b990$173b8100$ea10ba3f@defaultcomp> ----- Original Message ----- From: "Magnus Lycka" To: "Gregor Lingl" ; "geraldine lynch" Cc: Sent: Friday, January 10, 2003 6:10 AM Subject: Re: [Tutor] please help! > > >geraldine lynch schrieb: > >>How do I sum all the elements of an array? ... > > I'm assuming that "array" is a sequence (list or tuple) > of numbers of some kind... > > "sum(array)" would seem like a reasonable approach, > right? That's what I would do. You would have to > define the sum function first, but that is fairly > trivial. > > At 11:50 2003-01-10 +0100, Gregor Lingl wrote: > >you can use the builtin function reduce for this ... > > But a more conventional solution would be > > def sum(array): > s = 0 > for element in array: > s = s + element > return s > > Performance is roughly the same, and you don't need to introduce > any concepts that might be unknown to other programmers. Everybody > who has some basic understanding of Python understands those five > lines of code, and it reads more or less like English. > > operator.add(1,2) is probably less obvious than 1 + 2, and > reduce, filter and map are confusing to many programmers. > > "s = s + element" can be replaced with the shorter form > "s += element" if you prefer to type a little less... > > A sum function is certainly a reasonable thing to have in one's > tool box. Like the builtins min and max, it might be a good thing > if it can also handle things like "sum(1,2,3)". > > Let's see... > > >>> def sum(*args): > ... sum = 0 > ... for arg in args: > ... if hasattr(arg, '__len__'): > ... for x in arg: > ... sum += x > ... else: > ... sum += arg > ... return sum > ... > >>> sum(1,2,3) > 6 > >>> sum([1,2,3]) > 6 > >>> sum([1,2,3],4,(5,6)) > 21 > > Notice that this doesn't work like the builtin min and max. > They won't treat the third case like our sum does. Also note > that while we can sum all elements of several sequences, we > won't follow structures further. > But with just a little recursion, we can sum nested lists that are nested arbitrarilly deep: >>> def sum(*args): total = 0 for arg in args: print 'summing', arg if type(arg) in (list,tuple): for item in arg: total += sum(item) else: total += arg return total >>> sum(1,(2,(3,[4,8],(5,6)),7)) summing 1 summing (2, (3, [4, 8], (5, 6)), 7) summing 2 summing (3, [4, 8], (5, 6)) summing 3 summing [4, 8] summing 4 summing 8 summing (5, 6) summing 5 summing 6 summing 7 36 Don From francois.granger@free.fr Sat Jan 11 12:25:02 2003 From: francois.granger@free.fr (=?iso-8859-1?Q?Fran=E7ois?= Granger) Date: Sat Jan 11 12:25:02 2003 Subject: [Tutor] SimpleParse: how to identify the beginning of a line In-Reply-To: <20030111013406.13814.qmail@station172.com> References: <20030111013406.13814.qmail@station172.com> Message-ID: (I know nothing about this module... but...) A t 01:34 +0100 11/01/2003, in message [Tutor] SimpleParse: how to identify the beginning of a, prog wrote: >declaration=r''' >paper1 := [tn]*, section+ >section := AU, TI, SO, AB >AU := 'AU ', nonall >TI := 'TI ', nonall >SO := 'SO ', nonall >AB := 'AB ', nonall >all := char/number/string/escapedchar >nonall := -('AU '/'TI '/'SO '/'AB ')* >char := -[134"]+ >number := [0-9eE+.-]+ >string := (char/escapedchar)* >escapedchar := '134"' / '134134' What if you replace this line: >AU := 'AU ', nonall by: >AU := '\nAU ', nonall And then reuse these defs in the line >nonall := -('AU '/'TI '/'SO '/'AB ')* Making it: >nonall := -(AU/TI/SO/AB)* I don't know if this help. -- Recently using MacOSX....... From magnus@thinkware.se Sat Jan 11 12:44:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Sat Jan 11 12:44:01 2003 Subject: [Tutor] please help! In-Reply-To: <060801c2b990$173b8100$ea10ba3f@defaultcomp> References: <20030110103909.15328.qmail@web40407.mail.yahoo.com> <5.1.0.14.0.20030110124632.02c9dcc8@www.thinkware.se> Message-ID: <5.1.0.14.0.20030111184654.02c19d70@www.thinkware.se> At 10:39 2003-01-11 -0600, Don Arnold wrote: > if type(arg) in (list,tuple): I avoided this construct and checked whether the object had a __len__ atribute instead. My thought was that it would be good if it worked also with classes that act like sequences 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 antoneheyward@hotmail.com Sat Jan 11 13:04:05 2003 From: antoneheyward@hotmail.com (antone heyward) Date: Sat Jan 11 13:04:05 2003 Subject: [Tutor] process and progress bar Message-ID: I am running a command with popen or win32, which ever would be better for this situation, and have a progress bar going as the process is running. How do i link the two together and whats the best way to do this. This is under windows. _________________________________________________________________ MSN 8 helps eliminate e-mail viruses. Get 2 months FREE* http://join.msn.com/?page=features/virus From john@hazen.net Sat Jan 11 16:22:02 2003 From: john@hazen.net (John Hazen) Date: Sat Jan 11 16:22:02 2003 Subject: [Tutor] A little security In-Reply-To: Message-ID: Hmm, given that you specify that you're writing a CGI, it's possible that noone has offered help because this is not a python issue. The thread you referenced was about implementing a HTTPS *server*, not a CGI. So, yes. There is an easier solution. You need to configure your *web server* (not your python CGI) to support SSL. Your CGI will not need to be modified. But, we don't know what server software you are using, so can't help there. (And it's beyond the scope of this list.) However, a quick googling yields these (possibly helpful) links: http://www.tldp.org/HOWTO/SSL-Certificates-HOWTO/ http://en.tldp.org/HOWTO/SSL-RedHat-HOWTO.html http://tud.at/programm/apache-ssl-win32-howto.php3 Good luck! -John On Sat, 11 Jan 2003, John Abbe wrote: > I've asked this twice now and gotten no replies. Am i running afoul > of some rule, or just slipping through the cracks, or ... ? > > Thanks! Life, > John > > At 12:59 PM +0630 on 2003-01-08, John Abbe typed: > >Aksed before, but no answer, so: > > > >I'm working on a Python CGI using passwords, which for now i've > >implemented in a field that gets sent with the GET method. This is > >obviously insecure. I'm guessing that https might be the simplest > >way to add security, but am very open to any suggestions. > > > >If it is to be https, i'd love to hear about any simpler ways to use > >it than the stuff pointed at by this news thread: > > > >http://groups.google.com/groups?frame=left&th=3ad2d5de60bb5f05 > > -- > All you /\/\ John Abbe "If you don't like the news, > need \ / CatHerder go out and make some of your own." > is... \/ http://ourpla.net/john/ --Wes Nisker > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- John Hazen john@hazen.net eFax: 801.697.4349 ---------------------------------------------------------------------- Positive: mistaken at the top of your voice. From Don Arnold" <5.1.0.14.0.20030110124632.02c9dcc8@www.thinkware.se> <5.1.0.14.0.20030111184654.02c19d70@www.thinkware.se> Message-ID: <063101c2b9b9$052dc850$ea10ba3f@defaultcomp> ----- Original Message ----- From: "Magnus Lycka" To: "Don Arnold" ; "Gregor Lingl" ; "geraldine lynch" Cc: Sent: Saturday, January 11, 2003 11:48 AM Subject: Re: [Tutor] please help! > At 10:39 2003-01-11 -0600, Don Arnold wrote: > > if type(arg) in (list,tuple): > > I avoided this construct and checked whether the object had a > __len__ atribute instead. My thought was that it would be good > if it worked also with classes that act like sequences 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 > Good point. I hadn't thought of that. Don From charlie@begeistert.org Sat Jan 11 18:44:01 2003 From: charlie@begeistert.org (Charlie Clark) Date: Sat Jan 11 18:44:01 2003 Subject: [Tutor] Re: A little more security In-Reply-To: <20030111164129.17352.51137.Mailman@mail.python.org> References: <20030111164129.17352.51137.Mailman@mail.python.org> Message-ID: <20030112004635.371.1@.1042328076.fake> > > At 12:59 PM +0630 on 2003-01-08, John Abbe typed: > >Aksed before, but no answer, so: > > > >I'm working on a Python CGI using passwords, which for now i've > >implemented in a field that gets sent with the GET method. This is > >obviously insecure. I'm guessing that https might be the simplest way to > >add security, but am very open to any suggestions. > > > >If it is to be https, i'd love to hear about any simpler ways to use it > >than the stuff pointed at by this news thread: Hi John, the thread you point to deals with implementing an https server in Python but you shouldn't need to do that if you are writing a cgi program because cgi is on "the other side" of the web server. https occurs between browser and webserver, the web server should pass on the values unencrypted to the cgi-program. If you want to operate without https you might want to use a javascript.encode call in the browser to encrypt the data. Charlie From dman@dman.ddts.net Sat Jan 11 18:54:03 2003 From: dman@dman.ddts.net (Derrick 'dman' Hudson) Date: Sat Jan 11 18:54:03 2003 Subject: [Tutor] Re: replace windows quote In-Reply-To: <20030110122536.GA1097@burma> References: <20020921033729.GA8491@isis.visi.com> <017a01c26123$45270550$c009ba3f@defaultcomp> <20030110122536.GA1097@burma> Message-ID: <20030111235345.GB20973@dman.ddts.net> --WhfpMioaduB5tiZL Content-Type: text/plain; charset=iso-8859-1 Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Fri, Jan 10, 2003 at 01:25:36PM +0100, Pietro Ciuffo wrote: | Hi all. | I have to replace - inside a text file - a quote inserted | by Word X Windows with a simple plain quote. | The problem is to match the 'Win' quote: if I open the file in vim, I | see a '~R' blue sign, if I do cat -A, the output is a 'M-^R' sign. | Anyone could help me? The "win" quote is encoded with CP1252 (a Microsoft non-standard character set). I belive the value of the left quote is 0xb3 and the right quote is 0xb2. (they appear as superscript 3 and 2 in my environment) Try this in vim (or the equivalent in python) : :%s/=B3/'/g (enter the "weird" character by typing ^Vxb3, ^V means hold control and press v) HTH, -D --=20 If anyone would come after me, he must deny himself and take up his cross and follow me. For whoever wants to save his life will lose it, but whoever loses his life for me and for the gospel will save it. What good is it for a man to gain the whole world, yet forfeit his soul? Or what can a man give in exchange for his soul? Mark 8:34-37 =20 http://dman.ddts.net/~dman/ --WhfpMioaduB5tiZL Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAj4grokACgkQO8l8XBKTpRSVQwCgoisoUUw3cZOAsWtJD7msrcBI NocAoKSPnEAQ29yk0z+lIzx2Xk/wsWUr =sik/ -----END PGP SIGNATURE----- --WhfpMioaduB5tiZL-- From beercanz@hotmail.com Sat Jan 11 19:25:05 2003 From: beercanz@hotmail.com (Guess Who? Me) Date: Sat Jan 11 19:25:05 2003 Subject: [Tutor] My code freezes python. :-) Message-ID: I got tired of asking questions about things in the tutorial, so I decided to try to make a program that uses a random number (function call, I think its called?) to roll a dice. I messed around with it for a while, and I got it to the point where it freezes IDLE when I try to run it. :-) Here it is. ************************ #Make use of a random number integer function to make a dice roll program import random print "Welcome to my dice roll program." value=0 rolls=input("How many rolls would you like to make?") sides=input("How many sides does your dice have?") def dice(number,sides): #number being the number of times you roll times=number total=0 while times > -1 : value==random.randint(0,sides) total=value+total times=times+1 return value dice(rolls,sides) **************************************** I would like to know what the major malfunction is (excuse me, where the major malfunctionS ARE.) Thank you, Travis _________________________________________________________________ The new MSN 8: smart spam protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From dman@dman.ddts.net Sat Jan 11 19:36:27 2003 From: dman@dman.ddts.net (Derrick 'dman' Hudson) Date: Sat Jan 11 19:36:27 2003 Subject: [Tutor] Re: My code freezes python. :-) In-Reply-To: References: Message-ID: <20030112003524.GA21802@dman.ddts.net> --3MwIy2ne0vdjdPXF Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Sun, Jan 12, 2003 at 12:22:33AM +0000, Guess Who? Me wrote: | I got tired of asking questions about things in the tutorial, so I decide= d=20 | to try to make a program that uses a random number (function call, I thin= k=20 | its called?) to roll a dice. I messed around with it for a while, and I g= ot=20 | it to the point where it freezes IDLE when I try to run it. :-) Here it i= s. It's not frozen. It's running, but not doing anything (apparently) useful. | while times > -1 : We stop when 'times' is less than or equal to -1. Presumably 'times' is initially a positive number. | times=3Dtimes+1 Here times is incremented. It gets larger. Since it started >-1, it is now moving farther away. This loop can never end. Change the line to times =3D times - 1 Since your program deals with user input, there is some more you should do : 1) what if the user says to roll the dice 0 times? -10 times? 2) what if the user says to roll 0 dice >0 times? How about if they say -4 dice? (Hint: check for conditions like that and print an appropriate error message instead) -D --=20 Stay away from a foolish man, for you will not find knowledge on his lips. Proverbs 14:7 =20 http://dman.ddts.net/~dman/ --3MwIy2ne0vdjdPXF Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAj4guEwACgkQO8l8XBKTpRQSkwCfcYn+BDmukpfzXziwkrKIHV67 00oAnj7exf6pthwayZvXDOiVo11GN6yi =y0nz -----END PGP SIGNATURE----- --3MwIy2ne0vdjdPXF-- From beercanz@hotmail.com Sat Jan 11 19:45:02 2003 From: beercanz@hotmail.com (Guess Who? Me) Date: Sat Jan 11 19:45:02 2003 Subject: [Tutor] Ammendment to the freezing program problem Message-ID: I just amended a few things, and revised the code, but now instead of freezing it just returns a 0 - I figured out it freezes if I unindent the 'return total) line. I know its returning a 0 because I've given 'total=0', but I'm stumpted (so far) as to how to make this thing return a value that adds the values of the random numbers. New (still no good) source ********* #Make use of a random number integer function to make a dice roll program import random print "Welcome to my dice roll program." value=0 rolls=input("How many rolls would you like to make?") sides=input("How many sides does your dice have?") def dice(number,sides): #number being the number of times you roll total=0 ## < - Think the problem's here but I don't know what to do while number > -1 : value==random.randint(0,sides) total=value+total number=number+1 return total print dice(rolls,sides) ************************** Thanks, and sorry for that last Email, I should have re-read my source another time. Travis _________________________________________________________________ MSN 8 with e-mail virus protection service: 2 months FREE* http://join.msn.com/?page=features/virus From beercanz@hotmail.com Sat Jan 11 19:50:01 2003 From: beercanz@hotmail.com (Guess Who? Me) Date: Sat Jan 11 19:50:01 2003 Subject: [Tutor] Fixed freezing problem, have new one Message-ID: Sorry! Something came to me and this is the new source: *************************************** #Make use of a random number integer function to make a dice roll program import random print "Welcome to my dice roll program." value=0 rolls=input("How many rolls would you like to make?") sides=input("How many sides does your dice have?") def dice(number,sides): #number being the number of times you roll while number > -1 : value=random.randint(0,sides) total=0 total=value+total number=number+1 return total,dice(number-2,sides) print dice(rolls,sides) *********************************** With a sample run being: Welcome to my dice roll program. How many rolls would you like to make?5 How many sides does your dice have?6 (1, (4, (1, (0, (1, (0, None)))))) I think the program's doing what I want! But not with the output I want. The number-2 thing isn't working too well either it was kind of improvised, any ideas on how to refine that, also? Thanks again, and sorry for the two previous emails from me because they are previous revisions of this one. (Redundency (sp?) is bad). Travis _________________________________________________________________ Help STOP SPAM: Try the new MSN 8 and get 2 months FREE* http://join.msn.com/?page=features/junkmail From dman@dman.ddts.net Sat Jan 11 20:05:02 2003 From: dman@dman.ddts.net (Derrick 'dman' Hudson) Date: Sat Jan 11 20:05:02 2003 Subject: [Tutor] Re: Fixed freezing problem, have new one In-Reply-To: References: Message-ID: <20030112010430.GA22024@dman.ddts.net> --lrZ03NoBR/3+SXJZ Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Sun, Jan 12, 2003 at 12:48:49AM +0000, Guess Who? Me wrote: First I notice you are starting to pick up on one error : | number=3Dnumber+1 ^^ | return total,dice(number-2,sides) ^^ Since you (incorrectly) incremented by one first, you have to decrement by two to compensate. The correction is to simply decrement by one in the first place. Second, note the overall structure of the loop : while [condition] : [something] return [value] It isn't really a loop, even though it is spelled like one. That code can equivalently be written as if [condition] :=20 [something] return [value] or if not [condition] : return None [something] return [value] | return total,dice(number-2,sides) ^ Next look at the type of data you are returning. It is a tuple consisting of the random number chosen and the results of the dice() function. Looking at the dice() function, it returns a tuple. So what you end up with is a tuple containing a number and a tuple (which contains a number and a tuple ...). Hence the output looking like : (1, (4, (1, (0, (1, (0, None)))))) ^^ ^^ ^^ ^^ ^^ ^^ ^^^^ || || || || || || | || || || || || || - the last run gave no result, hence the || || || || || || implicitly returned None || || || || || |- a number || || || || || - a tuple || || || || |- a number || || || || - a tuple (etc.) Recursion is fine. It is a different way of expressing the same concept a loop expresses. Sometimes a loop is a shorter and easier way to write it, sometimes recursion is, sometimes it is just good to practice :-). If you want to do this with recursion instead of a loop, try this : def dice(number,sides): #number being the number of times you roll if number <=3D 0 : # if we don't roll, we get nothing return None # roll and see what we get value =3D random.randint(0,sides) if number =3D=3D 1 : # if we roll once we get only 1 number return value else : # we add up the rest of our rolls. total =3D value + dice( number-1, sides ) # ^^ only decrement by one return total # return just a single number See if you understand the difference here. HTH, -D --=20 Religion that God our Father accepts as pure and faultless is this: to look after orphans and widows in their distress and to keep oneself from being polluted by the world. James 1:27 =20 http://dman.ddts.net/~dman/ --lrZ03NoBR/3+SXJZ Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAj4gvx4ACgkQO8l8XBKTpRSeNwCeOgciGIpDK1fBNBiPAb606eDE 9yQAniJytig1cT4vCi01xFZV3HYcp1v/ =Fkmj -----END PGP SIGNATURE----- --lrZ03NoBR/3+SXJZ-- From gp@pooryorick.com Sat Jan 11 20:21:02 2003 From: gp@pooryorick.com (Poor Yorick) Date: Sat Jan 11 20:21:02 2003 Subject: [Tutor] __ name mangling Message-ID: <3E20C32B.6010101@pooryorick.com> I thought that in the following code, __var would be mangled, but it wasn't. Why not? >>> class myclass: def __init__(self): self.__var1 = 'hello' >>> instance = myclass() >>> dir(instance) ['__doc__', '__init__', '__module__', '_myclass__var1'] >>> instance.__var2 = 'hi' >>> dir(instance) ['__doc__', '__init__', '__module__', '__var2', '_myclass__var1'] >>> Poor Yorick gp@pooryorick.com From gp@pooryorick.com Sat Jan 11 20:35:02 2003 From: gp@pooryorick.com (Poor Yorick) Date: Sat Jan 11 20:35:02 2003 Subject: [Tutor] subclasses and conflicting variables Message-ID: <3E20C674.5090206@pooryorick.com> I understand when inheriting multiple classes, if there is an instance identifier name conflict, the leftmost inherited class takes priority. In the following code, instance.var1 = 'hello'. It seems to me that this behavior could wreak havoc in multiple layers of inheritance. In the code below, is there any way for instance to access classB.var1? class classA: def __init__(self): self.var1 = 'hello' class classB: def __init__(self): self.var1 = 'goodbye' class classC(classA, classB): def Print(self): print self.var1 instance = classC() instance.Print() Poor Yorick gp@pooryorick.com From darnold02@sprynet.com Sat Jan 11 20:51:01 2003 From: darnold02@sprynet.com (Don Arnold) Date: Sat Jan 11 20:51:01 2003 Subject: [Tutor] __ name mangling References: <3E20C32B.6010101@pooryorick.com> Message-ID: <06c801c2b9dc$e53589b0$ea10ba3f@defaultcomp> ----- Original Message ----- From: "Poor Yorick" To: Sent: Saturday, January 11, 2003 7:21 PM Subject: [Tutor] __ name mangling > I thought that in the following code, __var would be mangled, but it > wasn't. Why not? > > >>> class myclass: > def __init__(self): > self.__var1 = 'hello' > > > >>> instance = myclass() > >>> dir(instance) > ['__doc__', '__init__', '__module__', '_myclass__var1'] But it was: dir doesn't list '__var1', but instead '_myclass__var1'. > >>> instance.__var2 = 'hi' > >>> dir(instance) > ['__doc__', '__init__', '__module__', '__var2', '_myclass__var1'] > >>> This is because '__var2' is just an attribute of the instance. Only class attributes get mangled. Move __var2 into the __init__ of myclass and it gets mangled as expected. > > Poor Yorick > gp@pooryorick.com > HTH, Don From dyoo@hkn.eecs.berkeley.edu Sun Jan 12 01:47:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Jan 12 01:47:02 2003 Subject: [Tutor] Re: My code freezes python. :-) In-Reply-To: <20030112003524.GA21802@dman.ddts.net> Message-ID: > It's not frozen. It's running, but not doing anything (apparently) > useful. > > | while times > -1 : > > We stop when 'times' is less than or equal to -1. Presumably 'times' > is initially a positive number. > > | times=times+1 > > Here times is incremented. It gets larger. Since it started >-1, it > is now moving farther away. This loop can never end. Incidently, this chunk of code might have terminated in a language where arithmetic can overflow. In a more hardware-oriented language like C, numbers are restricted to a certain range, where going beyond that range makes us jump around to the other side of the range, that is, to "overflow". However, since Python has "long ints", overflow doesn't occur on addition: we'll be able to continue blissfully incrementing till we run out of virtual memory. *grin* From carroll@tjc.com Sun Jan 12 02:27:01 2003 From: carroll@tjc.com (Terry Carroll) Date: Sun Jan 12 02:27:01 2003 Subject: [Tutor] Python XML intro Message-ID: A few days ago, someone was asking for a good intro to processing XML with Python, preferably an online resource. Well, it's not online, but I just started reading the O'Reilly "Python & XML" last night, and so far, I really really like it. I've only read the first three chapters, but I feel that it demystifies the Simple API for XML (SAX) really well, to the point that I think I could code up some SAX Python now. I haven't actually tried any of the code (because I get most of my reading done in bed while my wife sleeps), but assuming there are no errors there, I recommend it. If you can't justify buying it, do what I did -- see if you can borrow it from your local public library. -- Terry Carroll | Santa Clara, CA | "The parties are advised to chill." carroll@tjc.com | - Mattel, Inc. v. MCA Records, Inc., Modell delendus est | no. 98-56577 (9th Cir. July 24, 2002) From dyoo@hkn.eecs.berkeley.edu Sun Jan 12 05:50:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Jan 12 05:50:01 2003 Subject: [Tutor] Fixed freezing problem, have new one In-Reply-To: Message-ID: On Sun, 12 Jan 2003, Guess Who? Me wrote: > Sorry! Something came to me and this is the new source: No need to apologize. Let's look at the dice-throwing program. > def dice(number,sides): #number being the number of times you roll > while number > -1 : > value=random.randint(0,sides) > total=0 > total=value+total > number=number+1 > return total,dice(number-2,sides) It looks like we're mixing recursion with looping, and mixing in the total-summing along with the dice picking. I think it's doing too much at once: we should dice this dice() into smaller dices. For the moment, I'm going to pull out the 'total' sum stuff out, because I think we should concentrate on the dice-tossing part first. Don't worry: we can always add in the total-sum stuff back in when dice() looks ok. It's easier to add features to a working program. *grin* Ok, so say that we start off with: ### def dice(number,sides): #number being the number of times you roll while number > -1 : value = random.randint(0,sides) number = number+1 return value,dice(number-2,sides) ### As we mentioned above, there's some mixing of loops and recursion here that we should probably avoid. We can define dice() picking by using either loops, or by using recursion, but I don't think we need to use both techniques: there's too much risk of getting mixed up. If we want to do it with just recursion, we can approach this by first thinking of a really simple "base" problem that we want to solve. For example, dice(1, 6) should be really easy to solve: what do we want to get out of dice() if we roll a single dice? > I think the program's doing what I want! But not with the output I want. Ah, that touches on something we need to know before we continue: what kind of output do you want to get out of something like dice(1, 6)? It's not that I'm lazy; it's just that I really don't want to guess wrong. *grin* And how about dice(2, 6)? Talk to you later! From Slayerchickbuffy@aol.com Sun Jan 12 08:58:01 2003 From: Slayerchickbuffy@aol.com (Slayerchickbuffy@aol.com) Date: Sun Jan 12 08:58:01 2003 Subject: [Tutor] Re: help Message-ID: <110.1e744503.2b52ce5a@aol.com> --part1_110.1e744503.2b52ce5a_boundary Content-Type: text/plain; charset="US-ASCII" Content-Transfer-Encoding: 7bit Ok so im new to this so could someone please explain to me about these langauges and tell me how i should go about trying to learn them please help me if you can thanks a lot Me --part1_110.1e744503.2b52ce5a_boundary Content-Type: text/html; charset="US-ASCII" Content-Transfer-Encoding: 7bit Ok so im new to this so could someone please explain to me about these langauges and tell me how i should go about trying to learn them
please help me if you can thanks a lot
Me
--part1_110.1e744503.2b52ce5a_boundary-- From Adam Vardy Sun Jan 12 11:36:02 2003 From: Adam Vardy (Adam Vardy) Date: Sun Jan 12 11:36:02 2003 Subject: [Tutor] My code freezes python. :-) In-Reply-To: References: Message-ID: <12854735745.20030112130504@roadrunner.nf.net> Saturday, January 11, 2003, 8:52:33 PM, you wrote: >> I got tired of asking questions about things in the tutorial, so I decided >> to try to make a program that uses a random number (function call, I think >> its called?) to roll a dice. I messed around with it for a while, and I got >> it to the point where it freezes IDLE when I try to run it. :-) Here it is. It does indeed. No idea why. >> value=0 >> rolls=input("How many rolls would you like to make?") >> sides=input("How many sides does your dice have?") >> def dice(number,sides): #number being the number of times you roll >> times=number >> total=0 >> while times > -1 : >> value==random.randint(0,sides) This line is asking if Value (which is 0) can compare with some random number the machine tries to come up with. Can't fathom what it will do with the answer to this question. So that's a typo. You were obviously trying to assign to Value, and use it later. You want one '='. >> total=value+total >> times=times+1 >> return value And return it. You would think the program would be kind enough to provide you with an error message, wouldn't you? -- Adam Vardy From ahimsa@onetel.net.uk Sun Jan 12 12:14:02 2003 From: ahimsa@onetel.net.uk (ahimsa) Date: Sun Jan 12 12:14:02 2003 Subject: [Tutor] Leap years Message-ID: <1042391564.1789.715.camel@localhost.localdomain> Hello Although the problem is relatively straight forward, I am wanting to think through the problem-solving process itself. I am trying to script a program that will enable a user to input a given 4 digit year and have the output state whether or not that year is a leap year. The basic idea is that a leap year happens once every four years, so therefore the year given should be divisible by 4 with no remainder. However, this doesn't always give an accurate result. This is the program thus far: _______________________________________________ # Calculating leap years for user input: year = input( "What year: " ) # Get user input leap = year % 4 # Leap years are divisible by 4 if leap == 0: # Modulus should be zero print "%s IS a leap year" % year else: print "%s is NOT a leap year" % year ________________________________________________ On the surface, this does work and correctly outputs leap years for: 1988, 2000, 2400, 1996, etc. Where it falls short is on those centuries that are not leap years, such as 2100. Those who use Linux can get a calendar to test this: $ cal 02 2100 , etc. Clearly, Feb 2100 only has 28 days, not the required 29. So now, I am stuck :( Rather than an answer, if someone can help me think through this problem so that I can learn the process/method involved, that would be best for me. Thank you in anticipation. Andrew -- ahimsa From Don Arnold" Message-ID: <074c01c2ba67$99158f40$ea10ba3f@defaultcomp> ----- Original Message ----- From: "ahimsa" To: Sent: Sunday, January 12, 2003 11:14 AM Subject: [Tutor] Leap years > Hello > > Although the problem is relatively straight forward, I am wanting to > think through the problem-solving process itself. > > I am trying to script a program that will enable a user to input a given > 4 digit year and have the output state whether or not that year is a > leap year. That's a good place to start. > > The basic idea is that a leap year happens once every four years, so > therefore the year given should be divisible by 4 with no remainder. > However, this doesn't always give an accurate result. That is because your definition of a leap year is incorrect: a year is a leap year if it is divisible by 4 and not by 100, or is divisible by 400. Using the correct definition will get rid of those 'false positives'. Once you get that working, you might want to see about turning this test into a function. In pseudocode: def isLeapYear(year): if year passes test for a leap year: return 1 else: return 0 This will return 1 (which is considered 'true') if the input year passes the test, or 0 (which is 'false') if it doesn't. That allows you to structure your print statements (or other conditionals) like this: if isLeapYear(year): print '%s is a leap year' % year else: print '%s is not a leap year' % year > > Rather than an answer, if someone can help me think through this problem > so that I can learn the process/method involved, that would be best for > me. That's good to hear. It lets us know that we're not doing one of your homework assignments for you. ; ) > > Thank you in anticipation. > > Andrew > -- > ahimsa HTH, Don From op73418@mail.telepac.pt Sun Jan 12 13:29:01 2003 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Sun Jan 12 13:29:01 2003 Subject: [Tutor] Leap years References: <1042391564.1789.715.camel@localhost.localdomain> Message-ID: <002a01c2ba69$4896ccd0$49120dd5@violante> ----- Original Message ----- From: "ahimsa" To: Sent: Sunday, January 12, 2003 5:14 PM Subject: [Tutor] Leap years > Hello > > Although the problem is relatively straight forward, I am wanting to > think through the problem-solving process itself. > > I am trying to script a program that will enable a user to input a given > 4 digit year and have the output state whether or not that year is a > leap year. > The rule is actually more complex: i ) A leap year is divisible by 4. ii) Exception to i) if it is divisible by 100 then it's not a leap year. iii) Exception to ii) if it is divisible by 400 then it is a leap year. > The basic idea is that a leap year happens once every four years, so > therefore the year given should be divisible by 4 with no remainder. > However, this doesn't always give an accurate result. > > This is the program thus far: > > _______________________________________________ > # Calculating leap years for user input: > > year = input( "What year: " ) # Get user input > > leap = year % 4 # Leap years are divisible by 4 > > if leap == 0: # Modulus should be zero > print "%s IS a leap year" % year > else: > print "%s is NOT a leap year" % year > ________________________________________________ > > On the surface, this does work and correctly outputs leap years for: > 1988, 2000, 2400, 1996, etc. > > Where it falls short is on those centuries that are not leap years, such > as 2100. Those who use Linux can get a calendar to test this: $ cal 02 > 2100 , etc. Clearly, Feb 2100 only has 28 days, not the required 29. > See above for the complete rule. > So now, I am stuck :( > > Rather than an answer, if someone can help me think through this problem > so that I can learn the process/method involved, that would be best for > me. > > Thank you in anticipation. > > Andrew > All the best, G. Rodrigues From ahimsa@onetel.net.uk Sun Jan 12 15:19:02 2003 From: ahimsa@onetel.net.uk (ahimsa) Date: Sun Jan 12 15:19:02 2003 Subject: [Tutor] re: Leap year problem Message-ID: <1042402474.1124.882.camel@localhost.localdomain> Thanks to Tim, Don, and Goncalo for your input. Don your response got me to think about the problem and to define a function ... much more elegant approach. However, I still run into problems when trying to determine whether or not an even century is or is not a leap year. At present, my little program spits out that 2000 wasn't a leap year, when we know it was. And so again, I am stuck. Anyway, here's my code if someone wants to take a squizz and tell me what I could do to correct that false positive: _____________________________ # Calculating leap years for user input: def isLeapYear(year): if year % 100 == 0: # Error catch on first line print "%s is NOT a leap year" % year elif year % 400 == 0: # Second test return 1 elif year % 4 == 0: # Third test return 1 else: print "%s is NOT a leap year" % year # Catch everything else leapyear = input( "Please enter a year: " ) # User input if isLeapYear(leapyear): print leapyear, "is a leap year." # Output line _____________________________________________________________________ Un/fortunately, I am not doing this for a formal education course, so it is just for own interest and learning ... keeps me out of mischief!!! :-) Cheers Andrew -- ________________________%%%%%%%%%%%%%%%%%____________________________ Proudly sent using Ximian Evolution 1.2.1 on a Linux Red Hat 8.0 box. From ahimsa@onetel.net.uk Sun Jan 12 15:25:01 2003 From: ahimsa@onetel.net.uk (ahimsa) Date: Sun Jan 12 15:25:01 2003 Subject: [Tutor] OT: seeing double Message-ID: <1042403199.1785.893.camel@localhost.localdomain> Is anyone else getting double delivery of mail to this list? I received 2x my own reply as well as 2x everyone else that replied to my earlier post? It is only happening with this list 'cos delivery from other lists is as it should be. It wouldn't have anything to do with Python Tutor being twice as good as other lists would it? :) Cheers Andrew -- ahimsa From darnold02@sprynet.com Sun Jan 12 15:42:01 2003 From: darnold02@sprynet.com (Don Arnold) Date: Sun Jan 12 15:42:01 2003 Subject: [Tutor] OT: seeing double References: <1042403199.1785.893.camel@localhost.localdomain> Message-ID: <07f801c2ba7a$df270cd0$ea10ba3f@defaultcomp> ----- Original Message ----- From: "ahimsa" To: Sent: Sunday, January 12, 2003 2:26 PM Subject: [Tutor] OT: seeing double > Is anyone else getting double delivery of mail to this list? I received > 2x my own reply as well as 2x everyone else that replied to my earlier > post? > It is only happening with this list 'cos delivery from other lists is as > it should be. It wouldn't have anything to do with Python Tutor being > twice as good as other lists would it? :) > Nope. It comes from the replier's hitting 'Reply All' when responding to a message. You end up receiving the reply that was sent directly to you, as well as the one delivered to the list. > Cheers > Andrew > -- > ahimsa > Don From dyoo@hkn.eecs.berkeley.edu Sun Jan 12 15:43:03 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Jan 12 15:43:03 2003 Subject: [Tutor] Fixed freezing problem, have new one (fwd) Message-ID: Hi Andrew, Let me forward this to the whole Tutor list; I think you sent a reply just to me when you actually meant to do a "reply to all". The questions you're asking are very much on topic. I'll try doing a real reply after lunch... *grin* Talk to you later! ---------- Forwarded message ---------- Date: 12 Jan 2003 18:07:52 +0000 From: ahimsa To: Danny Yoo Subject: Re: [Tutor] Fixed freezing problem, have new one I apologise in advance if this is too pedantic or tedious, or takes this thread too far off course for the original person who posted the query. On Sun, 2003-01-12 at 10:49, Danny Yoo wrote: > > Ok, so say that we start off with: > > ### > def dice(number,sides): #number being the number of times you roll > while number > -1 : > value = random.randint(0,sides) > number = number+1 > return value,dice(number-2,sides) > ### > Danny, I want to chip in here and pick your brains about this one if I may :) Am I correct, in looking at the above code, you are first creating a module (or function?) called 'dice' that is defined by the parameters of (a) number of times the dice are 'rolled' and (b) the number of sides of the dice? If so, why would you need to know the number of sides on a die, and would this be for one or both dice? And doesn't the number of sides on a dice stay constant (as in 6)? The module (or function) then initialises a control structure - the 'while' loop - that sets up the minimum limit as an error control - i.e. if the dice is not rolled, there can't be any output. Assuming that the while loop is initialised (i.e. number *is* > -1), the value is assigned from the calculation on the right side of the '=' sign. Where does one get the 'random.randint' part from? Is that a module that you imported or is it a keyword that Python recognises? I can't see it listed as a keyword anywhere though. Why then would you increment the number through 'number+1'? And, again, why have the value returned as 'dice(number-2, ...' - why would you subtract the 2? I am probably missing a huge chunk here and maybe even muddying the waters, but I'd find it helpful if you could walk through that a bit slower. Much obliged. Andrew -- ________________________%%%%%%%%%%%%%%%%%____________________________ Proudly sent using Ximian Evolution 1.2.1 on a Linux Red Hat 8.0 box. From ahimsa@onetel.net.uk Sun Jan 12 15:50:02 2003 From: ahimsa@onetel.net.uk (ahimsa) Date: Sun Jan 12 15:50:02 2003 Subject: [Tutor] OT: seeing double In-Reply-To: <07f801c2ba7a$df270cd0$ea10ba3f@defaultcomp> References: <1042403199.1785.893.camel@localhost.localdomain> <07f801c2ba7a$df270cd0$ea10ba3f@defaultcomp> Message-ID: <1042404688.1124.908.camel@localhost.localdomain> EEEEEEEEEEEEEEKKKKKKKKK - now I'm getting them four times!!!! Now Don and Danny are four times as prolific in their responses. From my side I am only hitting 'reply'/'send' once - is there a loop on the remailer? On Sun, 2003-01-12 at 20:40, Don Arnold wrote: > ----- Original Message ----- > From: "ahimsa" > To: > Sent: Sunday, January 12, 2003 2:26 PM > Subject: [Tutor] OT: seeing double > > > > Is anyone else getting double delivery of mail to this list? I received > > 2x my own reply as well as 2x everyone else that replied to my earlier > > post? > > It is only happening with this list 'cos delivery from other lists is as > > it should be. It wouldn't have anything to do with Python Tutor being > > twice as good as other lists would it? :) > > > > Nope. It comes from the replier's hitting 'Reply All' when responding to a > message. You end up receiving the reply that was sent directly to you, as > well as the one delivered to the list. > > > Cheers > > Andrew > > -- > > ahimsa > > > > Don > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- ahimsa From dyoo@hkn.eecs.berkeley.edu Sun Jan 12 15:59:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Jan 12 15:59:02 2003 Subject: [Tutor] Re: help In-Reply-To: <110.1e744503.2b52ce5a@aol.com> Message-ID: On Sun, 12 Jan 2003 Slayerchickbuffy@aol.com wrote: > Ok so im new to this so could someone please explain to me about these > langauges and tell me how i should go about trying to learn them please > help me if you can thanks a lot Hello! Welcome to Python-tutor! I'll try to cover a bit of your second question. Some people have organized a web site with links to dozens of online tutorials that you might want to look at: http://python.org/doc/Newbies.html One way to start learning Python is to browse through a few of these tutorials, and pick the one appeals to you and is easiest to learn from. Once you've found a good tutorial, go through it, and make sure to do the exercises. *grin* Sorry, it's dull advice, but without knowing more about your background, that's where we'll have to start. If we'd like to see examples of what programs we can write in Python, we can take a look at the cool Useless Python web site: http://uselesspython.com/ But is there any thing in particular that you're interested in? Programming for its own sake is ok, but it can be much more exciting if we tie it with another interest. There are ties to biology via the BioPython project: http://biopython.org/ as well as Linguists through the NLTK Natural Language Toolkit: http://nltk.sourceforge.net/ Python programmers who want to do games can meet up using PyGame: http://pygame.org/ So it really might be useful to see if there's some cross-discipline sort of thing that interests you. When you have questions, or if you get hung up on a difficult section, please feel free to ask questions here on Tutor. There are a lot of gurus as well as other Python learners who would be happy to chat and give moral support. Good luck! From ahimsa@onetel.net.uk Sun Jan 12 16:09:04 2003 From: ahimsa@onetel.net.uk (ahimsa) Date: Sun Jan 12 16:09:04 2003 Subject: [Tutor] Fixed freezing problem, have new one (fwd) In-Reply-To: References: Message-ID: <1042405762.1789.929.camel@localhost.localdomain> On Sun, 2003-01-12 at 20:42, Danny Yoo wrote: > Hi Andrew, > > Let me forward this to the whole Tutor list; I think you sent a reply just > to me when you actually meant to do a "reply to all". The questions > you're asking are very much on topic. > > > I'll try doing a real reply after lunch... *grin* Talk to you later! Great - I look forward to it. Thanks for making the effort. All the best Andrew -- ahimsa From Don Arnold" Message-ID: <080101c2ba82$1f7bff50$ea10ba3f@defaultcomp> ----- Original Message ----- From: "ahimsa" To: Sent: Sunday, January 12, 2003 2:19 PM Subject: [Tutor] re: Leap year problem > Thanks to Tim, Don, and Goncalo for your input. Don your response got me > to think about the problem and to define a function ... much more > elegant approach. However, I still run into problems when trying to > determine whether or not an even century is or is not a leap year. At > present, my little program spits out that 2000 wasn't a leap year, when > we know it was. And so again, I am stuck. Anyway, here's my code if > someone wants to take a squizz and tell me what I could do to correct > that false positive: > > _____________________________ > > # Calculating leap years for user input: > > def isLeapYear(year): > if year % 100 == 0: # Error catch on first line > print "%s is NOT a leap year" % year > elif year % 400 == 0: # Second test > return 1 > elif year % 4 == 0: # Third test > return 1 > else: > print "%s is NOT a leap year" % year # Catch everything else > The problem here is that the 'if ... elif ... else' construct exits as soon as one of its conditions is met. If year is divisible by 100, it satisfies the initial 'if' and falls through the rest of the structure, so you never get to the later tests. If you want to structure it like this, you have to start with the most specific test and work toward the more general ones: def isLeapYear(year): if year % 400 == 0: return 1 elif year % 100 == 0: return 0 elif year % 4 == 0: return 1 else: return 0 This implements the definition that Goncalo gave. To avoid having to order your tests from specific to general, you can eliminate the elif's by combining the conditions into a single one: def isLeapYear2(year): if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0): return 1 else: return 0 This is close to a word-for-word translation of the definition I gave, and (IMO) is easier to read. Either way, the net result is the same: year = int(raw_input('year: ')) while year != -1: print 'isLeapYear :', isLeapYear(year) print 'isLeapYear2:', isLeapYear2(year) print '' year = int(raw_input('year: ')) [begin script run] year: 2000 isLeapYear : 1 isLeapYear2: 1 year: 1900 isLeapYear : 0 isLeapYear2: 0 year: 1996 isLeapYear : 1 isLeapYear2: 1 year: 1997 isLeapYear : 0 isLeapYear2: 0 year: -1 [end script run] Also, it's a good idea to explicitly return 0 for false. If you don't specify a return value, the function will return None. That works here, but one of Python's guiding principles is 'Explicit is better than implicit'. > leapyear = input( "Please enter a year: " ) # User input > > if isLeapYear(leapyear): > print leapyear, "is a leap year." # Output line > > _____________________________________________________________________ > > Un/fortunately, I am not doing this for a formal education course, so it > is just for own interest and learning ... keeps me out of mischief!!! > :-) > I think that's probably how most of us got started programming. If anything, I'd say it's fortunate, since you're studying this because you're interested in it, not just because someone is making you. > Cheers > Andrew > HTH, Don From Don Arnold" <1042405762.1789.929.camel@localhost.localdomain> Message-ID: <081601c2ba83$a3004060$ea10ba3f@defaultcomp> ----- Original Message ----- From: "ahimsa" To: Cc: "Danny Yoo" Sent: Sunday, January 12, 2003 3:09 PM Subject: Re: [Tutor] Fixed freezing problem, have new one (fwd) > On Sun, 2003-01-12 at 20:42, Danny Yoo wrote: > > Hi Andrew, > > > > Let me forward this to the whole Tutor list; I think you sent a reply just > > to me when you actually meant to do a "reply to all". The questions > > you're asking are very much on topic. > > > > > > I'll try doing a real reply after lunch... *grin* Talk to you later! > > Great - I look forward to it. Thanks for making the effort. > > All the best > > Andrew > > -- > ahimsa > Danny's replies are always worth waiting for, so I'll steer clear of commenting on the code itself. But to answer a question from one of your other mails: "... why would you need to know the number of sides on a die ...? ... doesn't the number of sides on a dice stay constant (as in 6)?" Though 6-sided dice are the norm, 4, 8, 10, 12, and 20-sided ones (among others) exist and are commonly used in pencil-and-paper roleplaying games. Geekily yours, Don From gerrit@nl.linux.org Sun Jan 12 16:53:02 2003 From: gerrit@nl.linux.org (Gerrit Holl) Date: Sun Jan 12 16:53:02 2003 Subject: [Tutor] Leap years In-Reply-To: <074c01c2ba67$99158f40$ea10ba3f@defaultcomp> References: <1042391564.1789.715.camel@localhost.localdomain> <074c01c2ba67$99158f40$ea10ba3f@defaultcomp> Message-ID: <20030112215436.GA4866@nl.linux.org> Don Arnold schreef op zondag 12 januari om 19:24:22 +0000: > def isLeapYear(year): > if year passes test for a leap year: > return 1 > else: > return 0 I think it's better to use True and False here. Instead of "return 1", "return True". Instead of "return 0", "return False". It's boolean what's being expected from this function; not an integer. It's not natural to return an integer, as it's not natural to return a empty or non-empty sequence. yours, Gerrit. -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From maillist@kuwest.de Sun Jan 12 16:57:02 2003 From: maillist@kuwest.de (Jens Kubieziel) Date: Sun Jan 12 16:57:02 2003 Subject: [Tutor] Calculating a math formula and finding errors In-Reply-To: References: Message-ID: <20030112213244.GP799@kubieziel.de> On Sat, Jan 11, 2003 at 12:58:19AM -0800, Danny Yoo wrote: > Good grief, this looks like something out of Concrete Mathematics! > http://www-cs-faculty.stanford.edu/~knuth/gkp.html As I wrote I have this from the magazine "Wurzel 12/02". > without going through the pretensions of doing an iteration. So I'll > assume that someone mistyped the equation in LaTeX. *grin* I saw the original sources which are written by hand. There is an "i" and not a "j". > The equation also doesn't quite make sense until we qualify the domain > of 'n'. What happens if n=0 on the left hand side of the equation? It is not specified. > For what values of 'n' should we be able to trust this equation? For all. > combinatorial math. The definition above, though, doesn't define 0!: > you may want to change the base case of the recursion here so that 0! > works. OK, thanks I changed the code. > Furthermore, your choise of the name 'perm' may confuse some folks, as > it suggests a "permutation of k objects out of n", which is not what > the function is doing. I'd recommend renaming this function quick > before it confuses anyone else. *grin* I'll do. > abs(n+1 - 2*(i+1)) > here. Can you clarify which is correct? It is a typo. Right version: abs(n+1-2*(i+j)) -- Jens Kubieziel mailto:jens@kubieziel.de I had to hit him -- he was starting to make sense. From Don Arnold" <074c01c2ba67$99158f40$ea10ba3f@defaultcomp> <20030112215436.GA4866@nl.linux.org> Message-ID: <083e01c2ba88$361c2d10$ea10ba3f@defaultcomp> ----- Original Message ----- From: "Gerrit Holl" To: Sent: Sunday, January 12, 2003 3:54 PM Subject: Re: [Tutor] Leap years > Don Arnold schreef op zondag 12 januari om 19:24:22 +0000: > > def isLeapYear(year): > > if year passes test for a leap year: > > return 1 > > else: > > return 0 > > I think it's better to use True and False here. > Instead of "return 1", "return True". > Instead of "return 0", "return False". > > It's boolean what's being expected from this function; not an integer. > It's not natural to return an integer, as it's not natural to return > a empty or non-empty sequence. > That's true, but I believe True and False are recent additions to Python. Regardless, they're currently defined as ints with the values 1 and 0 respectively, so the result is the same. I guess I'm just used to coding it the old-fashioned way, a la the C language. However, since this was (thinly-veiled) pseudocode, True and False would have probably been better choices. > yours, > Gerrit. > > -- > Asperger Syndroom - een persoonlijke benadering: > http://people.nl.linux.org/~gerrit/ > Het zijn tijden om je zelf met politiek te bemoeien: > http://www.sp.nl/ Don From shalehperry@attbi.com Sun Jan 12 19:57:03 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Sun Jan 12 19:57:03 2003 Subject: [Tutor] OT: seeing double In-Reply-To: <1042404688.1124.908.camel@localhost.localdomain> References: <1042403199.1785.893.camel@localhost.localdomain> <07f801c2ba7a$df270cd0$ea10ba3f@defaultcomp> <1042404688.1124.908.camel@localhost.localdomain> Message-ID: <200301121656.23182.shalehperry@attbi.com> On Sunday 12 January 2003 12:51, ahimsa wrote: > EEEEEEEEEEEEEEKKKKKKKKK - now I'm getting them four times!!!! Now Don > and Danny are four times as prolific in their responses. From my side I > am only hitting 'reply'/'send' once - is there a loop on the remailer? > When you do, check the reply list. It should ONLY have tutor@python.org = in=20 it. From dyoo@hkn.eecs.berkeley.edu Sun Jan 12 20:02:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Jan 12 20:02:01 2003 Subject: [Tutor] Fixed freezing problem, have new one (fwd) In-Reply-To: Message-ID: > Danny, I want to chip in here and pick your brains about this one if I > may :) Ok, I'm back! Don Arnold answered your first question, so I can skip to the next one: > The module (or function) then initialises a control structure - the > 'while' loop - that sets up the minimum limit as an error control - i.e. > if the dice is not rolled, there can't be any output. Right: if we say something like "Roll zero numbers of dice", we should get some kind of empty output from the program. But we want to be careful what we mean by "empty" though: do we want to literally get the word "empty"? ### def dice(number, sides): if number <= 0: return "empty" ... ### or should we use the None value, or something else? It may seem a little nitpicky, but it actually does matter if we go for a recursive definition of dice(). We can talk about this if you'd like. > Assuming that the while loop is initialised (i.e. number *is* > -1), the > value is assigned from the calculation on the right side of the '=' > sign. > > Where does one get the 'random.randint' part from? Is that a module that > you imported or is it a keyword that Python recognises? I can't see it > listed as a keyword anywhere though. Yes, 'random' is a module that's in the Standard Library. It's specialized for generating "pseudorandom" numbers. There's some documentation about the 'random' module here: http://www.python.org/doc/lib/module-random.html If you read this, I'd recommend skipping down near the middle where the docs describe the "Functions for integers"; the stuff at the top and bottom is also very useful, but a bit specialized. > Why then would you increment the number through 'number+1'? And, again, > why have the value returned as 'dice(number-2, ...' - why would you > subtract the 2? Tthat's because the code needs a little retooling: it's doing more work than it really needs to do. I didn't want to just roll in refinements to the code all at once without some kind of feedback. Guess it's time to charge forward! Let's take a look at it again: ### def dice(number,sides): while number > -1 : value = random.randint(0, sides) number = number + 1 return value, dice(number - 2, sides) ### As an intermediate step, I'm going to do something that might look a little weird and arbitrary: I will change that 'while' loop into an 'if' block. ### def dice(number,sides): if number > -1 : value = random.randint(0, sides) number = number + 1 return value, dice(number - 2, sides) ### This has the same effect as the original code because, even though the original code used a "while loop", there was no looping involved due to that 'return' statement at the end of the loop body. But let's double check that this still works. ### >>> dice(3, 6) (6, (0, (3, (0, None)))) ### That's a bit odd. It's giving us FOUR dice rolls instead of three! The original code had the same problem because the condition we're checking, number > -1 is too permisive: we should really be checking if we're rolling a nonempty number of dice: number > 0. Let's make that change: ### def dice(number, sides): if number > 0: value = random.randint(0, sides) number = number + 1 return value, dice(number - 2, sides) ### Let's try that again. ### >>> dice(3, 6) (6, (0, (0, None))) >>> dice(3, 6) (4, (4, (1, None))) >>> dice(3, 6) (5, (0, (3, None))) >>> dice(3, 6) (4, (5, (5, None))) >>> dice(3, 6) (6, (2, (6, None))) >>> dice(3, 6) (1, (1, (2, None))) ### Ah, better. Sorry about getting sidetracked there. *grin* Let's go back to your question. > Why then would you increment the number through 'number+1'? And, again, > why have the value returned as 'dice(number-2, ...' - why would you > subtract the 2? That's because it's doing too much work. If we go one step forward, and two steps backwards, we end up one step backward. But how do we see this without just stating it? And how do we fix it? Let's do something unusual by trying to follow an artificial programming restriction: we won't allow "rebinding" a variable name that's already defined, but instead we'll add a new temporary variable. In technical terms, we'll be "Introducing a Temporary Variable". That is, we're not going to do any variable name reassignments. It's a little weird, but we'll see in a moment why this is a good idea. What does dice() look like if we follow this restriction? ### def dice(number, sides): if number > 0: value = random.randint(0,sides) next_number = number + 1 return value, dice(next_number - 2, sides) ### That programming rule --- no rebinding --- that we followed above isn't actually as arbitrary as it seems. It suddently allows us to do "plugging-in" safely. Whereever we see 'next_number', we can now "plug-in" and substitute the right-hand side value of 'next-number' and still have a program that behaves the same way: ### def dice(number, sides): if number > 0: value = random.randint(0, sides) next_number = number + 1 return value, dice((number + 1) - 2, sides) ### Once we've done this, we can just drop the initial assignment to 'next_number', since 'next_number' is a useless variable that's not being used anywhere anymore. ### def dice(number, sides): if number > 0: value = random.randint(0,sides) return value, dice(number + 1 - 2, sides) ### I don't think I need to outline the next step. *grin* But let's see what dice() looks like now: ### def dice(number, sides): if number > 0: value = random.randint(0, sides) return value, dice(number - 1, sides) ### Does this revision make more sense? Please feel free to ask more questions about this; I know I went fast on that one, but it's an exciting topic: if we're careful about reassignment, we can do controlled manipulation of our programs to clean them up. It's almost like factoring math equations to make them easier to understand. From syrinx@simplecom.net Sun Jan 12 23:45:02 2003 From: syrinx@simplecom.net (Scott) Date: Sun Jan 12 23:45:02 2003 Subject: [Tutor] threads Message-ID: <20030112224032.61f11db3.syrinx@simplecom.net> Is the following a true statement, or am I deluding myself? "Multi-threaded programs are very easy and shouldn't present any special problems as long as a child thread never changes the parent's data." From maillist@kuwest.de Mon Jan 13 05:40:08 2003 From: maillist@kuwest.de (Jens Kubieziel) Date: Mon Jan 13 05:40:08 2003 Subject: [Tutor] Calculating a math formula and finding errors In-Reply-To: References: <20030109165408.GA19944@kubieziel.de> Message-ID: <20030113103825.GC2584@kubieziel.de> On Fri, Jan 10, 2003 at 04:03:49PM +0100, Michael Janssen wrote: > On Thu, 9 Jan 2003, Jens Kubieziel wrote: > > {n-1 \choose i} =2 \left\lfloor \frac{n+2}{2} \right\rfloor "choose" is much better here. Thanks for this. > > def MBrechts(n): > > b=0 > > for i in range(0,n): > > for j in range(0,n-i): > > betrag = n + 1 - (2*i) - (2*j) > > if betrag < 0: > > betrag = betrag * -1 > > prod = betrag * perm(n-i,j) > > MBrechts is the left side, isn't it? It must be perm(n-1, i) to represent You're right, my fault. > latex: ${n-1 \choose i}$ (which is the binominalcoeffizient of n-1 and i) > But this won't make the output equal. Did you look at my note? The original formula has an "i" there, but it doesn't make much sense to mee. I assume that it must be a "j". > the "sigma-ranges" might (must? I don't know much about math notation) be > range(0,n+1) and range(0,n-i+1) (both zeros aren't neccessary in python > but provided for the readers convenience). (From the rest of the code I Yep, right. But when I add this, I get a runtime error: Traceback (most recent call last): File "Projekte/Python/MB-Wurzel.py", line 30, in ? print "n = %d, Formel rechts = %d, Formel links = %d" % (erg,MBrechts(erg),MBlinks(erg)) File "Projekte/Python/MB-Wurzel.py", line 22, in MBrechts prod = betrag * perm(n-i,j) File "Projekte/Python/MB-Wurzel.py", line 9, in facul return z*facul(z-1) RuntimeError: maximum recursion depth exceeded So I guess I have to change my "facul"-code. > guess, you're familar with "range" so this typo needn't be explained) No, it doesn't. I corrected this within my "perm", but forgot it in "MBrechts". > In case this doesn't already solve your problem, could you repost a > patched version (perhaps with english var-names to give the rest of > tutor-list a better chance :) and clean from rechts/links mess) so that > we can restart from a coherent version? #v+ #! /usr/bin/python import math def factorial(z): if z == 1 or z == 0: return 1 else: return z*factorial(z-1) def binomial(x,y): w = 1 for i in range(y+1,x+1): w = w * i return w/factorial(x-y) def MBleft(n): b=0 for i in range(0,n+1): for j in range(0,n-i+1): betrag = abs(n + 1 - 2*(i+j)) prod = betrag * binomial(n-i,j) b = b + prod return b def MBright(n): return 2 * math.floor((n+2)/2) * binomial(n+1,math.floor((n+1)/2)) - n - 1 for erg in range(1,6): print "n = %d, Formel rechts = %d, Formel links = %d" % (erg,MBrechts(erg),MBlinks(erg)) #v- I have to think about the factorial function. Because it seems that the recursion doesn't work with the correction in MBleft. -- Jens Kubieziel mailto:jens@kubieziel.de The study of non-linear physics is like the study of non-elephant biology. From dyoo@hkn.eecs.berkeley.edu Mon Jan 13 06:23:03 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Jan 13 06:23:03 2003 Subject: [Tutor] Calculating a math formula and finding errors In-Reply-To: <20030113103825.GC2584@kubieziel.de> Message-ID: On Mon, 13 Jan 2003, Jens Kubieziel wrote: > I have to think about the factorial function. Because it seems that the > recursion doesn't work with the correction in MBleft. Hi Jens, Let us take a look at factorial() for another moment: > def factorial(z): > if z == 1 or z == 0: > return 1 > else: > return z*factorial(z-1) This has the potential of looping forever if we ever give invalid input into factorial. For example: what happens if we feed a negative number as 'z'? This is not to say that factorial() is "broken", only that we have to be careful to give it nonnegative numbers for input. If we want to be careful, we should add an assertion check to make sure that the system will catch this invalid input as soon as possible. ### def factorial(z): assert z >= 0, "Invalid input: z must be nonnegative." if z == 1 or z == 0: return 1 else: return z*factorial(z-1) ### Invalid input to factorial() is probably where we are going astray. The definition of binomial(): > def binomial(x,y): > w = 1 > for i in range(y+1,x+1): > w = w * i > return w/factorial(x-y) will give factorial() a negative input if 'x < y'. But binomial() should instead return 0 instead from a combinatorial interpretation. ### def binomial(x,y): if x < y: return 0 w = 1 for i in range(y+1,x+1): w = w * i return w/factorial(x-y) ### I believe these two corrections should help trap the infinite loop bugs in the code, so that you can concentrate on the correctness of your code more easily. Have you revised the printed equation on the PDF page, or do you have a revised version of the LaTeX source? I am curious, and would like to double check to see if everything else is ok between the mathematics and the Python program. Best of wishes to you! From dyoo@hkn.eecs.berkeley.edu Mon Jan 13 06:35:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Jan 13 06:35:02 2003 Subject: [Tutor] threads In-Reply-To: <20030112224032.61f11db3.syrinx@simplecom.net> Message-ID: Hi Scott, > Is the following a true statement, or am I deluding myself? > > "Multi-threaded programs are very easy This is an opinion. There is no way to verify this in the bounds of logic. *grin* Empirically, it seems that multithreaded programs can be either easy or difficult, based on design. Personally, I think they're hard. As a concrete anecdote: the source to the excellent classic game "Star Control II" has just been released to the public, http://sc2.sourceforge.net/ but the volunteer programmers are finding dozens of threading and thread-synchronization bugs that are non-trivial to find and fix: http://sourceforge.net/tracker/?atid=491059&group_id=59452&func=browse I think that multithreading-related bugs can be extraordinarily frustrating to fix because they are often hard to replicate, requiring the interplay of child threads doing the wrong thing at the right time. *grin* Best of wishes to you! From dyoo@hkn.eecs.berkeley.edu Mon Jan 13 06:40:09 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Jan 13 06:40:09 2003 Subject: [Tutor] Leap years In-Reply-To: <083e01c2ba88$361c2d10$ea10ba3f@defaultcomp> Message-ID: > > > def isLeapYear(year): > > > if year passes test for a leap year: > > > return 1 > > > else: > > > return 0 > > > > I think it's better to use True and False here. > > Instead of "return 1", "return True". > > Instead of "return 0", "return False". Hi Don, But even better than explicitely returning True or False is to avoid using the 'if' statement altogether. The pseudocode above can be written like this: ### def isLeapYear(year): return (year passes test for a leap year) ### That is, if we're going to do something like: if something is true: return true else: return false it's usually an improvement to be direct and just say return (something is true) which is concise and avoids the controversy of using 0/1/True/False altogether. *grin* Best of wishes to you! From dick.kniep@lindix.nl Mon Jan 13 07:37:08 2003 From: dick.kniep@lindix.nl (Dick Kniep) Date: Mon Jan 13 07:37:08 2003 Subject: [Tutor] Upgrading of python 2.2.2 on RedHat 8.0 In-Reply-To: References: Message-ID: <1042465234.2328.1.camel@kniep04.kniep> Op za 11-01-2003, om 09:10 schreef Danny Yoo: > On 10 Jan 2003, Dick Kniep wrote: > > > Hi there, > > > > I am facing problems with upgrading the standard installation of Python > > 2.2.1 of RedHat 8 to Python 2.2.2. When I install it "according to the > > book", it places all files in usr/local/lib, whereas RedHat expects them > > in usr/lib. I haven't seen any RPM's for Redhat 8 (only for older > > versions) Just a few days ago, I found an RPM for Redhat 8. I tried to install it, but it gave dependency errors, as I had Python 2.2.1 already installed, and some other packages required specifically 2.2.1. So I installed with --nopdeps, and it works OK now. Regards, Dick > > Hi Dick, > > Yes, Python 2.2.2 is in Rawhide and the Redhat 8.1 beta, but it's not in > the standard distribution of Redhat 8 yet; I think Redhat's still testing > for compatibility with their own administrative scripts. > > > However, it's perfectly ok to have Python installed in /usr/local/bin; you > just have to make sure that you either explicitely type > > /usr/local/bin/python > > whenever you use Python, or that you place /usr/local/bin in your PATH > with higher priority than /usr/bin. Would this work for you? > > > Good luck to you! > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Dick Kniep Lindix From magnus@thinkware.se Mon Jan 13 07:40:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Jan 13 07:40:02 2003 Subject: [Tutor] subclasses and conflicting variables In-Reply-To: <3E20C674.5090206@pooryorick.com> Message-ID: <5.1.0.14.0.20030113103352.02beb168@www.thinkware.se> At 18:35 2003-01-11 -0700, Poor Yorick wrote: >I understand when inheriting multiple classes, if there is an instance >identifier name conflict, the leftmost inherited class takes priority. Actually, this has changed for the so called "diamond rule" in version 2.2 of python. What you say is true if the base classes don't have common heritage. See http://www.python.org/2.2/descrintro.html#mro >In the following code, instance.var1 = 'hello'. It seems to me that this >behavior could wreak havoc in multiple layers of inheritance. In the code >below, is there any way for instance to access classB.var1? If you need that, you might have misused multiple inheritance (MI). That variables hide each other is nothing specific for inheritance though. You can hide globals with locals, builtins with globals or locals and so on. In most language, but not in Python, you can hide attributes in classes with locals. But going back to MI, it's probalby a good idea to restrict its use to some special cases. We used to have a commercial for some kind of baby stuff on TV with a woman saying "I'm not just a nurse, I'm a mother as well..." Translated to Python you might write: class Person: ... class Mother(Person): ... class Nurse(Person): .... class NurseAndMother(Nurse, Mother): ... This is probably a bad idea though. I typically advice against using multiple inheritance in the object model that represent the business analysis, and to reserve MI to more technical aspects. This might be features like logging or persistence that you "plug in" to other classes. In my current project, I only use MI in 2 of 135 classes, and I think that is a reasonable proportion. In this case, it's one class that inherits UserString.UserString and ZODB's Persistence.Persistent, and another in the wxPython GUI that inherits wxListCtrl and wxListCtrlAutoWidthMixin. The wxListCtrlAutoWidthMixin is designed specifically to provide some extra features to wxListCtrl. In Java, it is at least claimed that, the reason to leave out MI was that it's often used in a way that causes problems. Instead, Java has interfaces which means that you have to duplicate implementations. :( In Python, as in C++, you have the choice to use MI where it fits, and the responsibility to not use it in situations where it will cause problems. While Python is considered a "beginner friendly" language, and a language where there is often "one way to do it", as opposed to the kind of confusion that e.g. Perl offers, this doesn't mean that useful features are left out because they are abused now and then. Guido is not taking responsibility for your programs. He provides you with an efficient tool that will usually be helpful and which doesn't contain a multitude of complications to prevent you from shooting yourself in the foot. It does contain features that both makes programming faster and reduces the risk of injuries, such as automatic memory management and easy to use high level constructs as lists and dictionaries, but it's certainly not a padded cell... If you bang your head in the wall, it will be painful. It's interesting that Guido discussed "language levels" in the Computer Programming For Everybody (CP4E) program, which was cancelled due to lack of funding. I can guess that MI might have been among the things that would have been disabled at the beginner level of Python. -- 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@thinkware.se Mon Jan 13 08:22:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Jan 13 08:22:01 2003 Subject: [Tutor] Leap years In-Reply-To: <1042391564.1789.715.camel@localhost.localdomain> Message-ID: <5.1.0.14.0.20030112224926.02c4ceb8@www.thinkware.se> At 17:14 2003-01-12 +0000, ahimsa wrote: >Where it falls short is on those centuries that are not leap years, such >as 2100. Those who use Linux can get a calendar to test this: $ cal 02 >2100 , etc. Clearly, Feb 2100 only has 28 days, not the required 29. Other and better solutions have been presented, but calendar *is* available cross platform if you run python. >>> import calendar >>> print calendar.month(2000,2) February 2000 Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 You could actually use that to implement leap(year). >>> def leap(year): ... import calendar ... return calendar.month(year, 2).find('29') != -1 ... >>> for y in range(1990,2010): ... print y, leap(y) ... 1990 0 1991 0 1992 1 ... 2007 0 2008 1 2009 0 There is actually a flagrant bug in the implementation above. Can you see it? How do you fix it? What other tradeoffs are there between this and the code below? def leap(year): return ((year % 100) and not (year % 4)) or not (year % 400) Finally, for a solution that requires slightly less headache, type... >>> import calendar >>> help(calendar) ...and look for a function whose name starts with 'i'... Why reinvent the wheel? -- 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 Shey@argonaut.com Mon Jan 13 09:30:02 2003 From: Shey@argonaut.com (Shey Crompton) Date: Mon Jan 13 09:30:02 2003 Subject: [Tutor] Importing a module I made Message-ID: <415C917D807AD411B72C00805FF7330B053F8359@MAILSRV> Hi all, I'm sure this has probably been asked before, but I deleted the mail this morning and can't find where it was mentioned in the achives, sorry. I have a file BankAccount_class02.py that I want to import into and use in another program. I have found that I can only import the file successfully if it is located in Python22\Lib. This is fine, but I would like to not have to copy every file I write, and want to import, out of my work folder (Python22\Python Stuff). For this to work do I have to do the PythonPath thing, or something similar? I'm using Win2K pro, and know how to get to the system\advanced\environmental variables, but I'm unsure of what to type in that area. Thanks in advance, Shey From magnus@thinkware.se Mon Jan 13 10:29:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Jan 13 10:29:01 2003 Subject: [Tutor] Importing a module I made In-Reply-To: <415C917D807AD411B72C00805FF7330B053F8359@MAILSRV> Message-ID: <5.1.0.14.0.20030113160855.02bf3808@www.thinkware.se> At 14:31 2003-01-13 +0000, Shey Crompton wrote: >I have a file BankAccount_class02.py that I want to import into and use in >another program. I have found that I can only import the file successfully >if it is located in Python22\Lib. This is fine, but I would like to not have >to copy every file I write, and want to import, out of my work folder >(Python22\Python Stuff). For this to work do I have to do the PythonPath >thing, or something similar? I'm using Win2K pro, and know how to get to the >system\advanced\environmental variables, but I'm unsure of what to type in >that area. There are a few different strategies here. First of all, I suggest that you don't put any of your own files in Python22/Lib. If you want them in a central location, put them in Python22/Lib/site-packages/. This directory are intended just for these files that don't come with your standard python install. Secondly, if the module is in the same directory as the program that imports it runs from, imports will work fine. This is the way most people handle their own software I think. If you want to import your module from the Python interpreter interactively, you can either do >>> import sys >>> sys.path.append('c:/where/ever/I/have/my/files/') or you can do the ordinary windows dance to change the properties of the shortcut or start menu entry you use, to start running from your directory. Other options are, as you suggested, to add your directory to the PYTHONPATH environment variable. In Win2k you do this from Control Panel -> System -> Advanced -> Environment Variables. Just set PYTHONPATH as variable (in the upper or lower field depending on whether you want this accessible for one particular user or for all) and write the path to the directory as value. Note that you need to restart your programs (Python interpreter or whatever) for them to become aware of the environment change). If you do work in Python/Python Stuff, you could actually do another convenient thing. First of all. Never ever ever use space characters in directory or file names!!! Secondly, put your directory under site-packages instead. Can you imagine having all the code that you write in Python22/Lib/site-packages/PythonStuff instead of that directory with the poor location and name ;) ? In that case you can make that directory into a package. It's dead simple. Just add an empty file called __init__.py ! Then you can do "import PythonStuff.BankAccount_class02"! And while I'm whining: This isn't Java, there is no reason to put each class in a file of its own... A file is a module, and in Python, classes, modules (files) and packages (directories with __init__.py) are different levels of modularization. Use that! -- 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 pietro.ciuffo@nekhem.com Mon Jan 13 10:56:28 2003 From: pietro.ciuffo@nekhem.com (Pietro Ciuffo) Date: Mon Jan 13 10:56:28 2003 Subject: [Tutor] zipfile Lib In-Reply-To: <5.1.0.14.0.20030113160855.02bf3808@www.thinkware.se> References: <415C917D807AD411B72C00805FF7330B053F8359@MAILSRV> <5.1.0.14.0.20030113160855.02bf3808@www.thinkware.se> Message-ID: <20030113155451.GA1985@burma> Hi all. I have to make a zip file for Unix and Windows. I tried the zipfile Library. It works - it produces a zip file - but the file is good for Unix but not for Win. Anybody could help me? Thanks a lot. Below the code I used: ::::::::::::::::::::::::::::::::::::: from cStringIO import StringIO import zipfile if RESPONSE is not None: RESPONSE.setHeader('Content-type','application/zip') RESPONSE.setHeader('Content-Disposition', 'inline;filename=%s.%s' % (FILENAME, SUFFIX)) t = StringIO() S = open(FILE, 'r') zfile = zipfile.ZipFile(file = t, mode = 'w') zfile.write(filename = FILE, arcname = 'myfile.txt') zfile.close() return zfile.getvalue() ::::::::::::::::::::::::::::::::::::: -- 'La scepsi si muove e si tiene nella luce del raggio, nella cui forma gia' ci tocca l'assolutezza dell'Assoluto, il quale, in se' e per se', e' presso di noi' From Shey@argonaut.com Mon Jan 13 11:44:01 2003 From: Shey@argonaut.com (Shey Crompton) Date: Mon Jan 13 11:44:01 2003 Subject: [Tutor] Importing a module I made Message-ID: <415C917D807AD411B72C00805FF7330B053F835C@MAILSRV> Oops, sent this directly to Magnus. Note to self: Use reply all in future. :-) Thanks for the top tips. I'm going with the Lib\site-packages\... option and seeing if I can get used to working that way. Just to clarify slightly if I put an empty file titled __init__.py in my (now) PythonStuff folder that will enable me to import a file by typing import PythonStuff.FileName. Is that correct? Thanks, Shey -----Original Message----- From: Magnus Lycka [mailto:magnus@thinkware.se] Sent: 13 January 2003 15:33 To: Shey Crompton; tutor@python.org Subject: Re: [Tutor] Importing a module I made At 14:31 2003-01-13 +0000, Shey Crompton wrote: >I have a file BankAccount_class02.py that I want to import into and use in >another program. I have found that I can only import the file successfully >if it is located in Python22\Lib. This is fine, but I would like to not have >to copy every file I write, and want to import, out of my work folder >(Python22\Python Stuff). For this to work do I have to do the PythonPath >thing, or something similar? I'm using Win2K pro, and know how to get to the >system\advanced\environmental variables, but I'm unsure of what to type in >that area. There are a few different strategies here. First of all, I suggest that you don't put any of your own files in Python22/Lib. If you want them in a central location, put them in Python22/Lib/site-packages/. This directory are intended just for these files that don't come with your standard python install. Secondly, if the module is in the same directory as the program that imports it runs from, imports will work fine. This is the way most people handle their own software I think. If you want to import your module from the Python interpreter interactively, you can either do >>> import sys >>> sys.path.append('c:/where/ever/I/have/my/files/') or you can do the ordinary windows dance to change the properties of the shortcut or start menu entry you use, to start running from your directory. Other options are, as you suggested, to add your directory to the PYTHONPATH environment variable. In Win2k you do this from Control Panel -> System -> Advanced -> Environment Variables. Just set PYTHONPATH as variable (in the upper or lower field depending on whether you want this accessible for one particular user or for all) and write the path to the directory as value. Note that you need to restart your programs (Python interpreter or whatever) for them to become aware of the environment change). If you do work in Python/Python Stuff, you could actually do another convenient thing. First of all. Never ever ever use space characters in directory or file names!!! Secondly, put your directory under site-packages instead. Can you imagine having all the code that you write in Python22/Lib/site-packages/PythonStuff instead of that directory with the poor location and name ;) ? In that case you can make that directory into a package. It's dead simple. Just add an empty file called __init__.py ! Then you can do "import PythonStuff.BankAccount_class02"! And while I'm whining: This isn't Java, there is no reason to put each class in a file of its own... A file is a module, and in Python, classes, modules (files) and packages (directories with __init__.py) are different levels of modularization. Use that! -- 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@thinkware.se Mon Jan 13 12:34:43 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Jan 13 12:34:43 2003 Subject: [Tutor] Importing a module I made In-Reply-To: <415C917D807AD411B72C00805FF7330B053F835B@MAILSRV> Message-ID: <5.1.0.14.0.20030113183537.02b1aea0@www.thinkware.se> At 15:53 2003-01-13 +0000, Shey Crompton wrote: >Thanks for the top tips. > >I'm going with the Lib\site-packages\... option and seeing if I can get used >to working that way. >Just to clarify slightly if I put an empty file titled __init__.py in my >(now) PythonStuff folder that will enable me to import a file by typing >import PythonStuff.FileName. Is that correct? Yes, if the PythonStuff folder is below site-packages or any other path in Python's sys.path. See http://www.python.org/doc/current/tut/node8.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 Jmllr891@cs.com Mon Jan 13 13:47:08 2003 From: Jmllr891@cs.com (Jmllr891@cs.com) Date: Mon Jan 13 13:47:08 2003 Subject: [Tutor] Shredding Files? Message-ID: <002401c2bb34$35c6a6e0$58bc8018@ne1.client2.attbi.com> ------=_NextPart_000_0021_01C2BB0A.4C1F9340 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable I'm concerned with my personal privacy and I've been trying file shredders l= eft and right for a while, but none of them seem to be good enough. Another=20= problem is that I don't have enough money to buy professional software, so..= . I was wondering if anyone knew where I could find a file shredder written in= Python or a tutorial or resource where I could find information about secur= ely deleting data with (specifically) Python. Thanks, Joshua Miller ------=_NextPart_000_0021_01C2BB0A.4C1F9340 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
I'm concerned with my personal privacy and=20= I've=20 been trying file shredders left and right for a while, but none of them seem= to=20 be good enough. Another problem is that I don't have enough money to buy=20 professional software, so...
 
I was wondering if anyone knew where I coul= d find a=20 file shredder written in Python or a tutorial or resource where I could find= =20 information about securely deleting data with (specifically)=20 Python.
 
Thanks,
Joshua Miller
------=_NextPart_000_0021_01C2BB0A.4C1F9340-- From gp@pooryorick.com Mon Jan 13 13:48:08 2003 From: gp@pooryorick.com (Poor Yorick) Date: Mon Jan 13 13:48:08 2003 Subject: [Tutor] searching the tutor archives Message-ID: <3E230A3C.1070506@pooryorick.com> Thanks to all for answers to my recent questions. I've learned a lot from you. I've wanted several times lately to search the archives, but short of downloading the archives, I haven't found a way to search them. Is there a way? Poor Yorick gp@pooryorick.com From syrinx@simplecom.net Mon Jan 13 14:12:11 2003 From: syrinx@simplecom.net (Scott) Date: Mon Jan 13 14:12:11 2003 Subject: [Tutor] threads In-Reply-To: References: <20030112224032.61f11db3.syrinx@simplecom.net> Message-ID: <20030113130731.0bdc7f73.syrinx@simplecom.net> On Mon, 13 Jan 2003 03:34:16 -0800 (PST) Danny Yoo wrote: > Empirically, it seems that multithreaded programs can be either easy > or difficult, based on design. Personally, I think they're hard. As > a concrete anecdote: the source to the excellent classic game "Star > Control II" has just been released to the public, If *you* think they're hard, maybe I ought to stay far away from them! But looks like for the program I'm trying to create, I have no choice really. (I have a sinking feeling I'm getting in over my head, as this project is requiring me to learn socket programming, threading, reverse-engineering of ip protocols, wxPython, among other things, all at the same time. I'm discovering my inner masochist. :) Thanks Danny for your insights. I'm going to bite the bullet and spawn a few threads, but really try to keep it simple! Oh, and I'm gonna check out Star Control II as well. Sounds interesting. From ATrautman@perryjudds.com Mon Jan 13 14:14:02 2003 From: ATrautman@perryjudds.com (Alan Trautman) Date: Mon Jan 13 14:14:02 2003 Subject: [Tutor] Shredding Files? Message-ID: <0BA95581EDA7D611841B00A0C9AD25DD2B595D@mail.pjinet.com> Joshua, Shredders are incredible OS and even controller (IDE or SCSI) specific. If you have a Journaled filed system (i.e. JFS, ext2a, Others) that allows an access for third party ports it can be relatively (for a non-beginner) to write a system that will block overwrite specific spots on a hard drive. You get the position and some even have a method of controlling that position to overwrite the text. The problem is that you can't just resave a file over the same name to shred an item. The hard drive controller or the hard drive itself may overwrite any where it wants. You have to write low level software that will record the physical location of the record/file. Then using those positions write 1's and 0's a couple of times. The problem is getting that specific location and the exact record length, locking the drive so it doesn't try to optimize file IO, and then marking and overwriting that sector(s) without corrupting the main file system. I have been proven wrong many times on this list but I think this would have to be done in C++ or assembler unless on of the journaled file systems has a python API. The only shredder I have written was for DOS and it used assembler because I talked directly to the hard drive controller and of course every other process was locked out while I was doing it. HTH Alan -----Original Message----- From: Jmllr891@cs.com [mailto:Jmllr891@cs.com] Sent: Monday, January 13, 2003 12:47 PM To: tutor@python.org Subject: [Tutor] Shredding Files? I'm concerned with my personal privacy and I've been trying file shredders left and right for a while, but none of them seem to be good enough. Another problem is that I don't have enough money to buy professional software, so... I was wondering if anyone knew where I could find a file shredder written in Python or a tutorial or resource where I could find information about securely deleting data with (specifically) Python. Thanks, Joshua Miller From mongo57a@comcast.net Mon Jan 13 14:17:20 2003 From: mongo57a@comcast.net (andy surany) Date: Mon Jan 13 14:17:20 2003 Subject: [Tutor] searching the tutor archives Message-ID: <031501c2bb38$99375c20$2502a8c0@emily.ewndsr01.nj.comcast.net> Maybe I'm not understanding the questions, but.... http://aspn.activestate.com/ASPN/Mail/Browse/Threaded/python-Tutor Upper right secion of the page is a search capability. HTH. -Andy -----Original Message----- From: Poor Yorick To: tutor@python.org Date: Monday, January 13, 2003 1:48 PM Subject: [Tutor] searching the tutor archives >Thanks to all for answers to my recent questions. I've learned a lot >from you. > >I've wanted several times lately to search the archives, but short of >downloading the archives, I haven't found a way to search them. Is >there a way? > >Poor Yorick >gp@pooryorick.com > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From magnus@thinkware.se Mon Jan 13 14:59:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Jan 13 14:59:01 2003 Subject: [Tutor] zipfile Lib In-Reply-To: <20030113155451.GA1985@burma> References: <5.1.0.14.0.20030113160855.02bf3808@www.thinkware.se> <415C917D807AD411B72C00805FF7330B053F8359@MAILSRV> <5.1.0.14.0.20030113160855.02bf3808@www.thinkware.se> Message-ID: <5.1.0.14.0.20030113191211.00bd11c8@www.thinkware.se> At 16:54 2003-01-13 +0100, Pietro Ciuffo wrote: > zfile = zipfile.ZipFile(file = t, mode = 'w') Hm... I see that it's not mentioned in the manual, but maybe you could try replacing "mode = 'w'" with "mode = 'wb'". While Unix don't, Windows differenciates between binary and text files. For opening ordinary file, 'w' and 'wb' matters on Windows. If this fixes your problem, I think you should issue a bug report about the faulty documentation at Sourceforge. -- 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 jeff@ccvcorp.com Mon Jan 13 15:13:06 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Mon Jan 13 15:13:06 2003 Subject: [Tutor] threads References: <20030112224032.61f11db3.syrinx@simplecom.net> <20030113130731.0bdc7f73.syrinx@simplecom.net> Message-ID: <3E231C81.9090401@ccvcorp.com> Scott wrote: >On Mon, 13 Jan 2003 03:34:16 -0800 (PST) >Danny Yoo wrote: > >>Empirically, it seems that multithreaded programs can be either easy >>or difficult, based on design. Personally, I think they're hard. As >>a concrete anecdote: the source to the excellent classic game "Star >>Control II" has just been released to the public, >> >> > >If *you* think they're hard, maybe I ought to stay far away from them! >But looks like for the program I'm trying to create, I have no choice >really. > IMO, threading can be anywhere from moderately straightforward to incredibly brainbending, depending on just how you're using those threads. The trick is to remember that you can't be sure of the timing of *anything* that happens in another thread unless you explicitly synchronize. For most purposes, synchronizing threads isn't all that difficult, but if you're doing something complex then the synchronization issues can quickly become extremely hairy. One resource that is invaluable for multithreading is the Queue module. Queues are threadsafe methods of passing data back and forth between threads. (Sharing a normal variable between threads is *not* safe, because you can never tell when the other thread might clobber your variable while you're in the middle of using it...) One of the standard architectures for multithreading is to designate a set of "producer" threads and a set of "consumer" threads. Since you mention sockets, one possibility is to hand a socket and one end of a queue to each producer thread. That thread will read data from the socket, package it up, and drop it into the queue. You can safely have several such threads dropping data into the same queue. Now you set up a consumer thread that reads data from the queue and then acts on it. It'll need to keep track of *which* socket the data came from (so that information needs to be in the packaging), but it doesn't need to worry about *how* to get the data. The synchronization trick comes in because you have no way of knowing which data arrived "first", only what socket it came from -- and you can be pretty sure (if you're using TCP sockets at least) that the data from any given socket is in order. But if (for example) you're receiving long streams of data on two different sockets, you can't be sure that you'll get all of stream 1 before stream 2, or vice versa -- probably you'll get both streams in many small chunks that are somewhat randomly interleaved. So, again, the trick with threads is to never trust the timing of anything, and to be careful any time that threads are doing anything that might be interpreted as sharing information. And be wary of the possibility that thread A may be waiting for thread B to provide some data, but thread B is blocked waiting for a resource that thread A has locked up... But yes, try it out a bit, keep it simple at first, and feel free to ask specific questions here. :) Jeff Shannon Technician/Programmer Credit International From syrinx@simplecom.net Mon Jan 13 15:17:02 2003 From: syrinx@simplecom.net (Scott) Date: Mon Jan 13 15:17:02 2003 Subject: [Tutor] threads In-Reply-To: <3E231C81.9090401@ccvcorp.com> References: <20030112224032.61f11db3.syrinx@simplecom.net> <20030113130731.0bdc7f73.syrinx@simplecom.net> <3E231C81.9090401@ccvcorp.com> Message-ID: <20030113141215.1886ec72.syrinx@simplecom.net> On Mon, 13 Jan 2003 12:07:29 -0800 "Jeff Shannon" wrote: > But yes, try it out a bit, keep it simple at first, and feel free to > ask specific questions here. :) Thanks for the advice. I'm keeping your message as a reference. :) From aicolburn@yahoo.com Mon Jan 13 15:21:24 2003 From: aicolburn@yahoo.com (Alan Colburn) Date: Mon Jan 13 15:21:24 2003 Subject: [Tutor] wxPython newbie, cont'd. Message-ID: <20030113202056.26563.qmail@web20504.mail.yahoo.com> I've continued experimenting with wxPython and am proud of my accomplishments (...if I say so myself :-) I managed to "GUIfy" an application I'd written previously. It's fairly simple, GUIwise, but it works. Commands are accessed via menus, output is mostly to the main frame (wxTE_MULTILINE), and input is mostly via dialogue boxes. Now I'd like to move on and improve the interface, but I need help. With one of the commands, currently, users select a name via wxSingleChoiceDialog and things are then done to the record corresponding to the name. Output, again, is to the main frame mentioned above. Here's what I'd like to do ... Upon selecting the command, users would see a wxListBox on one side of the frame and a wxTextControl on the other side of the frame (set up via wxHORIZONTAL sizer, right?). When a user clicks on a name in the list, information will be displayed on the wxTextControl. To do all this, do I need to create an entirely new frame? Any thoughts about how to set this up? As always, thanks ahead of time! -- Al C. __________________________________________________ Do you Yahoo!? Yahoo! Mail Plus - Powerful. Affordable. Sign up now. http://mailplus.yahoo.com From churmtom@hotmail.com Mon Jan 13 15:26:10 2003 From: churmtom@hotmail.com (Tom Churm) Date: Mon Jan 13 15:26:10 2003 Subject: [Tutor] Module Utility Message-ID: hi, before when i used to have ActivePython installed i'd discovered a utility somewhere in the package that, in a console window, displayed what modules where available on some kind of site-repository. if i wanted to, this tool would then connect to this site and download the module. now that i have the 'normal' version of python installed (2.2.2), i can no longer find this thing...is this tool only found in the ActivePython package, or how do i access this util again? (sorry, don't know what it's called...but i found it useful.) thanks much, Tom Churm churmtom@hotmail.com From magnus@thinkware.se Mon Jan 13 15:39:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Jan 13 15:39:01 2003 Subject: [Tutor] Importing a module I made In-Reply-To: <415C917D807AD411B72C00805FF7330B053F835C@MAILSRV> Message-ID: <5.1.0.14.0.20030113205456.0298b9f0@www.thinkware.se> At 16:45 2003-01-13 +0000, Shey Crompton wrote: >Oops, sent this directly to Magnus. Note to self: Use reply all in future. >:-) Another note to Shey (and others whom it might concern): Try to remember not to include more than needed of quotations from other mails when you send messages to a mailing list. There is enough duplication already. (Actually, the list has been fairly tidy lately, well apart from some deviations to topics like 42...) [Many lines snipped] -- 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@thinkware.se Mon Jan 13 15:44:32 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Jan 13 15:44:32 2003 Subject: [Tutor] Shredding files and searching the tutor archives In-Reply-To: <031501c2bb38$99375c20$2502a8c0@emily.ewndsr01.nj.comcast.n et> Message-ID: <5.1.0.14.0.20030113211545.02a53a18@www.thinkware.se> At 14:18 2003-01-13 -0500, andy surany wrote: >http://aspn.activestate.com/ASPN/Mail/Browse/Threaded/python-Tutor > >Upper right secion of the page is a search capability. But does it work? Since I answered the shredder question a month ago, I thought I'd whine a bit to Joshua Miller about not doing his homework before bothering the list. But searching for "shredder", I got no hits, even though the word is used both in Joshuas email now and in the thread about "Working with memory with Python" around December 6 to 8. But what is this? It was Joshua that asked then as well. Did you shred that from your memory??? ;) By the way, I saw that I made a spelling mistake then: > I think you can safely shred a dick if you just grind > it into small enough pieces... Ouch... That should have been disk, not dick. Sorry... I also wrote: >Rule 1. Keep your secrets away from computers. > >Rule 2. If you can't follow Rule 1, make sure your >computer is not networked, and that it's physically >secure. Obviously, a lot of people break this rule and put secrets on networked computers. But then physical protection is certainly an important aspect of the security, together with a lot of other stuff which is off topic here. >Rule 3. There is no Rule 3. ;) Actually, there is a Rule 3: If you really need to have secrets on your disk, use strong encryption. But unless you encrypt the entire disk (all disks?) this is also unsafe. As I wrote a month ago, there might be parts of your data in swap partitions or temporary files, left there by the OS or by software that you used to work with these secret files. And are you certain that there are no trojans or spyware on your computer? -- 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@hkn.eecs.berkeley.edu Mon Jan 13 16:19:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Jan 13 16:19:01 2003 Subject: [Tutor] searching the tutor archives In-Reply-To: <031501c2bb38$99375c20$2502a8c0@emily.ewndsr01.nj.comcast.net> Message-ID: On Mon, 13 Jan 2003, andy surany wrote: > Maybe I'm not understanding the questions, but.... > > http://aspn.activestate.com/ASPN/Mail/Browse/Threaded/python-Tutor > > Upper right secion of the page is a search capability. For people's convenience, we've linked that ActiveState search link to the Python-tutor front page at: http://mail.python.org/mailman/listinfo/tutor Good luck! From mongo57a@comcast.net Mon Jan 13 16:23:01 2003 From: mongo57a@comcast.net (andy surany) Date: Mon Jan 13 16:23:01 2003 Subject: [Tutor] Re: Shredding files and searching the tutor archives Message-ID: <04e201c2bb4a$18b6c380$2502a8c0@emily.ewndsr01.nj.comcast.net> I think that we are both right. Search is working for entries where the date is <10/31/02 (approx.). Looks like it needs to be updated. -----Original Message----- From: Magnus Lycka To: andy surany ; Poor Yorick ; tutor@python.org Cc: Jmllr891@cs.com Date: Monday, January 13, 2003 3:43 PM Subject: Shredding files and searching the tutor archives >At 14:18 2003-01-13 -0500, andy surany wrote: >>http://aspn.activestate.com/ASPN/Mail/Browse/Threaded/python-Tutor >> >>Upper right secion of the page is a search capability. > >But does it work? Since I answered the shredder question >a month ago, I thought I'd whine a bit to Joshua Miller >about not doing his homework before bothering the list. >But searching for "shredder", I got no hits, even though >the word is used both in Joshuas email now and in the thread >about "Working with memory with Python" around December >6 to 8. But what is this? It was Joshua that asked then >as well. Did you shred that from your memory??? ;) > >By the way, I saw that I made a spelling mistake then: > > > I think you can safely shred a dick if you just grind > > it into small enough pieces... > >Ouch... That should have been disk, not dick. Sorry... > >I also wrote: > >>Rule 1. Keep your secrets away from computers. >> >>Rule 2. If you can't follow Rule 1, make sure your >>computer is not networked, and that it's physically >>secure. > >Obviously, a lot of people break this rule and put >secrets on networked computers. But then physical >protection is certainly an important aspect of the >security, together with a lot of other stuff which >is off topic here. > >>Rule 3. There is no Rule 3. ;) > >Actually, there is a Rule 3: > >If you really need to have secrets on your disk, use >strong encryption. > >But unless you encrypt the entire disk (all disks?) >this is also unsafe. As I wrote a month ago, there >might be parts of your data in swap partitions or >temporary files, left there by the OS or by software >that you used to work with these secret files. And are >you certain that there are no trojans or spyware on >your computer? > > > >-- >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 jeff@ccvcorp.com Mon Jan 13 16:35:01 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Mon Jan 13 16:35:01 2003 Subject: [Tutor] Module Utility References: Message-ID: <3E2330A4.1050909@ccvcorp.com> Tom Churm wrote: >hi, > >before when i used to have ActivePython installed i'd discovered a utility >somewhere in the package that, in a console window, displayed what modules >where available on some kind of site-repository. if i wanted to, this tool >would then connect to this site and download the module. > You're probably thinking of PPM (Python Package Manager, IIRC). This is indeed an ActivePython-specific tool, which is installed by default with ActivePython. I don't know if it's available separately, however. The one issue I have with this tool is that the (ActiveState-hosted) site-repository doesn't hold many of the packages that I've needed -- it only holds packages that ActiveState has had the motivation (and the legal right) to put there. (I don't know how much of the lack of packages is due to ActiveState not having the time/motivation/resources to host a wider variety, and how much is due to copyright and other legal issues.) Another side-effect of this is that many of the packages that *are* there, do not have the latest version available, so that anyone needing the latest version (as I have) must go to the package's maintainers anyhow. This is hardly ActiveState's fault -- I'm sure they're doing the best they can under the circumstances -- but it severly limits the usefulness of the tool, at least to me. YMMV, of course. Jeff Shannon Technician/Programmer Credit International From dyoo@hkn.eecs.berkeley.edu Mon Jan 13 16:40:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Jan 13 16:40:02 2003 Subject: [Tutor] Shredding files and searching the tutor archives In-Reply-To: <5.1.0.14.0.20030113211545.02a53a18@www.thinkware.se> Message-ID: On Mon, 13 Jan 2003, Magnus Lycka wrote: > At 14:18 2003-01-13 -0500, andy surany wrote: > >http://aspn.activestate.com/ASPN/Mail/Browse/Threaded/python-Tutor > > > >Upper right secion of the page is a search capability. > > But does it work? Since I answered the shredder question a month ago, I > thought I'd whine a bit to Joshua Miller about not doing his homework > before bothering the list. But searching for "shredder", I got no hits, > even though the word is used both in Joshuas email now and in the thread > about "Working with memory with Python" around December 6 to 8. But what > is this? It was Joshua that asked then as well. Did you shred that from > your memory??? ;) I agree: I'm positive we talked a little bit about file shredding too. http://mail.python.org/pipermail/tutor/2002-December/019095.html http://mail.python.org/pipermail/tutor/2002-December/019098.html The word "shredder" is definitely in the body of those messages, yet ActiveState's search engine isn't seeing it. That's not good. I wonder what kind of indicer they're using. Is ActiveState just indicing the message headers, then? "Indicing" is a preprocessing step that's at the heart of fast search engines; there was an article about this on IBM's developerWorks: http://www-106.ibm.com/developerworks/xml/library/l-pyind.html Maybe it would make a nice project for someone to write a good search engine for Python-Tutor that works better than the one on ActiveState. It can't be that hard, can it? *grin* From gp@pooryorick.com Mon Jan 13 18:33:02 2003 From: gp@pooryorick.com (Poor Yorick) Date: Mon Jan 13 18:33:02 2003 Subject: [Tutor] searching the tutor archives References: Message-ID: <3E234D01.8040003@pooryorick.com> Danny Yoo wrote: > >On Mon, 13 Jan 2003, andy surany wrote: > >>Maybe I'm not understanding the questions, but.... >> >>http://aspn.activestate.com/ASPN/Mail/Browse/Threaded/python-Tutor >> >>Upper right secion of the page is a search capability. >> > >For people's convenience, we've linked that ActiveState search link to the >Python-tutor front page at: > > http://mail.python.org/mailman/listinfo/tutor > > >Good luck! > > > Thank you! If that was there before, I didn't see it because I always access the archives through a link on this page: http://www.python.org/psa/MailingLists.html Perhaps you could note the searchable interface there, too. Poor Yorick gp@pooryorick.com From magnus@thinkware.se Mon Jan 13 19:03:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Jan 13 19:03:02 2003 Subject: [Tutor] wxPython newbie, cont'd. In-Reply-To: <20030113202056.26563.qmail@web20504.mail.yahoo.com> Message-ID: <5.1.0.14.0.20030114010505.02aa7b28@www.thinkware.se> The wxPython-users mailing list is probably a much better forum for questions like these. Subscribe by sending an email to wxPython-users-subscribe@lists.wxwindows.org (I think...) At 12:20 2003-01-13 -0800, Alan Colburn wrote: >Here's what I'd like to do ... Upon selecting the >command, users would see a wxListBox on one side of >the frame and a wxTextControl on the other side of the >frame (set up via wxHORIZONTAL sizer, right?). When a >user clicks on a name in the list, information will be >displayed on the wxTextControl. > >To do all this, do I need to create an entirely new >frame? Any thoughts about how to set this up? -- 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 maillist@kuwest.de Tue Jan 14 03:08:03 2003 From: maillist@kuwest.de (Jens Kubieziel) Date: Tue Jan 14 03:08:03 2003 Subject: [Tutor] Calculating a math formula and finding errors In-Reply-To: References: <20030113103825.GC2584@kubieziel.de> Message-ID: <20030114075620.GA2356@kubieziel.de> On Mon, Jan 13, 2003 at 03:22:07AM -0800, Danny Yoo wrote: > > Have you revised the printed equation on the PDF page, or do you have a > revised version of the LaTeX source? I am curious, and would like to > double check to see if everything else is ok between the mathematics and > the Python program. I changed "i" to "j" in my LaTeX-source and in pdf-version on my page. Everything else is exactly like it is in the magazine. -- Jens Kubieziel mailto:jens@kubieziel.de Decision maker, n.: The person in your office who was unable to form a task force before the music stopped. From stoner_09@hotmail.com Tue Jan 14 04:21:02 2003 From: stoner_09@hotmail.com (uuu uuu) Date: Tue Jan 14 04:21:02 2003 Subject: [Tutor] (no subject) Message-ID: plz unsuscribe me _________________________________________________________________ Protect your PC - get McAfee.com VirusScan Online http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963 From dyoo@hkn.eecs.berkeley.edu Tue Jan 14 04:48:03 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Jan 14 04:48:03 2003 Subject: [Tutor] (no subject) In-Reply-To: Message-ID: On Tue, 14 Jan 2003, uuu uuu wrote: > plz unsuscribe > me Hello uuu uuu, You can unsubscribe yourself by revisiting that page you used to subscribe to Python-tutor: everything's done through the web for your convenience. If you visit: http://mail.python.org/mailman/listinfo/tutor and go down to the bottom, you'll see a form about editing your own options. If you enter that form, you'll see a button for unsubscribing yourself. Once you press that, you should be successfully unsubscribed. If you run into problems while doing this, please feel free to email the administrative address 'tutor-admin@python.org'. This will put you in touch directly with the administrators of the mailing list; we'll be better able to sort out problems that way. Best of wishes to you. From brad.reisfeld@colostate.edu Tue Jan 14 09:50:04 2003 From: brad.reisfeld@colostate.edu (Brad Reisfeld) Date: Tue Jan 14 09:50:04 2003 Subject: [Tutor] How to run a program on Linux from Windows Message-ID: Hi, I have created a complex simulation program in Python (and c/c++/Fortran) that runs on Linux from the command line as well as from a wxPython GUI. This, of course, requires a user to login to the server (and use an X client) to run the program. The GUI version of the program, at present, allows the user to specify input parameters, and once the simulation is complete, to 'interact' with the output (e.g. drill down into the data). I would like to find a method for users to access and run the program from a Windows (and Mac) platform. It would be nice if I could use the same wxPython interface, but another interface or tool would be acceptable. My major concerns are the following: I would like to maintain as much security on the server as possible. I do not want the clients running the program to have to have an x client or have to log in to the server. What are my options here? Can this be done using some sort of communications protocol through a socket? Would a (http protocol) browser-based approach be applicable? Would some sort of remote procedure call be the right approach? Would I create a daemon that would 'listen' for something on a certain port and then fire off the simulation? What Python modules should I be looking at? As you can read from my questions, I am painfully ignorant about the networking issues involved. Pointers to any relevant references are appreciated. Thanks for your help. -Brad From maillist@kuwest.de Tue Jan 14 09:53:02 2003 From: maillist@kuwest.de (Jens Kubieziel) Date: Tue Jan 14 09:53:02 2003 Subject: [Tutor] Calculating a math formula and finding errors In-Reply-To: References: <20030113103825.GC2584@kubieziel.de> Message-ID: <20030114145140.GA5714@kubieziel.de> On Mon, Jan 13, 2003 at 03:22:07AM -0800, Danny Yoo wrote: > def factorial(z): > assert z >= 0, "Invalid input: z must be nonnegative." ^^^^^^ Where can I find some information what this exactly does? I searched my docs and find something on $PYTHONDOC/ref/assert.html. Are there some other examples? Now this function _always_ raises an exception. And I'm a bit perplex ... -- Jens Kubieziel mailto:jens@kubieziel.de So, how's your love life? Still holding your own? From schalla@vasoftware.com Tue Jan 14 10:03:03 2003 From: schalla@vasoftware.com (shobhan) Date: Tue Jan 14 10:03:03 2003 Subject: [Tutor] Adding python handler to httpd.conf Message-ID: <3E242576.4030705@vasoftware.com> Hi Pythoners,

I want to add lines which handle python scripts in httpd.conf so that i can execute the python script via browser. Can anyone tell what lines i've to add to apache conf..??

I am not using mod_python but i have cgi_module.

Thanks in advance
Schalla

From Janssen@rz.uni-frankfurt.de Tue Jan 14 11:42:15 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Tue Jan 14 11:42:15 2003 Subject: [Tutor] assert - was: Calculating a math formula In-Reply-To: <20030114145140.GA5714@kubieziel.de> Message-ID: On Tue, 14 Jan 2003, Jens Kubieziel wrote: > On Mon, Jan 13, 2003 at 03:22:07AM -0800, Danny Yoo wrote: > > def factorial(z): > > assert z >= 0, "Invalid input: z must be nonnegative." > ^^^^^^ > Where can I find some information what this exactly does? I searched my > docs and find something on $PYTHONDOC/ref/assert.html. Are there some > other examples? another bit is in lib/module-exceptions.html#l2h-233: exception AssertionError Raised when an assert statement fails. assert tests if expression is true and raise "AssertionError" if not. In "long form": if not z >= 0: raise AssertionError, "Invalid input: z must be nonnegative." Why to use this? As ref/assert.html states: "Assert statements are a convenient way to insert debugging assertions into a program" - it's shorter and more meaningful than an if-raise statement. Michael > > Now this function _always_ raises an exception. And I'm a bit perplex ... sure? not on my system: >>> def factorial(z): ... assert z >= 0, "Invalid input: z must be nonnegative." ... if z == 1 or z == 0: ... return 1 ... else: ... return z*factorial(z-1) ... >>> for n in range(5,-2,-1): ... print n, ":", factorial(n) ... 5 : 120 4 : 24 3 : 6 2 : 2 1 : 1 0 : 1 -1 : > -- > Jens Kubieziel mailto:jens@kubieziel.de > So, how's your love life? Still holding your own? > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From ramrom@earthling.net Tue Jan 14 11:43:04 2003 From: ramrom@earthling.net (Bob Gailer) Date: Tue Jan 14 11:43:04 2003 Subject: [Tutor] Calculating a math formula and finding errors In-Reply-To: <20030114145140.GA5714@kubieziel.de> References: <20030113103825.GC2584@kubieziel.de> Message-ID: <5.2.0.9.0.20030114093828.034a83a8@66.28.54.253> --=======652C444A======= Content-Type: multipart/alternative; x-avg-checked=avg-ok-3DBD71BC; boundary="=====================_3886538==.ALT" --=====================_3886538==.ALT Content-Type: text/plain; x-avg-checked=avg-ok-3DBD71BC; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 03:51 PM 1/14/2003 +0100, Jens Kubieziel wrote: > def factorial(z): > assert z >= 0, "Invalid input: z must be nonnegative." >Where can I find some information what this exactly does? From the Language Reference: 6.2 Assert statements Assert statements are a convenient way to insert debugging assertions into a program: assert_statement ::= "assert" expression ["," expression] The simple form, "assert expression", is equivalent to: if __debug__: if not expression: raise AssertionError >Now this function _always_ raises an exception. And I'm a bit perplex ... It should raise the exception only for z < 0. That's how it works when I test it. Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=====================_3886538==.ALT Content-Type: text/html; x-avg-checked=avg-ok-3DBD71BC; charset=us-ascii Content-Transfer-Encoding: 8bit At 03:51 PM 1/14/2003 +0100, Jens Kubieziel wrote:

 def factorial(z):
     assert z >= 0, "Invalid input: z must be nonnegative."
Where can I find some information what this exactly does?

From the Language Reference:

6.2 Assert statements

Assert statements are a convenient way to insert debugging assertions into a program:
assert_statement  ::=  "assert" expression ["," expression]
The simple form, "assert expression", is equivalent to:
if __debug__:

   if not expression: raise AssertionError
Now this function _always_ raises an exception. And I'm a bit perplex ...
It should raise the exception only for z < 0. That's how it works when I test it.

Bob Gailer
mailto:ramrom@earthling.net
303 442 2625
--=====================_3886538==.ALT-- --=======652C444A======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-3DBD71BC Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.438 / Virus Database: 246 - Release Date: 1/7/2003 --=======652C444A=======-- From maillist@kuwest.de Tue Jan 14 12:32:02 2003 From: maillist@kuwest.de (Jens Kubieziel) Date: Tue Jan 14 12:32:02 2003 Subject: [Tutor] assert - was: Calculating a math formula In-Reply-To: References: <20030114145140.GA5714@kubieziel.de> Message-ID: <20030114173134.GB1337@kubieziel.de> On Tue, Jan 14, 2003 at 05:41:17PM +0100, Michael Janssen wrote: > In "long form": > if not z >= 0: > raise AssertionError, "Invalid input: z must be nonnegative." OK, understood. > > Now this function _always_ raises an exception. And I'm a bit perplex ... > > sure? not on my system: I guess there was a typo which I didn't saw. Thanks for your help -- Jens Kubieziel mailto:jens@kubieziel.de You have been bitchy since Tuesday and you'll probably get fired today. From schalla@vasoftware.com Tue Jan 14 13:11:03 2003 From: schalla@vasoftware.com (shobhan) Date: Tue Jan 14 13:11:03 2003 Subject: [Tutor] How to execute the file with root permissions from the browser..?? Message-ID: <3E245184.10602@vasoftware.com> Hi Pythoners,

Im executing a python on the browser, the script has some commands which should be executed as root user, but the problem is when i execute the
script in the browser its executed as httpd user and httpd user cannot execute the commands in the python script.

Is there anyway where i can set the UID to user in this script so that the httpd user can execute the script with root permissions...??

if anyone can give sample script that would be grateful

Thanks in advance
Schalla

From darwinchrisman@hotmail.com Tue Jan 14 13:18:02 2003 From: darwinchrisman@hotmail.com (Darwin Chrisman) Date: Tue Jan 14 13:18:02 2003 Subject: [Tutor] recursive loop strange behavior Message-ID:

Using: 
Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32
with Idle 0.8
 
This is the function I created:
def factor(num,primes,tempres=[]):
     res=tempres
     for x in primes:
          if num in primes:
               res.append(num)
               break
         if math.fmod(num,x)==0:
               res.append(x)
               factor(num/x,primes,res)
               break
         if num**.5 < x:
         res.append(num)
         break
     return res
 
the function itself seems to work fine, however if I dont specify an empty list for tempres when I call the function the next time I call it tempres defaults to the last value the function returned.
I can't figure out what I am doing wrong. Any help?
 
Thanks,
 
Darwin 


get 2 months FREE* From jeff@ccvcorp.com Tue Jan 14 13:38:10 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Tue Jan 14 13:38:10 2003 Subject: [Tutor] recursive loop strange behavior References: Message-ID: <3E2458A1.1080507@ccvcorp.com> Darwin Chrisman wrote: > This is the function I created: > def factor(num,primes,tempres=[]): > [...] > > the function itself seems to work fine, however if I dont specify an > empty list for tempres when I call the function the next time I call > it tempres defaults to the last value the function returned. > I can't figure out what I am doing wrong. Any help? The problem here is that Python only evaluates default arguments *once*, when the function is defined -- not each time it's called, which is what you seem to be expecting. So the second (and subsequent) times that you call factor(), you're getting the *same* list that it started out with -- and now it's not empty. The quickest solution is to change the default to be None, and test for that inside your function. def factor(num, primes, res = None): if not res: res = [] [...] This way, you'll create a *new* empty list every time you call this function without a res argument. Jeff Shannon Technician/Programmer Credit International From ahimsa@onetel.net.uk Tue Jan 14 16:50:01 2003 From: ahimsa@onetel.net.uk (ahimsa) Date: Tue Jan 14 16:50:01 2003 Subject: [Tutor] Fixed freezing problem, have new one (fwd) In-Reply-To: <081601c2ba83$a3004060$ea10ba3f@defaultcomp> References: <1042405762.1789.929.camel@localhost.localdomain> <081601c2ba83$a3004060$ea10ba3f@defaultcomp> Message-ID: <1042574809.1789.988.camel@localhost.localdomain> On Sun, 2003-01-12 at 21:43, Don Arnold wrote: > Danny's replies are always worth waiting for, so I'll steer clear of > commenting on the code itself. But to answer a question from one of your > other mails: > Yep - it's next on my Python-Tutor Inbox list, so I'm getting there ... :) > "... why would you need to know the number of sides on a die ...? ... > doesn't the number of > sides on a dice stay constant (as in 6)?" > > Though 6-sided dice are the norm, 4, 8, 10, 12, and 20-sided ones (among > others) exist and are commonly used in pencil-and-paper roleplaying games. Aaaah - enlightenment. Had no idea!! > > Geekily yours, > Don Naively yours Andrew =) -- ahimsa From ahimsa@onetel.net.uk Tue Jan 14 16:50:11 2003 From: ahimsa@onetel.net.uk (ahimsa) Date: Tue Jan 14 16:50:11 2003 Subject: [Tutor] re: Leap year problem In-Reply-To: <080101c2ba82$1f7bff50$ea10ba3f@defaultcomp> References: <1042402474.1124.882.camel@localhost.localdomain> <080101c2ba82$1f7bff50$ea10ba3f@defaultcomp> Message-ID: <1042574660.1785.985.camel@localhost.localdomain> Hi Don I know this is a bit belated, but dammit ... that work thing :-) On Sun, 2003-01-12 at 21:32, Don Arnold wrote: > The problem here is that the 'if ... elif ... else' construct exits as soon > as one of its conditions is met. If year is divisible by 100, it satisfies > the initial 'if' and falls through the rest of the structure, so you never > get to the later tests. If you want to structure it like this, you have to > start with the most specific test and work toward the more general ones: > > def isLeapYear(year): > if year % 400 == 0: > return 1 > elif year % 100 == 0: > return 0 > elif year % 4 == 0: > return 1 > else: > return 0 > OK - that makes sense to me, I thought by seeing if it divided by '100' first it would eliminate it from going through the rest of the conditions. Are there any quick and dirty guidelines about how one makes those kinds of determinations when constructing conditional statements - e.g. test large numbers first, or test for the rarely occurring variable first, or ... ? I don't know how clear that question is. If it isn't clear, let me know and I'll see if I can rephrase it. For instance, the above guideline is, as you've stated, check initially for the specifics of a case and then move to the more general. Would that apply in most cases with a conditional suite? > This implements the definition that Goncalo gave. To avoid having to order > your tests from specific to general, you can eliminate the elif's by > combining the conditions into a single one: > > def isLeapYear2(year): > if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0): > return 1 > else: > return 0 > Actually arranging these all on a line is new to me (which shouldn't come as a surprise considering that the whole language and endeavour is new to me!!!), and I hadn't come across it in the books and tutorials I have been reading ... probably just haven't gotten to that part yet. So, just to deconstruct this part if I may ... because 'if' and 'and' and 'or' are keywords, the Python interpreter reads these the same *as if* they were arranged in a vertical hierarchy, and also reads from right to left? Because you have specified that '100 != 0' (which would be the test to eliminate those years that do divide by 100 with no remainder), the year entered must satisfy *all* of these criteria to return a positive '1' value, or else will return a false '0' value. If the user enters a nonyear (e.g. a string that cannot be divided), will the failure of the input also be caught as a 0 or does one still need to add an additional error catch to this? I suspect that 'else: return 0' should be sufficient, but just want to confirm this. > This is close to a word-for-word translation of the definition I gave, and > (IMO) is easier to read. Either way, the net result is the same: > > year = int(raw_input('year: ')) > while year != -1: > print 'isLeapYear :', isLeapYear(year) > print 'isLeapYear2:', isLeapYear2(year) > print '' > year = int(raw_input('year: ')) > > [begin script run] > year: 2000 > isLeapYear : 1 > isLeapYear2: 1 > > year: 1900 > isLeapYear : 0 > isLeapYear2: 0 > > year: 1996 > isLeapYear : 1 > isLeapYear2: 1 > > year: 1997 > isLeapYear : 0 > isLeapYear2: 0 > > year: -1 > [end script run] > This is a bit confusing, so I want to pick this apart too if you can bear with me while I plod through this: These are my understandings line by line, please steer me right if I'm going off track here. line 1 => gets user input line 2 => runs program on the proviso that a number >= 0 is entered at input thereafter you are testing both ways of writing the program given specific years using '1' for yes it is a leap year and '0' for not. The last line with '-1' stops the program because it violates the while condition? > Also, it's a good idea to explicitly return 0 for false. If you don't > specify a return value, the function will return None. That works here, but > one of Python's guiding principles is 'Explicit is better than implicit'. Good point. Thanks. > I think that's probably how most of us got started programming. If anything, > I'd say it's fortunate, since you're studying this because you're interested > in it, not just because someone is making you. Well I am interested that's for sure, I'm sorry though if I'm being too pedantic about all of this. I come from a psych and philosophy background, and this really does require a different way of thinking, so I am trying to retrain my brain. > HTH, It did - thank you :) Andrew -- ahimsa From ahimsa@onetel.net.uk Tue Jan 14 16:51:02 2003 From: ahimsa@onetel.net.uk (ahimsa) Date: Tue Jan 14 16:51:02 2003 Subject: [Tutor] Fixed freezing problem, have new one (fwd) In-Reply-To: References: Message-ID: <1042579513.1789.1067.camel@localhost.localdomain> On Mon, 2003-01-13 at 01:01, Danny Yoo wrote: > Ok, I'm back! > Hope your lunch was good Danny :) > > Don Arnold answered your first question, so I can skip to the next one: He did - and the learning never stops!!! Even about dice! > > The module (or function) then initialises a control structure - the > > 'while' loop - that sets up the minimum limit as an error control - i.e. > > if the dice is not rolled, there can't be any output. > > Right: if we say something like "Roll zero numbers of dice", we should get > some kind of empty output from the program. But we want to be careful > what we mean by "empty" though: do we want to literally get the word > "empty"? Hmmmm - maybe I've lost the plot, but if the 'while' lopp controls the program by preventing it from beginning if no dice are rolled, then 'rolling zero numbers of dice' really would be 'nothing happens' - as in the program cannot begin because the first condition is not met. So I'm not sure how anything would happen after that point regardless of the hypothetical output of zero dice rolling (what is the sound of one hand clapping anyway?). What am I missing? > ### > def dice(number, sides): > if number <= 0: > return "empty" > ... > ### Why would this need to be included as part of the (function - is this what this is called or is it a module?) when it could be established as the first line of the program that decides whether or not this function/module should even be called. For me, and using a totally off-track analogy, it is a bit like this: while doorbell == ringing, open door. If doorbell != ringing, ergo door does not get opened. So why could the 'null' of this be controlled using the initial while, rather than including it in the definition as you seem to have done above? > or should we use the None value, or something else? It may seem a little > nitpicky, but it actually does matter if we go for a recursive definition > of dice(). We can talk about this if you'd like. > > Yes, 'random' is a module that's in the Standard Library. It's > specialized for generating "pseudorandom" numbers. There's some > documentation about the 'random' module here: > > http://www.python.org/doc/lib/module-random.html > If you read this, I'd recommend skipping down near the middle where the > docs describe the "Functions for integers"; the stuff at the top and > bottom is also very useful, but a bit specialized. > Thanks, I'll chase that link down. There is a lot of info about the modules to read up on, so that's as good a place as any to start. > Tthat's because the code needs a little retooling: it's doing more work > than it really needs to do. I didn't want to just roll in refinements to > the code all at once without some kind of feedback. Guess it's time to > charge forward! OK ... charging forward ... > > Let's take a look at it again: > > ### > def dice(number,sides): > while number > -1 : > value = random.randint(0, sides) > number = number + 1 > return value, dice(number - 2, sides) > ### > > As an intermediate step, I'm going to do something that might look a > little weird and arbitrary: I will change that 'while' loop into an 'if' > block. > > ### > def dice(number,sides): > if number > -1 : > value = random.randint(0, sides) > number = number + 1 > return value, dice(number - 2, sides) > ### > > This has the same effect as the original code because, even though the > original code used a "while loop", there was no looping involved due to > that 'return' statement at the end of the loop body. But let's double > check that this still works. > > ### > >>> dice(3, 6) > (6, (0, (3, (0, None)))) > ### > > That's a bit odd. It's giving us FOUR dice rolls instead of three! The > original code had the same problem because the condition we're checking, > > number > -1 > > is too permisive: we should really be checking if we're rolling a nonempty > number of dice: > > number > 0. > > > Let's make that change: > > ### > def dice(number, sides): > if number > 0: > value = random.randint(0, sides) > number = number + 1 > return value, dice(number - 2, sides) > ### > > Let's try that again. > > ### > >>> dice(3, 6) > (6, (0, (0, None))) > >>> dice(3, 6) > (4, (4, (1, None))) > >>> dice(3, 6) > (5, (0, (3, None))) > >>> dice(3, 6) > (4, (5, (5, None))) > >>> dice(3, 6) > (6, (2, (6, None))) > >>> dice(3, 6) > (1, (1, (2, None))) > ### > > > Ah, better. Sorry about getting sidetracked there. *grin* > > > Let's go back to your question. > > > Why then would you increment the number through 'number+1'? And, again, > > why have the value returned as 'dice(number-2, ...' - why would you > > subtract the 2? > > That's because it's doing too much work. If we go one step forward, and > two steps backwards, we end up one step backward. But how do we see this > without just stating it? And how do we fix it? > OK - I need to butt in here. I followed your explanation that the while loop was not really doing what a while loop is supposed to do because of the return statement; I also followed substituting the 'if' block, and also that the -1 was too 'permissive' (I assume because 0 is greater than -1 which would screw up the idea that if the dice aren't rolled/no dice are rolled x times, still yields a value of 0 - is that what you were meaning - and so correcting that by stating explicitly that it had to be a greater number of rolls than zero?). I'm stumbling over the 'number + 1'. Why are you doing that? What does the number + 1 do that is needed by the program that number by itself wouldn't do? And this gets even more confusing for me, because then later you are taking 2 off ( - 2 ). Taking 1 step fwd and 2 back *does* leave one 1 step back, but what does this have to do with programming a dice rolling program? There is obviously something that I am missing here about how you are conceptualising the components of a dice-rolling program. I would have approached it as (sorry, not fluent enough in code or psuedocode to write it out) something like: number of dice x number of rolls x 6 (still thinking of only 6-sided dice here) = whatever. The random module would be entered ... well, this is where my conception of the problem breaks down. I know that the random aspect needs to be included to represent the randomness of an actual (physical reality) dice throw, but not sure where to put it in. I'm not sure how else to ask this one, because this is the major stumbling point for me I reckon: how you are conceiving of the problem, and then conceiving of the solution. As an aside, I have just started (literally) reading the book by Abelson and Sussman "Structure & Interpretation of Computer Programs" http://mitpress.mit.edu/sicp/full-text/book/book.html and something they write in their 'Preface to the First Edition' really resonates for me and since it is related to my point above, I'll share it here: "[computer language] is a novel formal medium for expressing ideas about methodology" and later in the same section "The computer revolution is a revolution in the way we think and in the way we express what we think. The essence of this [...] is the emergence of what might best be called *procedural epistemology* - the study of the structure of knowledge from an imperative point of view [...]". And I reckon that does sum up where I am coming from with this question group Danny (and others): learning how to think about problems in such ways that the solutions proposed to those problems can be formally expressed in computational form. I suspect that once I am able to acquire that skill, then the formalities of the language itself become secondary. Anyway, I digress slightly, but I'd be interested in your perspectives on this too. > Let's do something unusual by trying to follow an artificial programming > restriction: we won't allow "rebinding" a variable name that's already > defined, but instead we'll add a new temporary variable. In technical > terms, we'll be "Introducing a Temporary Variable". That is, we're not > going to do any variable name reassignments. Are you saying that, for e.g.: you will not assign 1 to x and then assign 3 to x later, but rather, will make y take on the value of 3 instead of x? > It's a little weird, but we'll see in a moment why this is a good idea. > What does dice() look like if we follow this restriction? > > ### > def dice(number, sides): > if number > 0: > value = random.randint(0,sides) > next_number = number + 1 > return value, dice(next_number - 2, sides) > ### > > > That programming rule --- no rebinding --- that we followed above isn't > actually as arbitrary as it seems. It suddently allows us to do > "plugging-in" safely. Whereever we see 'next_number', we can now > "plug-in" and substitute the right-hand side value of 'next-number' and > still have a program that behaves the same way: > Sorry - I'm not getting this very clearly. I think I am, then try to explain it to myself and realise that I haven't got it. (a) Why are you doing this? What are you attempting to demonstrate? and (b) what are you meaning by 'plugging in'? It is probably really obvious but I still can't see it. Was this to demonstrate that we are taking 1 step forward and 2 backwards in computational terms (i.e. that the program is working too hard)? > ### > def dice(number, sides): > if number > 0: > value = random.randint(0, sides) > next_number = number + 1 > return value, dice((number + 1) - 2, sides) > ### > > > Once we've done this, we can just drop the initial assignment to > 'next_number', since 'next_number' is a useless variable that's not being > used anywhere anymore. > > > ### > def dice(number, sides): > if number > 0: > value = random.randint(0,sides) > return value, dice(number + 1 - 2, sides) > ### > > I don't think I need to outline the next step. *grin* But let's see what > dice() looks like now: > > ### > def dice(number, sides): > if number > 0: > value = random.randint(0, sides) > return value, dice(number - 1, sides) > ### > Does this revision make more sense? > > > > Please feel free to ask more questions about this; I know I went fast on > that one, but it's an exciting topic: if we're careful about reassignment, > we can do controlled manipulation of our programs to clean them up. It's > almost like factoring math equations to make them easier to understand. I can tell that there is a lot for me to learn here, because I was obviously pretty lost at times. I must confess though that it does seem a little less daunting than it did initially and makes a pseudo-sense to me as long as I don't probe that sense too critically. I think I am getting the drift of what you were attempting but would definitely not even know how to approach doing it myself. I am keeping this and as I continue with my readings and practice will refer back to this as a touchstone of sorts. Thank you for taking so much effort in doing this Danny, and I do apologise for the basic level of my questions. If this level is too tedious for this list I'm happy to take this off-list if that would be preferable. I will soldier on. Very much appreciated. Andrew -- ahimsa From ahimsa@onetel.net.uk Tue Jan 14 16:51:13 2003 From: ahimsa@onetel.net.uk (ahimsa) Date: Tue Jan 14 16:51:13 2003 Subject: [Tutor] Leap years In-Reply-To: <20030112215436.GA4866@nl.linux.org> References: <1042391564.1789.715.camel@localhost.localdomain> <074c01c2ba67$99158f40$ea10ba3f@defaultcomp> <20030112215436.GA4866@nl.linux.org> Message-ID: <1042574946.1789.991.camel@localhost.localdomain> On Sun, 2003-01-12 at 21:54, Gerrit Holl wrote: > I think it's better to use True and False here. > Instead of "return 1", "return True". > Instead of "return 0", "return False". > > It's boolean what's being expected from this function; not an integer. > It's not natural to return an integer, as it's not natural to return > a empty or non-empty sequence. > What kind of difference does the return actually make? I know that 'true' /'false' is more user friendly for the person awaiting output perhaps, but does it make any difference with respect to the programming itself? Andrew -- ahimsa From ahimsa@onetel.net.uk Tue Jan 14 16:51:27 2003 From: ahimsa@onetel.net.uk (ahimsa) Date: Tue Jan 14 16:51:27 2003 Subject: [Tutor] Leap years In-Reply-To: References: Message-ID: <1042579719.1789.1071.camel@localhost.localdomain> Hello It's me again ... On Mon, 2003-01-13 at 11:39, Danny Yoo wrote: > Hi Don, > > But even better than explicitely returning True or False is to avoid using > the 'if' statement altogether. The pseudocode above can be written like > this: > > ### > def isLeapYear(year): > return (year passes test for a leap year) > ### > > That is, if we're going to do something like: > > if something is true: > return true > else: > return false > > it's usually an improvement to be direct and just say > > return (something is true) > > which is concise and avoids the controversy of using 0/1/True/False > altogether. *grin* > But ... how does one construct the test of whether something is true or not without the test to establish that, which is what the 'if-else' block was intended to do? Puzzled ... :) Andrew From wilson@visi.com Tue Jan 14 17:23:01 2003 From: wilson@visi.com (Tim Wilson) Date: Tue Jan 14 17:23:01 2003 Subject: [Tutor] Leap years In-Reply-To: <1042579719.1789.1071.camel@localhost.localdomain> References: <1042579719.1789.1071.camel@localhost.localdomain> Message-ID: <200301141621.23351.wilson@visi.com> On Tuesday 14 January 2003 15:52, ahimsa wrote: > But ... how does one construct the test of whether something is true or > not without the test to establish that, which is what the 'if-else' > block was intended to do? That's a good question. Look at the following: wilson@copland:~> python Python 2.2.1 (#1, Oct 15 2002, 03:52:39) [GCC 3.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> def isEven(num): =2E.. if num % 2 =3D=3D 0: =2E.. return 1 =2E.. else: =2E.. return 0 =2E.. >>> isEven(4) 1 >>> isEven(5) 0 >>> def isEven(num): =2E.. return num % 2 =3D=3D 0 =2E.. >>> isEven(4) 1 >>> isEven(5) 0 I've created a very simply boolian function to illustrate this. The first version is certainly more explicit. If you haven't run across i= t=20 yet, the % operator in Python is called "mod" and is the same as the=20 remainder concept you probably recall from elementary school math class. = In=20 this case, any number that has 0 remainder when divided by 2 is event and= =20 anything else is odd. For a given value of "num," the statement num % 2 =3D=3D 0: is either true or false. By using the construct return num % 2 =3D=3D 0 I'm simply evaluating the "trueness" :-) of the num % 2 =3D=3D 0 expressi= on and=20 returning that straight away. As always, this idiom is optional, but quit= e=20 elegant I think. -Tim --=20 Tim Wilson Twin Cities, Minnesota, USA Science teacher, Linux fan, Zope developer, Grad. student, Daddy mailto:wilson@visi.com | http://qwerk.org/ | public key: 0x8C0F8813 From magnus@thinkware.se Tue Jan 14 17:33:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Jan 14 17:33:01 2003 Subject: [Tutor] How to execute the file with root permissions from the browser..?? In-Reply-To: <3E245184.10602@vasoftware.com> Message-ID: <5.1.0.14.0.20030114232308.02be6730@www.thinkware.se> At 23:35 2003-01-14 +0530, shobhan wrote: >Is there anyway where i can set the UID to user in this script so that the >httpd user can execute the script with root permissions...?? I hope you have considered the security implications of this. It's not typically recommended to run root only programs from the web. The typical unix way of solving this is to solve this by setting permission bits with chmod. See http://catcode.com/teachmod/setuid.html for instance. But to use set uid root is typically considered a big security risk, especially for scripts. -- 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 mongo57a@comcast.net Tue Jan 14 17:42:45 2003 From: mongo57a@comcast.net (andy surany) Date: Tue Jan 14 17:42:45 2003 Subject: [Tutor] An OO question Message-ID: <003501c2bc1e$1f166f80$2502a8c0@emily.ewndsr01.nj.comcast.net> Hi all, I have a class which creates (among many other things....), a simple pop-up window (using Tk), as follows: class WINMENU: def assist(self): self.popup=Toplevel(root) (Magnus, you will be pleased to note that I have learned not to throw away my reference......) Now, I have another class where I have written a mouse interrupt handler. class SCROLLEDLIST: def mouse_handler(self): What I want to do is on mouse interaction (in the main window), write something to the already created popup. I thought that I would just create an instance of "assist" in mouse_handler - but then I realized that it is not my method that needs to be referenced, but rather the window that was already created. I could use a bit of advice here.... TIA -Andy From magnus@thinkware.se Tue Jan 14 17:53:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Jan 14 17:53:01 2003 Subject: [Tutor] How to run a program on Linux from Windows In-Reply-To: Message-ID: <5.1.0.14.0.20030114233227.02bfddd0@www.thinkware.se> At 07:49 2003-01-14 -0700, Brad Reisfeld wrote: >I would like to find a method for users to access and run the program from a >Windows (and Mac) platform. It would be nice if I could use the same >wxPython interface, but another interface or tool would be acceptable. I assume that it's out of the question to actually run the program entirely on the Windows or Mac box? Otherwise that sounds like the simplest solution. Then the users won't load your Linux box! :) If you have used a layered approach in your code, with a thin GUI layer which isn't deeply involved in the application logic, it should certainly be possible to turn it into a client/server application. See the first three links below for ideas about how to implement that. >What are my options here? Plenty... >Can this be done using some sort of communications protocol through a >socket? Yes. >Would a (http protocol) browser-based approach be applicable? Yes. >Would some sort of remote procedure call be the right approach? Yes. >Would I create a daemon that would 'listen' for something on a certain port >and then fire off the simulation? Yes. >What Python modules should I be looking at? There are a number of different options here. Some resources: http://www.python.org/doc/current/lib/module-socket.html http://www.python.org/doc/current/lib/module-xmlrpclib.html http://www.python.org/doc/current/lib/module-SimpleXMLRPCServer.html http://www.thinkware.se/cgi-bin/thinki.cgi/UsingPythonWithOtherLanguages#line100 http://www.thinkware.se/cgi-bin/thinki.cgi/PythonForInternet#line23 http://pyro.sourceforge.net/ http://www.vex.net/parnassus/apyllo.py?i=549099265 http://www.zope.org/ http://www.cherrypy.org/ http://www.mems-exchange.org/software/quixote/ http://twistedmatrix.com/ http://www.python.org/cgi-bin/moinmoin/GoClientServer -- 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 ahimsa@onetel.net.uk Tue Jan 14 17:59:02 2003 From: ahimsa@onetel.net.uk (ahimsa) Date: Tue Jan 14 17:59:02 2003 Subject: [Tutor] Leap years In-Reply-To: <200301141621.23351.wilson@visi.com> References: <1042579719.1789.1071.camel@localhost.localdomain> <200301141621.23351.wilson@visi.com> Message-ID: <1042585187.1124.1092.camel@localhost.localdomain> Hello Tim :) On Tue, 2003-01-14 at 22:21, Tim Wilson wrote: > The first version is certainly more explicit. If you haven't run across it > yet, the % operator in Python is called "mod" and is the same as the > remainder concept you probably recall from elementary school math class. In > this case, any number that has 0 remainder when divided by 2 is event and > anything else is odd. > 'mod' as in 'modulus' - where it only yields the remainder or balance of the division rather than the number of times it is divisible? > For a given value of "num," the statement > > num % 2 == 0: > > is either true or false. By using the construct > > return num % 2 == 0 > > I'm simply evaluating the "trueness" :-) of the num % 2 == 0 expression and > returning that straight away. As always, this idiom is optional, but quite > elegant I think. I agree - I reckon that that *is* a really elegant way of doing this: it appeals to my appreciation of minimalism. Would you mind explaining - or referring me to an explanation of - the mechanics of this process where you are doing away with the the if-else test. I note that 'return' is a keyword/reserved word in Python, but I haven't found out what it does precisely. I am surmising that it 'returns' the value of an evaluation, but from the example you give above, it appears as if somehow it is also encapsulates the truth/falsity of an evaluation (does that make sense?) - i.e. 'squashes' or 'compresses' the 'if-else' test into a single 'function' (I'm not sure of the correct terminology here, sorry). If you could, I would appreciate it if you could unpack how 'return' works and also the data types or evaluation types it works with. Nevertheless, I do agree that it is an elegant substitution, and functionally/operationally seems exactly the same as the 'if-else' test. Thanks for the illustration. Andrew -- ahimsa From tim@johnsons-web.com Tue Jan 14 18:02:02 2003 From: tim@johnsons-web.com (Tim Johnson) Date: Tue Jan 14 18:02:02 2003 Subject: [Tutor] Comparative code questions: Python vs. Rebol Message-ID: <20030114230533.GK5446@johnsons-web.com> Hello All: I'm writing a column where I am comparing certain simple coding tasks in different programming languages. This time, I doing 'rebol' and 'python'. My first example is swapping values with a temporary variable (and I lifted this right out of "The Python Cookbook") # Python a,b,c = c,b,a ; Rebol set [a b c] reduce [c b a] Now here is a more complex example: Dynamically compose a series of functions such that # python print H3("This an html header of level 3") >>> "

This is an html header of level 3

" ; Rebol print H3 "This an html header of level 3" >> gives the same and so on from level 1 through level 6 In rebol, it works this way: repeat count 6[ do rejoin[ "H" count ": sub[val][val: reduce val ml[H" count "[(val)]]]" ] ] ; Here rebol composes a series of 6 strings and evaluates them as source ; code for functions, which are then installed in memory. ; Works well for short functions which may have small variances ; in a general code template Is it possible to do this in python? If so, an example would be appreciated. This will be published at http://www.frozen-north-linuxonline.com/ under the label "Code Corner". And frankly it's good way for me to ease back into Python... I've got to do some work with it. Thanks (and I hope I'm being clear here...) -- Tim Johnson http://www.alaska-internet-solutions.com http://www.johnsons-web.com From sarmstrong@shearwatercorp.com Tue Jan 14 18:03:37 2003 From: sarmstrong@shearwatercorp.com (SA) Date: Tue Jan 14 18:03:37 2003 Subject: [Tutor] Question on Time calculations. Message-ID: <788D1745-2814-11D7-B77E-00039315F4DA@shearwatercorp.com> How would I go about calculating a time using python. For instance. I have to do alot of calculations that take a specific calender date and a specific time for that day. Then, lets say five days later, I need to substract that date and time from the current date and time to produce an answer of how many total hours and minutes have elapsed: date/time2 - date/time1 = total elapsed hours/minutes Any ideas? Thanks. SA "I can do everything on my Mac I used to do on my PC, plus alot more ..." --Me From magnus@thinkware.se Tue Jan 14 18:12:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Jan 14 18:12:01 2003 Subject: [Tutor] An OO question In-Reply-To: <003501c2bc1e$1f166f80$2502a8c0@emily.ewndsr01.nj.comcast.n et> Message-ID: <5.1.0.14.0.20030114235306.02c2a008@www.thinkware.se> At 17:41 2003-01-14 -0500, andy surany wrote: >I have a class which creates (among many other things....), a simple >pop-up window (using Tk), as follows: > >class WINMENU: > def assist(self): > self.popup=Toplevel(root) I'm more of a wxPython-man myself, but should a pop-up really be a Toplevel? Aren't dialogs etc better suited for that. Being a top level window and a pop-up sound a bit like an oxymoron to me. >(Magnus, you will be pleased to note that I have learned not to throw >away my reference......) I was just going to ask about that! ;) >Now, I have another class where I have written a mouse interrupt >handler. > >class SCROLLEDLIST: > def mouse_handler(self): I assume this is just pseudo code. It seems a bit odd to have GUI classes with names like that in a Tkinter program that don't inherit from the Tkinter classes. >What I want to do is on mouse interaction (in the main window), write >something to the already created popup. I thought that I would just >create an instance of "assist" in mouse_handler - but then I realized >that it is not my method that needs to be referenced, but rather the >window that was already created. Do I understand correctly that a method in the ScrolledList (to use a more conventional way of writing class names) wants to do something in the self.popup of a WinMenu instance? I would write a method for this in WinMenu to avoid making Demeter very angry. class WinMenu: def assist(self): self.popup = ... def writeToPopup(self, message): self.popup.textLabel['text'] = message # or whatever I assume you can find a reasonable way of making the appropriate (maybe there is just one) instance of WinMenu available to the instance of ScrolledList. -- 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@thinkware.se Tue Jan 14 18:38:06 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Jan 14 18:38:06 2003 Subject: [Tutor] Question on Time calculations. In-Reply-To: <788D1745-2814-11D7-B77E-00039315F4DA@shearwatercorp.com> Message-ID: <5.1.0.14.0.20030115003632.02c087b0@www.thinkware.se> At 17:04 2003-01-14 -0600, SA wrote: >How would I go about calculating a time using python. In Python 2.2 or earlier: Use mxDateTime In Python 2.3 (or later?): Use the new DateTime module. -- 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@hkn.eecs.berkeley.edu Tue Jan 14 18:56:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Jan 14 18:56:01 2003 Subject: [Tutor] Leap years [return / if true return true else return false] In-Reply-To: <1042585187.1124.1092.camel@localhost.localdomain> Message-ID: > > I'm simply evaluating the "trueness" :-) of the num % 2 == 0 > > expression and returning that straight away. As always, this idiom is > > optional, but quite elegant I think. > Would you mind explaining - or referring me to an explanation of - the > mechanics of this process where you are doing away with the the if-else > test. > I note that 'return' is a keyword/reserved word in Python, but I haven't > found out what it does precisely. I am surmising that it 'returns' the > value of an evaluation, Yes. The 'return' keyword only makes sense if we're doing it within a function defintion though: return by itself doesn't make too much sense: ### >>> return SyntaxError: 'return' outside function ### But when we are withing a function, 'return' tells the system that the function "evaluates" to the returned value. For example: ### >>> def square(x): ... return x * x ... >>> square(3) + square(4) == square(5) 1 ### When Python encounters something like: square(3) + square(4) == square(5) it will take those three things "square(3)", "square(4)", and "square(5)", and try to run them --- to evaluate them --- and find out what values they correspond to, before doing the equality comparison. square(3) + square(4) == square(5) ==> 9 + square(4) == square(5) ==> 9 + 16 == square(5) ==> 25 == square(5) ==> 25 == 25 ==> True Actually, I have no clue what order Python will do the evaluation of those squares. *grin* I did it left-to-right, but that's just because I'm used to reading left-to-right. But if we went at it a different direction, we still should get the same answer, just as long as the check for equality is done last. Actually, we can do something unusual by forcing a particular order of evaluation by using parentheses. Can you think what might happen if we do something like: square(3) + (square(4) == square(5)) Think it out first, and then try it in the interpreter. > but from the example you give above, it appears as if somehow it is also > encapsulates the truth/falsity of an evaluation (does that make sense?) Ah: the return statement gives back its value unmolested: it can return any Python value (numbers/strings/other functions/classes/...). That's what makes it nice and versatile. There are certain expressions in Python that directly evaluate to true-and-false values. The most familiar of these are expressions that use "comparison" operations. ### >>> "apple" < "pie" ## less than comparison 1 >>> len("apple") < len("pie") ## less than comparison 0 >>> "lisp" == "l" + "i" + "s" + "p" ## equality comparison 1 ### And when we find ourselves using 'if' and 'return' statements in a certain pattern: ### def some_function(): if [some_expression]: return True else: return False ### we can remove the middle man, and just directly return the value of some_expression: ### def some_function_revised(): return [some_expression] ### For example: ### def is_vowel(letter): if letter in ('a', 'e', 'i', 'o', 'u'): return True else: return False ### fits this pattern, so we can apply our technique. If you're interested, try it out and see that it does work. Good luck to you! From john@hazen.net Tue Jan 14 19:20:02 2003 From: john@hazen.net (John Hazen) Date: Tue Jan 14 19:20:02 2003 Subject: [Tutor] Comparative code questions: Python vs. Rebol In-Reply-To: <20030114230533.GK5446@johnsons-web.com> Message-ID: On Tue, 14 Jan 2003, Tim Johnson wrote: > Dynamically compose a series of functions such that > # python > print H3("This an html header of level 3") > >>> "

This is an html header of level 3

" > > In rebol, it works this way: > repeat count 6[ > do rejoin[ "H" count ": sub[val][val: reduce val ml[H" count "[(val)]]]" ] > ] > > Is it possible to do this in python? If so, an example would > be appreciated. Here's my first shot: >>> for i in range(1,7): ... exec ("def H%d(txt): return '' + txt + ''" % (i,i,i)) ... >>> H3("foo") '

foo

' *Note: I am still a relative newbie, so I would wait for further comments before publishing. There may be a more elegant way to do this with list comprehensions that only needs to reference i once. Also, for production code, I would put the loop above into its own module. ie: for i in range(1,7): exec ("def H%d(txt): return '' + txt + ''" % (i,i,i)) from headers import * H3("foo") This gives the option of a clean __main__ namespace by doing this instead: import headers headers.H3("foo") -John -- John Hazen john@hazen.net eFax: 801.697.4349 ---------------------------------------------------------------------- If it happens, it must be possible. From mongo57a@comcast.net Tue Jan 14 19:27:00 2003 From: mongo57a@comcast.net (andy surany) Date: Tue Jan 14 19:27:00 2003 Subject: [Tutor] An OO question Message-ID: <003c01c2bc2d$1a6d0de0$2502a8c0@emily.ewndsr01.nj.comcast.net> >At 17:41 2003-01-14 -0500, andy surany wrote: >I'm more of a wxPython-man myself, but should a pop-up really be >a Toplevel? Aren't dialogs etc better suited for that. Being a >top level window and a pop-up sound a bit like an oxymoron to me. It is a bit more complicated. This window will contain the manipulated parsed results from user selections (via mouse) within the ScrolledList widget - as the user selects each item. >>class SCROLLEDLIST: >> def mouse_handler(self): > >I assume this is just pseudo code. It seems a bit odd to have GUI >classes with names like that in a Tkinter program that don't inherit >from the Tkinter classes. Yes, pseudo code it is. > >Do I understand correctly that a method in the ScrolledList (to >use a more conventional way of writing class names) wants to >do something in the self.popup of a WinMenu instance? Yes, it is a handle method within the scrolledlist class (time to change the name, I think....). > >I would write a method for this in WinMenu to avoid making >Demeter very angry. > >class WinMenu: > def assist(self): > self.popup = ... > > def writeToPopup(self, message): > self.popup.textLabel['text'] = message # or whatever > >I assume you can find a reasonable way of making the appropriate >(maybe there is just one) instance of WinMenu available to the >instance of ScrolledList. > > Yes, makes sense. Thanks Magnus! > >-- >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 Janssen@rz.uni-frankfurt.de Tue Jan 14 19:30:32 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Tue Jan 14 19:30:32 2003 Subject: [Tutor] re: Leap year problem In-Reply-To: <1042574660.1785.985.camel@localhost.localdomain> Message-ID: On 14 Jan 2003, ahimsa wrote: > On Sun, 2003-01-12 at 21:32, Don Arnold wrote: > > > > def isLeapYear(year): > > if year % 400 == 0: > > return 1 > > elif year % 100 == 0: > > return 0 > > elif year % 4 == 0: > > return 1 > > else: > > return 0 > > > > OK - that makes sense to me, I thought by seeing if it divided by '100' > first it would eliminate it from going through the rest of the > conditions. Are there any quick and dirty guidelines about how one makes > those kinds of determinations when constructing conditional statements - > e.g. test large numbers first, or test for the rarely occurring variable > first, or ... ? both these guidelines won't do the decision which condition should be tested first proper. The point is: Test first the condition which can't be overrunned by another. Then the decision which would only be overrunned by the already tested condition. Last take the remaining condition (what else? :-) (year %4 == 0) is a need not a must for "leapness", therefore it is not enough just to test this. (year %400 == 0) is a must (and a need) for "leapness". When this test is true year is leap for sure. (year %100 == 0) is (very different ;-) a *possible* and not-neccessary condition for non leapness. possible: only if not (year %400 == 0); not-neccessary: also years not (year %100 == 0) can be non-leap. It remembers me a bit to the common mathematical and philosophical concept to distinguish between "necessary" and "sufficient" conditions (sorry i'm not sure if these are the proper english terms; it's "notwendig" and "hinreichend" in german). "truth table" is, if applicable (?): necessary | sufficient | outcoming 1. x | x | true 2. x | | possible, futher testing needed 3. | x | impossible 4. | | impossible By now my little attempt to explain the logic of leapness testing has gone a bit off topic ;-) The above solution of leapness testing is easier than this necessary-sufficient-stuff. But take a look at the library function isleap in modul calendar: def isleap(year): """Return 1 for leap years, 0 for non-leap years.""" return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) this is the necessary ("year % 4 == 0") and sufficient ("(year % 100 != 0 or year % 400 == 0)") pattern (note: truth-table entry 3. can't occour)! Sidenote: In the case of a programm with to many conditions mixed up in hairy crossdependencies *I* would decide not to think to much about that and take the most common condition first. Your programm will very well be buggy but you spare programmingtime and runtime. Michael I don't know how clear that question is. If it isn't > clear, let me know and I'll see if I can rephrase it. For instance, the > above guideline is, as you've stated, check initially for the specifics > of a case and then move to the more general. Would that apply in most > cases with a conditional suite? no: to quote myself: "note: truth-table entry 3. can't occour". Without that testing the specific case could mean you test the sufficient condition and leave out the necessary. I leave it to your homework to understand this ;-) It's late. From dyoo@hkn.eecs.berkeley.edu Tue Jan 14 19:40:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Jan 14 19:40:02 2003 Subject: [Tutor] [Asking questions / good book quotes] In-Reply-To: <1042579513.1789.1067.camel@localhost.localdomain> Message-ID: > I'm not sure how else to ask this one, because this is the major > stumbling point for me I reckon: how you are conceiving of the problem, > and then conceiving of the solution. Hi Andrew, The problem I'm trying to solve is to show how one can go from the original code here: ### def dice(number,sides): while number > -1 : value = random.randint(0, sides) number = number + 1 return value, dice(number - 2, sides) ### which I felt had some flaws, and fix and fiddle with it to get to: ### def dice(number, sides): if number > 0: value = random.randint(0, sides) return value, dice(number - 1, sides) ### without having to invoke magic. There's a process involved in manipulating and fixing code, but all too easily, we can just jump to the "solution" without showing the intermediate steps. I wanted to show those intermediate steps, but now that I think about it, that message was too long. *grin* I have to keep in mind that you can't read my mind. So you're perfectly right to ask these questions. > As an aside, I have just started (literally) reading the book by Abelson > and Sussman "Structure & Interpretation of Computer Programs" > http://mitpress.mit.edu/sicp/full-text/book/book.html and something they > write in their 'Preface to the First Edition' really resonates for me Yes, I thought the quotes of that book were awesome too. I've put them up here: http://hkn.eecs.berkeley.edu/~dyoo/programming/human.html > I am coming from with this question group Danny (and others): learning > how to think about problems in such ways that the solutions proposed to > those problems can be formally expressed in computational form. I > suspect that once I am able to acquire that skill, then the formalities > of the language itself become secondary. Yes, the Python syntax itself is nice, but it's often not what we talk about on Python-Tutor. We can talk about programming issues fairly well in Scheme, or Perl, or C, or Java... but the ideas of computation trump all languages. (By the way, if you have SICP-related questions, please feel free to bring them up. I think a lot of us here on the list have experience with it, and we can help ground its ideas in Python if you'd like.) I think we should cut this message short for the moment; I'll try to get to the second half of it later tonight. Best of wishes to you! From dyoo@hkn.eecs.berkeley.edu Tue Jan 14 19:54:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Jan 14 19:54:02 2003 Subject: [Tutor] Comparative code questions: Python vs. Rebol In-Reply-To: Message-ID: > > Dynamically compose a series of functions such that > > # python > > print H3("This an html header of level 3") > > >>> "

This is an html header of level 3

" > > > > In rebol, it works this way: > > repeat count 6[ > > do rejoin[ "H" count ": sub[val][val: reduce val ml[H" count "[(val)]]]" ] > > ] > > > > Is it possible to do this in python? If so, an example would > > be appreciated. > > Here's my first shot: > > >>> for i in range(1,7): > ... exec ("def H%d(txt): return '' + txt + ''" % (i,i,i)) > ... > >>> H3("foo") > '

foo

' Hi John and Tim, This works well. If we have an allergy against eval(), we can still fiddle around with namespaces to get a similar effect. Every module has its own "global" namespace that contains every global variable we use: ### >>> globals() {'__builtins__': , '__name__': '__main__', '__doc__': None} >>> a = 42 >>> globals() {'__builtins__': , '__name__': '__main__', '__doc__': None, 'a': 42} ### It turns out to be a writable dictionary, so if we really want to abuse the language, here's one way to do it. *grin* We can define those six HEADER functions using a loop as well as some use of inner functions: ### >>> def make_new_header_function(i): ... def new_function(s): ... return '%s' % (i, s, i) ... return new_function ... >>> for i in range(1, 6+1): ... globals()['H%s' % i] = make_new_header_function(i) ... >>> H3('hello') '

hello

' >>> H1, H2, H3 (, , ) ### Hope this helps! From p.hartley@spitech.com Tue Jan 14 20:16:02 2003 From: p.hartley@spitech.com (Paul Hartley) Date: Tue Jan 14 20:16:02 2003 Subject: [Tutor] Search and replace Message-ID: <002501c2bc35$b2cf16c0$ebe710ac@pc7345> This is a multi-part message in MIME format. ------=_NextPart_000_0022_01C2BC78.C0D0C500 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable I have some text that contains semicolons surounded by spaces, for = example :- 123 ;345 ; 456; 55 ; ; ;123 abc And I want to remove those spaces, but not other spaces, so the above = line would be :- 123;345;456;55;;;123 abc I know there must be a simple way using re - I have done this but used = two while loops until all the spaces are gone, not very elegant. Another question, the text is in another application, my current = solution is to copy it to the clipboard, save in a file and then = convert. Is there a better way? Paul ------=_NextPart_000_0022_01C2BC78.C0D0C500 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
I have some text that contains = semicolons surounded=20 by spaces, for example :-
 
123 ;345   ;   456; = 55=20 ;    ;   ;123 abc
 
And I want to remove those spaces, but = not other=20 spaces, so the above line would be :-
 
123;345;456;55;;;123 abc
 
I know there must be a simple way using re - I have done this but = used two=20 while loops until all the spaces are gone, not very elegant.
 
Another question, the text is in another application, my current = solution=20 is to copy it to the clipboard, save in a file and then convert. Is = there a=20 better way?
 
Paul
------=_NextPart_000_0022_01C2BC78.C0D0C500-- From dyoo@hkn.eecs.berkeley.edu Tue Jan 14 20:52:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Jan 14 20:52:02 2003 Subject: [Tutor] Search and replace In-Reply-To: <002501c2bc35$b2cf16c0$ebe710ac@pc7345> Message-ID: On Wed, 15 Jan 2003, Paul Hartley wrote: > I have some text that contains semicolons surounded by spaces, for > example :- > > 123 ;345 ; 456; 55 ; ; ;123 abc > > And I want to remove those spaces, but not other spaces, so the above > line would be :- > > 123;345;456;55;;;123 abc Hi Paul: I see, so you want to strip off the whitespace around every field that's split up by semicolons. > I know there must be a simple way using re - I have done this but used > two while loops until all the spaces are gone, not very elegant. Yes, there's a clean way of doing this. If we take a look at the split(), strip(), and join() methods of strings: http://www.python.org/doc/lib/string-methods.html we should see the tools we need to strip() out the whitespace on each field of our string. For example: ### >>> sentence = "this+is+a+test" >>> sentence.split("+") ['this', 'is', 'a', 'test'] >>> words = sentence.split("+") >>> new_words = [w.capitalize() for w in words] >>> new_words ['This', 'Is', 'A', 'Test'] >>> '-'.join(new_words) 'This-Is-A-Test' ### shows a few ways that the string methods can simplify our string fiddling, without using loops. I'll be vague for the moment on how the pieces fit together exactly for your problem. *grin* If you run into problems, please feel free to ask again on Tutor. Good luck to you! From fredm@smartypantsco.com Tue Jan 14 21:05:02 2003 From: fredm@smartypantsco.com (Alfred Milgrom) Date: Tue Jan 14 21:05:02 2003 Subject: [Tutor] Search and replace In-Reply-To: <002501c2bc35$b2cf16c0$ebe710ac@pc7345> Message-ID: <5.1.0.14.0.20030115125811.00ac3090@192.168.1.1> I don't think you need re. A simple way to do it is by splitting the string into components and then using the built-in functions lstrip and rstrip is as follows: import string s='123 ;345 ; 456; 55 ; ; ;123 abc' l = s.split(';') l = [substring.lstrip() for substring in l] l = [substring.rstrip() for substring in l] s = string.join(l,';') print s '123;345;456;55;;;123 abc' (Common string operations can be found at http://www.python.org/doc/current/lib/module-string.html) I'm sorry I cannot help with you question of how to convert the string within another application. HTH, Fred Milgrom At 09:30 AM 15/01/03 +0800, Paul Hartley wrote: >I have some text that contains semicolons surounded by spaces, for example :- > >123 ;345 ; 456; 55 ; ; ;123 abc > >And I want to remove those spaces, but not other spaces, so the above line >would be :- > >123;345;456;55;;;123 abc > >I know there must be a simple way using re - I have done this but used two >while loops until all the spaces are gone, not very elegant. > >Another question, the text is in another application, my current solution >is to copy it to the clipboard, save in a file and then convert. Is there >a better way? > >Paul From shalehperry@attbi.com Tue Jan 14 21:07:01 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Tue Jan 14 21:07:01 2003 Subject: testing and its important was Re: [Tutor] re: Leap year problem In-Reply-To: References: Message-ID: <200301141806.16414.shalehperry@attbi.com> On Tuesday 14 January 2003 16:29, Michael Janssen wrote: > > no: to quote myself: "note: truth-table entry 3. can't occour". Without > that testing the specific case could mean you test the sufficient > condition and leave out the necessary. I leave it to your homework to > understand this ;-) It's late. > this is important to remember as you continue programming. Testing your = code=20 can be as difficult as writing it. Defining the problem in a pedantic wa= y=20 (and using truth tables sometimes) is a good start. For instance, let's say I asked you to write a function to tell me if a n= umber=20 was even. Sounds easy enough. Then think "how would i prove to myself t= hat=20 it worked?". 4 is even, 3 is odd, what about 1? 0? Same thing for this leap year check. You need to think "what years hit e= ach=20 condition?". For instance: A.D. 100 was not a leap year but it looks like it might be. Same with 17= 00=20 A.D. 1600 was a leap year though as was 2000. As you can see testing is just as important as writing. During a recent job interview I was asked to write code for an algorithm = (in=20 this case a sort). As I scribbled on the white board the interviewer cha= tted=20 with me about the mechanics of the problem as well as about how I intende= d to=20 prove it worked. He was just as interested in my ability to write good c= ode=20 as he was in my ability to test other people's. From Don Arnold" Message-ID: <01b301c2bc3e$f8289a80$19d1b241@defaultcomp> ----- Original Message ----- From: "Alfred Milgrom" To: "Paul Hartley" ; Sent: Tuesday, January 14, 2003 9:03 PM Subject: Re: [Tutor] Search and replace > I don't think you need re. > A simple way to do it is by splitting the string into components and then > using the built-in functions lstrip and rstrip is as follows: > > import string > > s='123 ;345 ; 456; 55 ; ; ;123 abc' > l = s.split(';') > l = [substring.lstrip() for substring in l] > l = [substring.rstrip() for substring in l] The strip() method combines the lstrip() and rstrip() functionality, so l = [substring.strip() for substring in l] will do the work of the 2 preceding lines with a single comprehension. > s = string.join(l,';') Since strings now have a join() method, this line can be rephrased as: s = ';'.join(l) and you no longer need to bother with importing the string module. > print s > > '123;345;456;55;;;123 abc' > > (Common string operations can be found at > http://www.python.org/doc/current/lib/module-string.html) > Many of these operations have corresponding string methods, so you can often get by without importing string. > I'm sorry I cannot help with you question of how to convert the string > within another application. > HTH, > > Fred Milgrom > Thanks, Don From tim@johnsons-web.com Tue Jan 14 21:42:02 2003 From: tim@johnsons-web.com (Tim Johnson) Date: Tue Jan 14 21:42:02 2003 Subject: [Tutor] Exec? [was comparative code questions] In-Reply-To: References: Message-ID: <20030115024510.GS5446@johnsons-web.com> I'm looking at page 456 in "The Python Cookbook" I quote as follows: "The exec statement is a last-ditch measure, to be used only when nothing else is available (which is basically never)" Do I understand from the above that 'exec' should not be used? TIA tim * Danny Yoo [030114 16:06]: > > > > > Dynamically compose a series of functions such that > > > # python > > > print H3("This an html header of level 3") > > > >>> "

This is an html header of level 3

" > > > > > > In rebol, it works this way: > > > repeat count 6[ > > > do rejoin[ "H" count ": sub[val][val: reduce val ml[H" count "[(val)]]]" ] > > > ] > > > > > > Is it possible to do this in python? If so, an example would > > > be appreciated. > > > > Here's my first shot: > > > > >>> for i in range(1,7): > > ... exec ("def H%d(txt): return '' + txt + ''" % (i,i,i)) > > ... > > >>> H3("foo") > > '

foo

' > > Hi John and Tim, > > This works well. If we have an allergy against eval(), we can still > fiddle around with namespaces to get a similar effect. Every module has > its own "global" namespace that contains every global variable we use: > > ### > >>> globals() > {'__builtins__': , '__name__': > '__main__', '__doc__': None} > >>> a = 42 > >>> globals() > {'__builtins__': , '__name__': > '__main__', '__doc__': None, 'a': 42} > ### > > > It turns out to be a writable dictionary, so if we really want to abuse > the language, here's one way to do it. *grin* We can define those six > HEADER functions using a loop as well as some use of inner functions: > > ### > >>> def make_new_header_function(i): > ... def new_function(s): > ... return '%s' % (i, s, i) > ... return new_function > ... > >>> for i in range(1, 6+1): > ... globals()['H%s' % i] = make_new_header_function(i) > ... > >>> H3('hello') > '

hello

' > >>> H1, H2, H3 > (, > , > ) > ### > > > Hope this helps! -- Tim Johnson http://www.alaska-internet-solutions.com http://www.johnsons-web.com From Don Arnold" <080101c2ba82$1f7bff50$ea10ba3f@defaultcomp> <1042574660.1785.985.camel@localhost.localdomain> Message-ID: <01be01c2bc41$1d32a670$19d1b241@defaultcomp> ----- Original Message ----- From: "ahimsa" To: "Don Arnold" Cc: Sent: Tuesday, January 14, 2003 3:51 PM Subject: Re: [Tutor] re: Leap year problem > Hi Don > I know this is a bit belated, but dammit ... that work thing :-) > I definitely know how that goes. Not a problem! of the leap year code itself. Thanks goes out to Michael Janssen for giving a more rigorous explanation of the code than mine.. > > year = int(raw_input('year: ')) > > while year != -1: > > print 'isLeapYear :', isLeapYear(year) > > print 'isLeapYear2:', isLeapYear2(year) > > print '' > > year = int(raw_input('year: ')) > > > > > > This is a bit confusing, so I want to pick this apart too if you can > bear with me while I plod through this: These are my understandings line > by line, please steer me right if I'm going off track here. > line 1 => gets user input > line 2 => runs program on the proviso that a number >= 0 is entered at > input > thereafter you are testing both ways of writing the program given > specific years using '1' for yes it is a leap year and '0' for not. > The last line with '-1' stops the program because it violates the while > condition? > Yes, entering -1 for the year invalidates the loop's condition and it terminates. > It did - thank you :) Your welcome. > > Andrew > > -- > ahimsa > Don From dyoo@hkn.eecs.berkeley.edu Tue Jan 14 22:40:25 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Jan 14 22:40:25 2003 Subject: [Tutor] Exec? [was comparative code questions] In-Reply-To: <20030115024510.GS5446@johnsons-web.com> Message-ID: On Tue, 14 Jan 2003, Tim Johnson wrote: > I'm looking at page 456 in "The Python Cookbook" > I quote as follows: > > "The exec statement is a last-ditch measure, to be used only > when nothing else is available (which is basically never)" > > Do I understand from the above that 'exec' should not > be used? Hi Tim, Mark Pilgrim, author of the nice "Dive Into Python" tutorial, actually wrote a blog about this very subject a few days ago. *grin* http://diveintomark.org/archives/2002/01/04.html eval() does have a reputation for being "evil": http://mail.python.org/pipermail/tutor/2002-April/013764.html eval() and exec() allow us to evaluation arbitrary strings as Python programs. This is a powerful feature, but dangerous if we consider that many strings come from the outside world. Think of the security fiascos with Microsoft Outlook, and that's the general idea of the problem: eval() is very exploitable. In simple programs for our own use, it's probably acceptable to use eval(). But for programs that are meant for outside use, eval() is often not a good idea because it's all too easy not to protect it from outside subversion. Talk to you later! From dyoo@hkn.eecs.berkeley.edu Tue Jan 14 22:56:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Jan 14 22:56:01 2003 Subject: [Tutor] Exec? [was comparative code questions] In-Reply-To: Message-ID: On Tue, 14 Jan 2003, Danny Yoo wrote: > Mark Pilgrim, author of the nice "Dive Into Python" tutorial, actually > wrote a blog about this very subject a few days ago. Err... I meant, a few days ago, modulo a year or so. *grin* From tim@johnsons-web.com Tue Jan 14 23:16:02 2003 From: tim@johnsons-web.com (Tim Johnson) Date: Tue Jan 14 23:16:02 2003 Subject: [Tutor] Exec? [was comparative code questions] In-Reply-To: References: <20030115024510.GS5446@johnsons-web.com> Message-ID: <20030115041928.GT5446@johnsons-web.com> * Danny Yoo [030114 18:55]: <..> > I'm looking at page 456 in "The Python Cookbook" > > I quote as follows: > > > > "The exec statement is a last-ditch measure, to be used only > > when nothing else is available (which is basically never)" <...> > eval() and exec() allow us to evaluation arbitrary strings as Python > programs. This is a powerful feature, but dangerous if we consider that > many strings come from the outside world. Think of the security fiascos > with Microsoft Outlook, and that's the general idea of the problem: eval() > is very exploitable. > > > In simple programs for our own use, it's probably acceptable to use > eval(). But for programs that are meant for outside use, eval() is often > not a good idea because it's all too easy not to protect it from outside > subversion. Aha! Transformational programming (using a scheme term), best use of of 'exec' and 'eval' may be to be used in adhoc code generation rather than 'on the fly evaluation'. Thanks Danny - for the "Dive into Mark" article as well. -- Tim Johnson http://www.alaska-internet-solutions.com http://www.johnsons-web.com From shalehperry@attbi.com Wed Jan 15 02:45:02 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Wed Jan 15 02:45:02 2003 Subject: [Tutor] Search and replace In-Reply-To: <01b301c2bc3e$f8289a80$19d1b241@defaultcomp> References: <5.1.0.14.0.20030115125811.00ac3090@192.168.1.1> <01b301c2bc3e$f8289a80$19d1b241@defaultcomp> Message-ID: <200301142344.16977.shalehperry@attbi.com> On Tuesday 14 January 2003 18:36, Don Arnold wrote: > > > s =3D string.join(l,';') > > Since strings now have a join() method, this line can be rephrased as: > > s =3D ';'.join(l) > > and you no longer need to bother with importing the string module. > unless you like writing code other people can read ............ yes I am still bitter about the .join() method. I keep trying not to hat= e it=20 and failing miserably. From dyoo@hkn.eecs.berkeley.edu Wed Jan 15 03:14:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Jan 15 03:14:01 2003 Subject: [Tutor] Fixed freezing problem, have new one (fwd) Message-ID: Hi everyone, I got Travis's ok to send this to the list, so here goes: ---------- Forwarded message ---------- Date: Tue, 14 Jan 2003 01:41:57 -0800 (PST) From: Danny Yoo To: Guess Who? Me Subject: Re: [Tutor] Fixed freezing problem, have new one On Tue, 14 Jan 2003, Guess Who? Me wrote: > >As we mentioned above, there's some mixing of loops and recursion here > >that we should probably avoid. We can define dice() picking by using > >either loops, or by using recursion, but I don't think we need to use > >both techniques: there's too much risk of getting mixed up. > > This is using loops and recursion? - I thought recursion created a loop > where you re-ran the function again, but thats what I got just by > looking at it. Hello! Yes, but it's trying to do the loopy behavior in two ways. Python supports looping through two main ways: 1. explicit "loops" with the 'if' and 'while' statements 2. recursion (a function calling itself) It turns out that they're pretty functionally equivalent. We can look at an example if you'd like; it might clear things up. Say that we're trying to write a function that uppercases a list of words. We can make a new list of uppercased words by using a for loop: ### def all_uppercase(words): uppered_words = [] for w in words: uppered_words.append(w.upper()) return uppered_words ### Alternatively, we can use the while loop: ### def all_uppercase(words): uppered_words = [] i = 0 while i < len(words): uppered_words.append(words[i]) i = i + 1 return uppered_words ### Both "looping" structures go through the indented body several times, and in that sense, we capture the idea of repeating a process. But there's another way we can approach the repetition of an action across a list: we can use the "self-calling" approach of recursion: ### def all_uppercase(words): if words == []: return [] return [words[0].upper()] + all_uppercase(words[1:]) ### A recursive approach often takes a little more subtlety than loops, since it's easier to go wrong with them. Still, they are an excellent tool, and fun even when they do go wrong... *grin* This is what we usually mean by using either loops or recursion: we can simulate one by using the other: they both allow us to repeat things. But if we're using both techniques at the same time in a single function, that's what triggers warning lights in my head. *grin* > It was also pointed out that my pointed goes in the wrong direction, so > instead of number+1, it should be number-1 > > def dice(number,sides): #number being the number of times you roll > while number > -1 : > value=random.randint(1,sides) #changed the 0 to a one, it was also > total=0 #pointed out that there are no 0 > total=value+total #sided dice. (or...conversely - infin > number=number+1 #itely many 0 sided dice. Trippy! > return total,dice(number,sides) > > You can't be lazy if you deal with questions like these with such care - > most people respond with a few lines of computer lingo that newbies and > non-programmers (myself included) don't know. Its greatly appreciated. Very true. When you every do hear us use computer lingo without explanation, ding us and get us to explain ourselves. *grin* Don't hesitate ask questions on the parts that sound completely weird. I won't take offense because I know that my explanations are often insufficient. It's extraordinarily difficult to get an idea written out perfectly right, so if there's awkwardness in the words, it's because I'm still wrangling with the ideas myself. The message: http://mail.python.org/pipermail/tutor/2003-January/019913.html shows how the original code actually turned out to have fairly correct behavior, and how we munged it systematically so it was clearer to see what was going on. Would it be ok to forward this to the rest of the Tutor list? Your questions are good ones. Hope this helps! From dyoo@hkn.eecs.berkeley.edu Wed Jan 15 03:18:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Jan 15 03:18:01 2003 Subject: [Tutor] Fixed freezing problem, have new one (fwd) In-Reply-To: Message-ID: On Wed, 15 Jan 2003, Danny Yoo wrote: > Alternatively, we can use the while loop: > > ### > def all_uppercase(words): > uppered_words = [] > i = 0 > while i < len(words): > uppered_words.append(words[i]) > i = i + 1 > return uppered_words > ### That code above doesn't do anything. I goofed up (again). The correct version of this should be: ### def all_uppercase(words): uppered_words = [] i = 0 while i < len(words): uppered_words.append(words[i].upper()) i = i + 1 return uppered_words ### Apologies for the confusion! From dyoo@hkn.eecs.berkeley.edu Wed Jan 15 03:31:33 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Jan 15 03:31:33 2003 Subject: [Tutor] Adding python handler to httpd.conf In-Reply-To: <3E242576.4030705@vasoftware.com> Message-ID: On Tue, 14 Jan 2003, shobhan wrote: > I want to add lines which handle python scripts in httpd.conf so that i > can execute the python script via browser. Can anyone tell what lines > i've to add to apache conf..?? Hi Shobhan, If you have the CGI module working, then all you probably need to do is add '.py' as an possible extension name for CGI scripts. Look for the line: AddHandler cgi-script cgi pl and add 'py' to the end of that list. That should do the trick. All the Python programs should have the magic line '#!/usr/bin/python', so that when Apache tries to run the CGI, it knows how to execute the Python program. You may want to read the official Apache documentation on CGI handling: http://httpd.apache.org/docs/howto/cgi.html which explains more details about running CGI's on Apache. The documentation uses Perl as their example CGI language, but it applies equally well to Python. Good luck to you! From magnus@thinkware.se Wed Jan 15 04:12:09 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Wed Jan 15 04:12:09 2003 Subject: [Tutor] Leap years [return / if true return true else return false] In-Reply-To: References: <1042585187.1124.1092.camel@localhost.localdomain> Message-ID: <5.1.0.14.0.20030115093755.02bf00e0@www.thinkware.se> At 15:55 2003-01-14 -0800, Danny Yoo wrote: >Actually, I have no clue what order Python will do the evaluation of those >squares. http://www.python.org/dev/doc/devel/ref/evalorder.html > *grin* I did it left-to-right, but that's just because I'm used >to reading left-to-right. But if we went at it a different direction, we >still should get the same answer, just as long as the check for equality >is done last. In this case, yes, but if squares() was replaced with another function that had some kind of side effects, it might be important to know the execution order, and whether it's guaranteed to be a certain way. >>> x = 1 >>> def a(n): ... global x ... x = x + n ... return x ... >>> a(1) * a(2) 8 >>> x = 1 >>> a(2) * a(1) 12 Or to make it more like the squares thingie: >>> a(1) * a(2) == a(4) 1 >>> x = 1 >>> a(2) * a(1) == a(4) 0 As you see, evaluation was left to right in this case. This is much less of a problem in Python than in many other languages though, since assignments aren't allowed to be expressions. In for instance C, you can do things like x = a++ * ++a - a -= 5 * a << 4 == b++ * ++b; -- 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 gp@pooryorick.com Wed Jan 15 04:47:02 2003 From: gp@pooryorick.com (Poor Yorick) Date: Wed Jan 15 04:47:02 2003 Subject: [Tutor] Leap years [return / if true return true else return false] References: <1042585187.1124.1092.camel@localhost.localdomain> <5.1.0.14.0.20030115093755.02bf00e0@www.thinkware.se> Message-ID: <3E252E6B.5020908@pooryorick.com> Magnus Lycka wrote: > . In for instance C, you can do things like > > x = a++ * ++a - a -= 5 * a << 4 == b++ * ++b; Magnus for President! Poor Yorick gp@pooryorick.com From magnus@thinkware.se Wed Jan 15 05:38:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Wed Jan 15 05:38:01 2003 Subject: [Tutor] Comparative code questions: Python vs. Rebol In-Reply-To: <20030114230533.GK5446@johnsons-web.com> Message-ID: <5.1.0.14.0.20030115101718.02bf8ea8@www.thinkware.se> At 14:05 2003-01-14 -0900, Tim Johnson wrote: > I'm writing a column where I am comparing certain simple >coding tasks in different programming languages. This time, >I doing 'rebol' and 'python'. Interesting. Will this be available to the public? >Now here is a more complex example: >Dynamically compose a series of functions such that ># python > print H3("This an html header of level 3") > >>> "

This is an html header of level 3

" I don't know anything about Rebol, but in Python it's not typical to dynamically compose functions, even if you can, as others have shown. I think most python programmers, maybe beginners in particular, prefer to see in their code what functions they have, rather than to infer that through another level of abstraction. There are a number of python libraries that do what you try to achieve here. >>> from HyperText.HTML import * >>> print H3('Thank you Andy Dustman!')

Thank you Andy Dustman!

>>> See http://dustman.net/andy/python/HyperText/ With this you will get a lot of other features as well. I realize that this is not what you are after, that the example is just there to demonstrate a language feature, but available libraries is maybe a stronger point in Python than its highly dynamic features. Of course, it might be useful sometimes to show how an idiom commonly used in one language can be used in another language as well, but typically, if you look at Python with a Rebol perspective, I assume Rebol will win. Hopefully Rebol is the best Rebol. Similarly, if you look at Rebol from a Python perspective, Rebol won't have a chance. You can exchange Rebol and Python for any other programming languages you like. Make sure that you don't miss the best features of Python. You will certainly find much more programming resources on the net for python for instance. I did a little test with google. Looking for either Rebol or Python together with some other buzz words I got this many hits. Buzz word Python Rebol xml-rpc 55 000 2 500 oracle 250 000 2 700 web services 470 000 4 500 html 1 640 000 20 100 If popularity with Google was the only factor, Java or Perl would obviously be even better, but the abundance of third party libraries is certainly a useful feature of Python. Maybe even more important is the standard library. In fact, while most non-significant Perl program which isn't completely reinventing the wheel will use third party module, the python standard library is broad and good enough to aid most programs with all they need. How do you write a web server or xml-rpc server in Rebol? In python a web server can be written in four lines of code or something like that, by using the features in the standard library. An xml-rpc server will be a little more... Also, the possibility to work interactively with python, its strong dynamic and introspective features are important. Having worked a bit with Visual Basic for Excel 97 yesterday, I must say that error handling, error messages and the system with trace backs in python is a really strong point. I saw a number of messages about unknown errors, and also several cases where I had made obvious programming mistakes, that were just silently ignored by Excel--I pushed my button and nothing happened! In my almost seven years with Python, I haven't seen as much strange behaviour as I did in an afternoon when I wrote 180 lines of Visual Basic code. For more opinions about Python, have a look at: http://www.thinkware.se/cgi-bin/thinki.cgi/PythonQuotes -- 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@thinkware.se Wed Jan 15 06:05:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Wed Jan 15 06:05:01 2003 Subject: testing and its important was Re: [Tutor] re: Leap year problem In-Reply-To: <200301141806.16414.shalehperry@attbi.com> References: Message-ID: <5.1.0.14.0.20030115114359.02c2f008@www.thinkware.se> At 18:06 2003-01-14 -0800, Sean 'Shaleh' Perry wrote: >A.D. 100 was not a leap year but it looks like it might be. This is way off topic, but 100 A.D. *was* a leap year! In Gregorian calendars, 100 A.D. would not be a leap year, but Gregorian calendars weren't used in 100 A.D. Gregory XIII who commissioned the development of this calendar became pope in 1572. "His" calendar was introduced in different years in different countries (except in Sweden were it's more complicated :). Before that, the Julian calendar, introduced by Julius Caesar in 45 B.C. was used. In Julian calendars every fourth was a leap year. That is why the Julian and Gregorian new years drifted away from each other. I don't think anyone had calculated the length of the year with high enough precision in 45 B.C. to make a better approximation than 365.25, even if the Mayan astronomers achieved higher precision long before Gregory's time... -- 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@thinkware.se Wed Jan 15 06:20:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Wed Jan 15 06:20:02 2003 Subject: [Tutor] Exec? [was comparative code questions] In-Reply-To: <20030115024510.GS5446@johnsons-web.com> References: Message-ID: <5.1.0.14.0.20030115120452.02bcfc50@www.thinkware.se> At 17:45 2003-01-14 -0900, Tim Johnson wrote: >"The exec statement is a last-ditch measure, to be used only > when nothing else is available (which is basically never)" > > Do I understand from the above that 'exec' should not > be used? No. It's there in the language. You can use it. But it is a loaded gun. Don't give it to the kids! ;) The problems with exec comes from the fact that if you don't know exectly what the string contains, running exec on it can be dangerous. What if you do "exec s", and s happens to contain 'import os; os.system("rm -rf /")' or in case of windows 'import os; os.system("DEL /S /Q /F C:\*.*")' ??? On the other hand, if you know the content of the string and feel certain that it's safe, there is no such problem. But if you know the content of the string, why would you need to run exec on it in the first place? The thing is, that python has a lot of convenient features that typically makes exec redundant. In other word, if you feel inclined to use exec (or eval), think again: Can I do this in a better way? Using exec means that you modify your program on the fly. For instance this means that tools that try to assess your code quality such as pyChecker won't work. Both testing and reviewing the code becomes more difficult. Using exec often means they you will dynamically introduce new names in a namespace, and this means that subtle bugs might occur. If you show us some meaningful examples of code using exec, we can probably show you better ways of doing the same thing... -- 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@thinkware.se Wed Jan 15 07:33:03 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Wed Jan 15 07:33:03 2003 Subject: [Tutor] Question on Time calculations. In-Reply-To: <391A847E-2835-11D7-B3EC-00039315F4DA@knology.net> References: <5.1.0.14.0.20030115003632.02c087b0@www.thinkware.se> Message-ID: <5.1.0.14.0.20030115125740.02c2fc98@www.thinkware.se> I assume this was meant for the list. (My private consultation service is not for free... ;) At 20:58 2003-01-14 -0600, SA wrote: >Here is what I have so far using the "time" module(most of this is pseudo >code): > >a => entered date in format ("Mon Jan 14 20:35:13 2003) >a is then converted to seconds relative to the epoch by > b = mktime(strptime(a)) >I can then do the same for the end time c > >all that is left is the math--> > >d = (c-b)/(60*60) > >now I have a floating point number for hours. > >Now my question is how do I get Python to take everything right of the >decimal point and convert to minutes? You can multiply it with 60! print "%02i:%02.0f" % (d, 60 * (d%1)) As I said, much it's better to use mxDateTime http://www.egenix.com/files/python/mxDateTime.html or the new datetime in python 2.3 http://www.python.org/dev/doc/devel/lib/module-datetime.html Example: >>> from mx import DateTime >>> x = DateTime.Parser.DateTimeFromString("Mon Jan 14 20:35:13 2003") >>> y = DateTime.now() >>> d = y - x >>> print d 16:35:36.37 >>> print d.hours 16.5934372222 >>> print d.hour 16 >>> print d.minute 35 >>> print d.second 36.3739999533 >>> print d.tuple() (0, 16, 35, 36.373999953269958) >>> print d.strftime("%H:%M:%S") 16:35:36 or >>> DateTime.today().iso_week (2003, 3, 3) For the cost of a quick download, you get a package with all date and time features than you will ever need! :) The time module only works in a small time interval, 1970 to early 2038 (on 32 bit computers). mxDateTime has a much wider scope. For instance you can do: >>> b = DateTime.Date(1,1,1) >>> e = DateTime.Date(100000,12,31) >>> print b, e, e-b 0001-01-01 00:00:00.00 100000-12-31 00:00:00.00 36524249:00:00:00.00 You can also do nice things like getting the fifth of next month. >>> print DateTime.today() + DateTime.RelativeDate(months = 1, day = 5) 2003-02-05 00:00:00.00 -- 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 norvell@houseofspearman.org Wed Jan 15 10:00:03 2003 From: norvell@houseofspearman.org (Norvell Spearman) Date: Wed Jan 15 10:00:03 2003 Subject: [Tutor] scope question Message-ID: <20030115145820.GA4948@houseofspearman.org> --pf9I7BMVVzbSWLtt Content-Type: text/plain; charset=us-ascii Content-Disposition: inline python v2.2.2 I think I'm confused about scope and functions' passing of parameters. I've been working through the ``How to Think Like a Computer Scientist'' tutorial and up 'til now everything has been fairly clear to me. The attached file is what I've typed in from exercises and examples in Chapter 13, ``Classes and Functions,'' with the last function, increment, being the one I'm having problems with. Below is a transcript from running the program and then manually calling some functions (in idle): ************************************************ Hours: 4 Minutes: 57 Seconds: 45 Seconds to add to given time: 34 The time is now: 4:57:45 >>> t1 = Time() >>> t1.hours, t1.minutes, t1.seconds = 4, 57, 45 >>> printTime(t1) 4:57:45 >>> increment(t1, 34) >>> printTime(t1) 4:57:45 >>> t1 = addTime(t1, makeTime(34)) >>> printTime(t1) 4:58:19 ************************************************ My question (finally) is this: Why doesn't increment alter t1 while ``t1 = addTime(t1, makeTime(34))'' in an interactive session does alter t1? Thanks much for any help with this. -- Norvell Spearman --pf9I7BMVVzbSWLtt Content-Type: text/plain; charset=us-ascii Content-Disposition: attachment; filename="classtime.py" import copy class Time: pass def printTime(Time): print "%d:%d:%d" % (Time.hours, Time.minutes, Time.seconds) def convertToSeconds(t): minutes = t.hours*60 + t.minutes seconds = minutes*60 + t.seconds return seconds def makeTime(seconds): time = Time() time.seconds = seconds%60 time.minutes = (seconds/60)%60 time.hours = seconds/3600 return time def addTime(t1, t2): seconds = convertToSeconds(t1) + convertToSeconds(t2) return makeTime(seconds) def after(t1, t2): if convertToSeconds(t1) > convertToSeconds(t2): return 1 else: return 0 # Figure out why following function doesn't work as expected: def increment(time, seconds): time = addTime(time, makeTime(seconds)) inTime = Time() inTime.hours = input("Hours: ") inTime.minutes = input("Minutes: ") inTime.seconds = input("Seconds: ") inSeconds = input("Seconds to add to given time: ") increment(inTime, inSeconds) print "The time is now: ", printTime(inTime) --pf9I7BMVVzbSWLtt-- From op73418@mail.telepac.pt Wed Jan 15 10:39:14 2003 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Wed Jan 15 10:39:14 2003 Subject: [Tutor] Exec? [was comparative code questions] References: <20030115024510.GS5446@johnsons-web.com> Message-ID: <007d01c2bcad$25324210$c01a0dd5@violante> ----- Original Message ----- From: "Tim Johnson" To: Sent: Wednesday, January 15, 2003 2:45 AM Subject: [Tutor] Exec? [was comparative code questions] > I'm looking at page 456 in "The Python Cookbook" > I quote as follows: > > "The exec statement is a last-ditch measure, to be used only > when nothing else is available (which is basically never)" > > Do I understand from the above that 'exec' should not > be used? No. Others have already given the reasons for mistrusting exec and eval. I will give you one situation where it is reasonable to use it: suppose you have a Python application and want to extend it by adding a scripting language. Since the application is already in Python, and the interpreter is always available, just use Python as the scripting language via exec. > > TIA > tim > All the best, G. Rodrigues From ramrom@earthling.net Wed Jan 15 12:27:05 2003 From: ramrom@earthling.net (Bob Gailer) Date: Wed Jan 15 12:27:05 2003 Subject: [Tutor] Comparative code questions: Python vs. Rebol In-Reply-To: <20030114230533.GK5446@johnsons-web.com> Message-ID: <5.2.0.9.0.20030115102528.027281f0@66.28.54.253> --=======3F0C7F35======= Content-Type: text/plain; x-avg-checked=avg-ok-3227408B; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 02:05 PM 1/14/2003 -0900, you wrote: >Dynamically compose a series of functions such that ># python > print H3("This an html header of level 3") > >>> "

This is an html header of level 3

" H = [eval("lambda v:''+v+'' ") for i in range(7)] This creates a list of functions that can be referenced by index: print H[3]("This an html header of level 3") gives

This an html header of level 3

Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======3F0C7F35======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-3227408B Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.438 / Virus Database: 246 - Release Date: 1/7/2003 --=======3F0C7F35=======-- From magnus@thinkware.se Wed Jan 15 12:31:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Wed Jan 15 12:31:01 2003 Subject: [Tutor] scope question In-Reply-To: <20030115145820.GA4948@houseofspearman.org> Message-ID: <5.1.0.14.0.20030115170916.02c3d6e0@www.thinkware.se> At 08:58 2003-01-15 -0600, Norvell Spearman wrote: >My question (finally) is this: Why doesn't increment alter t1 while >``t1 = addTime(t1, makeTime(34))'' in an interactive session does alter >t1? Believe it or not, but this has little to do with scopes... I haven't seen the definition of the increment function, but may I imagine that it contains an assignment to the parameter variable.? Parameter passing is like assignment. Roughly... def p(x): x = x + " world" print x greeting = "Hello" p(greeting) print greeting ...is basically the same thing as... greeting = "Hello" x = greeting x = x + "world" print x print greeting ...at least as far as your problem is concerned. Does that make sense? Does it explain what happens to your code? -- 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 norvell@houseofspearman.org Wed Jan 15 13:07:13 2003 From: norvell@houseofspearman.org (Norvell Spearman) Date: Wed Jan 15 13:07:13 2003 Subject: [Tutor] scope question In-Reply-To: <5.1.0.14.0.20030115170916.02c3d6e0@www.thinkware.se> References: <20030115145820.GA4948@houseofspearman.org> <5.1.0.14.0.20030115170916.02c3d6e0@www.thinkware.se> Message-ID: <20030115180506.GA5572@houseofspearman.org> On Wednesday, 2003.01.15, 18:30:04 +0100, Magnus Lycka wrote: > Believe it or not, but this has little to do with > scopes... I haven't seen the definition of the > increment function, but may I imagine that it contains > an assignment to the parameter variable.? I attached the code file to my first post because copying and pasting it into my mail client really screwed up the formatting. Here is the relevant information: ****************************************************************************** class Time: pass def printTime(Time): print "%d:%d:%d" % (Time.hours, Time.minutes, Time.seconds) def convertToSeconds(t): minutes = t.hours*60 + t.minutes seconds = minutes*60 + t.seconds return seconds def makeTime(seconds): time = Time() time.seconds = seconds%60 time.minutes = (seconds/60)%60 time.hours = seconds/3600 return time def addTime(t1, t2): seconds = convertToSeconds(t1) + convertToSeconds(t2) return makeTime(seconds) # Figure out why following function doesn't work as expected: def increment(time, seconds): time = addTime(time, makeTime(seconds)) ****************************************************************************** > Parameter passing is like assignment. Roughly... > > def p(x): > x = x + " world" > print x > > greeting = "Hello" > p(greeting) > print greeting > > ...is basically the same thing as... > > greeting = "Hello" > x = greeting > x = x + "world" > print x > print greeting OK, so function calls pass by value, not by reference, right? > ...at least as far as your problem is concerned. > Does that make sense? Does it explain what happens > to your code? Yes and not exactly. When I call increment from either the program or from the interactive Python shell, it doesn't change the time object passed to it --- which is consistent with your example function. But I don't understand why t1 = addTime(t1, makeTime(34)) alters t1 when called in the Python shell but not as the definition of increment. Now if I do something like this def increment(time, seconds): newTime = addTime(time, makeTime(seconds)) time.hours = newTime.hours time.minutes = newTime.minutes time.seconds = newTime.seconds then increment does what I expect, but I don't understand why. It appears the original increment works on pass-by-value and the second increment works on pass-by-reference. Why the difference? Thanks for responding so quickly and thanks for your patience with my questions. -- Norvell Spearman From jeff@ccvcorp.com Wed Jan 15 14:27:03 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Wed Jan 15 14:27:03 2003 Subject: [Tutor] Comparative code questions: Python vs. Rebol References: <20030114230533.GK5446@johnsons-web.com> Message-ID: <3E25B590.7030202@ccvcorp.com> Tim Johnson wrote: >Now here is a more complex example: >Dynamically compose a series of functions such that ># python > print H3("This an html header of level 3") > >>> "

This is an html header of level 3

" > Others have shown how you can make Python do what you ask, here. Instead of repeating that, I'll show you a way to achieve much the same ends, but in a more Pythonic way -- something that I think makes it easier to read, understand, and thus mantain. Instead of having a series of very similar functions that make almost-equivalent modifications to a string, it's much simpler to have a *single* function that takes a parameter to indicate which of several modifications to make. >>> def HtmlHeader(level, text): ... return "%s" % (level, text, level) ... >>> HtmlHeader(1, "This is level 1") '

This is level 1

' >>> HtmlHeader(3, "This is level 3") '

This is level 3

' >>> HtmlHeader(6, "This is level 6") '
This is level 6
' >>> The % operator, in this context, will make substitutions in the string in a manner similar to C's printf() formatting. By doing it this way, we have only one function to keep track of, instead of six. This is easier on both the writer of the library (this is simpler than the dynamic composition), and on the user of the library who has five less functions to keep track of. (In production code, I'd insert some sanity checking to ensure, for example, that the level was an integer value between one and six [inclusive], but that seems overkill for example code.) Jeff Shannon Technician/Programmer Credit International From SWidney@ci.las-vegas.nv.us Wed Jan 15 14:27:13 2003 From: SWidney@ci.las-vegas.nv.us (Scott Widney) Date: Wed Jan 15 14:27:13 2003 Subject: [Tutor] FW: recursion Message-ID: <0E5508EBA1620743B409A2B8365DE16FDC8302@SOVEREIGN> > On Mon, 13 Jan 2003, Scott Widney wrote: > > > > ### > > > def factorial(z): > > > assert z >= 0, "Invalid input: z must be nonnegative." > > > if z == 1 or z == 0: > > > return 1 > > > else: > > > return z*factorial(z-1) > > > ### > > > > Danny, you've talked before about tail recursion. Is this below a > > properly-formed (if a little terse), tail-recursive definition for > > factorial()? > > > > ### > > def factorial(x, result=1): > > assert x >= 0, "Number must be non-negative." > > if x <= 1: return result > > else: return factorial(x-1, x*result) > > ### > > Hi Scott, > > Yup. This is perfect. *grin* > > > > If you'd like more concrete information on what constitutes a > tail-recursive function, I can quote some stuff off a book > I'm reading now called "Concepts in Programming Languages". > It's a little dry, but it gives more formal definitions that > might be helpful. Here's the section: > > > """ > For tail recursive functions, which are subsequently described, > it is possible to reuse an activation record for a recursive > call to the function. This reduces the amount of space used by a > recursive function. > > The main programming language concept we need is the concept > of tail call. Suppose function f calls function g. Functions f > and g might be different functions or f and g could be the same > function. A call to f in the body of g is a "tail call" if g > returns the result of calling f without any further computation. > For example, in the function > > fun g(x) = > if x = 0 then f(x) > else f(x) * 2 > > the first call to f in the body of g is a tail call, as the > return value of g is exactly the return value of the call to f. > The second call to f in the body of g is not a tail call because > g performs a computation involving the return value of f before > g returns. > > A function f is "tail recursive" if all recursive calls in > the body of f are tail calls to f. > """ > > > The language they're using isn't Python, but we can translate > it to Python syntax pretty easily: > > ### > def g(x): > if x == 0: return f(x) > else: return f(x) * 2 > ### > > > Anyway, hope this helps! Thanks Danny! (^ ocaml ?) To the group at large: I timed the two versions above, looping each 100 times through range(100), and noticed that the non-tail-recursive function is faster (2.163 seconds versus 2.394 seconds). In your experience is that a common payoff between the two types of recursion (speed for space)? Scott From SWidney@ci.las-vegas.nv.us Wed Jan 15 15:20:11 2003 From: SWidney@ci.las-vegas.nv.us (Scott Widney) Date: Wed Jan 15 15:20:11 2003 Subject: [Tutor] Comparative code questions: Python vs. Rebol Message-ID: <0E5508EBA1620743B409A2B8365DE16FDC8304@SOVEREIGN> > Instead of having a series of very similar functions that make > almost-equivalent modifications to a string, it's much simpler > to have a *single* function that takes a parameter to indicate > which of several modifications to make. > > >>> def HtmlHeader(level, text): > ... return "%s" % (level, text, level) > ... > >>> HtmlHeader(1, "This is level 1") > '

This is level 1

' > >>> HtmlHeader(3, "This is level 3") > '

This is level 3

' > >>> HtmlHeader(6, "This is level 6") > '
This is level 6
' > >>> Or alternatively (and also pythonically): >>> def H(level, text): ... return "%(text)s" % vars() ... >>> print H(1, "This is level 1")

This is level 1

>>> print H(3, "This is level 3")

This is level 3

But now here's a challenge: is it possible, in the hypothetical context of these examples, to write the function so that you could enter: >>> print H(3, "This is level ?_? ") ^ # not sure what would go here and receive:

This is level 3

Wait! Give me a few minutes.... >>> def HH(level,text): ... temp = "%(text)s" % vars() ... temp = eval('"'+temp+'" % vars()') ... return temp ... >>> print HH(3, "This is level %(level)s")

This is level 3

>>> print HH(6, "This is level 6")
This is level 6
>>> Whoa. That's dangerous. ...head aches now; must find analgesics.... Scott From tim@johnsons-web.com Wed Jan 15 15:44:08 2003 From: tim@johnsons-web.com (Tim Johnson) Date: Wed Jan 15 15:44:08 2003 Subject: [Tutor] Comparative code questions: Python vs. Rebol In-Reply-To: <3E25B590.7030202@ccvcorp.com> References: <20030114230533.GK5446@johnsons-web.com> <3E25B590.7030202@ccvcorp.com> Message-ID: <20030115204718.GX5446@johnsons-web.com> * Jeff Shannon [030115 10:40]: > > > Tim Johnson wrote: > > >Now here is a more complex example: > >Dynamically compose a series of functions such that > ># python > > print H3("This an html header of level 3") > > >>> "

This is an html header of level 3

" > > > > Others have shown how you can make Python do what you ask, here. > Instead of repeating that, I'll show you a way to achieve much the same > ends, but in a more Pythonic way -- something that I think makes it > easier to read, understand, and thus mantain. > > Instead of having a series of very similar functions that make > almost-equivalent modifications to a string, it's much simpler to have a > *single* function that takes a parameter to indicate which of several > modifications to make. > > >>> def HtmlHeader(level, text): > ... return "%s" % (level, text, level) > ... > >>> HtmlHeader(1, "This is level 1") > '

This is level 1

' > >>> HtmlHeader(3, "This is level 3") > '

This is level 3

' > >>> HtmlHeader(6, "This is level 6") > '
This is level 6
' > >>> > > The % operator, in this context, will make substitutions in the string > in a manner similar to C's printf() formatting. By doing it this way, > we have only one function to keep track of, instead of six. This is > easier on both the writer of the library (this is simpler than the > dynamic composition), and on the user of the library who has five less > functions to keep track of. (In production code, I'd insert some sanity > checking to ensure, for example, that the level was an integer value > between one and six [inclusive], but that seems overkill for example code.) > > Jeff Shannon > Technician/Programmer > Credit International Hi Jeff: Thank you for the additional info. In truth, I agree and that is the approach that I would use, however my original query was to generate some material for a column that I'm writting. Thanks! -tim- -- Tim Johnson http://www.alaska-internet-solutions.com http://www.johnsons-web.com From montana@buc99.bsd.st Wed Jan 15 16:12:02 2003 From: montana@buc99.bsd.st (montana) Date: Wed Jan 15 16:12:02 2003 Subject: [Tutor] Question on Time calculations. Message-ID: <200301152113.h0FLD3cA000895@buc99.bsd.st> This what I've got so far. I'm no math wiz, so please email me any math corrections or any improvements you see: #!/usr/bin/env python from time import strptime, mktime stime = raw_input("Enter Start Date and Time: ") etime = raw_input("Enter End Date and Time: ") a = mktime(strptime(stime, "%m.%d.%y %H%M")) b = mktime(strptime(etime, "%m.%d.%y %H%M")) hours = int((b-a)/(60*60)) min = int(((b-a)%(60*60)/60)) print "The total time is: %d hrs, %d min" % (hours, min) Thanks. SA :) From maillist@kuwest.de Wed Jan 15 16:53:09 2003 From: maillist@kuwest.de (Jens Kubieziel) Date: Wed Jan 15 16:53:09 2003 Subject: Assign long integer (was: [Tutor] Calculating a math formula and finding errors) In-Reply-To: References: <20030113103825.GC2584@kubieziel.de> Message-ID: <20030115214637.GI21817@kubieziel.de> On Mon, Jan 13, 2003 at 03:22:07AM -0800, Danny Yoo wrote: > def factorial(z): > assert z >= 0, "Invalid input: z must be nonnegative." > if z == 1 or z == 0: > return 1 > else: > return z*factorial(z-1) I still try to improve above mentioned function and want to extend this for long integers. I read that I can do this by adding an "l". But how do I do this with variables? If I'd write zL it is like a new variable. So must be another way. -- Jens Kubieziel mailto:jens@kubieziel.de Mut ist oft Mangel an Einsicht, waehrend Feigheit nicht selten auf guten Informationen beruht." (Sir Peter Ustinov) From hall@ouhep1.nhn.ou.edu Wed Jan 15 17:03:01 2003 From: hall@ouhep1.nhn.ou.edu (Isaac Hall) Date: Wed Jan 15 17:03:01 2003 Subject: Assign long integer (was: [Tutor] Calculating a math formula and finding errors) In-Reply-To: <20030115214637.GI21817@kubieziel.de> Message-ID: Hi, you can turn any variable into a long variable simply by saying (assume z is an int variable here) z=long(z) Ike On Wed, 15 Jan 2003, Jens Kubieziel wrote: > On Mon, Jan 13, 2003 at 03:22:07AM -0800, Danny Yoo wrote: > > def factorial(z): > > assert z >= 0, "Invalid input: z must be nonnegative." > > if z == 1 or z == 0: > > return 1 > > else: > > return z*factorial(z-1) > > I still try to improve above mentioned function and want to extend this > for long integers. I read that I can do this by adding an "l". But how do > I do this with variables? > If I'd write zL it is like a new variable. So must be another way. > -- From gp@pooryorick.com Wed Jan 15 17:24:01 2003 From: gp@pooryorick.com (Poor Yorick) Date: Wed Jan 15 17:24:01 2003 Subject: [Tutor] scope question References: <20030115145820.GA4948@houseofspearman.org> <5.1.0.14.0.20030115170916.02c3d6e0@www.thinkware.se> <20030115180506.GA5572@houseofspearman.org> Message-ID: <3E25DFD6.4030806@pooryorick.com> Norvell Spearman wrote: > >def increment(time, seconds): > time = addTime(time, makeTime(seconds)) > >[snip] > > >Yes and not exactly. When I call increment from either the program or >from the interactive Python shell, it doesn't change the time object >passed to it --- which is consistent with your example function. > In Python, paramaters are always passed into function by reference. However, once you are inside the function, and type time = (something) You create a new identifier in the local scope which hides the "time" identifier which was passed in by reference. > >Now if I do something like this > >def increment(time, seconds): > newTime = addTime(time, makeTime(seconds)) > time.hours = newTime.hours > time.minutes = newTime.minutes > time.seconds = newTime.seconds > In this case, you are changing the values of identifies inside the scope of the "time" object which you passed into the function. You still have access to the "time" object because you didn't reassign the "time" identifier within the function. Poor Yorick gp@pooryorick.com From montana@buc99.bsd.st Wed Jan 15 17:26:15 2003 From: montana@buc99.bsd.st (montana) Date: Wed Jan 15 17:26:15 2003 Subject: [Tutor] Question on Time calculations. Message-ID: <200301152226.h0FMQshD000946@buc99.bsd.st> Thanks for the hint Magnus. I incorporaated the mx module and have an updated script for everyones perusal: #!/usr/bin/env python from time import asctime, strptime from mx import DateTime stime = raw_input("Enter Start Date and Time: ") etime = raw_input("Enter End Date and Time: ") def timeCalc(stime, etime): x = asctime(strptime(stime, "%m.%d.%y %H%M")) y = asctime(strptime(etime, "%m.%d.%y %H%M")) a = DateTime.Parser.DateTimeFromString(x) b = DateTime.Parser.DateTimeFromString(y) c = b - a return c c = timeCalc(stime, etime) hours = ((c.day*24)+c.hour) min = c.minute print "The total time is: %d hrs, %d min" % (hours, min) Please email me your suggestions for improvement. Thanks SA :) From gp@pooryorick.com Wed Jan 15 17:42:02 2003 From: gp@pooryorick.com (Poor Yorick) Date: Wed Jan 15 17:42:02 2003 Subject: [Tutor] scope question References: <20030115145820.GA4948@houseofspearman.org> <5.1.0.14.0.20030115170916.02c3d6e0@www.thinkware.se> <20030115180506.GA5572@houseofspearman.org> <3E25DFD6.4030806@pooryorick.com> Message-ID: <3E25E3D3.1050904@pooryorick.com> Poor Yorick wrote: > > In this case, you are changing the values of identifies inside the > scope of the "time" object which you passed into the function. You > still have access to the "time" object because you didn't reassign the > "time" identifier within the function. By the way, I finally got a good understanding of this by experimenting with passing mutable vs immutable objects into different test functions. You have to be careful when passing a mutable object like a list into a function because if you can change an element within the list the change will be visible to any variables referencing that list object, inside or outside of your function. Poor Yorick gp@pooryorick.com From norvell@houseofspearman.org Wed Jan 15 17:48:04 2003 From: norvell@houseofspearman.org (Norvell Spearman) Date: Wed Jan 15 17:48:04 2003 Subject: [Tutor] scope question In-Reply-To: <3E25DFD6.4030806@pooryorick.com> References: <20030115145820.GA4948@houseofspearman.org> <5.1.0.14.0.20030115170916.02c3d6e0@www.thinkware.se> <20030115180506.GA5572@houseofspearman.org> <3E25DFD6.4030806@pooryorick.com> Message-ID: <20030115224706.GA23787@houseofspearman.org> On Wednesday, 2003.01.15, 15:25:26 -0700, Poor Yorick wrote: > In Python, parameters are always passed into function by reference. > However, once you are inside the function, and type > > time = (something) > > You create a new identifier in the local scope which hides the "time" > identifier which was passed in by reference. OK. Thanks; that clears it up. > >Now if I do something like this > > > >def increment(time, seconds): > > newTime = addTime(time, makeTime(seconds)) > > time.hours = newTime.hours > > time.minutes = newTime.minutes > > time.seconds = newTime.seconds > > > > In this case, you are changing the values of identifies inside the scope > of the "time" object which you passed into the function. You still have > access to the "time" object because you didn't reassign the "time" > identifier within the function. So the only way to write a modifier (as opposed to a pure function) for an object is to change the object's attributes, right? One more question --- sorry to be a pain, but I want to make sure I understand this correctly: In the following function definition def foo(bar): ... bar = bam # bam has attributes x and y, as does parameter bar bar.x = x bar.y = y ``bar = bam'' is a new variable, local to the function and completely separate from the passed bar, but ``bar.x = x'' and ``bar.y = y'' will affect the parameter bar and not the function-local bar. Is that correct? The tutorial through which I'm working hasn't got to methods in detail yet (next chapter), but I gather from what little I've scanned ahead that methods circumvent this possible confusion, no? Thanks very much for your help. -- Norvell Spearman From magnus@thinkware.se Wed Jan 15 18:09:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Wed Jan 15 18:09:01 2003 Subject: [Tutor] scope question In-Reply-To: <20030115180506.GA5572@houseofspearman.org> References: <5.1.0.14.0.20030115170916.02c3d6e0@www.thinkware.se> <20030115145820.GA4948@houseofspearman.org> <5.1.0.14.0.20030115170916.02c3d6e0@www.thinkware.se> Message-ID: <5.1.0.14.0.20030115232608.02bceee0@www.thinkware.se> At 12:05 2003-01-15 -0600, Norvell Spearman wrote: >def increment(time, seconds): > time = addTime(time, makeTime(seconds)) As I though... >OK, so function calls pass by value, not by reference, right? You pass objects. The notion of pass by reference and pass by value are basically concepts used to try to explain the bizarre and complicated way most other languages work in. I'm so happy to be almost a full time Python programmer now. :) I almost forgot why we needed these difficult concepts of references and pointers and pointers to pointers and whatever in C++. Despite years of hard work, where most of my peers came to me to ask for help when it got tricky, I never really felt that I fully grasped it. Sure, I understood the concepts, but I still got lost and had to solve things by trial end error when it got difficult. Yuck! Inside the scope of increment, the variable "time" will initially point at the same object as the global variable "t1" did. But in the body of the function, you reassign "time" to a new object, created by addTime(). I guess you would want something like this. class Time: def __init__(self, secs=0): self.secs = 0 def addTime(self, secs): self.secs += secs ... def increment(time, secs): time.addTime(secs) In this case the increment function doesn't reassign its time-parameter. Instead it modifies the mutable object that the time variable refers to. All variables in python are references to objects. There are no references to references or anything like that, nothing like pointers to pointers in C. You don't need it, since the language is much smarter than C and friends. >But I don't understand why > >t1 = addTime(t1, makeTime(34)) > >alters t1 when called in the Python shell but not as the definition of >increment. I'm not sure what you mean. The above statement will mean that the variable t1 will stop pointing at the object you put into addTime, and instead point to the object created by addTime. In this case I guess they are object of the same class, but that's not relevant. It's equivalent to x = 5 # Now x refers to an integer x = str(x) # Now we have dropped our reference to 5, the # variable x will henceforth refer to the "5" # string object. It's imperative to distinguish between varaibles (names) and objects (things we have names for). Think about Rene Magritte's famous "This is not a pipe" painting, http://www.westegg.com/morgan/gifs/Pipe.gif or perhaps rather about what the English mathematician who called himself Lewis Carroll once wrote... `You are sad,' the Knight said in an anxious tone: `let me sing you a song to comfort you.' `Is it very long?' Alice asked, for she had heard a good deal of poetry that day. `It's long,' said the Knight, `but very, VERY beautiful. Everybody that hears me sing it--either it brings the TEARS into their eyes, or else--' `Or else what?' said Alice, for the Knight had made a sudden pause. `Or else it doesn't, you know. The name of the song is called "HADDOCKS' EYES."' `Oh, that's the name of the song, is it?' Alice said, trying to feel interested. `No, you don't understand,' the Knight said, looking a little vexed. `That's what the name is CALLED. The name really IS "THE AGED AGED MAN."' `Then I ought to have said "That's what the SONG is called"?' Alice corrected herself. `No, you oughtn't: that's quite another thing! The SONG is called "WAYS AND MEANS": but that's only what it's CALLED, you know!' `Well, what IS the song, then?' said Alice, who was by this time completely bewildered. `I was coming to that,' the Knight said. `The song really IS "A-SITTING ON A GATE": and the tune's my own invention.' http://www.ibiblio.org/gutenberg/etext91/lglass18.txt >Now if I do something like this > >def increment(time, seconds): > newTime = addTime(time, makeTime(seconds)) > time.hours = newTime.hours > time.minutes = newTime.minutes > time.seconds = newTime.seconds > >then increment does what I expect, but I don't understand why. It >appears the original increment works on pass-by-value and the second >increment works on pass-by-reference. Why the difference? Perhaps you have understood by now. With Alice's help? In this version of increment, you never reassign time. It continues to point at the same (mutable) object as the variable t1 does. What you do here is just the same as in the code below: a = [] b = a b.append(1) print a [1] Two variables refer to the same object. The object is mutable, and is modified using one of the varaibles that refer to it. Since it's the same object, the change will be visible through both names. -- 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@thinkware.se Wed Jan 15 18:27:40 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Wed Jan 15 18:27:40 2003 Subject: [Tutor] Question on Time calculations. In-Reply-To: <200301152226.h0FMQshD000946@buc99.bsd.st> Message-ID: <5.1.0.14.0.20030116001127.02996e00@www.thinkware.se> At 16:26 2003-01-15 -0600, montana wrote: > x = asctime(strptime(stime, "%m.%d.%y %H%M")) > y = asctime(strptime(etime, "%m.%d.%y %H%M")) > a = DateTime.Parser.DateTimeFromString(x) > b = DateTime.Parser.DateTimeFromString(y) It seem slightly odd to go via the representation of asctime. For instance, it means that you still rely on the time module with date restricted to 1970 - 2037. I suspect that you might also be bitten by locale settings. Are you sure asctime will always print a string in English? If you look through the mxDateTime docs, that you got a link to, I'm sure you will find more robust solutions. If you know that time is entered as "%m.%d.%y %H%M", you could do >>> stime = "12.31.2002 1259" >>> date, time = stime.split() >>> month, day, year = map(int,date.split('.')) >>> hour, min = map(int,[time[:-2], time[-2:]]) >>> print DateTime.DateTime(year, month, day, hour, min, 0) 2002-12-31 12:59:00.00 This is a few more lines of code, but it's certainly more robust. It will handle a much larger span in time, and it doesn't realy on particular locale settings 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 gp@pooryorick.com Wed Jan 15 18:29:01 2003 From: gp@pooryorick.com (Poor Yorick) Date: Wed Jan 15 18:29:01 2003 Subject: [Tutor] scope question References: <20030115145820.GA4948@houseofspearman.org> <5.1.0.14.0.20030115170916.02c3d6e0@www.thinkware.se> <20030115180506.GA5572@houseofspearman.org> <3E25DFD6.4030806@pooryorick.com> <20030115224706.GA23787@houseofspearman.org> Message-ID: <3E25EE60.3030603@pooryorick.com> Norvell Spearman wrote: >On Wednesday, 2003.01.15, 15:25:26 -0700, Poor Yorick wrote: > > >So the only way to write a modifier (as opposed to a pure function) for >an object is to change the object's attributes, right? > Not sure exactly what you mean. You can often use the return value of a function to modify something. For example: >>> def DoSomething(): var = 'Darth Vader' >>> name = 'Poor Yorick' >>> def ReturnSomething(): var = 'Darth Vader' return var >>> name = 'Poor Yorick' >>> print name Poor Yorick >>> name = ReturnSomething() >>> print name Darth Vader >>> > > >One more question --- sorry to be a pain, but I want to make sure I >understand this correctly: In the following function definition > >def foo(bar): > ... > bar = bam # bam has attributes x and y, as does parameter bar > bar.x = x > bar.y = y > >``bar = bam'' is a new variable, local to the function and completely >separate from the passed bar, but ``bar.x = x'' and ``bar.y = y'' will >affect the parameter bar and not the function-local bar. Is that >correct? > No, bar and bam are now identifiers for the sam object in memory, and that is the only object you are going to be changing. Within the scope of the function, you have effectively lost your handle to the object passed in as parameter "bar". Poor Yorick gp@pooryorick.com From norvell@houseofspearman.org Wed Jan 15 18:35:03 2003 From: norvell@houseofspearman.org (Norvell Spearman) Date: Wed Jan 15 18:35:03 2003 Subject: [Tutor] scope question In-Reply-To: <3E25E3D3.1050904@pooryorick.com> References: <20030115145820.GA4948@houseofspearman.org> <5.1.0.14.0.20030115170916.02c3d6e0@www.thinkware.se> <20030115180506.GA5572@houseofspearman.org> <3E25DFD6.4030806@pooryorick.com> <3E25E3D3.1050904@pooryorick.com> Message-ID: <20030115225458.GB23787@houseofspearman.org> On Wednesday, 2003.01.15, 15:42:27 -0700, Poor Yorick wrote: > By the way, I finally got a good understanding of this by experimenting > with passing mutable vs immutable objects into different test functions. > You have to be careful when passing a mutable object like a list into a > function because if you can change an element within the list the change > will be visible to any variables referencing that list object, inside or > outside of your function. The tutorial I'm using is pretty good about stating each data type's mutability or immutability; I probably need to go back and memorize them. Thanks. -- Norvell Spearman From gp@pooryorick.com Wed Jan 15 18:36:00 2003 From: gp@pooryorick.com (Poor Yorick) Date: Wed Jan 15 18:36:00 2003 Subject: [Tutor] scope question References: <20030115145820.GA4948@houseofspearman.org> <5.1.0.14.0.20030115170916.02c3d6e0@www.thinkware.se> <20030115180506.GA5572@houseofspearman.org> <3E25DFD6.4030806@pooryorick.com> <3E25E3D3.1050904@pooryorick.com> <20030115225458.GB23787@houseofspearman.org> Message-ID: <3E25F076.8090905@pooryorick.com> Norvell Spearman wrote: >On Wednesday, 2003.01.15, 15:42:27 -0700, Poor Yorick wrote: > >>By the way, I finally got a good understanding of this by experimenting >>with passing mutable vs immutable objects into different test functions. >>You have to be careful when passing a mutable object like a list into a >>function because if you can change an element within the list the change >>will be visible to any variables referencing that list object, inside or >>outside of your function. >> > >The tutorial I'm using is pretty good about stating each data type's >mutability or immutability; I probably need to go back and memorize >them. Thanks. > I spent most of this year studying Wesley Chun's "Core Python Programming", and highly recommend it. Once I felt quite familiar with all the principles in that book, I moved on to "Programming Python", by Mark Lutz. Taken together, these two books provided me a thorough introduction not only to programming in Python, but to the art of programming in general. It has also been invaluable to have people on this list reiterate the same principles in a their own ways. Poor Yorick gp@pooryorick.com From jeff@ccvcorp.com Wed Jan 15 19:09:19 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Wed Jan 15 19:09:19 2003 Subject: [Tutor] Comparative code questions: Python vs. Rebol References: <0E5508EBA1620743B409A2B8365DE16FDC8304@SOVEREIGN> Message-ID: <3E25F7CC.7070206@ccvcorp.com> Scott Widney wrote: >Or alternatively (and also pythonically): > > > >>>>def H(level, text): >>>> >>>> >... return "%(text)s" % vars() >... > > My personal preference is to avoid using vars() -- explicit is better than implicit, and this requires a few moments more thought to figure out just what vars() does and how that interacts with %. >But now here's a challenge: is it possible, in the hypothetical context of >these examples, to write the function so that you could enter: > > > >>>>print H(3, "This is level ?_? ") >>>> >>>> > ^ # not sure what would go here >and receive: > >

This is level 3

> It can be done without using eval(), as well -- >>> def HH(level, text): ... text = text % level ... return "%s" % (level, text, level) ... >>> HH(3, 'This is level %d') '

This is level 3

' >>> HH(6, 'This is level %d') '
This is level 6
' >>> As has been mentioned in another thread, there are very few circumstances in which eval() is the only (or even best) way to do things. :) However, I think that this is *not* a good function design, in either form (yours or mine), because in either case, it requires the user of the function to know too much about the implementation details of the function -- i.e., what special characters ('%d' or '%(level)d') to include in the text string in order to get the proper substitution. I'd rather have the more explicit version that doesn't do additional formatting of the text string -- formatting the text should be separate from converting it to a marked-up html header. Jeff Shannon Technician/Programmer Credit International From SWidney@ci.las-vegas.nv.us Wed Jan 15 19:34:01 2003 From: SWidney@ci.las-vegas.nv.us (Scott Widney) Date: Wed Jan 15 19:34:01 2003 Subject: [Tutor] % formatting Message-ID: <0E5508EBA1620743B409A2B8365DE16FDC830A@SOVEREIGN> > It can be done without using eval(), as well -- > > >>> def HH(level, text): > ... text = text % level > ... return "%s" % (level, text, level) > ... > >>> HH(3, 'This is level %d') > '

This is level 3

' > >>> HH(6, 'This is level %d') > '
This is level 6
' > >>> > > As has been mentioned in another thread, there are very few > circumstances in which eval() is the only (or even best) way to do > things. :) However, I think that this is *not* a good function > design, in either form (yours or mine), because in either case, it > requires the user of the function to know too much about the > implementation details of the function -- i.e., what special > characters ('%d' or '%(level)d') to include in the text string > in order to get the proper substitution. > I'd rather have the more explicit version that doesn't do > additional formatting of the text string -- formatting the text > should be separate from converting it to a marked-up html header. I agree wholeheartedly; it was just a curiousity / mental exercise thing. One thing I did not know was that % formatting worked outside the context of the 'print' statement. I think the C language partition in my head is biting me here; I've been thinking of 'print' as analogous to 'printf()'. Then (correct me if I'm wrong here): 'print' is not a function and '%' is, what, an overloaded operator ? Scott From jeff@ccvcorp.com Wed Jan 15 19:35:17 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Wed Jan 15 19:35:17 2003 Subject: [Tutor] Comparative code questions: Python vs. Rebol References: <20030114230533.GK5446@johnsons-web.com> <3E25B590.7030202@ccvcorp.com> <20030115204718.GX5446@johnsons-web.com> Message-ID: <3E25FDB1.5070907@ccvcorp.com> Tim Johnson wrote: >* Jeff Shannon [030115 10:40]: > > >>Others have shown how you can make Python do what you ask, here. >>Instead of repeating that, I'll show you a way to achieve much the same >>ends, but in a more Pythonic way -- something that I think makes it >>easier to read, understand, and thus mantain. >> >> > > Hi Jeff: > Thank you for the additional info. In truth, I agree and > that is the approach that I would use, however my > original query was to generate some material for a > column that I'm writting. > > Indeed, I understood that. I would contend, however, that you will be doing your readers a disservice if you only present "how to write Rebol-style code in Python", without also showing them that there are different ways of achieving the same ends, and that coding pythonic Python and rebolic Rebol is the best approach. You will be giving you readers an unfairly slanted view of Python, by showing them the contortions that must be done to use Python like Rebol. Jeff Shannon Technician/Programmer Credit International From jeff@ccvcorp.com Wed Jan 15 19:40:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Wed Jan 15 19:40:02 2003 Subject: Assign long integer (was: [Tutor] Calculating a math formula and finding errors) References: <20030113103825.GC2584@kubieziel.de> <20030115214637.GI21817@kubieziel.de> Message-ID: <3E25FEDC.1060207@ccvcorp.com> Jens Kubieziel wrote: >On Mon, Jan 13, 2003 at 03:22:07AM -0800, Danny Yoo wrote: > > >>def factorial(z): >> assert z >= 0, "Invalid input: z must be nonnegative." >> if z == 1 or z == 0: >> return 1 >> else: >> return z*factorial(z-1) >> >> > >I still try to improve above mentioned function and want to extend this >for long integers. I read that I can do this by adding an "l". But how do >I do this with variables? >If I'd write zL it is like a new variable. So must be another way. > > Actually, because Python will automatically convert to long integers if there's integer overflow, you don't need to do anything. >>> factorial(3) 6 >>> factorial(10) 3628800 >>> factorial(15) 1307674368000L >>> As you can see, the final result there is a number followed by an L. That means that the result is a long int, despite the fact that nothing in the function specifies a need to use long ints -- I've used exactly the same function posted here. Python has automagically handled the overflow by switching to longs, without us needing to do anything. Jeff Shannon Technician/Programmer Credit International From jeff@ccvcorp.com Wed Jan 15 19:49:07 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Wed Jan 15 19:49:07 2003 Subject: [Tutor] % formatting References: <0E5508EBA1620743B409A2B8365DE16FDC830A@SOVEREIGN> Message-ID: <3E260124.9050607@ccvcorp.com> Scott Widney wrote: >One thing I did not know was that % formatting worked outside the context of >the 'print' statement. I think the C language partition in my head is biting >me here; I've been thinking of 'print' as analogous to 'printf()'. Then >(correct me if I'm wrong here): 'print' is not a function and '%' is, what, >an overloaded operator ? > > That's exactly correct -- 'print' is a statement, not a function (which is why it doesn't require parentheses, why it is a keyword when built-in functions are not, etc). And '%' is ... well, perhaps not strictly overloaded, but close enough. When used with numeric operands, % performs the modulo operation, but when used with a string as the left operand, it performs string substitution. In effect, this is modulo operation of strings, it just bears no logical resemblance to the modulo operation of numbers. In C, there's a function (sprintf(), IIRC) which takes the format string and a variable list and performs the substitution, and returns a string (rather than printing it as printf() does). In Python, this is a standard string operation, done by the % operator without need for a function -- C requires it to be a function because C doesn't have a true string type, but Python does. Jeff Shannon Technician/Programmer Credit International From pythonpython@hotmail.com Wed Jan 15 20:23:03 2003 From: pythonpython@hotmail.com (Hy Python) Date: Wed Jan 15 20:23:03 2003 Subject: [Tutor] askfont in Tkinter? Message-ID: Could anyone please tell me is something like askfont function in Tkinter, or other GUI modules? In the tkColorChooser.py, we have askcolor function which helps with selecting a color. Is there something like that for select fonts. Thanks a lot. Hy _________________________________________________________________ MSN 8 with e-mail virus protection service: 2 months FREE* http://join.msn.com/?page=features/virus From norvell@houseofspearman.org Wed Jan 15 20:33:04 2003 From: norvell@houseofspearman.org (Norvell Spearman) Date: Wed Jan 15 20:33:04 2003 Subject: [Tutor] scope question In-Reply-To: <3E25EE60.3030603@pooryorick.com> References: <20030115145820.GA4948@houseofspearman.org> <5.1.0.14.0.20030115170916.02c3d6e0@www.thinkware.se> <20030115180506.GA5572@houseofspearman.org> <3E25DFD6.4030806@pooryorick.com> <20030115224706.GA23787@houseofspearman.org> <3E25EE60.3030603@pooryorick.com> Message-ID: <20030116013222.GA24512@houseofspearman.org> On Wednesday, 2003.01.15, 16:27:28 -0700, Poor Yorick wrote: > Not sure exactly what you mean. You can often use the return value of a > function to modify something. For example: I was using terminology from the ``Think'' tutorial. A pure function is like a mathematical function: f(x) = x**2 returns a value without modifying x. > No, bar and bam are now identifiers for the sam object in memory, and > that is the only object you are going to be changing. Within the scope > of the function, you have effectively lost your handle to the object > passed in as parameter "bar". Ah. Thanks. -- Norvell Spearman From norvell@houseofspearman.org Wed Jan 15 20:39:01 2003 From: norvell@houseofspearman.org (Norvell Spearman) Date: Wed Jan 15 20:39:01 2003 Subject: [Tutor] scope question In-Reply-To: <5.1.0.14.0.20030115232608.02bceee0@www.thinkware.se> References: <5.1.0.14.0.20030115170916.02c3d6e0@www.thinkware.se> <20030115145820.GA4948@houseofspearman.org> <5.1.0.14.0.20030115170916.02c3d6e0@www.thinkware.se> <5.1.0.14.0.20030115232608.02bceee0@www.thinkware.se> Message-ID: <20030116013815.GB24512@houseofspearman.org> On Thursday, 2003.01.16, 00:07:07 +0100, Magnus Lycka wrote: > It's imperative to distinguish between varaibles (names) and > objects (things we have names for). Think about Rene Magritte's > famous "This is not a pipe" painting, > http://www.westegg.com/morgan/gifs/Pipe.gif > or perhaps rather about what the English mathematician who called > himself Lewis Carroll once wrote... Thanks for the analogies and explanations. Things are getting clearer. -- Norvell Spearman From PMittal@Ceon.com Wed Jan 15 21:25:02 2003 From: PMittal@Ceon.com (Pankaj Mittal) Date: Wed Jan 15 21:25:02 2003 Subject: [Tutor] Sending Break in Telnet Message-ID: <46FEE020BCB4D3118C5800508B55C92801361151@SFOEXCHANGE> Hi I am developing a python program that connects to a server using telnet. When I use the unix telnet I have to send telnet . This has to be followed by sending a "^]" chartacter and then with "send break" on receiving a "telnet>" prompt. But when I try to send \035(equivalent of '^]', it does not work. Also I tried to send '\377\363'(255 and 243 - code as in RFC document). Following is the snippet of the successful transaction when done manually from the Solaris prompt. >telnet 192.168.1.0 10012 Trying 192.168.1.0 ... Connected to 192.168.1.0 . Escape character is '^]'. telnet> send break ?login Enter User Name Thanks Pankaj From BranimirP@cpas.com Wed Jan 15 23:12:02 2003 From: BranimirP@cpas.com (Branimir Petrovic) Date: Wed Jan 15 23:12:02 2003 Subject: [Tutor] Threads, locking and race condition Message-ID: <33678E78A2DD4D418396703A750048D41A63B9@RIKER> Flipping through wonderful 'Python Cookbook' I stumbled across this example that rang my 'alarm bells'. Looks like there is 'something little' having to do with multithreading that I do not quite get... I'll post the whole example here as it is brief. The cookbook recipe 6.1 - 'Storing Per-Thread Information': try: import thread except: """Single-threaded OS, return standard dictionary""" _tss = {} def get_thread_storage(): return _tss else: """OS supports multithreading, so - to work:""" _tss = {} _tss_lock = thread.allocate_lock() def get_thread_storage(): thread_id = thread.get_ident() tss = _tss.get(thread_id) if tss is None: # First time being called by this thread try: # Entering critical section _tss_lock.acquire() _tss[thread_id] = tss = {} finally: _tss_lock.release() return tss The idea behind this piece of code is fairly straightforward - namely to use the dictionary object to store other - thread specific dictionaries. Assuming we have number of concurrent threads and assuming each one gets its own little piece inside shared dictionary everything seems to be simple and clear. Each thread will be allowed to use/access only its own storage area, while unique ThreadID will be the key or 'pointer' to the proper 'piece of pie'. Soon after thinking a bit deeper about this concept, looking at the above code snippet, and pondering about locking and synchronizing access to shared object, I started feeling uneasy. Longer I thought about it - more questions I had. It got to the point where I am not sure about anything related to this subject. I must admit that I do not plan to use above example, but I do need to fully understand any issues related to concurrence and locking. What does not 'sit' with me very well in the above example is late locking - where 'late' is just my nagging impression that prompted this lengthy post. What will happen in following scenario: - Say Thread-3 needs to access its storage and calls the function: def get_thread_storage(): thread_id = thread.get_ident() tss = _tss.get(thread_id) At this very point having reached its 10-th byte code instruction, Thread-3 is suspended, so that other threads will get their chance to run. - By pure chance/coincidence Thread-6 is awaken, and being just about to call get_thread_storage() - this time it calls it indeed, and not only that it calls the function, but also it manages to exit from it by the time Thread-6 'fades' and goes to forced 'sleep', - By another remarkable turn of events, Thread-3 is awaken again, only to find variable tss that is now pointing to a value set by run of interrupting Tread-6. Thread-3 will not have slightest 'clue' that its own value was overwritten 'behind its back' while its execution was suspended. As a result Thread-3 will now return wrong dictionary? Do I see the problem that does not exist? If you spot anything wrong with my (contrived?) assumption/scenario - please let me know. Let's examine other option: - Say we change function in such a way as to obtain lock with very first step into the function: def get_thread_storage(): tss_lock.acquire() thread_id = thread.get_ident() # ...and so on ending with: finally: _tss_lock.release() return tss Is it possible that Thread-3 does its job and release the lock object, but just before returning tss - scheduler suspends it and run Thread-6 that calls the function, and manages to finish it and exit the function? Wouldn't Thread-3 if awaken now return the tss as left by Thread-6? The way I see two proposed scenarios - both are possible, second one less but nevertheless - still possible. Given long enough time - 'mishap' will happen for sure. Right or wrong? Which brings me to next nagging question: - How 'granular' are Python's byte code instructions? Is this: thread_id = thread.get_ident() one byte code instruction or more than one byte code instruction? To slightly re-phrase the question: - Is the 'line' of code (such as thread_id = thread.get_ident()) guaranteed to execute and fully finish before Python switches to another thread or not? - If 'yes' is answer to the above question, what would happen in this (admittedly - artificial) case: return choice and [yes][0] or [no][0] How many byte codes would that be? - And what about: return mySillyChoice() and toughChoiceA() or toughChoiceB() This will 'break' (be switched) at any convenient spot in any of three function calls yes/no? I would very much like to hear back (hopefully) on any of outlined questions. If you as far as this line, thanks for your patience. Branimir From pythonpython@hotmail.com Thu Jan 16 00:42:02 2003 From: pythonpython@hotmail.com (Hy Python) Date: Thu Jan 16 00:42:02 2003 Subject: [Tutor] convert '\\t' to '\t' Message-ID: Could anyone please give me some tips on converting things like '\\t' into '\t'? Thanks. Hy _________________________________________________________________ Add photos to your e-mail with MSN 8. Get 2 months FREE*. http://join.msn.com/?page=features/featuredemail From pythonpython@hotmail.com Thu Jan 16 01:07:02 2003 From: pythonpython@hotmail.com (Hy Python) Date: Thu Jan 16 01:07:02 2003 Subject: [Tutor] convert '\\t' to '\t' Message-ID: Thanks for you reply, Fred. This will not work. Python throws out "SyntaxError: invalid token" when you try to run textstring = textstring.replace('//', '/') '/' is not a valid string. Hy >From: Alfred Milgrom >To: tutor@python.org,pythonpython@hotmail.com >Subject: Re: [Tutor] convert '\\t' to '\t' Date: Thu, 16 Jan 2003 17:00:28 >+1100 > > >> Could anyone please give me some tips on converting things like '\\t' >into '\t'? > >I am not sure that's really your question. If it's just a simple string >substitution, you can use > >textstring = 'something or other containing //t' >textstring = textstring.replace('//', '/') > >But I suspect you actually want to do something else. >Fred Milgrom _________________________________________________________________ MSN 8 helps eliminate e-mail viruses. Get 2 months FREE* http://join.msn.com/?page=features/virus From fredm@smartypantsco.com Thu Jan 16 01:10:06 2003 From: fredm@smartypantsco.com (Alfred Milgrom) Date: Thu Jan 16 01:10:06 2003 Subject: [Tutor] convert '\\t' to '\t' Message-ID: <5.1.0.14.0.20030116165429.01ed7920@mail.milgromphoto.com> >> Could anyone please give me some tips on converting things like '\\t' into '\t'? I am not sure that's really your question. If it's just a simple string substitution, you can use textstring = 'something or other containing //t' textstring = textstring.replace('//', '/') But I suspect you actually want to do something else. Fred Milgrom From pythonpython@hotmail.com Thu Jan 16 01:17:02 2003 From: pythonpython@hotmail.com (Hy Python) Date: Thu Jan 16 01:17:02 2003 Subject: [Tutor] convert '\\t' to '\t' Message-ID: sorry. I confused \ with / textstring = textstring.replace('//', '/') is OK, but textstring = textstring.replace('\\', '\') does not work. sorry again. Hy >From: "Hy Python" >To: fredm@smartypantsco.com, tutor@python.org >Subject: Re: [Tutor] convert '\\t' to '\t' >Date: Thu, 16 Jan 2003 06:05:36 +0000 > >Thanks for you reply, Fred. > >This will not work. >Python throws out "SyntaxError: invalid token" >when you try to run textstring = textstring.replace('//', '/') > >'/' is not a valid string. > > >Hy > > > > >>From: Alfred Milgrom >>To: tutor@python.org,pythonpython@hotmail.com >>Subject: Re: [Tutor] convert '\\t' to '\t' Date: Thu, 16 Jan 2003 17:00:28 >>+1100 >> >> >> Could anyone please give me some tips on converting things like '\\t' >>into '\t'? >> >>I am not sure that's really your question. If it's just a simple string >>substitution, you can use >> >>textstring = 'something or other containing //t' >>textstring = textstring.replace('//', '/') >> >>But I suspect you actually want to do something else. >>Fred Milgrom > > >_________________________________________________________________ >MSN 8 helps eliminate e-mail viruses. Get 2 months FREE* >http://join.msn.com/?page=features/virus > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ The new MSN 8: smart spam protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From tony@tcapp.com Thu Jan 16 01:33:02 2003 From: tony@tcapp.com (Tony Cappellini) Date: Thu Jan 16 01:33:02 2003 Subject: [Tutor] problem with reload() Message-ID: <5.1.0.14.0.20030115223724.01ab3208@smtp.sbcglobal.net> After importing a module initially, when I try to reload a module in Ipython, PythonWin, or Idle I always get the following error message- like reload() doesn't work reload(ch2_10) Traceback (most recent call last): File "", line 1, in ? NameError: name 'ch2_10' is not defined ch2_10.py IS in the current directory, as verified by In [2]: os.chdir('e:\.ipython\pyclass\hw2') In [3]: os.system('dir ch2_10.*');raw_input() Volume in drive E is WIN_2000 Directory of e:\.ipython\pyclass\hw2 01/15/2003 09:39p 695 ch2_10.pyc 01/15/2003 09:51p 597 ch2_10.bak 01/15/2003 09:54p 592 ch2_10.py What am I doing wrong ? From magnus@thinkware.se Thu Jan 16 02:09:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Thu Jan 16 02:09:01 2003 Subject: [Tutor] problem with reload() In-Reply-To: <5.1.0.14.0.20030115223724.01ab3208@smtp.sbcglobal.net> Message-ID: <5.1.0.14.0.20030116080710.02c95090@www.thinkware.se> At 22:41 2003-01-15 -0800, Tony Cappellini wrote: >After importing a module initially, >when I try to reload a module in Ipython, PythonWin, or Idle >I always get the following error message- like reload() doesn't work Is there perhaps code in the imported module that changes your current directory? The fact that you did a os.chdir to show that it's there suggests that. Doesn't reload work after you chdir back? -- 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@thinkware.se Thu Jan 16 02:16:00 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Thu Jan 16 02:16:00 2003 Subject: [Tutor] convert '\\t' to '\t' In-Reply-To: Message-ID: <5.1.0.14.0.20030116080930.02acbe08@www.thinkware.se> At 05:40 2003-01-16 +0000, Hy Python wrote: >Could anyone please give me some tips on converting things like '\\t' into >'\t'? >>> "hello\\tworld".replace('\\t','\t') 'hello\tworld' Note that \ is used as an indicator for certain special symbols. '\\' is thus used to indicate that the string actually contains a literal \. '\\t' means that the string contains a \ followed by a t. '\t' is the indicator for a tab character, and it's needed to make it explicit that we have a tab, and not just some space characters in the string. Thus replacing '\\' with '\' will never work. '\' is an incomplete control sequence. You can't use that out of context like that. -- 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 pythonpython@hotmail.com Thu Jan 16 02:52:03 2003 From: pythonpython@hotmail.com (Hy Python) Date: Thu Jan 16 02:52:03 2003 Subject: [Tutor] convert '\\t' to '\t' Message-ID: I understand this. But what I really want to do is convert things like "\\n","\\r","\\s", "\\x" to "\n", "\r", "\s", "\x" So, is there a universal way to convert "\\" to "\" Thanks a lot. Hy >From: Magnus Lycka >To: "Hy Python" , tutor@python.org >Subject: Re: [Tutor] convert '\\t' to '\t' >Date: Thu, 16 Jan 2003 08:15:40 +0100 > >At 05:40 2003-01-16 +0000, Hy Python wrote: >>Could anyone please give me some tips on converting things like '\\t' into >>'\t'? > > >>> "hello\\tworld".replace('\\t','\t') >'hello\tworld' > >Note that \ is used as an indicator for certain special symbols. >'\\' is thus used to indicate that the string actually contains >a literal \. '\\t' means that the string contains a \ followed >by a t. '\t' is the indicator for a tab character, and it's needed >to make it explicit that we have a tab, and not just some space >characters in the string. > >Thus replacing '\\' with '\' will never work. '\' is an incomplete >control sequence. You can't use that out of context like that. > > >-- >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 > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ MSN 8 with e-mail virus protection service: 2 months FREE* http://join.msn.com/?page=features/virus From j.ezequiel@spitech.com Thu Jan 16 04:31:40 2003 From: j.ezequiel@spitech.com (Justin Ezequiel) Date: Thu Jan 16 04:31:40 2003 Subject: [Tutor] Search and replace Message-ID: <01C2BD84.D4F8C0C0@pc7486> >From reading the other's answer to this question, I guess regular expressions is not needed for this particular task. However, I decided to try using regular expressions anyway. Just as a learning exercise. I am still new at Python and I have not used the re module before. This is what I came up with. Comments are welcome. import re str = "123 ;345 ; 456; 55 ; ; ;123 abc" patt = "[^;]+" def trim(matchobj): return matchobj.group(0).strip() print re.sub(patt, trim, str) From lhleong@mail.com Thu Jan 16 04:43:02 2003 From: lhleong@mail.com (leong lau) Date: Thu Jan 16 04:43:02 2003 Subject: [Tutor] (no subject) Message-ID: <20030116094147.66762.qmail@mail.com> how to unsubscribe? my mailbox is going to explode! -- __________________________________________________________ Sign-up for your own FREE Personalized E-mail at Mail.com http://www.mail.com/?sr=signup Meet Singles http://corp.mail.com/lavalife From maillist@kuwest.de Thu Jan 16 05:02:02 2003 From: maillist@kuwest.de (Jens Kubieziel) Date: Thu Jan 16 05:02:02 2003 Subject: Assign long integer (was: [Tutor] Calculating a math formula and finding errors) In-Reply-To: <3E25FEDC.1060207@ccvcorp.com> References: <20030113103825.GC2584@kubieziel.de> <20030115214637.GI21817@kubieziel.de> <3E25FEDC.1060207@ccvcorp.com> Message-ID: <20030116094946.GR21817@kubieziel.de> On Wed, Jan 15, 2003 at 04:37:48PM -0800, Jeff Shannon wrote: > Jens Kubieziel wrote: > >On Mon, Jan 13, 2003 at 03:22:07AM -0800, Danny Yoo wrote: > > > > > >>def factorial(z): > >> assert z >= 0, "Invalid input: z must be nonnegative." > >> if z == 1 or z == 0: > >> return 1 > >> else: > >> return z*factorial(z-1) > > Actually, because Python will automatically convert to long integers if > there's integer overflow, you don't need to do anything. > > >>> factorial(3) > 6 > >>> factorial(10) > 3628800 > >>> factorial(15) > 1307674368000L > >>> I tried this also, but this doesn't work for me. I get an overflow error for all integers > 12. >>> for i in range(0,20): ... print i 1 1 2 6 24 120 720 5040 40320 362880 3628800 39916800 479001600 Traceback (most recent call last): File "factorial.py", line 10, in ? print factorial(i) File "factorial.py", line 7, in factorial return z*factorial(z-1) OverflowError: integer multiplication > in the function specifies a need to use long ints -- I've used exactly > the same function posted here. Python has automagically handled the I also copied Dannys version to to avoid typos. -- Jens Kubieziel mailto:jens@kubieziel.de do { : } while (!HELL_FROZEN_OVER); From =?Windows-1251?B?YW50b25tdWhpbiDt4CByYW1ibGVyLnJ1?= Thu Jan 16 05:14:04 2003 From: =?Windows-1251?B?YW50b25tdWhpbiDt4CByYW1ibGVyLnJ1?= (=?Windows-1251?B?YW50b25tdWhpbiDt4CByYW1ibGVyLnJ1?=) Date: Thu Jan 16 05:14:04 2003 Subject: [Tutor] Comparative code questions: Python vs. Rebol In-Reply-To: <3E25FDB1.5070907@ccvcorp.com> References: <20030114230533.GK5446@johnsons-web.com> <3E25B590.7030202@ccvcorp.com> <20030115204718.GX5446@johnsons-web.com> <3E25FDB1.5070907@ccvcorp.com> Message-ID: <751493076.20030116131330@rambler.ru> Hello, Tim! There is another approach that seems not to be mentioned yet. It might be a little bit closer to Rebol (actually, it's rather Lisp-ish): PythonWin 2.2.1 (#34, Apr 15 2002, 09:51:39) [MSC 32 bit (Intel)] on win32. Portions Copyright 1994-2001 Mark Hammond (mhammond@skippinet.com.au) - see 'Help/About PythonWin' for further copyright information. >>> def H(level): ... return lambda x: "" % level + x + "" % level ... >>> h1 = H(1) >>> h1("string") '

string

' >>> h2 = H(2) >>> h2("another string") '

another string

' HTH, Anton. From magnus@thinkware.se Thu Jan 16 08:15:06 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Thu Jan 16 08:15:06 2003 Subject: [Tutor] (no subject) In-Reply-To: <20030116094147.66762.qmail@mail.com> Message-ID: <5.1.0.14.0.20030116141238.02acbcc0@www.thinkware.se> At 04:41 2003-01-16 -0500, leong lau wrote: >how to unsubscribe? Go here http://mail.python.org/mailman/options/tutor/lhleong--at--mail.com -- 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@thinkware.se Thu Jan 16 08:19:06 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Thu Jan 16 08:19:06 2003 Subject: Assign long integer (was: [Tutor] Calculating a math formula and finding errors) In-Reply-To: <20030116094946.GR21817@kubieziel.de> References: <3E25FEDC.1060207@ccvcorp.com> <20030113103825.GC2584@kubieziel.de> <20030115214637.GI21817@kubieziel.de> <3E25FEDC.1060207@ccvcorp.com> Message-ID: <5.1.0.14.0.20030116141430.02ae8e90@www.thinkware.se> At 10:49 2003-01-16 +0100, Jens Kubieziel wrote: > > Actually, because Python will automatically convert to long integers if > > there's integer overflow, you don't need to do anything. > >I tried this also, but this doesn't work for me. I get an overflow error >for all integers > 12. Automatic conversion int -> long is a new feature. 2.2 or 2.1. -- 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@thinkware.se Thu Jan 16 08:25:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Thu Jan 16 08:25:01 2003 Subject: [Tutor] Comparative code questions: Python vs. Rebol In-Reply-To: <751493076.20030116131330@rambler.ru> References: <3E25FDB1.5070907@ccvcorp.com> <20030114230533.GK5446@johnsons-web.com> <3E25B590.7030202@ccvcorp.com> <20030115204718.GX5446@johnsons-web.com> <3E25FDB1.5070907@ccvcorp.com> Message-ID: <5.1.0.14.0.20030116141632.02c95310@www.thinkware.se> At 13:13 2003-01-16 +0300, antonmuhin =ED=E0 rambler.ru wrote: >There is another approach that seems not to be mentioned yet. It might >be a little bit closer to Rebol (actually, it's rather Lisp-ish): > > >>> def H(level): >... return lambda x: "" % level + x + "" % level >... > >>> h1 =3D H(1) > >>> h1("string") >'

string

' > >>> h2 =3D H(2) > >>> h2("another string") >'

another string

' Or if you don't like Lisp, use a class... I'll make it slightly more generic. >>> class Tag: ... def __init__(self, tag): ... self.tag =3D tag ... def __call__(self, text): ... return "<%s>%s" % (self.tag, text, self.tag) ... >>> H1 =3D Tag('h1') >>> HTML =3D Tag('html') >>> print HTML(H1('Hello')+'\nHow are you.\n'+H1('Goodbye')+'\nSee you=20 later.\n')

Hello

How are you.

Goodbye

See you later. --=20 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 =?ISO-8859-1?B?YW50b25tdWhpbiDt4CByYW1ibGVyLnJ1?= Thu Jan 16 08:47:01 2003 From: =?ISO-8859-1?B?YW50b25tdWhpbiDt4CByYW1ibGVyLnJ1?= (=?ISO-8859-1?B?YW50b25tdWhpbiDt4CByYW1ibGVyLnJ1?=) Date: Thu Jan 16 08:47:01 2003 Subject: Re[2]: [Tutor] Comparative code questions: Python vs. Rebol In-Reply-To: <5.1.0.14.0.20030116141632.02c95310@www.thinkware.se> References: <3E25FDB1.5070907@ccvcorp.com> <20030114230533.GK5446@johnsons-web.com> <3E25B590.7030202@ccvcorp.com> <20030115204718.GX5446@johnsons-web.com> <3E25FDB1.5070907@ccvcorp.com> <5.1.0.14.0.20030116141632.02c95310@www.thinkware.se> Message-ID: <214256629.20030116164614@rambler.ru> Hello Magnus, ML> Or if you don't like Lisp, use a class... ML> I'll make it slightly more generic. ML> >>> class Tag: ML> ... def __init__(self, tag): ML> ... self.tag = tag ML> ... def __call__(self, text): ML> ... return "<%s>%s" % (self.tag, text, self.tag) ML> ... ML> >>> H1 = Tag('h1') ML> >>> HTML = Tag('html') ML> >>> print HTML(H1('Hello')+'\nHow are you.\n'+H1('Goodbye')+'\nSee you ML> later.\n') ML>

Hello

ML> How are you. ML>

Goodbye

ML> See you later. ML> As usual Magnus suggested nice solution :) I only think that Magnus's solution is better situated for more complex problems. After I sent the previous letter, more Pythonic solution came in my mind (the only problem that it seems to demand something like Python2.2) def H(level): def f(s): return "" % level + s + "" % level return f -- Best regards, anton mailto:antonmuhin@rambler.ru From =?Windows-1251?B?YW50b25tdWhpbiDt4CByYW1ibGVyLnJ1?= Thu Jan 16 08:50:01 2003 From: =?Windows-1251?B?YW50b25tdWhpbiDt4CByYW1ibGVyLnJ1?= (=?Windows-1251?B?YW50b25tdWhpbiDt4CByYW1ibGVyLnJ1?=) Date: Thu Jan 16 08:50:01 2003 Subject: [Tutor] Search and replace Message-ID: <5514433564.20030116164910@rambler.ru> Hello Justin, Thursday, January 16, 2003, 12:29:31 PM, you wrote: >>From reading the other's answer to this question, JE> I guess regular expressions is not needed for this particular task. JE> However, I decided to try using regular expressions anyway. JE> Just as a learning exercise. JE> I am still new at Python and I have not used the re module before. JE> This is what I came up with. JE> Comments are welcome. JE> import re JE> str = "123 ;345 ; 456; 55 ; ; ;123 abc" JE> patt = "[^;]+" JE> def trim(matchobj): JE> return matchobj.group(0).strip() JE> print re.sub(patt, trim, str) And another solution: s = "123 ;345 ; 456; 55 ; ; ;123 abc" patt = "[^;]+" [s.strip() for s in re.findall(patt, s)] Just a note: Be careful with names like 'str'---it's a built-in function too! It'd better to use 's'. -- Best regards, anton mailto:antonmuhin@rambler.ru From shalehperry@attbi.com Thu Jan 16 10:32:38 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Thu Jan 16 10:32:38 2003 Subject: [Tutor] Search and replace In-Reply-To: <01C2BD84.D4F8C0C0@pc7486> References: <01C2BD84.D4F8C0C0@pc7486> Message-ID: <200301160730.04302.shalehperry@attbi.com> On Thursday 16 January 2003 01:29, Justin Ezequiel wrote: > From reading the other's answer to this question, > I guess regular expressions is not needed for this particular task. > However, I decided to try using regular expressions anyway. > Just as a learning exercise. > I am still new at Python and I have not used the re module before. > This is what I came up with. > Comments are welcome. > > import re > > str =3D "123 ;345 ; 456; 55 ; ; ;123 abc" > patt =3D "[^;]+" > > def trim(matchobj): > return matchobj.group(0).strip() > > print re.sub(patt, trim, str) > I would be more likely to write: patt =3D r'\s*;\s*' re.sub(patt, ';', s) # using the call it s not str as suggested earlier. Now you can easily split the string. When I defined this problem in my head I thought: "I have extra spaces ar= ound=20 the semicolons in a file, how do I remove them?". I tend to look at my=20 problems in this manner, especially when dealing with regexs. As to why people avoided regex it is simply because so many people immedi= ately=20 try to use one to solve a problem. The string methods are usually a good= =20 deal faster and in general more pythonic. From magnus@thinkware.se Thu Jan 16 10:53:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Thu Jan 16 10:53:01 2003 Subject: Re[2]: [Tutor] Comparative code questions: Python vs. Rebol In-Reply-To: <214256629.20030116164614@rambler.ru> References: <5.1.0.14.0.20030116141632.02c95310@www.thinkware.se> <3E25FDB1.5070907@ccvcorp.com> <20030114230533.GK5446@johnsons-web.com> <3E25B590.7030202@ccvcorp.com> <20030115204718.GX5446@johnsons-web.com> <3E25FDB1.5070907@ccvcorp.com> <5.1.0.14.0.20030116141632.02c95310@www.thinkware.se> Message-ID: <5.1.0.14.0.20030116160119.02a9b968@www.thinkware.se> At 16:46 2003-01-16 +0300, antonmuhin =ED=E0 rambler.ru wrote: >As usual Magnus suggested nice solution :) I only think that Magnus's >solution is better situated for more complex problems. Yes of course, it's one line longer than yours... ;) It's largely a matter of personal preference of course, but you might see that it *will* grow more complex soon if you do something like this. After a while you will need to set attributes in your tags, and do things like: H1('The Beginning', CLASS =3D 'important', onclick =3D "javascript:openWin('beginning.html')") You'll probably want to be able to set and change default attributes as well, as in: H1 =3D Tags('H1', CLASS=3D'important') page =3D [] page.append(H1('Chapter 1')) page.append(H1('Chapter 2')) H1.CLASS =3D 'no big deal' page.append(H1('Appendix')) print '\n'.join(page)

Chapter 1

Chapter 2

Appendix

Which path is easier to get here? Nested functions or classes? It's always tricky to determine what features to use, at least when other people who are not so familiar with python will be involved in the code. I don't have any qualms about using classes though, and certainly not about using __init__... I think it's good to expose __call__ to people as well. It's not very difficult to understand, is it? The sooner they get used to using classes, the better! I might well completely leave out lambdas, map, filter and reduce though. I have come to like them, but they are really redundant sugar. They introduce new concepts that needs to be learned without providing any really new features. Classes, on the other hand, really add something to Python. >>> class Tag: ... def __init__(self, tag, **kwargs): ... self._tag =3D tag ... for attr, val in kwargs.items(): ... setattr(self, attr, val) ... def __call__(self, text): ... return "<%s %s>%s" % (self._tag, ... self.attributes(), text, self._tag) ... def attributes(self): ... return " ".join(['%s=3D"%s"' % pair ... for pair in self.__dict__.items() ... if pair[0][0]!=3D'_']) ... >>> H1 =3D Tag('H1', CLASS =3D "important") >>> H1('A Beginning is a very delicate time...') '

A Beginning is a very delicate time...

' >>> del H1.CLASS >>> H1('Know then, that I am princess Irulan, daughter of the Padishah=20 emperor Shaddam IV') '

Know then, that I am princess Irulan, daughter of the Padishah=20 emperor Shaddam IV

' Implementing attributes in __call__ as well is left as an exercise to the reader. Soon, this class will grow fairly big, and you'll wonder why you didn't pick Andy Dustman's HyperText from the beginning... ;) Then you wouldn't have to maintain all that code... --=20 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 gp@pooryorick.com Thu Jan 16 11:19:01 2003 From: gp@pooryorick.com (Poor Yorick) Date: Thu Jan 16 11:19:01 2003 Subject: [Tutor] convert '\\t' to '\t' References: Message-ID: <3E26DBA2.5060409@pooryorick.com> Hy Python wrote: > I understand this. > But what I really want to do is > convert things like "\\n","\\r","\\s", "\\x" to "\n", "\r", "\s", "\x" > So, is there a universal way to convert "\\" to "\" Your question is still confusing because "\\n" already IS "\n" when you print it. Do mean that you have a text which displays "\\n" and you want that text to display "\n"? In that case something like this would work: >>> text = "he\\\\nllo" >>> print text he\\nllo >>> text2 = text.replace('\\\\n', '\\n') >>> print text2 he\nllo >>> Poor Yorick gp@pooryorick.com From shalehperry@attbi.com Thu Jan 16 11:35:02 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Thu Jan 16 11:35:02 2003 Subject: [Tutor] convert '\\t' to '\t' In-Reply-To: References: Message-ID: <200301160832.49414.shalehperry@attbi.com> On Wednesday 15 January 2003 23:42, Hy Python wrote: > I understand this. > But what I really want to do is > convert things like "\\n","\\r","\\s", "\\x" to "\n", "\r", "\s", "\x" > So, is there a universal way to convert "\\" to "\" > are you saying you want to go from printing 'backslash n' to printing a=20 newline (and the equivalent for the other items)? Or are you saying to w= ant=20 to go from 'backslash backslash n' to 'backslash n' and not get a newline= (or=20 equivalent). If the list understands exactly what you we can help you get there. Perh= aps=20 an example of actual usage would be helpful to all rather than being bogg= ed=20 down in "how many slashes do you want". From amd@atlas.ucpel.tche.br Thu Jan 16 11:56:01 2003 From: amd@atlas.ucpel.tche.br (Aurelio Magalhaes Dias) Date: Thu Jan 16 11:56:01 2003 Subject: [Tutor] convert '\\t' to '\t' In-Reply-To: <200301160832.49414.shalehperry@attbi.com> References: <200301160832.49414.shalehperry@attbi.com> Message-ID: I think what he wants is like: >>> text =3D "something\\nto print" >>> text =3D text.replace('\\n','\n') >>> print text something to print ----------------------------------------- Aur=E9lio Magalh=E3es Dias Ci=EAncia da Computa=E7=E3o UCPel - RS - Brasil ----------------------------------------- > are you saying you want to go from printing 'backslash n' to printing a > newline (and the equivalent for the other items)? Or are you saying to w= ant > to go from 'backslash backslash n' to 'backslash n' and not get a newline= (or > equivalent). > > If the list understands exactly what you we can help you get there. Perh= aps > an example of actual usage would be helpful to all rather than being bogg= ed > down in "how many slashes do you want". > From jeff@ccvcorp.com Thu Jan 16 12:58:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu Jan 16 12:58:02 2003 Subject: [Tutor] Comparative code questions: Python vs. Rebol References: <3E25FDB1.5070907@ccvcorp.com> <20030114230533.GK5446@johnsons-web.com> <3E25B590.7030202@ccvcorp.com> <20030115204718.GX5446@johnsons-web.com> <3E25FDB1.5070907@ccvcorp.com> <5.1.0.14.0.20030116141632.02c95310@www.thinkware.se> <214256629.20030116164614@rambler.ru> Message-ID: <3E26F204.8000407@ccvcorp.com> antonmuhin m` rambler.ru wrote: >After I sent the previous letter, more Pythonic solution came in my >mind (the only problem that it seems to demand something like >Python2.2) > >def H(level): > def f(s): > return "" % level + s + "" % level > return f > This bit of code uses nested scopes -- the internal function f() uses a variable (level) from an outside, but not global, scope. Python used to be unable to do this, and some contortions were needed to pass the outer variable into the inner scope. Nested scopes were introduced to avoid those contortions. In Python 2.1, nested scopes are available as a __future__ import (the first line of code in the module should be 'from __future__ import nested_scopes'), but it wasn't until Python 2.2 that nested scopes became the default behavior. Jeff Shannon Technician/Programmer Credit International From tim@johnsons-web.com Thu Jan 16 12:58:36 2003 From: tim@johnsons-web.com (Tim Johnson) Date: Thu Jan 16 12:58:36 2003 Subject: Re[2]: [Tutor] Comparative code questions: Python vs. Rebol In-Reply-To: <214256629.20030116164614@rambler.ru> References: <3E25FDB1.5070907@ccvcorp.com> <20030114230533.GK5446@johnsons-web.com> <3E25B590.7030202@ccvcorp.com> <20030115204718.GX5446@johnsons-web.com> <3E25FDB1.5070907@ccvcorp.com> <5.1.0.14.0.20030116141632.02c95310@www.thinkware.se> <214256629.20030116164614@rambler.ru> Message-ID: <20030116180154.GB15463@johnsons-web.com> Hello Magnus and antormuhin: I want to thank you and everyone else on the list for contributing to this thread. My original intent was to gather some code examples that illustrated "self-composing" code approaches in several languages. I will probably use both the 'exec' approach and Danny's 'dictionary' approach if only to stay in the context of the article that I'm=20 writing. For those of you who have problems with that, I assure you that disclaimers will be posted! :-) Please no flaming or scolding! Just for your own edification, I have written an article on an 'html generation approach in rebol. This can be read (among other places) at=20 http://www.johnsons-web.com/col/code-corner.txt.html I do a lot of cgi programming, have done some in python, lots in c/c++, but now mostly in rebol. I'm adding some python modules to one of my projects, will be using the Mysql package and HTMLgen (tentatively). - among others - This is a great mailing list. You'll see me here again, I'm sure as a bewildered newbie! Thanks to all -tim- * antonmuhin =ED=E0 rambler.ru [030116 05:02]: > Hello Magnus, >=20 > ML> Or if you don't like Lisp, use a class... > ML> I'll make it slightly more generic. >=20 > ML> >>> class Tag: > ML> ... def __init__(self, tag): > ML> ... self.tag =3D tag > ML> ... def __call__(self, text): > ML> ... return "<%s>%s" % (self.tag, text, self.tag) > ML> ... > ML> >>> H1 =3D Tag('h1') > ML> >>> HTML =3D Tag('html') > ML> >>> print HTML(H1('Hello')+'\nHow are you.\n'+H1('Goodbye')+'\nSee= you=20 > ML> later.\n') > ML>

Hello

> ML> How are you. > ML>

Goodbye

> ML> See you later. > ML> >=20 > As usual Magnus suggested nice solution :) I only think that Magnus's > solution is better situated for more complex problems. >=20 > After I sent the previous letter, more Pythonic solution came in my > mind (the only problem that it seems to demand something like > Python2.2) >=20 > def H(level): > def f(s): > return "" % level + s + "" % level > return f >=20 >=20 > --=20 > Best regards, > anton mailto:antonmuhin@rambler.ru >=20 >=20 > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor --=20 Tim Johnson http://www.alaska-internet-solutions.com http://www.johnsons-web.com From jeff@ccvcorp.com Thu Jan 16 13:00:10 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu Jan 16 13:00:10 2003 Subject: [Tutor] problem with reload() References: <5.1.0.14.0.20030115223724.01ab3208@smtp.sbcglobal.net> Message-ID: <3E26EFEB.4020301@ccvcorp.com> Tony Cappellini wrote: > After importing a module initially, > when I try to reload a module in Ipython, PythonWin, or Idle > I always get the following error message- like reload() doesn't work > > reload(ch2_10) > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'ch2_10' is not defined How did you import the module to begin with? The fact that you're getting a NameError suggests that your reload() is not matching your earlier import -- reload() needs the name that the module object is bound to. (Once imported, a module name is just a variable that's bound to a module object, just as a class name is bound to a class object.) Did you use something like 'import ch2_10 as ch2' ? In that case, you'd need to 'reload(ch2)' instead of 'reload(ch2_10)'. Did you import the module within a function or class? In that case, the reference to the module doesn't exist outside of that scope, and you'd need to import it within your current scope before you can reload it. Jeff Shannon Technician/Programmer Credit International From gp@pooryorick.com Thu Jan 16 13:44:02 2003 From: gp@pooryorick.com (Poor Yorick) Date: Thu Jan 16 13:44:02 2003 Subject: [Tutor] convert '\\t' to '\t' References: <200301160832.49414.shalehperry@attbi.com> Message-ID: <3E26FDC6.2010806@pooryorick.com> Aurelio Magalhaes Dias wrote: >I think what he wants is like: > >>>>text = "something\\nto print" >>>>text = text.replace('\\n','\n') >>>>print text >>>> >something >to print > In which case, the proper code would be: >>> text = "something\\nto print" >>> text = text.replace('\\n', '\n') >>> text 'something\nto print' >>> print text something to print >>> Poor Yorick gp@pooryorick.com From tony@tcapp.com Thu Jan 16 13:48:09 2003 From: tony@tcapp.com (Tony Cappellini) Date: Thu Jan 16 13:48:09 2003 Subject: [Tutor] problem with reload() In-Reply-To: <3E26EFEB.4020301@ccvcorp.com> Message-ID: <20030116104352.H4510-100000@yamato.yamato.com> >> How did you import the module to begin with? import ch2_10 >> the module within a function or class? no , I did this from the command line Thanks Tony From jeff@ccvcorp.com Thu Jan 16 13:58:36 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu Jan 16 13:58:36 2003 Subject: [Tutor] Threads, locking and race condition References: <33678E78A2DD4D418396703A750048D41A63B9@RIKER> Message-ID: <3E270054.7020905@ccvcorp.com> Branimir Petrovic wrote: >- Say Thread-3 needs to access its storage and calls the function: > > def get_thread_storage(): > thread_id = thread.get_ident() > tss = _tss.get(thread_id) > >At this very point having reached its 10-th byte code instruction, >Thread-3 is suspended, so that other threads will get their chance >to run. > >- By pure chance/coincidence Thread-6 is awaken, and being just >about to call get_thread_storage() - this time it calls it indeed, >and not only that it calls the function, but also it manages to exit >from it by the time Thread-6 'fades' and goes to forced 'sleep', > >- By another remarkable turn of events, Thread-3 is awaken again, >only to find variable tss that is now pointing to a value set by run of >interrupting Tread-6. Thread-3 will not have slightest 'clue' that its >own value was overwritten 'behind its back' while its execution was >suspended. As a result Thread-3 will now return wrong dictionary? > No, it won't. Each thread will have a different thread id, so the results of _tss.get(thread_id) will be different for each thread. But the tss variable that it's being stored in is a local variable -- it's only valid within that specific function. When Thread 6 runs through get_thread_storage(), it does so in a separate execution frame that is completely separate from Thread 3's execution frame, and therefore it cannot touch the local variables in Thread 3's execution frame. Note, however, that the thread module is very low-level. For writing actual application code, you're *much* better off using the higher-level threading module, which is built on top of the thread module. In particular, threading offers the Thread class, which makes many things much simpler. By using the Thread class and the Queue module, it's possible to create multithreaded applications without needing to worry nearly as much about contention and deadlock issues. I do realize that you're looking at the Cookbook code for educational purposes, and that's fine -- it's good to try to understand the lower-level aspects -- but it's also good to know that, at some point, you can trust that someone else has taken care of the details and you don't need to worry about it. :) Jeff Shannon Technician/Programmer Credit International > >Do I see the problem that does not exist? If you spot anything wrong >with my (contrived?) assumption/scenario - please let me know. > > > >Let's examine other option: > >- Say we change function in such a way as to obtain lock with very >first step into the function: > > def get_thread_storage(): > tss_lock.acquire() > thread_id = thread.get_ident() > ># ...and so on ending with: > > finally: > _tss_lock.release() > > return tss > >Is it possible that Thread-3 does its job and release the lock object, >but just before returning tss - scheduler suspends it and run Thread-6 >that calls the function, and manages to finish it and exit the >function? Wouldn't Thread-3 if awaken now return the tss as left by >Thread-6? > >The way I see two proposed scenarios - both are possible, second one >less but nevertheless - still possible. Given long enough time - >'mishap' will happen for sure. Right or wrong? > >Which brings me to next nagging question: >- How 'granular' are Python's byte code instructions? >Is this: > thread_id = thread.get_ident() >one byte code instruction or more than one byte code instruction? > >To slightly re-phrase the question: >- Is the 'line' of code (such as thread_id = thread.get_ident()) >guaranteed to execute and fully finish before Python switches to >another thread or not? > >- If 'yes' is answer to the above question, what would happen in >this (admittedly - artificial) case: > > return choice and [yes][0] or [no][0] > >How many byte codes would that be? > >- And what about: > return mySillyChoice() and toughChoiceA() or toughChoiceB() > >This will 'break' (be switched) at any convenient spot in any of three >function calls yes/no? > >I would very much like to hear back (hopefully) on any of outlined >questions. > >If you as far as this line, thanks for your patience. > >Branimir > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > From gp@pooryorick.com Thu Jan 16 14:04:04 2003 From: gp@pooryorick.com (Poor Yorick) Date: Thu Jan 16 14:04:04 2003 Subject: [Tutor] convert '\\t' to '\t' References: <200301160832.49414.shalehperry@attbi.com> <3E26FDC6.2010806@pooryorick.com> Message-ID: <3E270248.6030504@pooryorick.com> Poor Yorick wrote: > > > Aurelio Magalhaes Dias wrote: > >> I think what he wants is like: >> >>>>> text = "something\\nto print" >>>>> text = text.replace('\\n','\n') >>>>> print text >>>>> >> something >> to print >> > In which case, the proper code would be: Oops! Sorry for coming from the department of redundancy department on that last email! Poor Yorick gp@pooryorick.com From BranimirP@cpas.com Thu Jan 16 14:51:54 2003 From: BranimirP@cpas.com (Branimir Petrovic) Date: Thu Jan 16 14:51:54 2003 Subject: [Tutor] Threads, locking and race condition Message-ID: <33678E78A2DD4D418396703A750048D41A63BF@RIKER> > -----Original Message----- > From: Jeff Shannon [mailto:jeff@ccvcorp.com] > Sent: January 16, 2003 1:56 PM > To: Branimir Petrovic; 'tutor@python.org' > Subject: Re: [Tutor] Threads, locking and race condition > > > > > >own value was overwritten 'behind its back' while its execution was > >suspended. As a result Thread-3 will now return wrong dictionary? > > > > No, it won't. Each thread will have a different thread id, so the > results of _tss.get(thread_id) will be different for each > thread. But > the tss variable that it's being stored in is a local > variable -- it's > only valid within that specific function. When Thread 6 runs through > get_thread_storage(), it does so in a separate execution > frame that is > completely separate from Thread 3's execution frame, and therefore it > cannot touch the local variables in Thread 3's execution frame. Now this is the exact piece of info I was missing! I did not know (although had a feeling things weren't as bad as they looked to me) that each thread 'peels off' its own execution frame where local variables can happily and safely live their separate lives. It is quite a relief to get to know this! You were right - I was looking at this issue strictly from learning perspective. Now that I understand little better what goes on in lower levels.... (I am much more content and confident). I will be using higher level Threading module as I do not feel the urge of taking responsibility about concurrency and synchronization. Jerff, thanks a lot! Branimir From python@jaydorsey.com Thu Jan 16 15:39:02 2003 From: python@jaydorsey.com (Jay Dorsey) Date: Thu Jan 16 15:39:02 2003 Subject: [Tutor] IDLE on Windows Message-ID: <3E271822.7040900@jaydorsey.com> --------------000104060905030803090800 Content-Type: text/plain; charset=us-ascii; format=flowed Content-Transfer-Encoding: 7bit IDLE was working fine on my Windows XP machine up until two days ago. I used to be able to right click on a .py file, and choose Edit in IDLE, and IDLE would pop up just fine. Now, I can open up the process manager and see pythonw.exe open up, then close; I never see even a hint of an IDLE box. The last thing I remember doing was trying out some of the debugging features. Running IDLE from the command line executes the program partially (the program writes a file, but also has a prompt where you type in text for the file - the file gets written, but without the prompted text). I tried a reboot, uninstalling and reinstalling (2.2, with reboots in between). I even uninstalled 2.2 and tried the 2.3a release. Is it possible that while debugging, I flipped some switch that makes IDLE not work anymore? If so, can anyone tell me what I need to do to get IDLE running again? Also, before I did the first uninstall, I had another option when I right-clicked on a .py file - just plain old "Edit". I tried it once, and it popped up something similar to IDLE (can't recall the name of it). I've since uninstalled that program as well (tried to wipe python clean, and start over), but I thought it was part of the standard Python install (it's not); I can't recall the name of it, nor where I got it at. Any ideas? (sorry I don't have more details - I've really only just started w/ Python). Thanks for your time, Jay -- Jay Dorsey python@jaydorsey.com |"I didn't say it was your fault, I said I was blaming you"| --------------000104060905030803090800 Content-Type: text/html; charset=us-ascii Content-Transfer-Encoding: 7bit IDLE was working fine on my Windows XP machine up until two days ago.  I used to be able to right click on a .py file, and choose Edit in IDLE, and IDLE would pop up just fine.  Now, I can open up the process manager and see pythonw.exe open up, then close; I never see even a hint of an IDLE box.  The last thing I remember doing was trying out some of the debugging features.  Running IDLE from the command line executes the program partially (the program writes a file, but also has a prompt where you type in text for the file - the file gets written, but without the prompted text).

I tried a reboot, uninstalling and reinstalling (2.2, with reboots in between).  I even uninstalled 2.2 and tried the 2.3a release.

Is it possible that while debugging, I flipped some switch that makes IDLE not work anymore?  If so, can anyone tell me what I need to do to get IDLE running again?

Also, before I did the first uninstall, I had another option when I right-clicked on a .py file - just plain old "Edit".  I tried it once, and it popped up something similar to IDLE (can't recall the name of it).  I've since uninstalled that program as well (tried to wipe python clean, and start over), but I thought it was part of the standard Python install (it's not); I can't recall the name of it, nor where I got it at.  Any ideas? (sorry I don't have more details - I've really only just started w/ Python).

Thanks for your time,

Jay
--
Jay Dorsey
python@jaydorsey.com

"I didn't say it was your fault, I said I was blaming you"
--------------000104060905030803090800-- From gerrit@nl.linux.org Thu Jan 16 15:57:00 2003 From: gerrit@nl.linux.org (Gerrit Holl) Date: Thu Jan 16 15:57:00 2003 Subject: [Tutor] Leap years In-Reply-To: <1042574946.1789.991.camel@localhost.localdomain> References: <1042391564.1789.715.camel@localhost.localdomain> <074c01c2ba67$99158f40$ea10ba3f@defaultcomp> <20030112215436.GA4866@nl.linux.org> <1042574946.1789.991.camel@localhost.localdomain> Message-ID: <20030116205818.GA2762@nl.linux.org> ahimsa schreef op dinsdag 14 januari om 22:52:34 +0000: > > I think it's better to use True and False here. > > Instead of "return 1", "return True". > > Instead of "return 0", "return False". > > > > It's boolean what's being expected from this function; not an integer. > > It's not natural to return an integer, as it's not natural to return > > a empty or non-empty sequence. > > > > What kind of difference does the return actually make? I know that > 'true' /'false' is more user friendly for the person awaiting output > perhaps, but does it make any difference with respect to the programming > itself? It is more readable, and as of version 2.3, True and False are builtins of the type bool. It does not make any difference for the programming, which does not mean that it's not important! Remember, Beatiful is better than Ugly, Explicit is better than Implicit, and Readability Counts. Those Words come from Him, so they can only be the Truth ","",";)", ":)"])> yours, Gerrit. -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From magnus@thinkware.se Thu Jan 16 16:20:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Thu Jan 16 16:20:02 2003 Subject: [Tutor] Leap years In-Reply-To: <20030116205818.GA2762@nl.linux.org> References: <1042574946.1789.991.camel@localhost.localdomain> <1042391564.1789.715.camel@localhost.localdomain> <074c01c2ba67$99158f40$ea10ba3f@defaultcomp> <20030112215436.GA4866@nl.linux.org> <1042574946.1789.991.camel@localhost.localdomain> Message-ID: <5.1.0.14.0.20030116221802.02ab05a8@www.thinkware.se> At 21:58 2003-01-16 +0100, Gerrit Holl wrote: >Those Words come from Him You capitalize timbot? I thought GvR was the only object of such reverence in the church of Python. -- 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 op73418@mail.telepac.pt Thu Jan 16 16:36:02 2003 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Thu Jan 16 16:36:02 2003 Subject: [Tutor] Leap years References: <1042574946.1789.991.camel@localhost.localdomain> <1042391564.1789.715.camel@localhost.localdomain> <074c01c2ba67$99158f40$ea10ba3f@defaultcomp> <20030112215436.GA4866@nl.linux.org> <1042574946.1789.991.camel@localhost.localdomain> <5.1.0.14.0.20030116221802.02ab05a8@www.thinkware.se> Message-ID: <001601c2bda8$20055150$bf1b0dd5@violante> ----- Original Message ----- From: "Magnus Lycka" To: "Gerrit Holl" ; "ahimsa" Cc: Sent: Thursday, January 16, 2003 9:19 PM Subject: Re: [Tutor] Leap years > At 21:58 2003-01-16 +0100, Gerrit Holl wrote: > >Those Words come from Him > > You capitalize timbot? I thought GvR was the only > object of such reverence in the church of Python. > Ah, but those who knoweth the Son knoweth the Father, for the Father knoweth the Son perfectly and no one knoweth the Father perfectly but the Son, for all things the Father hath delivered to the Son. > > -- > Magnus Lycka, Thinkware AB With my best regards, G. Rodrigues From dyoo@hkn.eecs.berkeley.edu Thu Jan 16 16:42:04 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Jan 16 16:42:04 2003 Subject: Re[2]: [Tutor] Comparative code questions: Python vs. Rebol In-Reply-To: <20030116180154.GB15463@johnsons-web.com> Message-ID: On Thu, 16 Jan 2003, Tim Johnson wrote: > I do a lot of cgi programming, have done some in python, lots in c/c++, > but now mostly in rebol. Hi Tim, Very cool; tell us more about your Rebol article when it's done. Will it be online anywhere? It should be educational to see how Rebol handles programming problems and how its approaches compare to Python's. > This is a great mailing list. You'll see me here again, I'm sure as a > bewildered newbie! We hope to reduce that bewilderment. *grin* Good luck to you! From magnus@thinkware.se Thu Jan 16 17:29:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Thu Jan 16 17:29:01 2003 Subject: Re[2]: [Tutor] Comparative code questions: Python vs. Rebol In-Reply-To: <20030116180154.GB15463@johnsons-web.com> References: <214256629.20030116164614@rambler.ru> <3E25FDB1.5070907@ccvcorp.com> <20030114230533.GK5446@johnsons-web.com> <3E25B590.7030202@ccvcorp.com> <20030115204718.GX5446@johnsons-web.com> <3E25FDB1.5070907@ccvcorp.com> <5.1.0.14.0.20030116141632.02c95310@www.thinkware.se> <214256629.20030116164614@rambler.ru> Message-ID: <5.1.0.14.0.20030116230630.02aa0de8@www.thinkware.se> At 09:01 2003-01-16 -0900, Tim Johnson wrote: >My original intent was to >gather some code examples that illustrated "self-composing" >code approaches in several languages. What about the OO approach with __call__. I know, it's not the same, you don't magically introduce new names in any namespace, but in my opinion this is a big advantage, and it's more or less as convenient. I suggest you offer it as a more OO alternative. There are certainly more and less Pythonic ways of doing things, but Python is able to do things in several different fundamental paradigms: Structured, OO or more functional styles all work. In this case, that means nested functions, classes with callable instances and lambdas respectively. One of each might give a good picture of Pythons wide scope, unless you feel it's all too much. For a version closer to the original assignment, you could do: >>> class H: ... def __init__(self, level): ... self.level = level ... def __call__(self, text): ... return "%s\n" % (self.level, text, self.level) ... >>> H1, H2, H3, H4, H5, H6 = [H(x) for x in range(1,7)] >>> for heading in H1, H2, H3, H4, H5, H6: ... print heading('Hello') ...

Hello

Hello

Hello

Hello

Hello
Hello
Of course, you *can* combine this with Danny's approach if you want to confuse all code documentation and inspection tools along with a fair amount of coders and increase the chances of introducing bugs and so on (and on he rants 'til the end of time minus one minute). class H... for i in range(1, 7): globals()['H%i' % i] = H(i) The nested function verson offered by Danny has another value though. It shows how all functions can be assigned new names like any object can be assigned to a new variable. Thus it gives an example of Python's orthogonal everything-is-an-object approach. -- 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 montana@buc99.bsd.st Thu Jan 16 18:10:03 2003 From: montana@buc99.bsd.st (montana) Date: Thu Jan 16 18:10:03 2003 Subject: [Tutor] Question on Time calculations. Message-ID: <200301162311.h0GNB02B001786@buc99.bsd.st> Magnus wrote: If you look through the mxDateTime docs, that you got a link to, I'm sure you will find more robust solutions. If you know that time is entered as "%m.%d.%y %H%M", you could do >>> stime = "12.31.2002 1259" >>> date, time = stime.split() >>> month, day, year = map(int,date.split('.')) >>> hour, min = map(int,[time[:-2], time[-2:]]) >>> print DateTime.DateTime(year, month, day, hour, min, 0) 2002-12-31 12:59:00.00 This is a few more lines of code, but it's certainly more robust. It will handle a much larger span in time, and it doesn't realy on particular locale settings etc. But then how do you get the date parsed? Parser.DateTimeFromString does not like "2002-12-31 12:59:00.00" when I enter that. I used asctime to put it in a format that the parser would like. Thanks. SA :) From montana@buc99.bsd.st Thu Jan 16 18:12:01 2003 From: montana@buc99.bsd.st (montana) Date: Thu Jan 16 18:12:01 2003 Subject: [Tutor] Question on Time calculations. Message-ID: <200301162312.h0GNCWpH001794@buc99.bsd.st> Nevermind. I think I see my mistake. Thanks. SA :) From blackmariah@shmups.com Thu Jan 16 18:32:02 2003 From: blackmariah@shmups.com (Michael Miller) Date: Thu Jan 16 18:32:02 2003 Subject: [Tutor] OOP explanation article Message-ID: <200301161729.40199.blackmariah@shmups.com> I want it known right now I am very much NOT a programmer. I wrote this as a result of a conversation I had about Object Oriented Programming and a lack of good explanations of what it was. It seems that every OOP related tutorial or article I've seen assumes that the reader already knows what OOP is. I'm writing this intending it to be a quick primer on what OOP is and what it does. You can find the file (in plain text) here http://onlinerock.com/musicians/blackmariah//ooptut.txt The problem is that I, as I already stated, am not a programmer. Not a good one, anyway. I understand all the basics of programming, but I'm at the point where more advanced topics such as OOP escape me. This is based on my understanding of OOP right now. I would appreciate it quite a bit if some more knowledgeable people than myself looked it over and pointed out any errors I may have made. Thanks. Michael Miller From magnus@thinkware.se Thu Jan 16 18:54:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Thu Jan 16 18:54:02 2003 Subject: [Tutor] Question on Time calculations. In-Reply-To: <200301162311.h0GNB02B001786@buc99.bsd.st> Message-ID: <5.1.0.14.0.20030117005110.02985b90@www.thinkware.se> At 17:11 2003-01-16 -0600, montana wrote: >But then how do you get the date parsed? There is a whole row of Date, Time and DateTime constructors in mxDateTime. mx.DateTime.DateTime() takes integers for year, month and so on. The ISO and ARPA modules takes its own formats and soforth... -- 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 fredm@smartypantsco.com Thu Jan 16 19:36:02 2003 From: fredm@smartypantsco.com (Alfred Milgrom) Date: Thu Jan 16 19:36:02 2003 Subject: [Tutor] OOP explanation article In-Reply-To: <200301161729.40199.blackmariah@shmups.com> Message-ID: <5.1.0.14.0.20030117110803.00aca800@192.168.1.1> Hi Michael: I am also a recent convert to OO programmer (not completely not a programmer - I did some programming 30 years ago, but OOP didn't exist then.) When I tried to get my head around Classes I was really confused about the use of 'self', and Alan Gauld (who regularly contributes to this list) suggested that I could use other words instead of 'self', like 'this' or 'that'. The point really being that 'self' (as I understand it) describes the particular instance of the Class. So think of the line self.contents.append(element) as reading: thisParticularInstance.contents.append(element) Classes (again as I understand it) cannot be called outside of specific instances. So in your article you say you can call Basket.add(ITEM) to add an item to your basket. This is not correct, as you also need to specify which basket you want to add the item to. (You can tell this because the 'add' method input asks for two variables: self and item). Instead you may have: bicycleBasket = Basket() briefcase = Basket() defining two different Baskets, and then you can add things to each different instance of the Basket class as follows: bicycleBasket.add(helmet) briefcase.add(notepad) What happens is that when the program executes the code is substitutes bicycleBasket or briefcase for the 'self' reference. Each basket has its own list of contents. (As an aside, you can also write the last line as Basket.add(briefcase, notepad) but I don't think it reads as well). Hope this helps. Fred Milgrom (As a final comments, perhaps you could simplify some of the code for your description of classes. I think you could confuse beginning programmers with constructs such as def __init__(self,contents=None): self.contents = contents or [] The same concepts described in your article can be explained using: class Basket: def __init__(self,name): self.name = name self.contents = [] def add(self, newItem): self.contents = self.contents + [newItem] def describe (self): print self.name, "contains", self.contents Then: >>> briefcase = Basket('my briefcase') >>> briefcase.add('money') >>> briefcase.describe() my briefcase contains ['money'] The print output is perhaps not as pretty as you may like, but it's simple to follow the code. At 05:29 PM 16/01/03 -0500, Michael Miller wrote: >I want it known right now I am very much NOT a programmer. I wrote this >as a result of a conversation I had about Object Oriented Programming >and a lack of good explanations of what it was. It seems that every OOP >related tutorial or article I've seen assumes that the reader already knows >what OOP is. I'm writing this intending it to be a quick primer on what >OOP is and what it does. You can find the file (in plain text) here >http://onlinerock.com/musicians/blackmariah//ooptut.txt > >The problem is that I, as I already stated, am not a programmer. Not a good >one, anyway. I understand all the basics of programming, but I'm at the point >where more advanced topics such as OOP escape me. This is based on my >understanding of OOP right now. I would appreciate it quite a bit if some >more knowledgeable people than myself looked it over and pointed out any >errors I may have made. Thanks. > >Michael Miller > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From blackmariah@shmups.com Thu Jan 16 19:42:07 2003 From: blackmariah@shmups.com (Michael Miller) Date: Thu Jan 16 19:42:07 2003 Subject: [Tutor] OOP explanation article In-Reply-To: <5.1.0.14.0.20030117110803.00aca800@192.168.1.1> References: <5.1.0.14.0.20030117110803.00aca800@192.168.1.1> Message-ID: <200301161839.44984.blackmariah@shmups.com> > So in your article you say you can call Basket.add(ITEM) to add > an item to your basket. This is not correct, as you also need to specify > which basket you want to add the item to. I was aware of that, but decided it might be clearer if I omitted that fact. After having it pointed out, it does seem kind of silly not to have it in the article. I'll fix that later. > The same concepts described in your article can be explained using: > > class Basket: > def __init__(self,name): > self.name = name > self.contents = [] > > def add(self, newItem): > self.contents = self.contents + [newItem] > > def describe (self): > print self.name, "contains", self.contents > Thanks a lot for that. I grabbed that code from Magnus lie Hetland's Python tutorial with the intention of replacing it with something else eventually. Would you mind if I used your simplified code instead? Michael From pythonpython@hotmail.com Thu Jan 16 19:52:01 2003 From: pythonpython@hotmail.com (Hy Python) Date: Thu Jan 16 19:52:01 2003 Subject: [Tutor] convert '\\t' to '\t' Message-ID: Thanks to all who replied! Appreciated. What I want is to convert the raw string version of r'\n' into a real newline '\n'. For example: >>>myRaw=raw_input("type your string here:") type your string here: hello there!\n a newline! >>>print myRaw hello there!\n a newline! >>> The problem with myRaw=myRaw.replace('\\n','\n') is that it only deals with the '\\n' case. I am interested in something universal which can convert things like '\\s', '\\t', '\\r', etc. Thanks again for all your help. Hy >From: Poor Yorick >CC: tutor@python.org >Subject: Re: [Tutor] convert '\\t' to '\t' >Date: Thu, 16 Jan 2003 12:04:40 -0700 > > > >Poor Yorick wrote: > >> >> >>Aurelio Magalhaes Dias wrote: >> >>>I think what he wants is like: >>> >>>>>>text = "something\\nto print" >>>>>>text = text.replace('\\n','\n') >>>>>>print text >>>>>> >>>something >>>to print >>> >>In which case, the proper code would be: > >Oops! Sorry for coming from the department of redundancy department on >that last email! > >Poor Yorick >gp@pooryorick.com > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ The new MSN 8: smart spam protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From j.ezequiel@spitech.com Thu Jan 16 22:57:00 2003 From: j.ezequiel@spitech.com (Justin Ezequiel) Date: Thu Jan 16 22:57:00 2003 Subject: [Tutor] RE: Search and replace Message-ID: <01C2BE1F.3DBAA160@pc7486> >>s = "123 ;345 ; 456; 55 ; ; ;123 abc" Thanks to all for the responses! >>patt = "[^;]+" >>[s.strip() for s in re.findall(patt, s)] and >>patt = r'\s*;\s*' >>re.sub(patt, ';', s) I would love to have more time for Python. From syrinx@simplecom.net Thu Jan 16 23:18:01 2003 From: syrinx@simplecom.net (Scott) Date: Thu Jan 16 23:18:01 2003 Subject: [Tutor] simple wxpython question Message-ID: <20030116221245.22f5bec3.syrinx@simplecom.net> I know the answer must be staring me in the face, but I'm having a heck of a time figuring out how to do something really basic. When I create a custom dialog and show it with ShowModal(), when the dialog is dismissed (user clicks 'OK') how do I get the data that was entered into the dialog's controls? Thanks to anyone who can remove the blinders from my eyes. From syrinx@simplecom.net Thu Jan 16 23:28:03 2003 From: syrinx@simplecom.net (Scott) Date: Thu Jan 16 23:28:03 2003 Subject: [Tutor] simple wxpython question Message-ID: <20030116222316.5f1e151d.syrinx@simplecom.net> Never mind. The obvious answer popped into my mind as soon as I sent the question. But, relatedly, if anyone has a good real-world example of using classes derived from wxPyValidator, I would like to know about it. Thanks. From fredm@smartypantsco.com Fri Jan 17 00:55:02 2003 From: fredm@smartypantsco.com (Alfred Milgrom) Date: Fri Jan 17 00:55:02 2003 Subject: [Tutor] OOP explanation article Message-ID: <5.1.0.14.0.20030117164753.01ed9ae0@mail.milgromphoto.com> Hi Michael: > Would you mind if I used your simplified code instead? Feel free to use my example code in any way you like, modify it, etc. :) Best regards, Fred Milgrom From blackmariah@shmups.com Fri Jan 17 01:41:09 2003 From: blackmariah@shmups.com (Michael Miller) Date: Fri Jan 17 01:41:09 2003 Subject: [Tutor] OOP explanation article In-Reply-To: <5.1.0.14.0.20030117164753.01ed9ae0@mail.milgromphoto.com> References: <5.1.0.14.0.20030117164753.01ed9ae0@mail.milgromphoto.com> Message-ID: <200301170038.37897.blackmariah@shmups.com> > Feel free to use my example code in any way you like, modify it, etc. :) > > Best regards, > Fred Milgrom Thanks a lot. I'll get the rewrite done soon. Michael Miller From abli@freemail.hu Fri Jan 17 04:28:01 2003 From: abli@freemail.hu (Abel Daniel) Date: Fri Jan 17 04:28:01 2003 Subject: [Tutor] askfont in Tkinter? In-Reply-To: References: Message-ID: <20030117092740.GA1640@hooloovoo> Hy Python (pythonpython@hotmail.com) wrote: > Could anyone please tell me is something like askfont function in Tkinter, > or other GUI modules? > I didn't find one in the standard distribution. A font selection dialog is needed in most non-trivial apps, so one can hope somebody made one before. Here is what i found: http://mail.python.org/pipermail/python-announce-list/2002-July/001583.html " ----- Font dialog leoFontPanel.py puts up a Font dialog. This dialog dispenses with the typical "sample" pane and instead changes text immediately directly on the screen. Comes with Ok, Cancel and Revert buttons. IMO, this dialog is much better than the sample Tk/Tkinter font dialogs available on the web." http://pmwcontribd.sourceforge.net/ " FontChooserDialog The FontChooserDialog provides a UI for interactively changing a Tk font specification. The user sees a preview of the font they are selecting." This second one requires pmw, which is built on top ok tkinter in pure python. Pmw provides more widgets than the standard tkinter distribution but the way of using them is a bit different than tkinter. (imho better.) (see http://pmw.sourceforge.net/) abli abli@freemail.hu From =?ISO-8859-1?B?YW50b25tdWhpbiDt4CByYW1ibGVyLnJ1?= Fri Jan 17 05:13:02 2003 From: =?ISO-8859-1?B?YW50b25tdWhpbiDt4CByYW1ibGVyLnJ1?= (=?ISO-8859-1?B?YW50b25tdWhpbiDt4CByYW1ibGVyLnJ1?=) Date: Fri Jan 17 05:13:02 2003 Subject: Re[3]: [Tutor] Comparative code questions: Python vs. Rebol In-Reply-To: <5.1.0.14.0.20030116160119.02a9b968@www.thinkware.se> References: <5.1.0.14.0.20030116141632.02c95310@www.thinkware.se> <3E25FDB1.5070907@ccvcorp.com> <20030114230533.GK5446@johnsons-web.com> <3E25B590.7030202@ccvcorp.com> <20030115204718.GX5446@johnsons-web.com> <3E25FDB1.5070907@ccvcorp.com> <5.1.0.14.0.20030116141632.02c95310@www.thinkware.se> <5.1.0.14.0.20030116160119.02a9b968@www.thinkware.se> Message-ID: <8210644736.20030117131145@rambler.ru> Hello Magnus, ML> It's largely a matter of personal preference of course, ML> but you might see that it *will* grow more complex soon if ML> you do something like this. After a while you will need ML> to set attributes in your tags, and do things like: ML> Which path is easier to get here? Nested functions or classes? IMHO, it depends on circumstances. If I write quick'n'dirty script with Python as I mostly do (unfortunately, I have to use C++ and I'm getting to hate it as long I started to use Python for my personal tasks) lambdas, nested functions are really good. However, for big projects like hypothetic HTML system you described your solution is much better. ML> It's always tricky to determine what features to use, at ML> least when other people who are not so familiar with ML> python will be involved in the code. I don't have any ML> qualms about using classes though, and certainly not ML> about using __init__... I think it's good to expose __call__ ML> to people as well. It's not very difficult to understand, ML> is it? The sooner they get used to using classes, the ML> better! I might well completely leave out lambdas, map, ML> filter and reduce though. I have come to like them, but ML> they are really redundant sugar. They introduce new concepts ML> that needs to be learned without providing any really new ML> features. Classes, on the other hand, really add something ML> to Python. Regarding your paragraph above, I'd like to suggest a topic that was discussed many times, but I still think we might talk about it more :) I do really like OOP, but I think that it has its shortcomings too. One that is most important for me, bad treating of code blocks. You see, for me lambdas and nested functions are substitution for more general construction --- code blocks. It seems that Python moves a little bit towards it: list comprehensions actually partly introduce code blocks. And with comprehensions I don't use map anymore. However, code blocks in Ruby and Rebol (if I understand Tim's article correctly) seems really nice. For example, I like Ruby's way to work with files. Sure, one can wrap code blocks in classes. However, from pure theoretical point of view it might be bad solution: code is really different from data. BTW, wrapping functions in classes often leads to class names like SomeFunctionCaller (at least in my code :) or alike that are deprecated by some theorists. And, at least for me, syntactic sugar is really important: one of the reason I hate C++ is that I must wrap function calls in classes too often. And the last simple question: what about introducing a kind of comprehensions for other predicates like reduce? Something like: [x + y for x, y reducing [1, 2, 3]] that calculates 6 ([] seems bad here, sorry). What do you think about it? -- Best regards, anton mailto:antonmuhin@rambler.ru From magnus@thinkware.se Fri Jan 17 05:33:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Fri Jan 17 05:33:02 2003 Subject: [Tutor] convert '\\t' to '\t' In-Reply-To: Message-ID: <5.1.0.14.0.20030117095419.02adc788@www.thinkware.se> At 00:50 2003-01-17 +0000, Hy Python wrote: >The problem with myRaw=myRaw.replace('\\n','\n') is that it only deals >with the '\\n' case. I am interested in something universal which can >convert things like '\\s', '\\t', '\\r', etc. But it's not quite that simple. See http://www.python.org/doc/current/ref/strings.html For instance, \x42 should be replaced by B, \103 by C and \u, \U and \N are used with Unicode characters. I suggest you keep it simple, and just code translations for the sequences you know. Surely, it's at least as easy to code one transformation as it is to document it so that the user will understand it. Naturally, you could use the dreaded exec. That would surely mean that all escape sequences are handled the way python expects... >>> x = raw_input() >>> x 'tab\\tnew line\\n' >>> exec "s = '%s'" % x >>> s 'tab\tnew line\n' >>> print s tab new line But beware of security aspects... >>> x = raw_input() >>> print x he he!!';print 5*3, 'hm >>> exec "s = '%s'" % x 15 hm >>> s 'he he!!' As you see, In this case I could easily get the program to execute arbitrary code by including a ' in the string. Instead of printing '15 hm' I could have made python reformat the disk... I saw a bug like this in a Linux firewall distribution where a system administrator who was perverse enough to choose a password like for instance "hello;rm -rf /" would end up with the password "hello" and an empty file system. That was NOT a python product though... ;) It could easily have been though. This C program made the equivalent of os.system("htpasswd -b /xxx/yyyy admin %s" % newPasswdString) We can try to avoid the problem in this particular case with: >>> x = x.replace("'","''") >>> exec "s = '%s'" % x >>> print s he he!!;print 5*3, hm Now all of x will end up in s. But are you really sure that there are no other security issues with this? Let's see... >>> x = raw_input() >>> x = x.replace("'","''") >>> exec "s = '%s'" % x Gotcha! >>> print s ' Yes, I could go around that as well. It's left as an exercise to the reader to figure out what I typed in to raw_input()... >>> print x ???????????????????????????????????????????????? ;) Actually, if we do x = x.replace("'","\'") instead, it's probably safer, but maybe someone can craft a way to trick that as well? Either way, using exec, it's probably impossible to avoid SyntaxError to occur with some input. But on the other hand, since the user is to provide some kind of processing information, there is always a risk that the instructions will be incorrect. The SyntaxError can be caught with a try block. -- 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 churmtom@hotmail.com Fri Jan 17 05:49:01 2003 From: churmtom@hotmail.com (Tom Churm) Date: Fri Jan 17 05:49:01 2003 Subject: [Tutor] Working with Umlauts Message-ID: hi, i need to replace umlauts in a string. something that looks, very inelegantly, like this: lastNameOfUser = string.replace(lastNameOfUser,"ä","ae") lastNameOfUser = string.replace(lastNameOfUser,"ö","oe") lastNameOfUser = string.replace(lastNameOfUser,"ü","ue") lastNameOfUser = string.replace(lastNameOfUser,"ß","ss") lastNameOfUser = string.replace(lastNameOfUser,"Ä","Ae") lastNameOfUser = string.replace(lastNameOfUser,"Ö","Oe") lastNameOfUser = string.replace(lastNameOfUser,"Ü","Ue") but then i get the error that: UnicodeError: ASCII decoding error: ordinal not in range(128) and i get this same error when i try to use: string.replace(lastNameOfUser,chr(228),"ae") ## for 'ä' there's gotta be a quick & easy solution for this, but i'm afraid i don't know what it is... --tom _________________________________________________________________ The new MSN 8 is here: Try it free* for 2 months http://join.msn.com/?page=dept/dialup From magnus@thinkware.se Fri Jan 17 06:03:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Fri Jan 17 06:03:02 2003 Subject: [Tutor] OOP explanation article In-Reply-To: <5.1.0.14.0.20030117110803.00aca800@192.168.1.1> References: <200301161729.40199.blackmariah@shmups.com> Message-ID: <5.1.0.14.0.20030117113353.02ac6860@www.thinkware.se> At 11:34 2003-01-17 +1000, Alfred Milgrom wrote: >Hi Michael: > >I am also a recent convert to OO programmer (not completely not a >programmer - I did some programming 30 years ago, but OOP didn't exist then.) Yes it did! In Norway... Simula was developed in Oslo between 1961 and 1967. The first public appearence (Simula I) was in 1964. One of the inventors (whom I met in Bergen three years ago) died last August, http://www.ifi.uio.no/in_memoriam_kristen/ just three days after Dijkstra http://www.cs.utexas.edu/users/EWD/ >When I tried to get my head around Classes I was really confused about the >use of 'self', and Alan Gauld (who regularly contributes to this list) >suggested that I could use other words instead of 'self', like 'this' or >'that'. Although it's encouraged to use "self" in "real" programs to avoid confusing other programmers... It's called "this" in some programming languages (C++ for instance) and self in others (there is even a programming language called Self). In Python the convention is to use the name self for the instance parameter. >The point really being that 'self' (as I understand it) describes the >particular instance of the Class. >So think of the line > self.contents.append(element) >as reading: > thisParticularInstance.contents.append(element) Yes. >(As an aside, you can also write the last line as Basket.add(briefcase, >notepad) but I don't think it reads as well). No, not in your everyday code, but maybe we should start writing method calls like that? Perhaps it would give us a better understanding of what we do? On the other hand it's probably not a good thing to first learn how to do things the wrong way... Typing Basket.add(briefcase, notepad) will make it harder to maintain your code. Maybe briefcase will one day be changed into SmallBasket which is a subclass of Basket? Anyway, briefcase.add(notepad) *is* just a convenient shortcut for Basket.add(briefcase, notepad) or if you don't know that briefcase is a Basket, briefcase.__class__.add(briefcase, notepad) After all, the methods reside in the class, not in each instance. If we think of a.f(x) as a shortcut for A.f(a, x) where a in an instance of class A, I think things will fall in place better. It will also fit the error messages we recieve better. For instance, if you would do briefcase.add() without any (explicit) parameter, python will complain that the second parameter is missing. The first parameter is briefcase of course. Try it! > def add(self, newItem): > self.contents = self.contents + [newItem] self.contents.append(newItem) is better. -- 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 =?ISO-8859-1?B?YW50b25tdWhpbiDt4CByYW1ibGVyLnJ1?= Fri Jan 17 06:10:03 2003 From: =?ISO-8859-1?B?YW50b25tdWhpbiDt4CByYW1ibGVyLnJ1?= (=?ISO-8859-1?B?YW50b25tdWhpbiDt4CByYW1ibGVyLnJ1?=) Date: Fri Jan 17 06:10:03 2003 Subject: Re[2]: [Tutor] OOP explanation article In-Reply-To: <200301161839.44984.blackmariah@shmups.com> References: <5.1.0.14.0.20030117110803.00aca800@192.168.1.1> <200301161839.44984.blackmariah@shmups.com> Message-ID: <10014103369.20030117140923@rambler.ru> Hello Michael, One more comment on your understanding of OOP. Constructors like __init__ in Python don't *create* an instance, but *initialize* data of instance. Let's consider an example: class Foo: def __init__(self, param): self.param = param When Python executes foo = Foo(value) it works more or less the following way: 1. Allocate a memory for new instance. By now the instance has some garbage values. Actually, in Python, as far as I'm aware, it contains some minimal data for class, but let's skip it. 2. Call __init__ and pass the instance that have been created as value for self. This method sets up some initial values. And another one. You missed some important features of OOP: 1. Inheritance. 2. Polymorphism. -- Best regards, anton mailto:antonmuhin@rambler.ru From magnus@thinkware.se Fri Jan 17 06:14:05 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Fri Jan 17 06:14:05 2003 Subject: Re[3]: [Tutor] Comparative code questions: Python vs. Rebol In-Reply-To: <8210644736.20030117131145@rambler.ru> References: <5.1.0.14.0.20030116160119.02a9b968@www.thinkware.se> <5.1.0.14.0.20030116141632.02c95310@www.thinkware.se> <3E25FDB1.5070907@ccvcorp.com> <20030114230533.GK5446@johnsons-web.com> <3E25B590.7030202@ccvcorp.com> <20030115204718.GX5446@johnsons-web.com> <3E25FDB1.5070907@ccvcorp.com> <5.1.0.14.0.20030116141632.02c95310@www.thinkware.se> <5.1.0.14.0.20030116160119.02a9b968@www.thinkware.se> Message-ID: <5.1.0.14.0.20030117120453.02b6fbb0@www.thinkware.se> At 13:11 2003-01-17 +0300, antonmuhin =ED=E0 rambler.ru wrote: > [x + y for x, y reducing [1, 2, 3]] > >that calculates 6 ([] seems bad here, sorry). What do you think about it= ? I think you already figured out that it's not right. You should not use [] when you don't make a list. List comprehension syntax only fits when you make a list, and I'm not really convinced that adding it to Python was a good thing. I think it's a good thing to keep the number of concept programmers have to learn low. I'm not sure that s =3D 0 for i in [1, 2, 3]: s +=3D i is such a bad thing. And I don't see that a syntax mimicing list comprehension for reduce would be better than reduce is today. Despite my mixed feelings about adding new and redundant concepts to Python, I do realize than list comprehension adds some new convenience to Python by combining map, filter and lambda in one construct. But it is a construction for creating lists. --=20 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@thinkware.se Fri Jan 17 06:52:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Fri Jan 17 06:52:01 2003 Subject: [Tutor] Working with Umlauts In-Reply-To: Message-ID: <5.1.0.14.0.20030117121711.02aedc08@www.thinkware.se> At 11:47 2003-01-17 +0100, Tom Churm wrote: >but then i get the error that: >UnicodeError: ASCII decoding error: ordinal not in range(128) You are mixing unicode and the Latin1 ASCII extension I fear. That won't work. Where does lastNameOfUser come from? Or are you perchance working in IDLE? Face it: IDLE doesn't work! Get IDLEfork from http://sourceforge.net/projects/idlefork/ instead, or use something like PythonWin or SciTE. Or use a good editor like vim or emacs, and run the code outside the editor. I sure hope IDLEfork will replace IDLE in the default install soon. I'm not sure what they are waiting for, to me it seems much better already. I think the problem with IDLE is that it's written by someone who uses emacs when he does his own programming, and who works with other people who do the same. It's just like the GUI front ends for Oracle, ClearCase, DB2 etc. They have been written by someone to satisfy some imaginary user, not to scratch a personal itch, or to get irritated colleagues of ones back... Still, it might be a good idea to handle non-ASCII strings explicitly using encode/decode 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 churmtom@hotmail.com Fri Jan 17 07:07:02 2003 From: churmtom@hotmail.com (Tom Churm) Date: Fri Jan 17 07:07:02 2003 Subject: [Tutor] Working with Umlauts Message-ID: >Where does lastNameOfUser come from? this is one of my variables...employee names that--unfortunately!--sometimes contain umlauts >you perchance working in IDLE? Face it: IDLE doesn't work! i'm using PythonWin, ActivePython build 2.1.212, and no, this doesn't work so great sometimes either. --tom _________________________________________________________________ MSN 8 with e-mail virus protection service: 2 months FREE* http://join.msn.com/?page=features/virus From fasal.waseem@cis.co.uk Fri Jan 17 07:39:01 2003 From: fasal.waseem@cis.co.uk (fasal.waseem@cis.co.uk) Date: Fri Jan 17 07:39:01 2003 Subject: [Tutor] Install Errors Message-ID: Hi All I am trying to insall python 1.6 on AIX server, and when I do make install, I get following errors: PYTHONPATH=/usr/local/lib/python1.6 ./python -t /usr/local/lib/python1.6/compileall.py /usr/local/lib/python1.6 Fatal Python error: unlock_import: not holding the import lock make: 1254-059 The signal code from the last command is 6 Does any body know what the signal code 6 is amd how do I deal with th Fatal error. Regards Faz Distributed System Analyst CIS Miller Street Manchester M60 0AL 0161 837 4487 (office) www.cis.co.uk (our web page) ************************************************************************* This e-mail may contain confidential information or be privileged. It is intended to be read and used only by the named recipient(s). If you are not the intended recipient(s) please notify us immediately so that we can make arrangements for its return: you should not disclose the contents of this e-mail to any other person, or take any copies. Unless stated otherwise by an authorised individual, nothing contained in this e-mail is intended to create binding legal obligations between us and opinions expressed are those of the individual author. The CIS marketing group, which is regulated for Investment Business by the Financial Services Authority, includes: Co-operative Insurance Society Limited Registered in England number 3615R - for life assurance and pensions CIS Unit Managers Limited Registered in England and Wales number 2369965 - for unit trusts and PEPs CIS Policyholder Services Limited Registered in England and Wales number 3390839 - for ISAs and investment products bearing the CIS name Registered offices: Miller Street, Manchester M60 0AL Telephone 0161-832-8686 Internet http://www.cis.co.uk E-mail cis@cis.co.uk CIS Deposit and Instant Access Savings Accounts are held with The Co-operative Bank p.l.c., registered in England and Wales number 990937, P.O. Box 101, 1 Balloon Street, Manchester M60 4EP, and administered by CIS Policyholder Services Limited as agent of the Bank. CIS is a member of the General Insurance Standards Council CIS & the CIS logo (R) Co-operative Insurance Society Limited ******************************************************************************** From dyoo@hkn.eecs.berkeley.edu Fri Jan 17 13:01:38 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Jan 17 13:01:38 2003 Subject: [Tutor] What is "reduce"? In-Reply-To: <8210644736.20030117131145@rambler.ru> Message-ID: On Fri, 17 Jan 2003, [ISO-8859-1] antonmuhin =ED=E0 rambler.ru wrote: > And, at least for me, syntactic sugar is really important: one of the > reason I hate C++ is that I must wrap function calls in classes too > often. > > And the last simple question: what about introducing a kind of > comprehensions for other predicates like reduce? Something like: > > [x + y for x, y reducing [1, 2, 3]] > > that calculates 6 ([] seems bad here, sorry). What do you think about > it? For people who haven't had experience with a "reducing" operation: what Anton wants to do in the example above is apply the addition operation between elements of a list, so that reducing [1, 2, 3] with addition ends up doing 1 + 2 + 3 --> 6. There is already a reduce() builtin, as well as a set of operation functions in the 'operator' module, so that we can do Anton's example in Python: ### >>> import operator >>> reduce(operator.add, [1,2,3]) 6 ### (For more information on the operations that live in 'operator', we can look at: http://www.python.org/doc/lib/module-operator.html ) reduce() is a powerful function because it makes certain "accumulating" operations fairly easy to define: ### >>> def sum_all(things): =2E.. return reduce(operator.add, things) =2E.. >>> sum_all(["hello", "world"]) 'helloworld' >>> def multiply_all(things): =2E.. return reduce(operator.mul, things) =2E.. >>> multiply_all([1,2,3,4,5,6,7]) 5040 >>> def factorial(n): =2E.. return multiply_all(range(1,n+1)) =2E.. >>> factorial(10) 3628800 ### Hope this helps! From carroll@tjc.com Fri Jan 17 14:32:02 2003 From: carroll@tjc.com (Terry Carroll) Date: Fri Jan 17 14:32:02 2003 Subject: [Tutor] assert - was: Calculating a math formula In-Reply-To: Message-ID: On Tue, 14 Jan 2003, Michael Janssen wrote: > On Tue, 14 Jan 2003, Jens Kubieziel wrote: > > > On Mon, Jan 13, 2003 at 03:22:07AM -0800, Danny Yoo wrote: > > > def factorial(z): > > > assert z >= 0, "Invalid input: z must be nonnegative." > assert tests if expression is true and raise "AssertionError" if not. > > In "long form": > if not z >= 0: > raise AssertionError, "Invalid input: z must be nonnegative." This is a nit, but it's actually equivalent to: if __debug__: if not z >= 0: raise AssertionError, "Invalid input: z must be nonnegative." That is, if __debug__ is not set, the assert statement is ignored. Because it's strictly intended as a debugging aid, the assert statement optimized away if the -O (optimize) command line option is used (which also sets __debug__, which is ordinarily set to 1, to 0). -- Terry Carroll | Santa Clara, CA | "The parties are advised to chill." carroll@tjc.com | - Mattel, Inc. v. MCA Records, Inc., Modell delendus est | no. 98-56577 (9th Cir. July 24, 2002) From montana@buc99.bsd.st Fri Jan 17 15:39:29 2003 From: montana@buc99.bsd.st (montana) Date: Fri Jan 17 15:39:29 2003 Subject: [Tutor] Question on Time calculations. Message-ID: <200301172038.h0HKcJ8I002585@buc99.bsd.st> Got it. Thanks. That what I thought I goofed on. I now have the following: #!/usr/bin/env python from time import asctime, strptime from mx import DateTime start = raw_input("Enter Start Date and Time: ") end = raw_input("Enter End Date and Time: ") def enterTime(dt): date, time = dt.split() month, day, year = map(int,date.split('.')) hour, min = map(int,[time[:-2], time[-2:]]) outtime = DateTime.DateTime(year, month, day, hour, min, 0) return outtime def timeCalc(stime, etime): c = etime - stime hours = ((c.day*24)+c.hour) min = c.minute return hours, min stime = enterTime(start) etime = enterTime(end) hours, min = timeCalc(stime, etime) print "The total time is: %d hrs, %d min" % (hours, min) Does this look better? Thanks for the help. SA :) On Thursday, January 16, 2003, at 05:52 PM, Magnus Lycka wrote: At 17:11 2003-01-16 -0600, montana wrote: But then how do you get the date parsed? There is a whole row of Date, Time and DateTime constructors in mxDateTime. mx.DateTime.DateTime() takes integers for year, month and so on. The ISO and ARPA modules takes its own formats and soforth... From magnus@thinkware.se Fri Jan 17 15:42:21 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Fri Jan 17 15:42:21 2003 Subject: [Tutor] Working with Umlauts In-Reply-To: Message-ID: <5.1.0.14.0.20030117173557.02b68348@www.thinkware.se> At 13:06 2003-01-17 +0100, Tom Churm wrote: >>Where does lastNameOfUser come from? >this is one of my variables...employee names=20 >that--unfortunately!--sometimes contain umlauts Yes, I understand those parts. I wonder how the string data ends up in the variable. By divine intervention or what? Do you get it through COM fro ma Windows application, or do you get it via ODBC from Access or what? Read from a text file? The big issue is: Are you sure it is of type string? Or is it a Unicode object? What does print type(lastNameOfUser) say? >>you perchance working in IDLE? Face it: IDLE doesn't work! >i'm using PythonWin, ActivePython build 2.1.212, >and no, this doesn't work so great sometimes either. PythinWin works like a charm for me except when I backspace on non-ASCII characters. Then I sometimes get some odd character that I need to remove as well. When I try: lastNameOfUser =3D """string.replace(lastNameOfUser,"=E4","ae") lastNameOfUser =3D string.replace(lastNameOfUser,"=F6","oe") lastNameOfUser =3D string.replace(lastNameOfUser,"=FC","ue") lastNameOfUser =3D string.replace(lastNameOfUser,"=DF","ss") lastNameOfUser =3D string.replace(lastNameOfUser,"=C4","Ae") lastNameOfUser =3D string.replace(lastNameOfUser,"=D6","Oe") lastNameOfUser =3D string.replace(lastNameOfUser,"=DC","Ue")""" lastNameOfUser =3D string.replace(lastNameOfUser,"=E4","ae") lastNameOfUser =3D string.replace(lastNameOfUser,"=F6","oe") lastNameOfUser =3D string.replace(lastNameOfUser,"=FC","ue") lastNameOfUser =3D string.replace(lastNameOfUser,"=DF","ss") lastNameOfUser =3D string.replace(lastNameOfUser,"=C4","Ae") lastNameOfUser =3D string.replace(lastNameOfUser,"=D6","Oe") lastNameOfUser =3D string.replace(lastNameOfUser,"=DC","Ue") print lastNameOfUser in PythonWin I get: string.replace(lastNameOfUser,"ae","ae") lastNameOfUser =3D string.replace(lastNameOfUser,"oe","oe") lastNameOfUser =3D string.replace(lastNameOfUser,"ue","ue") lastNameOfUser =3D string.replace(lastNameOfUser,"ss","ss") lastNameOfUser =3D string.replace(lastNameOfUser,"Ae","Ae") lastNameOfUser =3D string.replace(lastNameOfUser,"Oe","Oe") lastNameOfUser =3D string.replace(lastNameOfUser,"Ue","Ue") Just as expected. --=20 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 churmtom@hotmail.com Fri Jan 17 16:23:05 2003 From: churmtom@hotmail.com (Tom Churm) Date: Fri Jan 17 16:23:05 2003 Subject: [Tutor] Working with Umlauts References: <5.1.0.14.0.20030117173557.02b68348@www.thinkware.se> Message-ID: > Yes, I understand those parts. I wonder how the string > data ends up in the variable. By divine intervention or > what? Do you get it through COM fro ma Windows application, > or do you get it via ODBC from Access or what? Read from > a text file? The big issue is: Are you sure it is of type > string? Or is it a Unicode object? What does > print type(lastNameOfUser) > say? oops...sorry about that...i get it from COM from Lotus Notes (yech!). i left the script at work unfortunately, but i think the snippet is like sess = (make Notes Session) sess.GetSessionUserName ..somethin' like that.. our sys admin for Lotus says that he's not sure if all user names in Lotus are in unicode, so i gotta make sure and convert them, especially since i'm then later accessing a different text file (not part of Lotus but placed on our network) based on the user's name but with the umlauts replaced. something, i gotta replace those umlauts, and there's gotta be a way.. tom ----- Original Message ----- From: "Magnus Lycka" To: "Tom Churm" ; Sent: Friday, January 17, 2003 9:40 PM Subject: Re: [Tutor] Working with Umlauts > At 13:06 2003-01-17 +0100, Tom Churm wrote: > >>Where does lastNameOfUser come from? > >this is one of my variables...employee names > >that--unfortunately!--sometimes contain umlauts > > Yes, I understand those parts. I wonder how the string > data ends up in the variable. By divine intervention or > what? Do you get it through COM fro ma Windows application, > or do you get it via ODBC from Access or what? Read from > a text file? The big issue is: Are you sure it is of type > string? Or is it a Unicode object? What does > print type(lastNameOfUser) > say? > > >>you perchance working in IDLE? Face it: IDLE doesn't work! > >i'm using PythonWin, ActivePython build 2.1.212, > >and no, this doesn't work so great sometimes either. > > > PythinWin works like a charm for me except when I backspace on > non-ASCII characters. Then I sometimes get some odd character > that I need to remove as well. > > When I try: > > lastNameOfUser = """string.replace(lastNameOfUser,"ä","ae") > lastNameOfUser = string.replace(lastNameOfUser,"ö","oe") > lastNameOfUser = string.replace(lastNameOfUser,"ü","ue") > lastNameOfUser = string.replace(lastNameOfUser,"ß","ss") > lastNameOfUser = string.replace(lastNameOfUser,"Ä","Ae") > lastNameOfUser = string.replace(lastNameOfUser,"Ö","Oe") > lastNameOfUser = string.replace(lastNameOfUser,"Ü","Ue")""" > > lastNameOfUser = string.replace(lastNameOfUser,"ä","ae") > lastNameOfUser = string.replace(lastNameOfUser,"ö","oe") > lastNameOfUser = string.replace(lastNameOfUser,"ü","ue") > lastNameOfUser = string.replace(lastNameOfUser,"ß","ss") > lastNameOfUser = string.replace(lastNameOfUser,"Ä","Ae") > lastNameOfUser = string.replace(lastNameOfUser,"Ö","Oe") > lastNameOfUser = string.replace(lastNameOfUser,"Ü","Ue") > > print lastNameOfUser > > in PythonWin I get: > > string.replace(lastNameOfUser,"ae","ae") > lastNameOfUser = string.replace(lastNameOfUser,"oe","oe") > lastNameOfUser = string.replace(lastNameOfUser,"ue","ue") > lastNameOfUser = string.replace(lastNameOfUser,"ss","ss") > lastNameOfUser = string.replace(lastNameOfUser,"Ae","Ae") > lastNameOfUser = string.replace(lastNameOfUser,"Oe","Oe") > lastNameOfUser = string.replace(lastNameOfUser,"Ue","Ue") > > Just as expected. > > > -- > 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 churmtom@hotmail.com Fri Jan 17 16:40:02 2003 From: churmtom@hotmail.com (Tom Churm) Date: Fri Jan 17 16:40:02 2003 Subject: [Tutor] Working with Umlauts References: <5.1.0.14.0.20030117173557.02b68348@www.thinkware.se> Message-ID: i just tried this in IDLE and it worked: >>> import string >>> lastNameOfUser = "töm" >>> lastNameOfUser = string.replace(lastNameOfUser,"ö","oe") >>> print lastNameOfUser toem so it looks like this is a problem with my PythonWin on ActivePython (here at home i'm using the python.org python installation). i'm going to call it quits with ActivePython and install the normal python distribution at work, and then look for another editor. thanks for the help! Tom Churm churmtom@hotmail.com ----- Original Message ----- From: "Magnus Lycka" To: "Tom Churm" ; Sent: Friday, January 17, 2003 9:40 PM Subject: Re: [Tutor] Working with Umlauts > At 13:06 2003-01-17 +0100, Tom Churm wrote: > >>Where does lastNameOfUser come from? > >this is one of my variables...employee names > >that--unfortunately!--sometimes contain umlauts > > Yes, I understand those parts. I wonder how the string > data ends up in the variable. By divine intervention or > what? Do you get it through COM fro ma Windows application, > or do you get it via ODBC from Access or what? Read from > a text file? The big issue is: Are you sure it is of type > string? Or is it a Unicode object? What does > print type(lastNameOfUser) > say? > > >>you perchance working in IDLE? Face it: IDLE doesn't work! > >i'm using PythonWin, ActivePython build 2.1.212, > >and no, this doesn't work so great sometimes either. > > > PythinWin works like a charm for me except when I backspace on > non-ASCII characters. Then I sometimes get some odd character > that I need to remove as well. > > When I try: > > lastNameOfUser = """string.replace(lastNameOfUser,"ä","ae") > lastNameOfUser = string.replace(lastNameOfUser,"ö","oe") > lastNameOfUser = string.replace(lastNameOfUser,"ü","ue") > lastNameOfUser = string.replace(lastNameOfUser,"ß","ss") > lastNameOfUser = string.replace(lastNameOfUser,"Ä","Ae") > lastNameOfUser = string.replace(lastNameOfUser,"Ö","Oe") > lastNameOfUser = string.replace(lastNameOfUser,"Ü","Ue")""" > > lastNameOfUser = string.replace(lastNameOfUser,"ä","ae") > lastNameOfUser = string.replace(lastNameOfUser,"ö","oe") > lastNameOfUser = string.replace(lastNameOfUser,"ü","ue") > lastNameOfUser = string.replace(lastNameOfUser,"ß","ss") > lastNameOfUser = string.replace(lastNameOfUser,"Ä","Ae") > lastNameOfUser = string.replace(lastNameOfUser,"Ö","Oe") > lastNameOfUser = string.replace(lastNameOfUser,"Ü","Ue") > > print lastNameOfUser > > in PythonWin I get: > > string.replace(lastNameOfUser,"ae","ae") > lastNameOfUser = string.replace(lastNameOfUser,"oe","oe") > lastNameOfUser = string.replace(lastNameOfUser,"ue","ue") > lastNameOfUser = string.replace(lastNameOfUser,"ss","ss") > lastNameOfUser = string.replace(lastNameOfUser,"Ae","Ae") > lastNameOfUser = string.replace(lastNameOfUser,"Oe","Oe") > lastNameOfUser = string.replace(lastNameOfUser,"Ue","Ue") > > Just as expected. > > > -- > 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@thinkware.se Fri Jan 17 17:06:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Fri Jan 17 17:06:01 2003 Subject: [Tutor] Working with Umlauts In-Reply-To: References: <5.1.0.14.0.20030117173557.02b68348@www.thinkware.se> Message-ID: <5.1.0.14.0.20030117225942.02b4bc10@www.thinkware.se> At 22:38 2003-01-17 +0100, Tom Churm wrote: >i just tried this in IDLE and it worked: > > >>> import string > >>> lastNameOfUser =3D "t=F6m" > >>> lastNameOfUser =3D string.replace(lastNameOfUser,"=F6","oe") Why not lastNameOfUser.replace("=F6","oe") ? You rarely need to import string since Python 2.0. (Unless you need constants like string.letter, string.digits etc) > >>> print lastNameOfUser >toem Using ActivePython 2.2.1: Python 2.2.1 (#34, Sep 27 2002, 18:37:42) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. IDLE 0.8 -- press F1 for help >>> import string >>> lastNameOfUser =3D "t=F6m" UnicodeError: ASCII encoding error: ordinal not in range(128) >>> But I've had a localization problems in IDLE before. At some stage it used the locale setting for decimal separator, so with Swedish settings that use decimal comma, it didn't understand that >>> 1.5 was a floating point number, and of cource >>> 1,5 (1, 5) :( >so it looks like this is a problem with my PythonWin on ActivePython (he= re >at home i'm using the python.org python installation). Or Python version? >i'm going to call it quits with ActivePython and install the normal pyth= on >distribution at work, and then look for another editor. I'm happy with PythonWin. Have been for years. I think I couldn't survive without a folding editor not that I'm used to it. --=20 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 aicolburn@yahoo.com Fri Jan 17 17:18:03 2003 From: aicolburn@yahoo.com (Alan Colburn) Date: Fri Jan 17 17:18:03 2003 Subject: [Tutor] Two quick, easy questions ... Message-ID: <20030117221726.5526.qmail@web20506.mail.yahoo.com> Hi all -- I'm hoping to clean up two little deficiences in my Python knowledge, if you have the time for a quick response. First, sometimes I see methods that begin with a double underscore in their definition statements: def __newMethod(self): Often, but not always, the statements end with another double underscore: def __init__(self): What's the effect of the leading double underscore? Second, sometimes I also see methods or classes whose input variables include "keywds" and/or "args," in each case preceeded by one or two *'s. I'd love to get a quick lesson about what's going on there. As always, thanks for taking the time to respond to my posts. I appreciate it! -- Al C. __________________________________________________ Do you Yahoo!? Yahoo! Mail Plus - Powerful. Affordable. Sign up now. http://mailplus.yahoo.com From magnus@thinkware.se Fri Jan 17 17:28:04 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Fri Jan 17 17:28:04 2003 Subject: [Tutor] Working with Umlauts In-Reply-To: References: <5.1.0.14.0.20030117173557.02b68348@www.thinkware.se> Message-ID: <5.1.0.14.0.20030117230530.02c4e608@www.thinkware.se> At 22:22 2003-01-17 +0100, Tom Churm wrote: >oops...sorry about that...i get it from COM from Lotus Notes (yech!). Thought so... >our sys admin for Lotus says that he's not sure if all user names in Lot= us >are in unicode, so i gotta make sure and convert them, especially since = i'm >then later accessing a different text file (not part of Lotus but placed= on >our network) based on the user's name but with the umlauts replaced. Most stuff you get from COM is Unicode, but it's no big deal to turn unicode objects into string objects of the encoding of your choice. lastNameOfUser =3D lastNameOfUser.encode('latin1') Now you have a string...and the rest will work. >something, i gotta replace those umlauts, and there's gotta be a way.. I guess the really elegant way is to write a codec for this, so that you can simply do lastNameOfUser =3D lastNameOfUser.encode('ASCIIfiedUmlauts') or something like that. --=20 Magnus Lyck=E5, Thinkware AB =C4lvans v=E4g 99, SE-907 50 UME=C5 tel: 070-582 80 65, fax: 070-612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From magnus@thinkware.se Fri Jan 17 17:41:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Fri Jan 17 17:41:01 2003 Subject: [Tutor] Two quick, easy questions ... In-Reply-To: <20030117221726.5526.qmail@web20506.mail.yahoo.com> Message-ID: <5.1.0.14.0.20030117232811.02b166c8@www.thinkware.se> At 14:17 2003-01-17 -0800, Alan Colburn wrote: >First, sometimes I see methods that begin with a >double underscore in their definition statements: > def __newMethod(self): >Often, but not always, the statements end with another >double underscore: > def __init__(self): >What's the effect of the leading double underscore? I'm starting to loose count on how many times I've explained that this winter... __magic__ <= Has special meaning in python. E.g. del x will invoke x.__del__() and len(x) will invoke x.__len__() __private <= These attributes aren't accessible from outside the class. (Unless you try hard.) >>> class WithPrivate: ... def __init__(self, secret): ... self.__secret = secret ... def tell(self): ... print "Ok, it you promise not to tell anyone else,", self.__secret ... >>> x = WithPrivate('Mary had a little albatross') >>> x.__secret Traceback (most recent call last): File "", line 1, in ? AttributeError: WithPrivate instance has no attribute '__secret' >>> x.tell() Ok, it you promise not to tell anyone else, Mary had a little albatross More details in the tutor archives. >Second, sometimes I also see methods or classes whose >input variables include "keywds" and/or "args," in >each case preceeded by one or two *'s. I'd love to get >a quick lesson about what's going on there. Maybe an example helps... >>> def giveMeAnything(*argsIsAList, **kwargsIsADictionary): ... print "Non-keyword arguments" ... for arg in argsIsAList: ... print arg ... print "Keyword arguments" ... for key, value in kwargsIsADictionary.items(): ... print key, '=', value ... >>> giveMeAnything(1, 2, 3, 'Hello', style=1, colour = 'red') Non-keyword arguments 1 2 3 Hello Keyword arguments style = 1 colour = red -- 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 sonny_c187@hotmail.com Fri Jan 17 17:57:01 2003 From: sonny_c187@hotmail.com (Sonny Collinson) Date: Fri Jan 17 17:57:01 2003 Subject: [Tutor] Network programming tutorials Message-ID: where can i find tutorials on network programming with python as i am very interested learning more in this area _________________________________________________________________ The new MSN 8 is here: Try it free* for 2 months http://join.msn.com/?page=dept/dialup From wilson@visi.com Fri Jan 17 18:21:01 2003 From: wilson@visi.com (Tim Wilson) Date: Fri Jan 17 18:21:01 2003 Subject: [Tutor] Network programming tutorials In-Reply-To: References: Message-ID: <200301171721.56312.wilson@visi.com> On Friday 17 January 2003 17:13, you wrote: > wow thats a quick reply thanks lol. Well i was thinking of learning > socket programming, is this a good place to start? Python has socket and SocketServer modules. See=20 http://python.org/doc/current/lib/module-socket.html for more information= =20 about those. If you already know about socket programming, this may be al= l=20 you need to get going. Otherwise, try the Socket Programmin How-To at=20 http://www.amk.ca/python/howto/sockets/ -Tim --=20 Tim Wilson Twin Cities, Minnesota, USA Science teacher, Linux fan, Zope developer, Grad. student, Daddy mailto:wilson@visi.com | http://qwerk.org/ | public key: 0x8C0F8813 From magnus@thinkware.se Fri Jan 17 18:23:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Fri Jan 17 18:23:01 2003 Subject: [Tutor] Network programming tutorials In-Reply-To: Message-ID: <5.1.0.14.0.20030118002143.02c76ea0@www.thinkware.se> At 22:55 2003-01-17 +0000, Sonny Collinson wrote: >where can i find tutorials on network programming with python as i am very >interested learning more in this area If you don't mind paper books, I can suggest Steve Holden's Python Web Programming. -- 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 wheelcrdan@hotmail.com Fri Jan 17 20:07:04 2003 From: wheelcrdan@hotmail.com (Danny) Date: Fri Jan 17 20:07:04 2003 Subject: [Tutor] Database driven web sites with python Message-ID: This is a multi-part message in MIME format. ------=_NextPart_000_0028_01C2BE53.0EEAB120 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hello everyone, Quick and easy question, can you use python to build database driven web = sites. Thanks ahead of time for everyone help, and have a great weekend... Danny D ------=_NextPart_000_0028_01C2BE53.0EEAB120 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hello everyone,
 
Quick and easy question, can you use = python to=20 build database driven web sites.
Thanks ahead of time for everyone help, = and have a=20 great weekend...
 
Danny D
------=_NextPart_000_0028_01C2BE53.0EEAB120-- From ramrom@earthling.net Fri Jan 17 21:27:01 2003 From: ramrom@earthling.net (Bob Gailer) Date: Fri Jan 17 21:27:01 2003 Subject: [Tutor] Two quick, easy questions ... In-Reply-To: <5.1.0.14.0.20030117232811.02b166c8@www.thinkware.se> References: <20030117221726.5526.qmail@web20506.mail.yahoo.com> Message-ID: <5.2.0.9.0.20030117191711.037e3340@66.28.54.253> --=======20B7174======= Content-Type: text/plain; x-avg-checked=avg-ok-6DC5BEE; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit In re *args and **kwargs, also note that one may use these forms when passing arguments in a function call: def a(*b,**c): print b, c t = (1,2,3) d = {'1':2, '3':4} a(*t, **d) # results in: (1, 2, 3) {'1': 2, '3': 4} This can be particularly handy when writing wrapper code around a function that expects either form of argument lists. Also note that def makedict(**kwargs):return kwargs # is a great shorthand for creating dictionaries print makedict(a=2,b=4) # results in: {'a': 2, 'b': 4} Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======20B7174======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-6DC5BEE Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.438 / Virus Database: 246 - Release Date: 1/7/2003 --=======20B7174=======-- From ramrom@earthling.net Fri Jan 17 21:29:01 2003 From: ramrom@earthling.net (Bob Gailer) Date: Fri Jan 17 21:29:01 2003 Subject: [Tutor] Database driven web sites with python In-Reply-To: Message-ID: <5.2.0.9.0.20030117192746.037e1650@66.28.54.253> --=======1B8868EA======= Content-Type: multipart/alternative; x-avg-checked=avg-ok-6DC5BEE; boundary="=====================_10371483==.ALT" --=====================_10371483==.ALT Content-Type: text/plain; x-avg-checked=avg-ok-6DC5BEE; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 06:05 PM 1/17/2003 -0700, Danny wrote: >Quick and easy question, can you use python to build database driven web >sites. In general the answer is yes. Do you have something specific in mind? Have you looked at ZOPE? www.zope.org Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=====================_10371483==.ALT Content-Type: text/html; x-avg-checked=avg-ok-6DC5BEE; charset=us-ascii Content-Transfer-Encoding: 8bit At 06:05 PM 1/17/2003 -0700, Danny wrote:
Quick and easy question, can you use python to build database driven web sites.

In general the answer is yes. Do you have something specific in mind?

Have you looked at ZOPE? www.zope.org

Bob Gailer
mailto:ramrom@earthling.net
303 442 2625
--=====================_10371483==.ALT-- --=======1B8868EA======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-6DC5BEE Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.438 / Virus Database: 246 - Release Date: 1/7/2003 --=======1B8868EA=======-- From magnus@thinkware.se Sat Jan 18 04:40:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Sat Jan 18 04:40:01 2003 Subject: [Tutor] Database driven web sites with python In-Reply-To: Message-ID: <5.1.0.14.0.20030118094725.02c4b628@www.thinkware.se> At 18:05 2003-01-17 -0700, Danny wrote: >Quick and easy question, can you use python to build database driven web >sites. Short answer: Yes. Long answer: Of course you can, and many people do. Some of the worlds leading web sites and applications are python powered. There are two paper books dedicated to the subject, see http://www.python.org/cgi-bin/moinmoin/WebProgrammingBooks For some other resoures, see http://www.python.org/cgi-bin/moinmoin/WebProgramming http://www.thinkware.se/cgi-bin/thinki.cgi/PythonForInternet and http://www.python.org/topics/database/ One factor you have to take into consideration is how you are going to deploy your application. Are you able to execute long-running processes on the server, or do you have to restrict yourself to cgi-scripts? Some tools, such as Zope are fairly hopeless to run as CGI scripts. They have all too long startup time. One tool that I like is CherryPy, http://www.cherrypy.org/ . It fits my brain. It contains the stuff I need, and it restricts itself to web stuff. I don't like tools that try to be everything at once, but prefer a layered approach. It also wants to have a long running process though. ZOPE, http://www.zope.org/ , as Bob mentioned is a big system for creating dynamic web content. Too big, some may say. Actually, you might work a long time in Zope without ever writing a line of python code... It *is* intented to be usable for non-programmers, but there is a lot of zopeish things to learn, so in addition to python, there are a lot of other things to think about. Also, the things you create such as layout, access rules, page structures etc are stored in Zope's builtin object database. This means that you can't use standard stuff file handling tools as grep and find to search for things in your application. Personally I don't like this--I get a little lost, just as when I develop things in tools like Excel or Visual Basic. I want everything to be plain code in text files. On the other hand, there is not other tool that will give you as many features for free as Zope does. It really has an amazing amount of modules and features. If your system is to grow big, you might have to develop a lot of these things on your own if you don't use Zope. Your choice of tools really depends on how you want to work and what kind of web site it is. Is there a lot of advanced logic, or are you mainly serving pages? Do you need user authentication and security aspects? Is it a small system or a big system? What kind of control do you have over the server? Don't trust anyone who says that one size fits all... /Magnus -- 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 graemea@xtra.co.nz Sat Jan 18 06:38:02 2003 From: graemea@xtra.co.nz (Graeme Andrew) Date: Sat Jan 18 06:38:02 2003 Subject: [Tutor] Simply Regular Expression or Matching question ? Message-ID: <000901c2bee5$e1a6fa00$0201a8c0@graeme> Hi Folks ... I am trying to parse some source code that includes some delimited text in the form of {abcd ...} ... ie text delimited by curly brackets. I am reading in each line of source code and need a list of all occurences of this for all lines. Is there a simple 're' that will return all occurences of the text between the curly brackets as descibed above ? ...(or do I even need to use 're' ) Any help most appreciated ! Cheers Graeme Andrew Kiwi From ramrom@earthling.net Sat Jan 18 09:09:01 2003 From: ramrom@earthling.net (Bob Gailer) Date: Sat Jan 18 09:09:01 2003 Subject: [Tutor] Simply Regular Expression or Matching question ? In-Reply-To: <000901c2bee5$e1a6fa00$0201a8c0@graeme> Message-ID: <5.2.0.9.0.20030118070717.01a07548@66.28.54.253> --=======44751008======= Content-Type: text/plain; x-avg-checked=avg-ok-B74577E; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 12:36 AM 1/19/2003 +1300, Graeme Andrew wrote: >parse code that includes some delimited text in the form {abcd ...} . > >Is there a simple 're' that will return all occurences of the text between >the curly brackets as descibed above >>> import re >>> s = 'a{b}\nc{d}' >>> re.findall(r'{.*}', s) ['{b}', '{d}'] Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======44751008======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-B74577E Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.438 / Virus Database: 246 - Release Date: 1/7/2003 --=======44751008=======-- From magnus@thinkware.se Sat Jan 18 10:36:00 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Sat Jan 18 10:36:00 2003 Subject: [Tutor] Simply Regular Expression or Matching question ? In-Reply-To: <5.2.0.9.0.20030118070717.01a07548@66.28.54.253> References: <000901c2bee5$e1a6fa00$0201a8c0@graeme> Message-ID: <5.1.0.14.0.20030118160532.02b70310@www.thinkware.se> At 07:08 2003-01-18 -0700, Bob Gailer wrote: >At 12:36 AM 1/19/2003 +1300, Graeme Andrew wrote: >>parse code that includes some delimited text in the form {abcd ...} . >> >>Is there a simple 're' that will return all occurences of the text between >>the curly brackets as descibed above > > >>> import re > >>> s = 'a{b}\nc{d}' > >>> re.findall(r'{.*}', s) >['{b}', '{d}'] Almost there, but this code has three problems. First of all, it doesn't find the text *between* the curly braces. It finds the curly braces *and* the text between. There are two more problems. See below: >>> s = ''' bla bla { some text ... that spans more than one line } ... {this} ... {is} ... {ok} ... {several} blocks {on} one {line} ... ''' >>> re.findall(r'{.*}', s) ['{this}', '{is}', '{ok}', '{several} blocks {on} one {line}'] As you see, it only finds patterns where both { and } are one the same line. Secondly, it will match the first { and the last } on the line, which is hardly what we want... Let's fix these things one at a time. The manual is our friend http://www.python.org/doc/current/lib/re-syntax.html We should first remove the burly braces... Look in the manual: (...) Matches whatever regular expression is inside the parentheses, and indicates the start and end of a group; the contents of a group can be retrieved after a match has been performed, and can be matched later in the string with the \number special sequence, described below. To match the literals "(" or ")", use \( or \), or enclose them inside a character class: [(] [)]. So... >>> re.findall(r'{(.*)}', s) ['this', 'is', 'ok', 'several} blocks {on} one {line'] Now we find text *between braces*, not the braces themselves *and* text between. The things outside () is only there to provide context now, not to be a part of what we extract. Now, let's look at the problem with {}-blocks spanning several lines. "." (Dot.) In the default mode, this matches any character except a newline. If the DOTALL flag has been specified, this matches any character including a newline. So, let's use the DOTALL flag. I think we need to compile a regular expression for that. (I always do that anyway.) >>> pattern = re.compile(r'{(.*)}', re.DOTALL) >>> pattern.findall(s) [' some text\nthat spans more than one line }\n{this}\n{is}\n{ok}\n{several} blocks {on} one {line'] There we are. Now we just have to fix the last problem. But what's really the problem? Let's read some more. What are we doing? . means any character (including or excluding \n depending on re.DOTALL) * means 0 or more repetitions of whatever was before. ('.' in this case.) {.*} Means start with { and end with } and anything in between. This could be interpreted in two ways. Either find as much as possible in .* that will satisfy the whole re...and that is what happens now. It's called a greedy match. The other option is to get as little as possible in .* that will still satisfy the requirement of a } after. That is what we want, right? Read the manual again. *?, +?, ?? The "*", "+", and "?" qualifiers are all greedy; they match as much text as possible. Sometimes this behaviour isn't desired; if the RE <.*> is matched against '

title

', it will match the entire string, and not just '

'. Adding "?" after the qualifier makes it perform the match in non-greedy or minimal fashion; as few characters as possible will be matched. Using .*? in the previous expression will match only '

'. Seems simple... >>> pattern = re.compile(r'{(.*?)}', re.DOTALL) >>> pattern.findall(s) [' some text\nthat spans more than one line ', 'this', 'is', 'ok', 'several', 'on', 'line'] Better like this? Do you want more, some removal of whitespace for instance? -- 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 pversteegen@gcnetmail.net Sat Jan 18 11:06:02 2003 From: pversteegen@gcnetmail.net (Pete Versteegen) Date: Sat Jan 18 11:06:02 2003 Subject: [Tutor] Formatter Message-ID: Hi, I'm new to python. I have been reading tutorials, scouring the Internet, and running sample problems. I have selected Python as a language to be learned thoroughly because of its capabilities to do scientific work, web work, and developing GUIs. I have written a fairly large C++ application for estimating building construction costs that I've stated to convert to Python. I want to eventually put a GUI around the input data preparation process and results display it rather than using text editors and other database and graphing applications. I would like not to reinvent the wheel and use or adapt what others have done already. I have not found anything that is convenient to format columns of numbers and text. I found Textformatter, but it doesn=B9t what I would like to do. Does anyone know of an easy way to format a mixture of floats, integers, spaces, and text in well arranged columns? My thoughts wander towards the way the Fortran language does it. I'm considered a function (class) that would be called as follows: format((a, alf, i), "f10.2, a10, 10x, i5") This would print the three items in the tuple according to the specifaction= s listed between the quote marks, whee f10.2 (float, 10 wide, 2 digits after decimal point) a10 (alpha number of 10 wide 10x (1o blank spaces) i5 (integer of 5 digits wide) There or obviously other features that can be introduced. Any thoughts by anyone? Thanks! From ramrom@earthling.net Sat Jan 18 11:38:26 2003 From: ramrom@earthling.net (Bob Gailer) Date: Sat Jan 18 11:38:26 2003 Subject: [Tutor] Simply Regular Expression or Matching question ? In-Reply-To: <5.1.0.14.0.20030118160532.02b70310@www.thinkware.se> References: <5.2.0.9.0.20030118070717.01a07548@66.28.54.253> <000901c2bee5$e1a6fa00$0201a8c0@graeme> Message-ID: <5.2.0.9.0.20030118093551.034b28c8@66.28.54.253> --=======2A477B65======= Content-Type: text/plain; x-avg-checked=avg-ok-B74577E; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit Thanks for expanding my solution into a really useful pattern. I've been working with re for under a month, and it definitely has a learning curve. At 04:34 PM 1/18/2003 +0100, Magnus Lycka wrote: >At 07:08 2003-01-18 -0700, Bob Gailer wrote: >>At 12:36 AM 1/19/2003 +1300, Graeme Andrew wrote: >>>parse code that includes some delimited text in the form {abcd ...} . >>> >>>Is there a simple 're' that will return all occurences of the text between >>>the curly brackets as descibed above >> >> >>> import re >> >>> s = 'a{b}\nc{d}' >> >>> re.findall(r'{.*}', s) >>['{b}', '{d}'] > >Almost there, but this code has three problems. > >First of all, it doesn't find the text *between* the curly >braces. It finds the curly braces *and* the text between. > >There are two more problems. See below: > >>> s = ''' bla bla { some text >... that spans more than one line } >... {this} >... {is} >... {ok} >... {several} blocks {on} one {line} >... ''' > >>> re.findall(r'{.*}', s) >['{this}', '{is}', '{ok}', '{several} blocks {on} one {line}'] > >As you see, it only finds patterns where both { and } are >one the same line. Secondly, it will match the first { and >the last } on the line, which is hardly what we want... > >Let's fix these things one at a time. The manual is our friend >http://www.python.org/doc/current/lib/re-syntax.html > >We should first remove the burly braces... Look in the manual: > >(...) >Matches whatever regular expression is inside the parentheses, and indicates >the start and end of a group; the contents of a group can be retrieved after >a match has been performed, and can be matched later in the string with the >\number special sequence, described below. To match the literals "(" or ")", >use \( or \), or enclose them inside a character class: [(] [)]. > >So... > >>> re.findall(r'{(.*)}', s) >['this', 'is', 'ok', 'several} blocks {on} one {line'] > >Now we find text *between braces*, not the braces themselves >*and* text between. The things outside () is only there to >provide context now, not to be a part of what we extract. > >Now, let's look at the problem with {}-blocks spanning several >lines. > >"." > (Dot.) In the default mode, this matches any character except a newline. >If the DOTALL flag has been specified, this matches any character including >a newline. > >So, let's use the DOTALL flag. I think we need to compile a regular >expression for that. (I always do that anyway.) > > >>> pattern = re.compile(r'{(.*)}', re.DOTALL) > >>> pattern.findall(s) >[' some text\nthat spans more than one line >}\n{this}\n{is}\n{ok}\n{several} blocks {on} one {line'] > >There we are. Now we just have to fix the last problem. But what's >really the problem? Let's read some more. What are we doing? > >. means any character (including or excluding \n depending on re.DOTALL) >* means 0 or more repetitions of whatever was before. ('.' in this case.) > >{.*} Means start with { and end with } and anything in between. This could >be interpreted in two ways. Either find as much as possible in .* that will >satisfy the whole re...and that is what happens now. It's called a greedy >match. The other option is to get as little as possible in .* that will still >satisfy the requirement of a } after. That is what we want, right? Read the >manual again. > >*?, +?, ?? >The "*", "+", and "?" qualifiers are all greedy; they match as much text as >possible. Sometimes this behaviour isn't desired; if the RE <.*> is matched >against '

title

', it will match the entire string, and not just >'

'. Adding "?" after the qualifier makes it perform the match in >non-greedy or minimal fashion; as few characters as possible will be >matched. Using .*? in the previous expression will match only '

'. > >Seems simple... > > >>> pattern = re.compile(r'{(.*?)}', re.DOTALL) > >>> pattern.findall(s) >[' some text\nthat spans more than one line ', 'this', 'is', 'ok', >'several', 'on', 'line'] > >Better like this? > >Do you want more, some removal of whitespace for instance? > > >-- >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 > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > >--- >Incoming mail is certified Virus Free. >Checked by AVG anti-virus system (http://www.grisoft.com). >Version: 6.0.438 / Virus Database: 246 - Release Date: 1/7/2003 Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======2A477B65======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-B74577E Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.438 / Virus Database: 246 - Release Date: 1/7/2003 --=======2A477B65=======-- From ramrom@earthling.net Sat Jan 18 11:49:02 2003 From: ramrom@earthling.net (Bob Gailer) Date: Sat Jan 18 11:49:02 2003 Subject: [Tutor] Formatter In-Reply-To: Message-ID: <5.2.0.9.0.20030118093822.034b0c40@66.28.54.253> --=======7A544C95======= Content-Type: text/plain; x-avg-checked=avg-ok-B74577E; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 11:05 AM 1/18/2003 -0500, Pete Versteegen wrote: >I have selected Python as a language to be >learned thoroughly because of its capabilities to do scientific work, web >work, and developing GUIs. Not to mention that its a LOT easier than C++ >Does anyone know of an easy way to format a mixture of floats, integers, >spaces, and text in well arranged columns? > >My thoughts wander towards the way the Fortran language does it. I'm >considered a function (class) that would be called as follows: >format((a, alf, i), "f10.2, a10, 10x, i5") >This would print the three items in the tuple according to the specifactions >listed between the quote marks, whee >f10.2 (float, 10 wide, 2 digits after decimal point) >a10 (alpha number of 10 wide >10x (1o blank spaces) >i5 (integer of 5 digits wide) See http://www.python.org/doc/current/lib/typesseq-strings.html#l2h-148 for string formatting. You can probably get what you need there. For your example: print '%10.2f%10s %5d' % (2.3, 'asdf', 4) # gives " 2.30 asdf 4" Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======7A544C95======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-B74577E Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.438 / Virus Database: 246 - Release Date: 1/7/2003 --=======7A544C95=======-- From ramrom@earthling.net Sat Jan 18 12:43:01 2003 From: ramrom@earthling.net (Bob Gailer) Date: Sat Jan 18 12:43:01 2003 Subject: [Tutor] Formatter Message-ID: <5.2.0.9.0.20030118100043.034a91b0@66.28.54.253> --=======5B0344B5======= Content-Type: text/plain; x-avg-checked=avg-ok-B74577E; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 11:05 AM 1/18/2003 -0500, Pete Versteegen wrote: >Does anyone know of an easy way to format a mixture of floats, integers, >spaces, and text in well arranged columns? > >My thoughts wander towards the way the Fortran language does it. I'm >considered a function (class) that would be called as follows: >format((a, alf, i), "f10.2, a10, 10x, i5") def format(values, format): formatlist = format.split(',') sf = '' for formatitem in formatlist: type = formatitem[0] if type in 'fi': sf += '%' + formatitem[1:] + type if type == 'a': sf += ' '*int(formatitem[1:]) elif formatitem[-1] == 'x': sf += '%' + formatitem[:-1] + 's' return sf % values a = 5 alf = 'qwer' i = 3 print format((a, alf, i), "f10.2,a10,10x,i5") result: 5.00 qwer 3 For simplicity I removed the spaces between the fortran format items. A little more code would handle them. Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======5B0344B5======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-B74577E Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.438 / Virus Database: 246 - Release Date: 1/7/2003 --=======5B0344B5=======-- From charlie@begeistert.org Sat Jan 18 13:14:01 2003 From: charlie@begeistert.org (Charlie Clark) Date: Sat Jan 18 13:14:01 2003 Subject: [Tutor] Database driven web sites with python In-Reply-To: <20030118170006.7840.1710.Mailman@mail.python.org> References: <20030118170006.7840.1710.Mailman@mail.python.org> Message-ID: <20030118191253.581.1@.1042911554.fake> Hi Danny, I'll go along with most of of what Magnus says, as usual: listen to him. On 2003-01-18 at 18:00:06 [+0100], tutor@python.org wrote: > One tool that I like is CherryPy, http://www.cherrypy.org/ . It fits my > brain. It contains the stuff I need, and it restricts itself to web > stuff. I don't like tools that try to be everything at once, but prefer a > layered approach. It also wants to have a long running process though. I've just looked at some of the CherryPy documentation. I don't think it would be for me (too much code mixed in the HTML) which isn't to say its bad!!! > ZOPE, http://www.zope.org/ , as Bob mentioned is a big system for > creating dynamic web content. Too big, some may say. Actually, you might > work a long time in Zope without ever writing a line of python code... It > *is* intented to be usable for non-programmers, but there is a lot of > zopeish things to learn, so in addition to python, there are a lot of > other things to think about. Also, the things you create such as layout, > access rules, page structures etc are stored in Zope's builtin object > database. This means that you can't use standard stuff file handling > tools as grep and find to search for things in your application. > Personally I don't like this--I get a little lost, just as when I develop > things in tools like Excel or Visual Basic. I want everything to be plain > code in text files. On the other hand, there is not other tool that will > give you as many features for free as Zope does. It really has an amazing > amount of modules and features. If your system is to grow big, you might > have to develop a lot of these things on your own if you don't use Zope. Definitely agree with this. Zope really is big and for lots of things *great*. You can get up and running quickly, there are all kinds of modules to use and there is a big and supportive user community. But... once you start to do more adventurous things Zope starts to get more complex and you have to start going through the source to find out what you have to change. It seems to be standard practice to have to extend things at some point but I think this applies to all systems. Marcus' objection about storage is now only partly true. You can now have stuff saved in files or CVS though none of the solutions are entirely stable. I really like being able (re)organise parts of the site as it develops: Zope is quite nice when you change things and I've become a big fan of PageTemplates. But it has all taken time. Expect to need about 6 weeks before feeling comfortable with Zope because it is an application server and can be compared with the big boys. If you enjoy working on source then you might enjoy joining in Zope 3 development which is going to tidy up a lot of the things that have been put in over time. You might also want to look at the eGenix Web Application server. http://www.egenix.com/ It has rock-solid database support and a nice approach to embedding Python code in HTML and will have excellent web service support. Charlie From shalehperry@attbi.com Sat Jan 18 13:28:01 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Sat Jan 18 13:28:01 2003 Subject: [Tutor] Simply Regular Expression or Matching question ? In-Reply-To: <5.2.0.9.0.20030118093551.034b28c8@66.28.54.253> References: <5.2.0.9.0.20030118070717.01a07548@66.28.54.253> <000901c2bee5$e1a6fa00$0201a8c0@graeme> <5.2.0.9.0.20030118093551.034b28c8@66.28.54.253> Message-ID: <200301181026.44367.shalehperry@attbi.com> On Saturday 18 January 2003 08:37, Bob Gailer wrote: > Thanks for expanding my solution into a really useful pattern. I've bee= n > working with re for under a month, and it definitely has a learning cur= ve. > for both you and the original submitter, look into the O'Reilly book=20 "Mastering Regular Expressions". It is not a Python book and has more Pe= rl=20 than some would like but it does teach how to deal with regex in a good,=20 clear manner. From gapetard@stsams.org Sat Jan 18 13:53:02 2003 From: gapetard@stsams.org (Bob Rea) Date: Sat Jan 18 13:53:02 2003 Subject: [Tutor] Simply Regular Expression or Matching question ? In-Reply-To: <200301181026.44367.shalehperry@attbi.com> References: <5.2.0.9.0.20030118070717.01a07548@66.28.54.253> <5.2.0.9.0.20030118093551.034b28c8@66.28.54.253> <200301181026.44367.shalehperry@attbi.com> Message-ID: <200301181352.17682.gapetard@stsams.org> On Saturday 18 January 2003 1:26 pm, Sean 'Shaleh' Perry=20 wrote: > for both you and the original submitter, look into the > O'Reilly book "Mastering Regular Expressions". It is not > a Python book and has more Perl than some would like but > it does teach how to deal with regex in a good, clear > manner. I have been trying to learn reg exps and have read some of=20 this book. What I really need is a set of graduated=20 exercises to learn re's. Something like my high school=20 algebra text book with lots of exercises. --=20 Bob Rea mailto:gapetard@stsams.org http://www.petard.us What do you say to Jesus when he comes again? Where have you been. You said you were coming right back. From pversteegen@gcnetmail.net Sat Jan 18 14:44:02 2003 From: pversteegen@gcnetmail.net (Pete Versteegen) Date: Sat Jan 18 14:44:02 2003 Subject: [Tutor] Formatter In-Reply-To: <5.2.0.9.0.20030118100043.034a91b0@66.28.54.253> Message-ID: On 1/18/03 12:42 PM, "Bob Gailer" wrote: > At 11:05 AM 1/18/2003 -0500, Pete Versteegen wrote: >> Does anyone know of an easy way to format a mixture of floats, integers, >> spaces, and text in well arranged columns? >> >> My thoughts wander towards the way the Fortran language does it. I'm >> considered a function (class) that would be called as follows: >> format((a, alf, i), "f10.2, a10, 10x, i5") > > def format(values, format): > formatlist = format.split(',') > sf = '' > for formatitem in formatlist: > type = formatitem[0] > if type in 'fi': > sf += '%' + formatitem[1:] + type > if type == 'a': > sf += ' '*int(formatitem[1:]) > elif formatitem[-1] == 'x': > sf += '%' + formatitem[:-1] + 's' > return sf % values > a = 5 > alf = 'qwer' > i = 3 > print format((a, alf, i), "f10.2,a10,10x,i5") > > result: 5.00 qwer 3 > > For simplicity I removed the spaces between the fortran format items. A > little more code would handle them. > > Bob Gailer > mailto:ramrom@earthling.net > 303 442 2625 > > > --- > Outgoing mail is certified Virus Free. > Checked by AVG anti-virus system (http://www.grisoft.com). > Version: 6.0.438 / Virus Database: 246 - Release Date: 1/7/2003 > From pversteegen@gcnetmail.net Sat Jan 18 14:46:01 2003 From: pversteegen@gcnetmail.net (Pete Versteegen) Date: Sat Jan 18 14:46:01 2003 Subject: [Tutor] Formatter In-Reply-To: <5.2.0.9.0.20030118100043.034a91b0@66.28.54.253> Message-ID: Sorry about the last message (without a comment) Thanks for your responses. They're very helpful.. This also shows agian the flexibility and versatility of Python. Yes definitely easier to learn than C++! Pete Versteegen pversteegen@gcnetmail.net __________________________ On 1/18/03 12:42 PM, "Bob Gailer" wrote: > At 11:05 AM 1/18/2003 -0500, Pete Versteegen wrote: >> Does anyone know of an easy way to format a mixture of floats, integers, >> spaces, and text in well arranged columns? >> >> My thoughts wander towards the way the Fortran language does it. I'm >> considered a function (class) that would be called as follows: >> format((a, alf, i), "f10.2, a10, 10x, i5") > > def format(values, format): > formatlist = format.split(',') > sf = '' > for formatitem in formatlist: > type = formatitem[0] > if type in 'fi': > sf += '%' + formatitem[1:] + type > if type == 'a': > sf += ' '*int(formatitem[1:]) > elif formatitem[-1] == 'x': > sf += '%' + formatitem[:-1] + 's' > return sf % values > a = 5 > alf = 'qwer' > i = 3 > print format((a, alf, i), "f10.2,a10,10x,i5") > > result: 5.00 qwer 3 > > For simplicity I removed the spaces between the fortran format items. A > little more code would handle them. > > Bob Gailer > mailto:ramrom@earthling.net > 303 442 2625 > > > --- > Outgoing mail is certified Virus Free. > Checked by AVG anti-virus system (http://www.grisoft.com). > Version: 6.0.438 / Virus Database: 246 - Release Date: 1/7/2003 > From graemea@xtra.co.nz Sat Jan 18 15:11:01 2003 From: graemea@xtra.co.nz (Graeme Andrew) Date: Sat Jan 18 15:11:01 2003 Subject: [Tutor] Simply Regular Expression or Matching question ? References: <000901c2bee5$e1a6fa00$0201a8c0@graeme> <5.1.0.14.0.20030118160532.02b70310@www.thinkware.se> Message-ID: <009201c2bf2d$88a5dc80$0201a8c0@graeme> Many thanks for the help on my 're' problem .... I have read your solution carefully Magnus and it was most helpful .. Cheers Graeme Andrew Kiwi ----- Original Message ----- From: "Magnus Lycka" To: "Bob Gailer" ; "Graeme Andrew" ; Sent: Sunday, January 19, 2003 4:34 AM Subject: Re: [Tutor] Simply Regular Expression or Matching question ? > At 07:08 2003-01-18 -0700, Bob Gailer wrote: > >At 12:36 AM 1/19/2003 +1300, Graeme Andrew wrote: > >>parse code that includes some delimited text in the form {abcd ...} . > >> > >>Is there a simple 're' that will return all occurences of the text between > >>the curly brackets as descibed above > > > > >>> import re > > >>> s = 'a{b}\nc{d}' > > >>> re.findall(r'{.*}', s) > >['{b}', '{d}'] > > Almost there, but this code has three problems. > > First of all, it doesn't find the text *between* the curly > braces. It finds the curly braces *and* the text between. > > There are two more problems. See below: > >>> s = ''' bla bla { some text > ... that spans more than one line } > ... {this} > ... {is} > ... {ok} > ... {several} blocks {on} one {line} > ... ''' > >>> re.findall(r'{.*}', s) > ['{this}', '{is}', '{ok}', '{several} blocks {on} one {line}'] > > As you see, it only finds patterns where both { and } are > one the same line. Secondly, it will match the first { and > the last } on the line, which is hardly what we want... > > Let's fix these things one at a time. The manual is our friend > http://www.python.org/doc/current/lib/re-syntax.html > > We should first remove the burly braces... Look in the manual: > > (...) > Matches whatever regular expression is inside the parentheses, and indicates > the start and end of a group; the contents of a group can be retrieved after > a match has been performed, and can be matched later in the string with the > \number special sequence, described below. To match the literals "(" or ")", > use \( or \), or enclose them inside a character class: [(] [)]. > > So... > >>> re.findall(r'{(.*)}', s) > ['this', 'is', 'ok', 'several} blocks {on} one {line'] > > Now we find text *between braces*, not the braces themselves > *and* text between. The things outside () is only there to > provide context now, not to be a part of what we extract. > > Now, let's look at the problem with {}-blocks spanning several > lines. > > "." > (Dot.) In the default mode, this matches any character except a newline. > If the DOTALL flag has been specified, this matches any character including > a newline. > > So, let's use the DOTALL flag. I think we need to compile a regular > expression for that. (I always do that anyway.) > > >>> pattern = re.compile(r'{(.*)}', re.DOTALL) > >>> pattern.findall(s) > [' some text\nthat spans more than one line > }\n{this}\n{is}\n{ok}\n{several} blocks {on} one {line'] > > There we are. Now we just have to fix the last problem. But what's > really the problem? Let's read some more. What are we doing? > > . means any character (including or excluding \n depending on re.DOTALL) > * means 0 or more repetitions of whatever was before. ('.' in this case.) > > {.*} Means start with { and end with } and anything in between. This could > be interpreted in two ways. Either find as much as possible in .* that will > satisfy the whole re...and that is what happens now. It's called a greedy > match. The other option is to get as little as possible in .* that will still > satisfy the requirement of a } after. That is what we want, right? Read the > manual again. > > *?, +?, ?? > The "*", "+", and "?" qualifiers are all greedy; they match as much text as > possible. Sometimes this behaviour isn't desired; if the RE <.*> is matched > against '

title

', it will match the entire string, and not just > '

'. Adding "?" after the qualifier makes it perform the match in > non-greedy or minimal fashion; as few characters as possible will be > matched. Using .*? in the previous expression will match only '

'. > > Seems simple... > > >>> pattern = re.compile(r'{(.*?)}', re.DOTALL) > >>> pattern.findall(s) > [' some text\nthat spans more than one line ', 'this', 'is', 'ok', > 'several', 'on', 'line'] > > Better like this? > > Do you want more, some removal of whitespace for instance? > > > -- > 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 ahimsa@onetel.net.uk Sat Jan 18 17:08:02 2003 From: ahimsa@onetel.net.uk (ahimsa) Date: Sat Jan 18 17:08:02 2003 Subject: [Tutor] Python Tutorial rel 2.2.2 - need debug for 4.4. Code example Message-ID: <1042923604.1124.1239.camel@localhost.localdomain> Hello all Could someone help me to understand - and even debug - the following. It is verbatim of 4.4 of the Python Tutorial Release 2.2.2 - the section on 'More Control Flow Loops'. I have tested it several times and still get the same ouput. I have also experimented with changing the division operator '/' to '//' but that didn't make any difference. Any ideas? Thanks Andrew Code follows: ############################################# >>> for n in range( 2, 10 ): for x in range( 2, n ): if n % x == 0: print n, 'equals', x, '*', n/x break else: print n, 'is a prime number.' 3 is a prime number. 4 equals 2 * 2 5 is a prime number. 5 is a prime number. 5 is a prime number. 6 equals 2 * 3 7 is a prime number. 7 is a prime number. 7 is a prime number. 7 is a prime number. 7 is a prime number. 8 equals 2 * 4 9 is a prime number. 9 equals 3 * 3 ################################## -- ahimsa From norvell@houseofspearman.org Sat Jan 18 17:21:40 2003 From: norvell@houseofspearman.org (Norvell Spearman) Date: Sat Jan 18 17:21:40 2003 Subject: [Tutor] Python Tutorial rel 2.2.2 - need debug for 4.4. Code example In-Reply-To: <1042923604.1124.1239.camel@localhost.localdomain> References: <1042923604.1124.1239.camel@localhost.localdomain> Message-ID: <20030118222014.GA4783@houseofspearman.org> On Saturday, 2003.01.18, 22:09:53 +0000, ahimsa wrote: > Hello all > > Could someone help me to understand - and even debug - the following. It > is verbatim of 4.4 of the Python Tutorial Release 2.2.2 - the section on > 'More Control Flow Loops'. I have tested it several times and still get > the same ouput. I have also experimented with changing the division > operator '/' to '//' but that didn't make any difference. > Any ideas? I moved the break statement after the else and with the same indentation level as the if and else. This seems to have fixed the problem. -- Norvell Spearman From ramrom@earthling.net Sat Jan 18 17:33:01 2003 From: ramrom@earthling.net (Bob Gailer) Date: Sat Jan 18 17:33:01 2003 Subject: [Tutor] Python Tutorial rel 2.2.2 - need debug for 4.4. Code example In-Reply-To: <1042923604.1124.1239.camel@localhost.localdomain> Message-ID: <5.2.0.9.0.20030118153125.02757f48@66.28.54.253> --=======69725E0C======= Content-Type: text/plain; x-avg-checked=avg-ok-B74577E; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit Change the indentation of the last 2 lines: for n in range( 2, 10 ): for x in range( 2, n ): if n % x == 0: print n, 'equals', x, '*', n/x break else: print n, 'is a prime number.' At 10:09 PM 1/18/2003 +0000, ahimsa wrote: >Could someone help me to understand - and even debug - the following. >for n in range( 2, 10 ): > for x in range( 2, n ): > if n % x == 0: > print n, 'equals', x, '*', n/x > break > else: > print n, 'is a prime number.' > >3 is a prime number. >4 equals 2 * 2 >5 is a prime number. >5 is a prime number. >5 is a prime number. >6 equals 2 * 3 >7 is a prime number. >7 is a prime number. >7 is a prime number. >7 is a prime number. >7 is a prime number. >8 equals 2 * 4 >9 is a prime number. >9 equals 3 * 3 Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======69725E0C======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-B74577E Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.438 / Virus Database: 246 - Release Date: 1/7/2003 --=======69725E0C=======-- From norvell@houseofspearman.org Sat Jan 18 17:34:41 2003 From: norvell@houseofspearman.org (Norvell Spearman) Date: Sat Jan 18 17:34:41 2003 Subject: [Tutor] Python Tutorial rel 2.2.2 - need debug for 4.4. Code example In-Reply-To: <1042923604.1124.1239.camel@localhost.localdomain> References: <1042923604.1124.1239.camel@localhost.localdomain> Message-ID: <20030118223353.GA4890@houseofspearman.org> That wasn't really nice of me. First off, moving the break statement comes back saying that 9 is prime. Secondly, according to the documentation, break is for exiting out of the nearest enclosing while or for loop, so it shouldn't really matter where the break is --- that is, after the if or after the else. I should have let someone else answer that; sorry. -- Norvell Spearman From norvell@houseofspearman.org Sat Jan 18 17:43:01 2003 From: norvell@houseofspearman.org (Norvell Spearman) Date: Sat Jan 18 17:43:01 2003 Subject: [Tutor] Python Tutorial rel 2.2.2 - need debug for 4.4. Code example In-Reply-To: <1042923604.1124.1239.camel@localhost.localdomain> References: <1042923604.1124.1239.camel@localhost.localdomain> Message-ID: <20030118224138.GB4890@houseofspearman.org> On Saturday, 2003.01.18, 22:09:53 +0000, ahimsa wrote: > Hello all > > Could someone help me to understand - and even debug - the following. It > is verbatim of 4.4 of the Python Tutorial Release 2.2.2 - the section on > 'More Control Flow Loops'. Looking back at the tutorial, the code is indented correctly. When I first tried it, I typed in your code verbatim and thus got the same behavior. -- Norvell Spearman From magnus@thinkware.se Sat Jan 18 18:20:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Sat Jan 18 18:20:02 2003 Subject: [Tutor] Database driven web sites with python In-Reply-To: <20030118191253.581.1@.1042911554.fake> References: <20030118170006.7840.1710.Mailman@mail.python.org> <20030118170006.7840.1710.Mailman@mail.python.org> Message-ID: <5.1.0.14.0.20030118224645.02beb2f0@www.thinkware.se> At 19:12 2003-01-18 +0100, Charlie Clark wrote: >I've just looked at some of the CherryPy documentation. I don't think it >would be for me (too much code mixed in the HTML) which isn't to say its >bad!!! *I* think mixing HTML and code is typically bad, but having looked at a lot of stuff, CherryPy is the package I like best in this field. You CAN mix HTML and code, although in a fairly clean way, but you don't have to, just forget the masks, and use views that read in HTML files with your CHTL tags. This is certainly a better way of working if HTML content is produced by someone who is not a programmer. In the simplest case just use something like: view: def index(self): return file('index.html').read() In many real cases I'd let HTML writers write complete HTML files, but then I'd place the "meat" of that file in a different context. Something like: view: def index(self): raw = file('index.html').read() bodyPattern = re.compile(r'(.*)', re.DOTALL) body = bodyPattern.findall(raw)[0] return self.makePage('index', body) where self.makePage would contain something like def makePage(pageName, content) return '%s%s%s' % (self.getHeader(pageName), content, self.getFooter()) Another good thing is that it's fairly small. This means that there are not so many concepts that have to be mastered at once. It also fits in the way I want to work, assembling small components that follow the old unix tenet of doing one thing and doing it well. WebWare for instance tries to be a web tool, a maiddleware and a lot of other things as well. This means that I get in trouble if I want to move my app from a web UI to a GUI or if I decide that one of the components don't quite fit. Another thing I like with CherryPy is the templating language CHTL which puts all the dynamic data in attributes. This means that the guy who writes HTML can use sample data in his files, and see what the page will look like in a web browser without running the application. He can simply open his HTML file in Mozilla or whatever. When it's running in the application, his sample data will be replaced by live data. The attributes can also survive most HTML editors, so an HTML file can go back and forth between HTML writer and Python coder without things getting messed up. (Unless the HTML writer is stupid enough to erase those funny attributes like py-eval that he doesn't understand, but he won't see them in WYSIWYG mode...) What I dislike a bit, is that it's a python pre processor. What you write is almost Python, and it slightly violates python syntax, although that is only in very specific locations. If I remember correctly, there are also stricter rules on whitespace in CherryPy, but I'm sure that could be fixed fairly easily if someone really cared. A more serious problem is that as far as I understand it has to be run like a long running process, and I don't always have the ability to set up such processes on web sites I work with. >Marcus' objection Who's Marcus? ;) >about storage is now only partly true. You can now have >stuff saved in files or CVS though none of the solutions are entirely >stable. Right... As in "Except that it doesn't work, how do you like this software?" ;) >I really like being able (re)organise parts of the site as it >develops: Zope is quite nice when you change things and I've become a big >fan of PageTemplates. But it has all taken time. Expect to need about 6 >weeks before feeling comfortable with Zope I always gave up faster than that every time I tried. :( Other Zope critisism can be found at http://www.amk.ca/python/writing/why-not-zope.html >because it is an application >server and can be compared with the big boys. If you enjoy working on >source then you might enjoy joining in Zope 3 development which is going to >tidy up a lot of the things that have been put in over time. That's what I'm waiting for. Well, I'll probably wait for 3.1... For the past two years, I've used the object database in Zope, ZODB, and it's served us well I think. >You might also want to look at the eGenix Web Application server. >http://www.egenix.com/ >It has rock-solid database support and a nice approach to embedding Python >code in HTML and will have excellent web service support. You mean if he wants to buy a service from Guru Lemburg? Or is that available some other way? "We currently do not market the eGenix Application Server as stand-alone product. It is only available as part of solutions we provide to our customers, such as the Siena Web Service Architecture where it is used for the server side implementation of the service engine." -- 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@thinkware.se Sat Jan 18 18:35:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Sat Jan 18 18:35:01 2003 Subject: [Tutor] Python Tutorial rel 2.2.2 - need debug for 4.4. Code example In-Reply-To: <1042923604.1124.1239.camel@localhost.localdomain> Message-ID: <5.1.0.14.0.20030119002442.02ac58f8@www.thinkware.se> At 22:09 2003-01-18 +0000, ahimsa wrote: >Could someone help me to understand - and even debug - the following. It >is verbatim of 4.4 of the Python Tutorial Release 2.2.2 No, it's not! ;) > >>> for n in range( 2, 10 ): > for x in range( 2, n ): > if n % x == 0: > print n, 'equals', x, '*', n/x > break > else: > print n, 'is a prime number.' As Bob pointed out, you have indented the last two lines one step too much. I can understand this, since no other languages I know of have for-else or while-else loops. I'm not sure it was a wise choice to put that feature in Python since it's so odd. It's no problem once you are used to it, and it's useful now and then, and certainly, if-statement are very much like one-pass loops ;), but it might well confuse people to begin with...as it did here... I can only suggest that you read the section headings more carefully the next time: "4.4 break and continue Statements, and else Clauses on Loops" The text just before the code is also a hint... Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement. This is exemplified by the following loop, which searches for prime numbers: -- 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 antoneheyward@hotmail.com Sat Jan 18 19:56:44 2003 From: antoneheyward@hotmail.com (antone heyward) Date: Sat Jan 18 19:56:44 2003 Subject: [Tutor] wxpython memory usage Message-ID: how can i have wxpython not use as much memory? tkinter seems to use 2x less but i wanted to move over to using wxpython. Or is this out of my control? _________________________________________________________________ Add photos to your e-mail with MSN 8. Get 2 months FREE*. http://join.msn.com/?page=features/featuredemail From mongo57a@comcast.net Sat Jan 18 21:05:14 2003 From: mongo57a@comcast.net (andy surany) Date: Sat Jan 18 21:05:14 2003 Subject: [Tutor] Formatter Message-ID: <005701c2bf5f$55a0e000$2502a8c0@emily.ewndsr01.nj.comcast.net> I learned from this example as well.... Thanks!! I noticed that the format of each field is right justified. How would you make it left justified? Andy -----Original Message----- From: Pete Versteegen To: Bob Gailer ; Tutor@python.org Date: Saturday, January 18, 2003 2:46 PM Subject: Re: [Tutor] Formatter >Sorry about the last message (without a comment) > >Thanks for your responses. They're very helpful.. This also shows agian the >flexibility and versatility of Python. Yes definitely easier to learn than >C++! > > > >Pete Versteegen >pversteegen@gcnetmail.net >__________________________ > > > >On 1/18/03 12:42 PM, "Bob Gailer" wrote: > >> At 11:05 AM 1/18/2003 -0500, Pete Versteegen wrote: >>> Does anyone know of an easy way to format a mixture of floats, integers, >>> spaces, and text in well arranged columns? >>> >>> My thoughts wander towards the way the Fortran language does it. I'm >>> considered a function (class) that would be called as follows: >>> format((a, alf, i), "f10.2, a10, 10x, i5") >> >> def format(values, format): >> formatlist = format.split(',') >> sf = '' >> for formatitem in formatlist: >> type = formatitem[0] >> if type in 'fi': >> sf += '%' + formatitem[1:] + type >> if type == 'a': >> sf += ' '*int(formatitem[1:]) >> elif formatitem[-1] == 'x': >> sf += '%' + formatitem[:-1] + 's' >> return sf % values >> a = 5 >> alf = 'qwer' >> i = 3 >> print format((a, alf, i), "f10.2,a10,10x,i5") >> >> result: 5.00 qwer 3 >> >> For simplicity I removed the spaces between the fortran format items. A >> little more code would handle them. >> >> Bob Gailer >> mailto:ramrom@earthling.net >> 303 442 2625 >> >> >> --- >> Outgoing mail is certified Virus Free. >> Checked by AVG anti-virus system (http://www.grisoft.com). >> Version: 6.0.438 / Virus Database: 246 - Release Date: 1/7/2003 >> > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From Don Arnold" Message-ID: <0bf501c2bf70$29ed38d0$19d1b241@defaultcomp> ----- Original Message ----- From: "andy surany" To: "Pete Versteegen" ; "Bob Gailer" ; Sent: Saturday, January 18, 2003 8:06 PM Subject: Re: [Tutor] Formatter > I learned from this example as well.... Thanks!! > > I noticed that the format of each field is right justified. How would > you make it left justified? > > Andy This lets you prepend '-' to the specifier to left justify the field. I swapped the format string and values arguments so you don't need to specify the values in a tuple.I also flipped the function of the 'a' and 'x' specifiers so they match the original specification: def format(format, *values): formatlist = format.split(',') sf = '' for formatitem in formatlist: if formatitem[0] == '-': leftjust = 1 formatitem = formatitem[1:] else: leftjust = 0 type = formatitem[0] if type in 'fi': sf += '%' + (leftjust * '-') + formatitem[1:] + type if type == 'a': sf += '%' + (leftjust * '-') + formatitem[1:] + 's' elif formatitem[-1] == 'x': sf += ' '*int(formatitem[:-1]) return sf % values a = 5 alf = 'qwer' i = 3 print '------------------------------------------------' print format("f10.2,a10,10x,i5",a,alf,i) print format("-f10.2,-a10,10x,-i5",a,alf,i) print '12345678901234567890123456789012345 RULER LINE' [script run (looks bad without a fixed-width font):] ------------------------------------------------ 5.00 qwer 3 5.00 qwer 3 12345678901234567890123456789012345 RULER LINE HTH, Don P.S. Big thanks to Bob! I never would've been able to come up with his original code on my own. From mongo57a@comcast.net Sat Jan 18 23:56:08 2003 From: mongo57a@comcast.net (andy surany) Date: Sat Jan 18 23:56:08 2003 Subject: [Tutor] Formatter Message-ID: <006801c2bf77$3056bf00$2502a8c0@emily.ewndsr01.nj.comcast.net> That worked..... however, maybe it's just me..., but I thought that "a10" would yield a "block" of 10 spaces for the alpha. I find that in my implementation, I have more than 10 - and according to your ruler, I think you do as well...... Andy -----Original Message----- From: Don Arnold To: andy surany ; Pete Versteegen ; Bob Gailer ; Tutor@python.org Date: Saturday, January 18, 2003 11:08 PM Subject: Re: [Tutor] Formatter > >----- Original Message ----- >From: "andy surany" >To: "Pete Versteegen" ; "Bob Gailer" >; >Sent: Saturday, January 18, 2003 8:06 PM >Subject: Re: [Tutor] Formatter > > >> I learned from this example as well.... Thanks!! >> >> I noticed that the format of each field is right justified. How would >> you make it left justified? >> >> Andy > >This lets you prepend '-' to the specifier to left justify the field. I >swapped the format string and values arguments so you don't need to specify >the values in a tuple.I also flipped the function of the 'a' and 'x' >specifiers so they match the original specification: > >def format(format, *values): > formatlist = format.split(',') > sf = '' > for formatitem in formatlist: > if formatitem[0] == '-': > leftjust = 1 > formatitem = formatitem[1:] > else: > leftjust = 0 > > type = formatitem[0] > > if type in 'fi': > sf += '%' + (leftjust * '-') + formatitem[1:] + type > if type == 'a': > sf += '%' + (leftjust * '-') + formatitem[1:] + 's' > elif formatitem[-1] == 'x': > sf += ' '*int(formatitem[:-1]) > > return sf % values > >a = 5 >alf = 'qwer' >i = 3 >print '------------------------------------------------' >print format("f10.2,a10,10x,i5",a,alf,i) >print format("-f10.2,-a10,10x,-i5",a,alf,i) >print '12345678901234567890123456789012345 RULER LINE' > > >[script run (looks bad without a fixed-width font):] >------------------------------------------------ > 5.00 qwer 3 >5.00 qwer 3 >12345678901234567890123456789012345 RULER LINE > > >HTH, >Don > >P.S. Big thanks to Bob! I never would've been able to come up with his >original code on my own. > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From Don Arnold" Message-ID: <0c0c01c2bf7a$6126c000$19d1b241@defaultcomp> ----- Original Message ----- From: "andy surany" To: "Don Arnold" ; "Pete Versteegen" ; "Bob Gailer" ; Sent: Saturday, January 18, 2003 10:56 PM Subject: Re: [Tutor] Formatter > That worked..... however, maybe it's just me..., but I thought that > "a10" would yield a "block" of 10 spaces for the alpha. I find that in > my implementation, I have more than 10 - and according to your ruler, I > think you do as well...... > > Andy Hmmm... I don't think so. From Pete's original post: ''' My thoughts wander towards the way the Fortran language does it. I'm considered a function (class) that would be called as follows: format((a, alf, i), "f10.2, a10, 10x, i5") This would print the three items in the tuple according to the specifactions listed between the quote marks, whee f10.2 (float, 10 wide, 2 digits after decimal point) a10 (alpha number of 10 wide 10x (1o blank spaces) i5 (integer of 5 digits wide) ''' Bob's code had 'a' being used to specify spaces and 'x' used for strings. I switched their meanings back to match what Pete had said. When I execute 'print format("-f10.2,-a10,10x,-i5", 5, 'qwer', 3)' in Idle, I get: '5.00' followed by 6 spaces (width of 10 bytes total) 'qwer' followed by 6 spaces (10 bytes) 10 spaces (10 bytes) '3' followed by 4 spaces (5 bytes) Looks okay to me. Don From mongo57a@comcast.net Sun Jan 19 00:51:02 2003 From: mongo57a@comcast.net (andy surany) Date: Sun Jan 19 00:51:02 2003 Subject: [Tutor] Formatter Message-ID: <007501c2bf7e$b2199240$2502a8c0@emily.ewndsr01.nj.comcast.net> You're right; I'm wrong. Might help if I didn't put spaces between my format descriptors...... Thanks again. -----Original Message----- From: Don Arnold To: andy surany ; Pete Versteegen ; Bob Gailer ; Tutor@python.org Date: Sunday, January 19, 2003 12:20 AM Subject: Re: [Tutor] Formatter > >----- Original Message ----- >From: "andy surany" >To: "Don Arnold" ; "Pete Versteegen" >; "Bob Gailer" ; > >Sent: Saturday, January 18, 2003 10:56 PM >Subject: Re: [Tutor] Formatter > > >> That worked..... however, maybe it's just me..., but I thought that >> "a10" would yield a "block" of 10 spaces for the alpha. I find that in >> my implementation, I have more than 10 - and according to your ruler, I >> think you do as well...... >> >> Andy > >Hmmm... I don't think so. From Pete's original post: > >''' >My thoughts wander towards the way the Fortran language does it. I'm >considered a function (class) that would be called as follows: >format((a, alf, i), "f10.2, a10, 10x, i5") >This would print the three items in the tuple according to the specifactions >listed between the quote marks, whee >f10.2 (float, 10 wide, 2 digits after decimal point) >a10 (alpha number of 10 wide >10x (1o blank spaces) >i5 (integer of 5 digits wide) >''' > >Bob's code had 'a' being used to specify spaces and 'x' used for strings. I >switched their meanings back to match what Pete had said. > >When I execute 'print format("-f10.2,-a10,10x,-i5", 5, 'qwer', 3)' in Idle, >I get: > >'5.00' followed by 6 spaces (width of 10 bytes total) >'qwer' followed by 6 spaces (10 bytes) >10 spaces (10 bytes) >'3' followed by 4 spaces (5 bytes) > >Looks okay to me. > >Don > > > > > From carroll@tjc.com Sun Jan 19 02:23:01 2003 From: carroll@tjc.com (Terry Carroll) Date: Sun Jan 19 02:23:01 2003 Subject: [Tutor] Differences between Python 2.2 and 1.5? Message-ID: On my home system, I have Python 2.2.2 (November 2002) installed. My ISP has, on its most current system, Python 1.5.2 (July 2001). I'm a new and casual Python user, just writing a few prgrams for my own use, and am wondering if there are any differences a casual user would run into between 1.5.2 and 2.2.2. If so, I'll ask them to upgrade. I don't think many on my ISP use Python, and quite frankly, our sysadmin is a busy and highly competent guy, and I don't want to unnecessarily take his time away from other projects he's working on. (Older systems being phased out have Python 1.3 (June 1996) installed! I wouldn't ask for an upgrade on those; the appropriate response would be to do my Python work on a different machine, or install it myself in my own space (which I may do anyway)). -- Terry Carroll | Santa Clara, CA | "The parties are advised to chill." carroll@tjc.com | - Mattel, Inc. v. MCA Records, Inc., Modell delendus est | no. 98-56577 (9th Cir. July 24, 2002) From tony@tcapp.com Sun Jan 19 03:45:02 2003 From: tony@tcapp.com (Tony Cappellini) Date: Sun Jan 19 03:45:02 2003 Subject: [Tutor] raw_input() seems to cause minor text mis-alignment Message-ID: <5.1.0.14.0.20030119005247.01ab4338@smtp.sbcglobal.net> --=====================_95918393==_.ALT Content-Type: text/plain; charset="us-ascii"; format=flowed The program below is exhibiting a 1 character text alignment problem. When I remove the call to raw_input(), I don't have the alignment problem. Can anyone explain why this happens ? import os os.system('cls') count=0 print"\nText printed outside the loop is aligned ok.\n" while( count < 3 ): print"Text printed inside the loop if offset by 1 space. WHY ?", raw_input() count=count+1 ################################################################################################ # program output Text printed outside the loop is aligned ok. Text printed inside the loop if offset by 1 space. WHY ? Text printed inside the loop if offset by 1 space. WHY ? Text printed inside the loop if offset by 1 space. WHY ? --=====================_95918393==_.ALT Content-Type: text/html; charset="us-ascii"

The program below is exhibiting a 1 character text alignment problem.
When I remove the call to raw_input(), I don't have the alignment problem.

Can anyone explain why this happens ?



import os
os.system('cls')

count=0
print"\nText printed outside the loop is aligned ok.\n"
while( count < 3 ):
    print"Text printed inside the loop if offset by 1 space. WHY ?",
    raw_input()
    count=count+1

################################################################################################
# program output

Text printed outside the loop is aligned ok.

Text printed inside the loop if offset by 1 space. WHY ?
 Text printed inside the loop if offset by 1 space. WHY ?
 Text printed inside the loop if offset by 1 space. WHY ?
--=====================_95918393==_.ALT-- From magnus@thinkware.se Sun Jan 19 04:38:47 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Sun Jan 19 04:38:47 2003 Subject: [Tutor] raw_input() seems to cause minor text mis-alignment In-Reply-To: <5.1.0.14.0.20030119005247.01ab4338@smtp.sbcglobal.net> Message-ID: <5.1.0.14.0.20030119103500.00be6980@www.thinkware.se> At 00:53 2003-01-19 -0800, Tony Cappellini wrote: >print"\nText printed outside the loop is aligned ok.\n" >while( count < 3 ): > print"Text printed inside the loop if offset by 1 space. WHY ?", Don't know why raw_input puts a space on stdout after you press enter, but you can easily work around it by starting your printed string with a carriage return, to get it back to the start of the line. I.e. print "\rText printed inside the loop is NOT offset by 1 space.", > raw_input() > count=count+1 -- 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@thinkware.se Sun Jan 19 05:07:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Sun Jan 19 05:07:01 2003 Subject: [Tutor] Differences between Python 2.2 and 1.5? In-Reply-To: Message-ID: <5.1.0.14.0.20030119103808.029b23b0@www.thinkware.se> At 23:22 2003-01-18 -0800, Terry Carroll wrote: >I'm a new and casual Python user, just writing a few prgrams for my own >use, and am wondering if there are any differences a casual user would run >into between 1.5.2 and 2.2.2. If so, I'll ask them to upgrade. I don't >think many on my ISP use Python, and quite frankly, our sysadmin is a busy >and highly competent guy, and I don't want to unnecessarily take his time >away from other projects he's working on. First of all a warning. Don't use 1.6 at all, it's broken. 1.5.2 was a stable and good version. There are a number of changes made since then though. A major one is string methods introduced in 1.6, which means that you can write "hello world".upper() instead of import string string.upper("hello world") Some other big changes: * Unicode support * XML support * distutils - standard for installing 3rd party python packages * nested scopes - useful if you use nested functions or lambdas * class/type merge - now you can subclass int, string etc. * changed division - 5 / 2 => 2.5 if you do "from __future__ import division" * List comprehension - as in l = [int(x) for x in y if x in "0123456789"] * Improved garbage collection - No more worry about cycles. * Augmented assignment - x += 5 etc. See: http://www.python.org/1.6.1/ http://www.amk.ca/python/2.0/ http://www.amk.ca/python/2.1/ http://www.python.org/doc/2.2.1/whatsnew/ You can certainly do a lot of good things in 1.5.2 but it seems a bit silly if you can't use several years of python improvements. And many third party packages no longer support 1.5.2. This means that you might download some module that does something you find useful, just to discover that you can't use it. If you could get all your plaforms up to 2.2.2, it's a good thing. After all, 1.5.2 is fairly old, and not even Red Hat stick to it any longer... If your ISP is running a non-current Red Hat, they need to have 1.5.2 as /usr/bin/python. Then they can have (might already have?) a newer python installed as /usr/bin/python2. Perhaps you should check that? -- 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 ahimsa@onetel.net.uk Sun Jan 19 05:09:02 2003 From: ahimsa@onetel.net.uk (ahimsa) Date: Sun Jan 19 05:09:02 2003 Subject: [Tutor] Python Tutorial rel 2.2.2 - need debug for 4.4. Code example In-Reply-To: <5.1.0.14.0.20030119002442.02ac58f8@www.thinkware.se> References: <5.1.0.14.0.20030119002442.02ac58f8@www.thinkware.se> Message-ID: <1042971073.2523.4.camel@localhost.localdomain> On Sat, 2003-01-18 at 23:33, Magnus Lycka wrote: > No, it's not! ;) > Magnus - you are right!! Thanks. I think what had happened is two things: 1. as you suggested, I hadn't anticipated an 'else' to be coupled with a 'for' and just really didn't look at it; and 2. allowed the auto-indent of my interpreter to control the amount of white-space allocated to the else which - understandably enough - aligned it with the 'if' block, and because (I have printed the Tut out) the code runs over 2 pages I didn't bother to check the alignment with the print out either. Two lessons from this: 1. While it might be wise to work towards being a lazy programmer, it is NOT wise to be careless one 2. When in doubt - ask: my eyes just couldn't pick it up, so thanks. Have changed the indenting and all works fine ... :) All the best Andrew > > >>> for n in range( 2, 10 ): > > for x in range( 2, n ): > > if n % x == 0: > > print n, 'equals', x, '*', n/x > > break > > else: > > print n, 'is a prime number.' > > As Bob pointed out, you have indented the last two lines > one step too much. I can understand this, since no other > languages I know of have for-else or while-else loops. I'm > not sure it was a wise choice to put that feature in Python > since it's so odd. It's no problem once you are used to it, > and it's useful now and then, and certainly, if-statement > are very much like one-pass loops ;), but it might well > confuse people to begin with...as it did here... > > I can only suggest that you read the section headings more > carefully the next time: > > "4.4 break and continue Statements, and else Clauses on Loops" > > The text just before the code is also a hint... > > Loop statements may have an else clause; it is executed when the > loop terminates through exhaustion of the list (with for) or when > the condition becomes false (with while), but not when the loop > is terminated by a break statement. This is exemplified by the > following loop, which searches for prime numbers: -- ahimsa From magnus@thinkware.se Sun Jan 19 05:12:04 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Sun Jan 19 05:12:04 2003 Subject: [Tutor] Formatter In-Reply-To: <005701c2bf5f$55a0e000$2502a8c0@emily.ewndsr01.nj.comcast.n et> Message-ID: <5.1.0.14.0.20030119110643.02ac9440@www.thinkware.se> At 21:06 2003-01-18 -0500, andy surany wrote: >I noticed that the format of each field is right justified. How would >you make it left justified? It might be more effective to read the library reference http://www.python.org/doc/current/lib/typesseq-strings.html instead of asking questions here for these normal features that are well described in the documents. You will probably find additional information you didn't think of asking about, but will find very useful. I've said it before, and I'll say it again. Chapter 2 of the library ref http://www.python.org/doc/current/lib/builtin.html is very useful. Read through it now and then. -- 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 charlie@begeistert.org Sun Jan 19 06:31:40 2003 From: charlie@begeistert.org (Charlie Clark) Date: Sun Jan 19 06:31:40 2003 Subject: [Tutor] Database driven web sites with python In-Reply-To: <5.1.0.14.0.20030118224645.02beb2f0@www.thinkware.se> References: <20030118170006.7840.1710.Mailman@mail.python.org> <20030118170006.7840.1710.Mailman@mail.python.org> <5.1.0.14.0.20030118224645.02beb2f0@www.thinkware.se> Message-ID: <20030119123004.618.1@.1042971159.fake> On 2003-01-19 at 00:19:27 [+0100], Magnus Lycka wrote: > *I* think mixing HTML and code is typically bad, but having looked I think it's important to menation why it's bad: it takes a while to focus your mind on the important bit and separate code from HTML. > Another thing I like with CherryPy is the templating language CHTL which > puts all the dynamic data in attributes. This means that the guy who > writes HTML can use sample data in his files, and see what the page will > look like in a web browser without running the application. He can simply > open his HTML file in Mozilla or whatever. When it's running in the > application, his sample data will be replaced by live data. The > attributes can also survive most HTML editors, so an HTML file can go > back and forth between HTML writer and Python coder without things > getting messed up. (Unless the HTML writer is stupid enough to erase > those funny attributes like py-eval that he doesn't understand, but he > won't see them in WYSIWYG mode...) This is the same as Zope Page Templates. However, you are able to use proper Python functions in ZPT:
Statements have to be put in PythonScripts and this works very well once you get used to it. Using xHTML namespaces to do this seems to be standard practice now as well for "tag libraries" in JSP and .NET Works great with the Zope External Editor > A more serious problem is that as far as I understand it has to be run > like a long running process, and I don't always have the ability to set > up such processes on web sites I work with. pcgi? It's probably possible to run it inside the webserver via redirection just like it is with Zope. > >Marcus' objection > Who's Marcus? ;) Magnus, verlaat me! > Right... As in "Except that it doesn't work, how do you like this > software?" ;) No, as in none of the products has been declared stable. "Adaptable storage" looks very promising and seeing as it's been developed by Shane Hathaway of Zope Corp., looks like it may well make it. One of the aims of Zope 3 is to have better support for this kind of thing. > >I really like being able (re)organise parts of the site as it develops: > >Zope is quite nice when you change things and I've become a big fan of > >PageTemplates. But it has all taken time. Expect to need about 6 weeks > >before feeling comfortable with Zope > > I always gave up faster than that every time I tried. :( I can understand that. But once I'd done the built-in tutorial I was in a better position to start. I have the advantage of being able to compare with it with several content management systems and know that they're no better. I've really learned a lot about Zope over the last couple of months haveing started on a very simple project which has continually grown. > Other Zope critisism can be found at > http://www.amk.ca/python/writing/why-not-zope.html Yes, Andrew makes some good points. > That's what I'm waiting for. Well, I'll probably wait for 3.1... I wish I was good enuff at programming to make a contribution. Maybe by 4.x... > >You might also want to look at the eGenix Web Application server. > >http://www.egenix.com/ > >It has rock-solid database support and a nice approach to embedding > >Python code in HTML and will have excellent web service support. > > You mean if he wants to buy a service from Guru Lemburg? Or is that > available some other way? oh, I've got the documentation and I think it should be commercially available at some point. I thought it was only fair to mention a commercial product. Separation of code and HTML in eGenix is quite good. Charlie From churmtom@hotmail.com Sun Jan 19 08:58:02 2003 From: churmtom@hotmail.com (Tom Churm) Date: Sun Jan 19 08:58:02 2003 Subject: [Tutor] Trying to Learn OOP via Boa Constructor Message-ID: familiar story: guy starts learning python, finds it pretty easy. guy starts learning gui programming in python. guy discovers that it's--finally!--time to learn OOP..which is, uh, suddenly not so easy. since i'm impatient, i started experimenting with Boa Constructor (perhaps a bad idea so early, i know). now i've hit a roadblock, which i know has an easy solution. i just have to modify my initialization function-- main( ) --below to get the thing to run: ############################# #!/usr/bin/env python #Boa:PyApp:main modules ={'wxDialog1': [0, '', 'wxDialog1.py'], 'wxFrame1': [0, '', 'wxFrame1.py']} def main(): pass if __name__ == '__main__': main() ############################# if my main frame-creation function in wxFrame1.py looks like this, how do i replace the 'pass' statement above to call this function, thus creating the main frame in wxPython? ############################# def create(parent): return wxFrame1(parent) ... ############################# i know i have to replace 'pass' in the first code snippet with something like: create(?) but what parameter do i feed this function with for 'parent' (ie: the question mark above)? thanks for the help! --tom From nicholas_wieland@yahoo.it Sun Jan 19 10:41:18 2003 From: nicholas_wieland@yahoo.it (Nicholas Wieland) Date: Sun Jan 19 10:41:18 2003 Subject: [Tutor] GUI design Message-ID: <20030119022350.GA10684@localhost> Hello, I'd like some comments and suggestions about my design: personally I think it's quite horrible and I'm sure it comes from all the bad habits I learned using C and GTK+ (BTW: I _love_ GTK+, but it's *so* different...). I'm using wxPython 2.4.0.1, but I don't think it's important. I want my classes to be rausable and *clean*. from wxPython.wx import * from wxPython.lib.wxPlotCanvas import * class App( wxApp ): def OnInit( self ): frame = Frame() frame.Show( 1 ) self.SetTopWindow( frame ) return 1 class Frame( wxFrame ): def __init__( self ): wxFrame.__init__( self, None, -1, "ToolBar" ) ID_ENTER_M = wxNewId() ID_EXIT_M = wxNewId() ID_ENTER_T = wxNewId() menu_bar = wxMenuBar() menu_bar.Append( self.G_FileMenu( ID_ENTER_M, ID_EXIT_M ), "&File" ); self.SetMenuBar( menu_bar ) self.G_ToolBox( ID_ENTER_T ) def G_FileMenu( self, ID_ENTER_M, ID_EXIT_M ): menu_file = wxMenu() menu_file.Append( ID_ENTER_M, "&Enter...", "Enter a measure" ) EVT_MENU( self, ID_ENTER_M, self.OnEnter ) menu_file.AppendSeparator() menu_file.Append( ID_EXIT_M, "E&xit", "Exit application" ) EVT_MENU( self, ID_EXIT_M, self.OnExit ) return menu_file def G_ToolBox( self, ID_ENTER_T ): tb = self.CreateToolBar( wxTB_HORIZONTAL| wxNO_BORDER|wxTB_FLAT ) meter_icon = wxBitmap( "meter.xpm", wxBITMAP_TYPE_XPM ) tb.AddSimpleTool( ID_ENTER_T, meter_icon, "Enter...", "Enter a measure..." ) EVT_TOOL( self, ID_ENTER_T, self.OnEnter ) tb.Realize() def OnEnter( self, event ): mf = wxMiniFrame( self, -1, "Enter record", pos = wxDefaultPosition, size = wxSize( 140, 120 ), style = wxDEFAULT_FRAME_STYLE ) mf.Show( 1 ) def OnExit( self, event ): self.Close( 1 ) app = App( 0 ) app.MainLoop() As you can see I don't like having a lot of stuff in __init__, so I tried to make the class more modular... but I'm obviously wrong, this code IS NOT reusable, G_ToolBox and G_FileMenu are a big nonsense. I'm a little lost :) Every comment, suggestion, pointers to 'state of the art' code, flame-war and *PLONK* is greatly appreciated. TIA, Nicholas From pversteegen@gcnetmail.net Sun Jan 19 10:50:07 2003 From: pversteegen@gcnetmail.net (Pete Versteegen) Date: Sun Jan 19 10:50:07 2003 Subject: [Tutor] Formatter In-Reply-To: <0c0c01c2bf7a$6126c000$19d1b241@defaultcomp> Message-ID: Thanks folks for helping me on the formatter issue! That gives me a great start and it showed me how to solve problems of this nature with Python. There are a couple of other field descriptors that I would like to incorporate, e.g., exponential notation, 1.2345e-01, and octal representation, and creating records that are subsequently written to other files. I enjoy reading the questions and answers and rebuttals on the list. Pete pversteegen@gcnetmail.net __________________________ From darnold02@sprynet.com Sun Jan 19 11:26:01 2003 From: darnold02@sprynet.com (Don Arnold) Date: Sun Jan 19 11:26:01 2003 Subject: [Tutor] Formatter References: Message-ID: <0cfb01c2bfd7$333b18a0$19d1b241@defaultcomp> ----- Original Message ----- From: "Pete Versteegen" To: "Don Arnold" ; Cc: "andy surany" Sent: Sunday, January 19, 2003 9:49 AM Subject: Re: [Tutor] Formatter > > Thanks folks for helping me on the formatter issue! That gives me a great > start and it showed me how to solve problems of this nature with Python. > There are a couple of other field descriptors that I would like to > incorporate, e.g., exponential notation, 1.2345e-01, and octal > representation, and creating records that are subsequently written to other > files. I enjoy reading the questions and answers and rebuttals on the list. > While seeing how to decode a 'roll your own' format string is an interesting exercise, we definitely are reinventing the wheel here. All this code really does is translate your format specifier scheme into Python's own. As Magnus pointed out, you really should take a look at http://www.python.org/doc/current/lib/typesseq-strings.html . It lists all of the string formatting specifiers that Python uses. scientific notation: >>> '%20.5e' % .045678957 ' 4.56790e-002' octal: >>> '%10o' % 4096 ' 10000' > > Pete > pversteegen@gcnetmail.net HTH, Don From magnus@thinkware.se Sun Jan 19 11:29:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Sun Jan 19 11:29:02 2003 Subject: [Tutor] Database driven web sites with python In-Reply-To: <20030119123004.618.1@.1042971159.fake> References: <5.1.0.14.0.20030118224645.02beb2f0@www.thinkware.se> <20030118170006.7840.1710.Mailman@mail.python.org> <20030118170006.7840.1710.Mailman@mail.python.org> <5.1.0.14.0.20030118224645.02beb2f0@www.thinkware.se> Message-ID: <5.1.0.14.0.20030119170348.02aa86f8@www.thinkware.se> At 12:30 2003-01-19 +0100, Charlie Clark wrote: >On 2003-01-19 at 00:19:27 [+0100], Magnus Lycka wrote: > > *I* think mixing HTML and code is typically bad, but having looked >I think it's important to menation why it's bad: it takes a while to foc= us >your mind on the important bit and separate code from HTML. Not only that: Content, Style and Logic are three separate things. It should be possible to deal with these things independently, and by different people. Your project might start small, and grow, and then suddenly you realize that you need to have someone who thinks HTML is a programing language fiddle in your Python code with embedded HTML. Horror... As I see it, it's a big advantage if the content people can just write "documents" without having to worry about technical aspects, and that layout people should be able to design layout in HTML and CSS without understanding the technical implementation or anything about Python. (...code thingies in HTML tag attributes) >This is the same as Zope Page Templates. Yes I think ZPT and CHTL are similar. IIRC I first heard of the concept by someone who tried to "reinvent" ZOPE using this concept and others, but Zope is a huge, monolithic "monster" compared to little CherryPy. (Nothing bad about monsters... Many of my best friends are monsters! ;) > > A more serious problem is that as far as I understand it has to be ru= n > > like a long running process, and I don't always have the ability to s= et > > up such processes on web sites I work with. >pcgi? It's probably possible to run it inside the webserver via redirect= ion >just like it is with Zope. Yes, but you still need to have a long running process to avoid repeated startup delays, right? Even if the communication goes via Apache etc. >Magnus, verlaat me! Sure. Was that dutch? Close to Swedish: "F=F6rl=E5t mig" (For English people, that's pronounced "furLORT may", and means "forgive me".) > > Right... As in "Except that it doesn't work, how do you like this > > software?" ;) >No, as in none of the products has been declared stable. Aha. That can mean anything from vapourware to rock solid. People seem to have very different opinions about when to say: Done! >"Adaptable >storage" looks very promising and seeing as it's been developed by Shane >Hathaway of Zope Corp., looks like it may well make it. One of the aims = of >Zope 3 is to have better support for this kind of thing. As I said, I'll have a look when 3.1 is out. I hope that Zope will "come back" to the rest of the tool chest, so that it's not all a mystery in ZODB... I like ZODB, and I use it a lot, but for data, not for "code". > > I always gave up faster than that every time I tried. :( >I can understand that. But once I'd done the built-in tutorial I was in = a >better position to start. I have the advantage of being able to compare >with it with several content management systems and know that they're no >better. I've really learned a lot about Zope over the last couple of mon= ths >haveing started on a very simple project which has continually grown. I guess I never really NEEDED to use it... We'll see... Maybe my brain backfires one day, and I sign a contract do build a big, dynamic web site. I must say that my user experience with things like Plone etc are not very positive. I prefer MoinMoin every time. --=20 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@thinkware.se Sun Jan 19 11:41:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Sun Jan 19 11:41:02 2003 Subject: [Tutor] Formatter In-Reply-To: References: <0c0c01c2bf7a$6126c000$19d1b241@defaultcomp> Message-ID: <5.1.0.14.0.20030119172905.02cb3d70@www.thinkware.se> At 10:49 2003-01-19 -0500, Pete Versteegen wrote: >There are a couple of other field descriptors that I would like to >incorporate, e.g., exponential notation, 1.2345e-01, and octal >representation, This is also in the library reference. Right? http://www.python.org/doc/current/lib/typesseq-strings.html >and creating records that are subsequently written to other >files. These operations work for all strings. All strings can be written to files. QED. If you want to store data from your python code in files, there are a number of options though. If the objective is to retrieve the data in python programs (others or the same) and not in other systems, I suggest you read Patrick O'Brien's article on persistence at IBM DeveloperWorks. -- 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@thinkware.se Sun Jan 19 12:36:08 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Sun Jan 19 12:36:08 2003 Subject: [Tutor] GUI design In-Reply-To: <20030119022350.GA10684@localhost> Message-ID: <5.1.0.14.0.20030119174422.02c50b58@www.thinkware.se> At 03:23 2003-01-19 +0100, Nicholas Wieland wrote: >Every comment, suggestion, pointers to 'state of the art' code, flame-wa= r=20 >and *PLONK* is greatly appreciated. May I suggest that you never mix tabs with spaces in Python code? I know that my fellow Swede in Link=F6ping, Mr Lundh, likes tabs, but may I suggest four spaces for indentation. Most editors can give you that when you press Tab, and the good ones will remove as much if you press Shift-Tab or backspace. Tabnanny can be used to clean up existing code. Your code was a wee bit tiresome to read due to the messed up indentation. BTW, I find that an empty line between methods also increases readability. (Then I have two empty lines between classes and at some occations empty lines inside larger methods where we obviously go from doing one thing to doing something else. This typically happens in __init__, when I build menues etc. Otherwise, it didn't look too bad I think, but as I said, it was hard to read, so I'm not sure. I've often felt that it should be possible to build both menus and screen layout in a much smarter way, by wrapping things like wxMenu.Append() in functions that just takes some kind of sequence. Then we just write something like: myMenu =3D ( ('&File', ('New', (ALT, 'N'), self.OnFileNew), ('Open', (ALT, 'O'), self.OnFileOpen), ('Close', (ALT, 'C'), self.OnFileClose)), ('%Edit', ('Cut', (CTRL, 'X'), self.OnEditCut), ('Copy', (CTRL, 'C'), self.OnEditCopy), ('Paste', (CTRL, 'V'), self.OnEditPaste))) and then we feed that to some standard method in some kind of mixin class that we can use with Frames etc. --=20 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 carroll@tjc.com Sun Jan 19 13:31:46 2003 From: carroll@tjc.com (Terry Carroll) Date: Sun Jan 19 13:31:46 2003 Subject: [Tutor] Differences between Python 2.2 and 1.5? In-Reply-To: <5.1.0.14.0.20030119103808.029b23b0@www.thinkware.se> Message-ID: On Sun, 19 Jan 2003, Magnus Lycka wrote: > If your ISP is running a non-current Red Hat, they need to have 1.5.2 as > /usr/bin/python. Then they can have (might already have?) a newer python > installed as /usr/bin/python2. Perhaps you should check that? They do! Thanks! -- Terry Carroll | Santa Clara, CA | "The parties are advised to chill." carroll@tjc.com | - Mattel, Inc. v. MCA Records, Inc., Modell delendus est | no. 98-56577 (9th Cir. July 24, 2002) From nicholas_wieland@yahoo.it Sun Jan 19 14:34:01 2003 From: nicholas_wieland@yahoo.it (Nicholas Wieland) Date: Sun Jan 19 14:34:01 2003 Subject: [Tutor] GUI design In-Reply-To: <5.1.0.14.0.20030119174422.02c50b58@www.thinkware.se>; from magnus@thinkware.se on dom, gen 19, 2003 at 18:35:35 +0100 References: <5.1.0.14.0.20030119174422.02c50b58@www.thinkware.se> Message-ID: <20030119191216.GA3580@localhost> On 2003.01.19 18:35 Magnus Lycka wrote: > At 03:23 2003-01-19 +0100, Nicholas Wieland wrote: >> Every comment, suggestion, pointers to 'state of the art' code,=20 >> flame-war and *PLONK* is greatly appreciated. >=20 > May I suggest that you never mix tabs with spaces in Python code? > I know that my fellow Swede in Link=F6ping, Mr Lundh, likes tabs, > but may I suggest four spaces for indentation. Most editors can > give you that when you press Tab, and the good ones will remove > as much if you press Shift-Tab or backspace. I'm really sorry, I cut & paste from Emacs in an x-term and it messed=20 up :( > Tabnanny can be used to clean up existing code. >=20 > Your code was a wee bit tiresome to read due to the messed up > indentation. BTW, I find that an empty line between methods also > increases readability. (Then I have two empty lines between classes > and at some occations empty lines inside larger methods where we > obviously go from doing one thing to doing something else. This > typically happens in __init__, when I build menues etc. Good hints ! Thank you very much. > Otherwise, it didn't look too bad I think, but as I said, it > was hard to read, so I'm not sure. >=20 > I've often felt that it should be possible to build both menus > and screen layout in a much smarter way, by wrapping things like > wxMenu.Append() in functions that just takes some kind of sequence. >=20 > Then we just write something like: >=20 > myMenu =3D ( > ('&File', > ('New', (ALT, 'N'), self.OnFileNew), > ('Open', (ALT, 'O'), self.OnFileOpen), > ('Close', (ALT, 'C'), self.OnFileClose)), > ('%Edit', > ('Cut', (CTRL, 'X'), self.OnEditCut), > ('Copy', (CTRL, 'C'), self.OnEditCopy), > ('Paste', (CTRL, 'V'), self.OnEditPaste))) >=20 > and then we feed that to some standard method in some kind of > mixin class that we can use with Frames etc. It's a really good idea... I'll post the results when I suceed. Ciao, Nicholas From charlie@begeistert.org Sun Jan 19 15:49:02 2003 From: charlie@begeistert.org (Charlie Clark) Date: Sun Jan 19 15:49:02 2003 Subject: [Tutor] Database driven web sites with python In-Reply-To: <5.1.0.14.0.20030119170348.02aa86f8@www.thinkware.se> References: <5.1.0.14.0.20030118224645.02beb2f0@www.thinkware.se> <20030118170006.7840.1710.Mailman@mail.python.org> <20030118170006.7840.1710.Mailman@mail.python.org> <5.1.0.14.0.20030118224645.02beb2f0@www.thinkware.se> <5.1.0.14.0.20030119170348.02aa86f8@www.thinkware.se> Message-ID: <20030119214831.1504.6@.1043004029.fake> > Not only that: Content, Style and Logic are three separate things. It > should be possible to deal with these things independently, and by > different people. This is correct and it's the theory. Most of the projects I have worked on usually involve layouts -> HTML-templates -> CMS-templates + code and it isn't long before a small team is basically doing all the maintenance: design doesn't change that often so you need programmers who know HTML anyway. > Your project might start small, and grow, and then suddenly you realize > that you need to have someone who thinks HTML is a programing language > fiddle in your Python code with embedded HTML. Horror... Agreed particularly as they quite often think HTML is easy. Well, it would be if it wasn't constantly being abused for presentation stuff. > Yes I think ZPT and CHTL are similar. IIRC I first heard of the concept > by someone who tried to "reinvent" ZOPE using this concept and others, > but Zope is a huge, monolithic "monster" compared to little CherryPy. > (Nothing bad about monsters... Many of my best friends are monsters! ;) Have to agree with you on this. Zope really is an application server but it's surprisingly easy to use when you consider that. It's kind of beguiling by the fact that you can get started so quickly with it on to bash your head with permissions and local roles and all kinds other things you never expected to meet. Zope gives you a whole lot including security and scalability. For advances projects of whatever nature you need programmers and the fact that extensions are programmed in Python is an advantage for Zope in comparison with other systems. Python is the secret weapon as Jim Fulton is fond of saying it. > Sure. Was that dutch? Close to Swedish: "F=F6rl=E5t mig" (For English peo= ple, > that's pronounced "furLORT may", and means "forgive me".) Yes, it was and bad Dutch at that. I know how to say f=F6rlaat me (don't have =B0a on my keyboard) but had forgotten how to spell it. Urs=E4kta! Really need to practice my Swedish. > Aha. That can mean anything from vapourware to rock solid. People seem to= > have very different opinions about when to say: Done! Very, very true especially in the realm of free software and really true when it comes to Zope products. > As I said, I'll have a look when 3.1 is out. I hope that Zope will "come > back" to the rest of the tool chest, so that it's not all a mystery in > ZODB... I like ZODB, and I use it a lot, but for data, not for "code". Zope 3 kind of relies on CVS which is probably one of the reasons to expect= improved support. > I guess I never really NEEDED to use it... We'll see... Maybe my brain > backfires one day, and I sign a contract do build a big, dynamic web site= . No, please don't! Leave them to rest of us! ;-) > I must say that my user experience with things like Plone etc are not > very positive. I prefer MoinMoin every time. I can't say I've used either. I know that Plone has received an awful lot of focussed development and has really brought Zope's CMF on a lot - nobody= really seemed to understand what to do with the CMF until Plone started. There are, however, complete CMS based on Zope like torped's Easy Publisher= and I tbink it's important to note here that Zope really shines as a basis for building applications even if it's still a warty monster. I've worked with lots of CMS in my time and yet to see one which makes me say: that does things which Zope never could. But one size *never* fits all. Charlie From carroll@tjc.com Sun Jan 19 15:59:02 2003 From: carroll@tjc.com (Terry Carroll) Date: Sun Jan 19 15:59:02 2003 Subject: [Tutor] Sorting a dictionary in one line? Message-ID: This isn't a practical question; I just want to get a better handle on why something I tried didn't work. I want to print a dictionary, sorted by key. This works: dict = { 'Kate': 'Bush', 'Paul': 'McCartney', 'Debbie': 'Gibson', 'Faye': 'Wong', 'David': 'Bowie', 'Keith': 'Emerson', 'Tori': 'Amos', 'John': 'Lennon', 'Sarah': 'Brightman', 'Jimmy': 'Buffet' } keylist = dict.keys() keylist.sort() for x in keylist: print x, dict[x] In my first attempt, I tried to combine the sort() and keys() calls, right in the for statement, without using a temporary list, and it doesn't work. I tried several variations on a theme, but here's a general idea illustrating what I was attempting: for x in dict.keys().sort(): print x, dict[x] (TypeError: iteration over non-sequence) My questions: 1) Why doesn't this work? If I understand this right, dict.keys() returns a list, and lists have a sort() method, which returns a list, which is a sequence; so why is this an iteration over a non-sequence? 2) Not that it's important to do this in one line, but is it possible? -- Terry Carroll | Santa Clara, CA | "The parties are advised to chill." carroll@tjc.com | - Mattel, Inc. v. MCA Records, Inc., Modell delendus est | no. 98-56577 (9th Cir. July 24, 2002) From carroll@tjc.com Sun Jan 19 16:24:02 2003 From: carroll@tjc.com (Terry Carroll) Date: Sun Jan 19 16:24:02 2003 Subject: [Tutor] Sorting a dictionary in one line? In-Reply-To: Message-ID: On Sun, 19 Jan 2003, Terry Carroll wrote: > 1) Why doesn't this work? If I understand this right, dict.keys() returns > a list, and lists have a sort() method, which returns a list, which is a > sequence; so why is this an iteration over a non-sequence? Okay, I found my flaw here: sort() doesn't return a ListType object -- it returns a NoneType object. Still, out of curiosity: > 2) Not that it's important to do this in one line, but is it possible? Or, put another way, is it possible to operate on an anonymously sorted list (e.g., dict.keys().sort() )? -- Terry Carroll | Santa Clara, CA | "The parties are advised to chill." carroll@tjc.com | - Mattel, Inc. v. MCA Records, Inc., Modell delendus est | no. 98-56577 (9th Cir. July 24, 2002) From magnus@thinkware.se Sun Jan 19 17:14:09 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Sun Jan 19 17:14:09 2003 Subject: [Tutor] Sorting a dictionary in one line? In-Reply-To: Message-ID: <5.1.0.14.0.20030119221850.02c50ca0@www.thinkware.se> At 12:56 2003-01-19 -0800, Terry Carroll wrote: >This isn't a practical question; Right. Since the answer is "you can't". >I just want to get a better handle on why >something I tried didn't work. Sure. >I want to print a dictionary, sorted by key. This works: [Conventional method (why do it differently?) snipped.] >In my first attempt, I tried to combine the sort() and keys() calls, right >in the for statement, without using a temporary list, and it doesn't work. >I tried several variations on a theme, but here's a general idea >illustrating what I was attempting: > >for x in dict.keys().sort(): > print x, dict[x] >1) Why doesn't this work? If I understand this right, dict.keys() returns >a list, and lists have a sort() method, which returns a list, which is a >sequence; so why is this an iteration over a non-sequence? No. .sort() returns None! >>> a = [3,4,2,1] >>> print a.sort() None >>> print a [1, 2, 3, 4] Lists can obviously be very big. For that reason it's important that we are able to perform sorts without having to duplicate the list. Thus .sort() modifies the original list, not a copy of it. The .sort() method could still have had a "return self" in the end as a convenience, but it doesn't. The thing is that if we wrote "sortedList = myList.sort()" it would be very confusing to discover that "myList" had become sorted in the operation. For that reason .sort() returns None. You need to do: sortedList = myList; sortedList.sort() Now there is no ambiguity. >2) Not that it's important to do this in one line, but is it possible? Well, you can write your own function that does this, and call that in one line... :) That function will be more than one logical line though. While I was reading Peter Pan to my son, he added: >Or, put another way, is it possible to operate on an anonymously sorted >list (e.g., dict.keys().sort() )? No. If you do a.b().c().d() etc, the result of this expression will always be the return value of the last operation. To access the result of a.b().c() you need to store that, as in x = a.b().c() x.d() This isn't so bad, is it? If we want to work later with a certain value that pops up in our program, we create a refeence to it, typically by assigning a variable. But it might seem a little odd that it's permitted to do such a meaningless thing as to sort a list that there are no references to. Maybe a syntax checker or something like that should notice such things. But it's not so simple. We somehow need to keep track of functions that neither have varying return values, nor have any external side effects, and tag warn for performing such methods on objects that we don't have any references to. Ok, we know that sort() and reverse() are such methods, but divining whether another function belongs to this category is non-trivial. And who knows what the programmer intends. Perhaps he is measuring the time a sort- operation takes, and doesn't care about the result? -- 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 tim@johnsons-web.com Sun Jan 19 21:35:11 2003 From: tim@johnsons-web.com (Tim Johnson) Date: Sun Jan 19 21:35:11 2003 Subject: [Tutor] Overriding a function method(HTMLgen) Message-ID: <20030120023904.GM1461@johnsons-web.com> Hello All: I am implementing the HTMLgen library. Very nice. I am using the SimpleDocument object and wished to insert internal css code with the object. After looking at the code and experimenting with it, I felt that it wasn't possible. In HTMLgen.py at line 289, I found the following code: if self.style: s.append('\n\n' % self.style) well, all that *seemed* to do (python newbie here) was insert a comment tag. I made the following change s.append('\n\n' % string.join(self.style,'\n ')) which allows me to write an interface like this: style=[ 'a:visited { color:Darkred; text-decoration: none }', 'a:link { color:Darkred; text-decoration:none;}' 'a:hover { color:Darkred; text-decoration:underline; background-color: #EEDD82;}', # etc, etc, ] which is what I was looking for. Produced a
i need to creata a data structure... i = don't know=20 what to use... it should be something like this:
 
node[0].name
node[0].state
 
or this:
 
node['A'].name
node['A'].state
 
 
i have already done a class... and = experimented=20 with lists.... and it works just fine...
i need to know if access and = modifications to the=20 structure get slower using a dictionar instead of lists....
 
 
it is a big data structure.... 10.000 = nodes.... and=20 about 10 fields.... (small fields.. numbers and small=20 strings..)
------=_NextPart_000_001A_01C2C0A0.7D928590-- From op73418@mail.telepac.pt Mon Jan 20 12:13:09 2003 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Mon Jan 20 12:13:09 2003 Subject: [Tutor] Lists or Dictionary? References: <000001c2c0a4$acceaab0$d0f417c3@novo> Message-ID: <001201c2c0a7$fb2f7ce0$1c120dd5@violante> ----- Original Message ----- From: Tiago Duarte Felix To: Tutor@python.org Sent: Monday, January 20, 2003 4:25 PM Subject: [Tutor] Lists or Dictionary? >i need to creata a data structure... i don't know what to use... it should be something like this: > >node[0].name >node[0].state > >or this: > >node['A'].name >node['A'].state > >i have already done a class... and experimented with lists.... and it works just fine... >i need to know if access and modifications to the structure get slower using a dictionar instead of lists.... List acess-by-index is O(1) as is dictionary acess-by-key. Since by the above, you can have keys that are strings this seems to rule out lists. > >it is a big data structure.... 10.000 nodes.... and about 10 fields.... (small fields.. numbers and small strings..) A dictionary of nodes, probably? Encapsulate your "small fields" in a Node (or whatever you want to name it) class and then stuff it's instances in the dictionary. Although 10000 * 10 attributes of "numbers and small strings" does not seem a lot for today's memory standards you could consider the __slots__ feature (Python >= 2.2) to save some memory. If you need an extended interface on the dictionary you could also subclass dict (Python >= 2.2 ). To say more, more info is needed. With my best regards, G. Rodrigues From alan.gauld@bt.com Mon Jan 20 12:24:05 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Jan 20 12:24:05 2003 Subject: [Tutor] Sorting a dictionary in one line? Message-ID: <7497DCA1C240C042B28F6657ADFD8E0974DA8E@i2km11-ukbr.domain1.systemhost.net> > >>> d = {'Magnus':'clever', 'Charlie':'stupid'} > >>> a = d.keys() > >>> d['GvR'] = 'BDFL' > >>> a > ['Magnus', 'Charlie'] > >>> d.keys() > ['Magnus', 'Charlie', 'GvR'] > >>> a == d.keys() # shows why '=' != '==' in Python! > 0 > > mm, 'a' is assigned to a list created when the method > d.keys() is called? Correct, just a plain ole list of values. > ie. d.keys() isn't an attribute of the dictionary although my > brain tells it's kind of obvious that a dictionary has an index... But your brain is unreliable. You'll need to find a CS book to explain how hashes work. But its not as simple as having an index. Thats why dictionary lookups are usually faster than list lookups. > so when I change the dictionary 'a' isn't affected because it > is referring to an object which itself is not actually > referencing the dictionary. Correct, a holds the keys extracted from the dictionary when you called keys() the first time. After that those values are not related in any way to the dictionary keys. They are just copies of the keys held in a list. > It would seem to be me to be okay for 'a' to be > referencing a dictionary attribute called keys and for this > be continually updated But such an attribute does not exist in the dictionary. The dictionary internally is a hash not a list... Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From alan.gauld@bt.com Mon Jan 20 12:31:06 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Jan 20 12:31:06 2003 Subject: [Tutor] Lists or Dictionary? Message-ID: <7497DCA1C240C042B28F6657ADFD8E09702337@i2km11-ukbr.domain1.systemhost.net> > i need to creata a data structure... i don't know what to use... > it should be something like this: > > node[0].name > node[0].state Which implies a list of objects. >or this: >node['A'].name >node['A'].state Which suggests a dictionary of objects. > i have already done a class... Good, you need that in either scenario. > and experimented with lists.... and it works just fine... So use lists! :-) > i need to know if access and modifications to the structure > get slower using a dictionar instead of lists.... No they usually get faster. But if it works "just fine" with lists then carry on using them. Unless performance is a known problem for you why add the extra complexity of managing a dictionary when you've already solved it for lists!? > it is a big data structure.... 10.000 nodes.... Either lists or dictionaries should be fine. > and about 10 fields.... (small fields.. numbers and small strings..) That only affects the class design and has no impact on the list/dictionary debate. Both will just hold a reference to the object. HTH, Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From magnus@thinkware.se Mon Jan 20 12:31:22 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Jan 20 12:31:22 2003 Subject: [Tutor] Sorting a dictionary in one line? In-Reply-To: <20030120171325.1659.8@.1043071433.fake> References: <5.1.0.14.0.20030120162901.02c3bc28@www.thinkware.se> <20030120105502.25675.81799.Mailman@mail.python.org> <20030120105502.25675.81799.Mailman@mail.python.org> <5.1.0.14.0.20030120162901.02c3bc28@www.thinkware.se> Message-ID: <5.1.0.14.0.20030120174244.02c47550@www.thinkware.se> At 17:13 2003-01-20 +0100, Charlie Clark wrote: >It's a funny name and I've still got to get used to it. But the Python >Cookbook has some good illustrations of its use and it makes more sense to >me than map, lambda and reduce. I'd throw in zip as another thing likely to >cause confusion. Well, the name might suggest that it has something to do with compression I guess... I think the name zip fits much better here than in compression programs. They should really be called squeeze or pack or something like that. But prior art matters. But I think syntax is more important than function names... >This is exactly the kind of confusion I get into. I had tested stuff in the >shell before writing it in the mail. Not the next line. ;) > > >d = {'b':2, 'c':3, '2'} > > > > What did you try to do here? A listionary? ;) >hehe >hands up who else frequently types the wrong symbols for the data structure! >This isn't helped by the fact that {[]} all require the modifier key on a >German keyboard :-( And Swedish etc. > >From the Terminal: Good! :) ># is keys() a method or an attribute? All methods are attributes. This particular attribute is a method. Typically, only methods handle the () after the attribute name. (There are some non-method attributes that can be invoked like methods though. But never mind that now.) >>> print d.keys Here we come back to another Python principle: "Explicit is better than implicit." In many programming languages, the parenthesis can be skipped when you call a function without parameters. In some languages, you can even skip the parenthesis when you have parameters. The explicit distinction between a function object and the invocation of a function object makes it simple to pass objects around etc. sin = math.sin is certainly not the same as sin = math.sin() > >>> a = d.keys() The d.keys() method call returns a list. I.e. a new object is created here, and you make if accessible through the variable 'a'. There is no list of keys as a built-in component of a dict. Dicts aren't built like that. If they were, I guess we would have used d.keys instead of d.keys(). As we said. Explicit is better than implicit. > >>> d['GvR'] = 'BDFL' > >>> a >['Magnus', 'Charlie'] > >>> d.keys() >['Magnus', 'Charlie', 'GvR'] > >>> a == d.keys() # shows why '=' != '==' in Python! >0 Right. As you see 'a' points to a 'normal' list. typing "print type(a)" will print , not >mm, 'a' is assigned to a list created when the method d.keys() is called? Yes. >ie. d.keys() isn't an attribute of the dictionary although my brain tells >it's kind of obvious that a dictionary has an index... No, it hasn't. Not like that. It's a hash table. I.e. you perform a mathematical operation on the key value to find a slot in a list, and then you only have to look through a few items (often just one) to find your value. This makes it possible to find a value almost as quickly in a dict with 100 000 items as in one with 10 items. >so when I change the dictionary 'a' isn't affected because it is referring >to an object which itself is not actually referencing the dictionary. Is >this correct? Yes. .keys() retrieves all the keys in the dict, creates a list on the heap, just as any list you create in you code, and put the key values in that list. It's completely decoupled from the dictionary after that. It's just a plain list. You might remove all the keys from that list and store statistics from your poker games there instead. >It would seem to be me to be okay for 'a' to be referencing a >dictionary attribute called keys and for this be continually updated but >this isn't the case and this is for a reason. I'm just not very sure of the >reason... Well, I can name a few... * As I said, dicts don't really have index lists like you think. Have a look in dictobject.c in the Python source package, or read Vol 3 of Don Knuth's "The Art of Computer Programming", page 528- (Algorithm D.) * It would have been invoked as d.keys, not d.keys() * keys = d.keys; keys.append(5) would add a new key without a value to the list? Or should it be a read-only attribute? In that case you can't sort it, so what would the point be then? -- 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 jeff@ccvcorp.com Mon Jan 20 14:13:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Mon Jan 20 14:13:02 2003 Subject: [Tutor] Lists or Dictionary? References: <000001c2c0a4$acceaab0$d0f417c3@novo> Message-ID: <3E2C497D.5060106@ccvcorp.com> Tiago Duarte Felix wrote: > i have already done a class... and experimented with lists.... and it > works just fine... > i need to know if access and modifications to the structure get slower > using a dictionar instead of lists.... > > it is a big data structure.... 10.000 nodes.... and about 10 > fields.... (small fields.. numbers and small strings..) Whether a list or dictionary is preferable depends entirely on what you intend to be doing with it. In both cases, accessing by numeric index (for lists) or key (for dictionaries) is very fast, and does not depend on the size of the collection. Adding items is also independent of size, as long as you're only adding to the end on lists -- inserting in the middle implies shifting all the items after it, which can be slow, but dictionaries are unordered so this doesn't apply. If you are intending to iterate over each node in turn, you need a list. If you will be adding and removing nodes in an arbitrary order, you want a dictionary. Other than that, the decision largely comes down to whether it's more convenient for you to index your collection based on numbers (list) or more complex (strings, tuples, whatever) keys (dictionary). Jeff Shannon Technician/Programmer Credit International From dman@dman.ddts.net Mon Jan 20 18:13:22 2003 From: dman@dman.ddts.net (Derrick 'dman' Hudson) Date: Mon Jan 20 18:13:22 2003 Subject: [Tutor] Re: Sorting a dictionary in one line? In-Reply-To: <5.1.0.14.0.20030119221850.02c50ca0@www.thinkware.se> References: <5.1.0.14.0.20030119221850.02c50ca0@www.thinkware.se> Message-ID: <20030120231127.GA22163@dman.ddts.net> --9amGYk9869ThD9tj Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Sun, Jan 19, 2003 at 11:13:50PM +0100, Magnus Lycka wrote: | At 12:56 2003-01-19 -0800, Terry Carroll wrote: [...] | >1) Why doesn't this work? If I understand this right, dict.keys() returns | >a list, and lists have a sort() method, which returns a list, which is a | >sequence; so why is this an iteration over a non-sequence? |=20 | No. .sort() returns None! |=20 | >>> a =3D [3,4,2,1] | >>> print a.sort() | None | >>> print a | [1, 2, 3, 4] |=20 | Lists can obviously be very big. For that reason it's important | that we are able to perform sorts without having to duplicate | the list. Thus .sort() modifies the original list, not a copy of | it. The .sort() method could still have had a "return self" in | the end as a convenience, but it doesn't. The thing is that if | we wrote "sortedList =3D myList.sort()" it would be very confusing | to discover that "myList" had become sorted in the operation. For | that reason .sort() returns None. You need to do: |=20 | sortedList =3D myList; sortedList.sort() |=20 | Now there is no ambiguity. Just be aware that in the above two lines of code, "both" lists are sorted because the two names are really references to the same mutable object. If you want to have a sorted and unsorted version of the list, make a copy : sortedList =3D myList[:] sortedList.sort() -D --=20 No harm befalls the righteous, but the wicked have their fill of trouble. Proverbs 12:21 =20 http://dman.ddts.net/~dman/ --9amGYk9869ThD9tj Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAj4sgh8ACgkQO8l8XBKTpRT89ACgoIov3xkNu7/pRok8nOla9iTF gssAoJuXk0IcGf0IDh9kNamIV4lHNSDe =ZUeM -----END PGP SIGNATURE----- --9amGYk9869ThD9tj-- From magnus@thinkware.se Mon Jan 20 18:30:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Jan 20 18:30:02 2003 Subject: [Tutor] =?ISO-8859-1?B?UmU6IFtUdXRvcl0gTGlzdHMgb3IgRGljdGlvbmFyeT8=?= Message-ID: Tiago Duarte Felix wrote: > i need to creata a data structure... i don't know what to use... it shoul= d be something like this: ... I'm not sure what your structure looks like, but lists and dicts are very different. With a dict you can use any unique key that you like. With a list containing n elements, your "keys" will be the integers 0 to n-1. If you remove element x, all objects with locations higher in the list than x will shift keys, unless you just leave an empty=20 space in the list (myList[x] =3D None), but then you might end up with=20 a big list full of holes, not very effective. So, if you need to=20 maintain some kind of searchable object identifiers, dicts are nice, but if you use lists you might end up having to make a linear search for your objects. :( =20 > i have already done a class... and experimented with lists.... and it wor= ks just fine...=20 As Alan said: If it works, why change it? That is...if it works with the amount of data it's intended for... > i need to know if access and modifications to the structure get slower us= ing a dictionar instead of lists.... Access is fast in both cases. Modification is always fast=20 for dictionaries. On insert and removal lists get slower the further away from the tail of the list that you get.=20 You can easily test this. --=20 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@thinkware.se Mon Jan 20 18:41:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Jan 20 18:41:01 2003 Subject: [Tutor] =?ISO-8859-1?B?UmU6IFtUdXRvcl0gUmU6IFNvcnRpbmcgYSBkaWN0aW9uYXJ5IGluIG9uZSBsaW5lPw==?= Message-ID: Derrick 'dman' Hudson wrote: > On Sun, Jan 19, 2003 at 11:13:50PM +0100, Magnus Lycka wrote: > | sortedList =3D myList; sortedList.sort() > |=20 > | Now there is no ambiguity. I should obviously have written: "Now this was all pointless." =20 > Just be aware that in the above two lines of code, "both" lists are > sorted because the two names are really references to the same mutable > object. If you want to have a sorted and unsorted version of the > list, make a copy : >=20 > sortedList =3D myList[:] > sortedList.sort() Oops, silly me. I generalized the keys =3D d.keys() case without using that thing above my neck. Thanks for correcting that! No wonder newbies get bitten by mutable objects like that if old foxes like me fall into the trap. I guess I should follow my own advice and always type in the interpreter, test properly, and then paste in my emails. I usually do that, but now and then I get afflicted by hubris and think that I can use my brain as a python interpreter for simple one or two line scripts... --=20 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 mongo57a@comcast.net Mon Jan 20 19:56:41 2003 From: mongo57a@comcast.net (andy surany) Date: Mon Jan 20 19:56:41 2003 Subject: [Tutor] Blt v.2.4z Message-ID: <017701c2c0e8$031d6940$2502a8c0@emily.ewndsr01.nj.comcast.net> Anyone know if the subject is stable? I found one reference on the web (no date...) indicating that it was unstable, and I can't seem to get it to work with Pmw_1_1. TIA. Andy From gp@pooryorick.com Mon Jan 20 20:11:44 2003 From: gp@pooryorick.com (Poor Yorick) Date: Mon Jan 20 20:11:44 2003 Subject: [Tutor] Re: [Tutor] Re: Sorting a dictionary in one line? References: Message-ID: <3E2C9D17.7090509@pooryorick.com> Magnus Lycka wrote: > >Oops, silly me. I generalized the keys = d.keys() case without > It's actually very inspiring to see that people like you and Danny make mistakes and express things like, "...code gets much harder to understand if I can't keep all the relevant parts in my primary field of vision at the same time." Because of the mountain of things I still have to learn and the slow pace of my progress, I often think that programming is not for mere mortals like me, and consider giving up the endeavor. But then I think something like, "That guy Magnus Lycka seems to be human enough, and HE got through all this. Keep going." Thanks! Poor Yorick gp@pooryorick.com From pythonpython@hotmail.com Mon Jan 20 21:59:01 2003 From: pythonpython@hotmail.com (Hy Python) Date: Mon Jan 20 21:59:01 2003 Subject: [Tutor] a question related to modal in Tkinter Message-ID: How can I make some a Toplevel object a REAL modal window? Please try to the following codes, and you will see what I am talking about. The second Toplevel object created in the program actually comes IN FRONT of the the first Toplevel object I tried to make modal. Could someone please tell me why? Is there a way to overcome this, and insure that the first Toplevel object is modal? Thanks a lot. Hy ----------------------------------------------------- from Tkinter import * def showWindow(master): myToplevel=Toplevel(master) Label(myToplevel, text="MY MAIN TOPLEVEL WINDOWS").pack() Button(myToplevel, text="CLICK", command=(lambda myToplevel=myToplevel:showMoreWindow(myToplevel))).pack() myToplevel.focus() myToplevel.grab_set() myToplevel.wait_window() def showMoreWindow(master): Toplevel(master) master.focus() master.grab_set() master.wait_window() root=Tk() Button(root, text="HI", command=(lambda root=root:showWindow(root))).pack() root.mainloop() _________________________________________________________________ The new MSN 8: smart spam protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From magnus@thinkware.se Tue Jan 21 07:23:03 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Jan 21 07:23:03 2003 Subject: [Tutor] Re: [Tutor] Re: Sorting a dictionary in one line? In-Reply-To: <3E2C9D17.7090509@pooryorick.com> References: Message-ID: <5.1.0.14.0.20030121122802.02c07248@www.thinkware.se> At 18:06 2003-01-20 -0700, Poor Yorick wrote: >It's actually very inspiring to see that people like you and Danny make >mistakes and express things like, "...code gets much harder to understand >if I can't keep all the relevant parts in my primary field of vision at >the same time." What ever qualities I might have, or have had, a photographic memory was never one of them... Even if I *can* remember things now and then, there's certainly less risk of making mistakes if I can view all the relevant factors at once. Imagine a car where there was no wind shield, visible mirrors or instrumentation. All we saw was a CRT. In that CRT we could watch all instruments, a forward view, a left view, a right view and a rear view. Since they all fill up the screen, you have to scroll it so that the forward view disappears when you look at the left view or at the instrumentation. I don't think you'd like to drive such a car. Ok, it's not quite the same thing--you will hardly collide head on with another computer program and die if you scroll away that piece of code that you tried to debug, but to understand and solve problems efficiently, it certainly helps to have all the relevant facts available at the same time. In this way, python is much more helpful than Java or C++ etc. (And without nasty side effects of obscurity as in Perl.) I'm an electronics engineer by education, and I've designed electronics some years. There is a reason that CAE stations typically have large screens. There is a reason circuit diagrams are often printed on large sheets of paper and not on a pile of letter size sheets. (The alternative is if blocks of circuits can easily be abstracted into a unit, then we can sometimes apply a modular approach and use several smaller sheets.) But there is a difference between hardware and software here. On a schematic diagram you can zoom out to see more of an overview and navigate between parts of the design. Then you can zoom in to see details. And typically, there is little coupling between things that are located far away in the diagram. There are practical and physical reasons for this. This zooming works on scren, but it really works better when you have the paper sheet pinned to a wall in front of you. (On the other hand, changing the schematic in a pretty way is easier on the screen.) Software is different. Software has no shape. Zooming out from the source code won't give you an overview, it will just give hundreds of lines of text that is so small that it can't be read. UI experts have been struggling for many years to find better ways of changing perspectives in large documents, but the old unix editors vi and emacs are still the best tools for programming according to many. Some prefer IDE's but there is certainly no revolutionary difference. Diagramming tools etc are useful to solve a *bit* of this software problem. That might aid in giving a better understanding of the basic structure of the program, but it's often of limited aid in debugging and other tasks where you work with tiny details. >Because of the mountain of things I still have to learn and the slow pace >of my progress, I often think that programming is not for mere mortals >like me, and consider giving up the endeavor. I started programming about 20 years ago, and began with python in 1997. It takes time to learn, and that's nice, because learning things is a fun thing to do, and it would be boring if we would eventually have nothing more to learn...both individually and as a collective. > But then I think something like, "That guy Magnus Lycka seems to be > human enough, and HE got through all this. Keep going." I'm certainly not flawless. Ask my wife! ;) I'm sure my IQ peaked a number of years ago, but I'm still getting wiser I hope. And learning new things. Besides, how ever clever we are at these things, there are always higher mountains to claim, so I think we all have to follow the same basic steps, about being careful in what we do, trying to keep things as simple as possible (but no simpler) and so on. Admitting ones fallability, to oneself and to others, and to behave accordingly, is certainly important for code quality. Don't forget about doing proper tests of all your code. The unittest module is your friend. Testing before coding is not a bad idea... -- 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@thinkware.se Tue Jan 21 08:19:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Jan 21 08:19:01 2003 Subject: [Tutor] a question related to modal in Tkinter In-Reply-To: Message-ID: <5.1.0.14.0.20030121132259.02c47ec0@www.thinkware.se> At 02:58 2003-01-21 +0000, Hy Python wrote: >How can I make some a Toplevel object a REAL modal window? I think you've misunderstood how to use .wait_window(). Also, the new windows should (I guess) have a parent that still lives when you close the modal. (Otherwaise you can never use them.) Finally, .lower() is useful. Did you mean like this? from Tkinter import * def showWindow(master): myToplevel=Toplevel(master) Label(myToplevel, text="MY MAIN TOPLEVEL WINDOWS").pack() Button(myToplevel, text="CLICK", command=(lambda myToplevel=myToplevel:showMoreWindow(master, myToplevel) )).pack() master.wait_window(myToplevel) def showMoreWindow(master, modal): x = Toplevel(master) x.lower(modal) x.wait_window(modal) root=Tk() Button(root, text="HI", command=( lambda root=root:showWindow(root))).pack() root.mainloop() -- 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 alan.gauld@bt.com Tue Jan 21 09:18:03 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Jan 21 09:18:03 2003 Subject: [Tutor] a question related to modal in Tkinter Message-ID: <7497DCA1C240C042B28F6657ADFD8E09702342@i2km11-ukbr.domain1.systemhost.net> > How can I make some a Toplevel object a REAL modal window? > Please try to the following codes, and you will see what I am > talking about. > > The second Toplevel object created in the program actually > comes IN FRONT of the the first Toplevel object I tried to > make modal. Could someone please tell me why? Presumably you pressed the button in your initial top level window? Could you define what you think modal implies? Top me it implies that you can't do anything with the parent window while the modal child is active. Howevber it does not prevent you from creating child windows(whether modal or not) from that initial modal window. > Is there a way to overcome this, and insure that the first > Toplevel object is modal? So far as I can see it is Modal. Or do you mean that you can still press the original button and bring up a second copy of the original window? - Sorry my python at work doesn't have Tkinter installed so I can't try the code... (Its also v1.3!) Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From dyoo@hkn.eecs.berkeley.edu Tue Jan 21 12:14:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Jan 21 12:14:02 2003 Subject: [Tutor] Overriding a function method(HTMLgen) In-Reply-To: <20030120023904.GM1461@johnsons-web.com> Message-ID: On Sun, 19 Jan 2003, Tim Johnson wrote: > I am implementing the HTMLgen library. Very nice. I am using the > SimpleDocument object and wished to insert internal css code with the > object. After looking at the code and experimenting with it, I felt that > it wasn't possible. > > In HTMLgen.py at line 289, I found the following code: > if self.style: > s.append('\n\n' % self.style) > well, all that *seemed* to do (python newbie here) was insert a comment > tag. Hi Tim, Actually, I think the commenting is intentional! it's supposed to provide compatible with older web browsers: http://www.devguru.com/Technologies/html/quickref/html_style.html So you may not even need to change anything. Can you check to see if using the unmodified HTMLgen code allows your CSS pages to work too? Good luck to you! From dyoo@hkn.eecs.berkeley.edu Tue Jan 21 12:29:09 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Jan 21 12:29:09 2003 Subject: [Tutor] Database driven web sites with python [Phil and Alex's Guide to Web Publishing] In-Reply-To: Message-ID: On Fri, 17 Jan 2003, Danny wrote: > Quick and easy question, can you use python to build database driven web > sites. Thanks ahead of time for everyone help, and have a great > weekend... Out of curiosity, what kind of database-driven web site are you thinking of building? If you haven't seen this already, you may find "Phil and Alex's Guide to Web Publishing" a useful (and amusing) web book to browse through: http://philip.greenspun.com/panda/ In particular: http://philip.greenspun.com/panda/databases-interfacing talks about the basics of writing database-driven sites. He uses a programming language called Tcl/Tk to implement his site, but you can translate that code to Python pretty easily. And even with the book's non-Python focus, it gives a lot of good ideas that you can use to help build your site. Good luck to you! From ATrautman@perryjudds.com Tue Jan 21 12:32:49 2003 From: ATrautman@perryjudds.com (Alan Trautman) Date: Tue Jan 21 12:32:49 2003 Subject: [Tutor] Overriding a function method(HTMLgen) Message-ID: <0BA95581EDA7D611841B00A0C9AD25DD2B5981@mail.pjinet.com> Tim, > s.append('\n\n' % self.style) Those comments are necessary only for older browser support and somewhat older browsers that have CSS disabled. I generally use them for extranet work and leave them out for intranet work where the browser standard is controlled. Leave them in both the latest IE and Mozilla support the command and will perform the style sheet rendering unless style sheets have been turned off. I only remove them because I find them confusing. They are a must for Netscape 4.xx most versions. HTH, Alan From dyoo@hkn.eecs.berkeley.edu Tue Jan 21 12:50:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Jan 21 12:50:02 2003 Subject: [Tutor] Re: [Tutor] Re: Sorting a dictionary in one line? [programming is hard / Dijkstra's remarks] In-Reply-To: <5.1.0.14.0.20030121122802.02c07248@www.thinkware.se> Message-ID: On Tue, 21 Jan 2003, Magnus Lycka wrote: > At 18:06 2003-01-20 -0700, Poor Yorick wrote: > > >It's actually very inspiring to see that people like you and Danny make > >mistakes and express things like, "...code gets much harder to > >understand if I can't keep all the relevant parts in my primary field > >of vision at the same time." By the way, Edsgar Dijkstra, for his Turing Lecture speech, gave a talk about "The Humble Programmer": http://www.cs.utexas.edu/users/EWD/ewd03xx/EWD340.PDF (The typography of this paper is atrocious though... if I have the time, perhaps I can retype in it TeX...) The "Turing Award" is Computer Science's equivalent to the Nobel prize, so it's also inspiring when a Turing recipient says that programming is hard. Here are the last two paragraphs of his talk: """Let me conclude. Automatic computers have now been with us for a quarter of a century. They have had a great impact on our society in their capacity of tools, but in that capacity their influence will be but a ripple on the surface of our culture, compared with the much more profound influence they will have in their capacity of intellectual challenge without precendent in the cultural history of mankind. Hierarchical systems seem to have the property that something considered as an undivided entity on one level, is considered as a composite object on the next lower level of greater detail; as a result the natural grain of space or time that is applicable at each level decreases by an order of magnitude when we shift our attention from one level to the next lower one. We understand walls in terms of bricks, bricks in terms of crystals, crystals in terms of molecules etc. As a result the number of levels that can be distinguished meaningfully in a hierarchial system is kind of proportional to the logarithm of the ratio between the largest and the smallest grain, and therefore, unless this ratio is very large, we cannot expect many levels. In computer programming our basic building block has an associated time grain of less than a microsecond, but our program may take hours of computation time. I do not know of any other technology covering a ratio of 10^{10} or more: the computer, by virtue of its fantastic speed, seems to be the first to provide us with an environment where highly hierarchial artifacts are both possible and necessary. This challenge, viz. the confrontation with the programming task, is so unique that this novel experience can teach us a lot about ourselves. It should deepen our understanding of the processes of design and creation, it should give us better control over the task of organizing our thoughts. If it did not do so, to my taste we should not deserve the computer at all! It has already taught us a few lessons, and the one I have chosen to stress in this talk is the following. We shall do a much better programming job, provided that we approach the task with a full appreciation of its tremendous difficulty, provided that we stick to modest and elegant programming languages, provided that we respect the intrinsic limitations of the human mind and approach the task as Very Humble Programmers.""" There's a small eulogy to Dijkstra here: http://lwn.net/Articles/6993/ as well as a complete collection of his papers: http://www.cs.utexas.edu/users/EWD/ From ckreider@gte.net Tue Jan 21 13:01:02 2003 From: ckreider@gte.net (Carl Kreider) Date: Tue Jan 21 13:01:02 2003 Subject: [Tutor] Sorting a dictionary in one line? In-Reply-To: <5.1.0.14.0.20030120105128.02c07440@www.thinkware.se> References: <5.1.0.14.0.20030119221850.02c50ca0@www.thinkware.se> <5.1.0.14.0.20030120105128.02c07440@www.thinkware.se> Message-ID: <20030120210214.A24910@gte.net> On Mon, Jan 20, 2003 at 11:53:21AM +0100, Magnus Lycka wrote: > > (snip) > I guess the typical thing that you learn in school is to > put each thing on a line and preferably spice the code with > plenty of comments. If you have something, as in most simple > school examples, that could be written in 3 compact lines, it > might be easier to understand (for a beginner at least) if > you write it in 12 lines instead, but if you have a 20 line > function that fits well on the screen, I doubt that people > will understand it better if it grows to 80 lines and won't > even fit on one page if you print it out. At least for me, > code gets much harder to understand if I can't keep all the > relevant parts in my primary field of vision at the same > time. Maybe it's just my poor memory? I don't think it is your memory. I find the same thing. One of my syle rules is that a function has to fit on one page. I maintain a lot of code that I have written and work on code others have written. One thing I observe is that comments often do not match the code because code (even with good design practices) tends to evolve, if for no other reason than the users needs/wants evolve. I prefer to write code that is obvious and eliminage the comments a smuch as possible. -- Carl Kreider aka ckreider@acm.org ckreider@gte.net ckreider@doctordesign.com ============================================================= You may now return to bashing UNIX and its smug complacent users. We in return will return to our smug complacency -- after all, we don't have any machines to disinfect this weekend. -- Jim Hill ============================================================= From paul@entropia.co.uk Tue Jan 21 14:04:01 2003 From: paul@entropia.co.uk (paul butler) Date: Tue Jan 21 14:04:01 2003 Subject: [Tutor] Tkinter headaches Message-ID: <0d1a33702191513PCOW057M@blueyonder.co.uk> Dear list, I installed the latest python( a few times ) on NT4, but IDLE obstinately refuses to appear, After messing about with path: %SystemRoot%\system32;%SystemRoot%;c:\Program Files\Mts;D:\SQLANY\Im5i32;D:\SQLANY\Sys32;D:\SQLANY50\wi n32;C:\PROGRA~1\COMMON~1\Odbc\FILEMA~1;D:\Executive\;C: \python22\;c:\Python22\tcl\ and pythonpath C:\Python22\ ;C:\Python22\Tools\;C:\Python22\DLLs\;C:\Python22\include\;C:\Py thon22\Lib\;C:\Python22\libs\;C:\Python22\tcl\;C:\Python22\Lib\lib- tk\;C:\python22\tcl\tcl8.3\ I got Tkinter to load on running the test from a console this was the result Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import Tkinter >>> Tkinter._test() Traceback (most recent call last): File "", line 1, in ? File "C:\Python22\Lib\lib-tk\Tkinter.py", line 3094, in _test root = Tk() File "C:\Python22\Lib\lib-tk\Tkinter.py", line 1495, in __init__ self.tk = _tkinter.create(screenName, baseName, className) TclError: Can't find a usable init.tcl in the following directories: {} C:/Python22/lib/tcl8.3 C:/lib/tcl8.3 lib/tcl8.3 lib/tcl8.3/library librar y ../tcl8.3/library This probably means that Tcl wasn't installed properly. >>> Any idea how I can install TCL properly, the directories and the files are there (in C:/Python22/lib/tcl8.3) Never had this much trouble with python before TIA Paul Butler From sxa@fluent.com Tue Jan 21 14:09:01 2003 From: sxa@fluent.com (Sebastien Auclair) Date: Tue Jan 21 14:09:01 2003 Subject: [Tutor] Redistribute Python for a C++ app that embed python ... Message-ID: <00da01c2c180$8dbb9250$8ae4e9c0@sxapc> Hi folks ! All SDK or API defines procedures for redistributing software made from them. For a C++ application that embeds Python... What python files should we put in our software installation CD ? We would put Lib and Lib\site-packages and python22.dll of course but what else ? We also tried to set PYTHONPATH like it is set on our development machines and it doesn't seem to be enough. Thanks. From gp@pooryorick.com Tue Jan 21 14:12:08 2003 From: gp@pooryorick.com (Poor Yorick) Date: Tue Jan 21 14:12:08 2003 Subject: [Tutor] Re: Composing codecs using codecs.EncodedFile / UTF-16 DOS format converted to Unix ASCII References: Message-ID: <3E2D9BE2.3050706@pooryorick.com> Danny Yoo wrote: > > >Small amendment: that last part of u_newlines.py is wrong; I should not >have touched codecs.register. Sorry about that! The corrected code, >along with a small test case, follows below: > Danny, I've modified your code a little to make it platform-independent, and added my own "overridden" version of codecs.open. My goal is to use yCodecs.open in all my Python development and to abandon __builtin__.open completely. For my projects, it's essential to be able to handle files of various text encodings with grace and in a platform-independent manner. I have two questions about the following code: Why is it not necessary to register the codec using codec.register? Isn't that essential to Python being able to find the codec? I figured it out by trial and error, but I don't understand why, in my class Codec, StreamWriter inherits from StreamReader and StreamReader inherits from StreamWriter. ### yCodecs.py### ___________________ #! /usr/bin/env python '''yCodecs.open provides an "wrapper" to codecs.open, adding transparent newline conversion when files are opened in text mode. Note that codecs.open actually opens all files in binary mode. ''' import codecs import yu_newlines def open(filename, mode='rb', encoding=None, errors='strict', buffering=1): '''same as codecs.open with addition of automatic conversion of os.linesep to "\n" in Python ''' fh1 = codecs.open(filename, mode, encoding, errors, buffering) if 'b' not in mode: fh2 = codecs.EncodedFile(fh1, 'yu_newlines') return fh2 else: return fh1 ____________________ ### yu_newlines.py ### ____________________ #! /usr/bin/env python ''' used by yCodecs.py to provide transparent conversion from os.linesep to "\n" in Python. Based on code by Danny Yoo (dyoo@hkn.eecs.berkeley.edu) ''' import codecs import os class Codec(codecs.Codec): def encode(self, input, errors="strict"): linesep = os.linesep final = input.replace(linesep, "\n"), len(input) return final def decode(self, input, errors="strict"): linesep = os.linesep final = input.replace("\n", linesep), len(input) return final class StreamWriter(Codec, codecs.StreamReader): pass class StreamReader(Codec, codecs.StreamWriter): pass def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) Poor Yorick gp@pooryorick.com From hall@ouhep1.nhn.ou.edu Tue Jan 21 14:35:02 2003 From: hall@ouhep1.nhn.ou.edu (Isaac Hall) Date: Tue Jan 21 14:35:02 2003 Subject: [Tutor] Checking for the existence of a file Message-ID: Hi python list! I was wondering if someone could point me to some of the methods available for checking to see whether a file called aaaa.bbb exists through a python script. The current method I use is: if os.popen('ls '+filename).read()[:-1]==filename: exists=1 else: exists=0 however, sometimes, I run into a small problem with that.... sometimes, but not all the time, the script will tell me that the Index is out of range. I am unable to replicate this error in the interactive interpreter, and I was wondering if there is a better way to do this. Thanks Ike -- From drewp@bigasterisk.com Tue Jan 21 14:49:05 2003 From: drewp@bigasterisk.com (Drew Perttula) Date: Tue Jan 21 14:49:05 2003 Subject: [Tutor] Checking for the existence of a file In-Reply-To: Your message of "Tue, 21 Jan 2003 13:34:08 CST." Message-ID: <200301211948.h0LJmDs27624@bang.houseoflove> > script. The current method I use is: > > if os.popen('ls '+filename).read()[:-1]==filename: > exists=1 > else: > exists=0 Yikes! :) Check out os.path.exists (and also os.listdir for other directory listing needs). -Drew From tim@johnsons-web.com Tue Jan 21 15:48:02 2003 From: tim@johnsons-web.com (Tim Johnson) Date: Tue Jan 21 15:48:02 2003 Subject: [Tutor] Overriding a function method(HTMLgen) In-Reply-To: References: <20030120023904.GM1461@johnsons-web.com> Message-ID: <20030121205031.GR1461@johnsons-web.com> * Danny Yoo [030121 08:25]: > > > On Sun, 19 Jan 2003, Tim Johnson wrote: > > > I am implementing the HTMLgen library. Very nice. I am using the > > SimpleDocument object and wished to insert internal css code with the > > object. After looking at the code and experimenting with it, I felt that > > it wasn't possible. > > > > In HTMLgen.py at line 289, I found the following code: > > if self.style: > > s.append('\n\n' % self.style) > > well, all that *seemed* to do (python newbie here) was insert a comment > > tag. > > > Hi Tim, > > Actually, I think the commenting is intentional! it's supposed to provide > compatible with older web browsers: > > http://www.devguru.com/Technologies/html/quickref/html_style.html > > So you may not even need to change anything. Can you check to see if > using the unmodified HTMLgen code allows your CSS pages to work too? Thanks Danny: Yes I did try that and all css rules were inserted into a comment tag. And it turns out that the rules are applied. Sorry to bother you on this! > > > Good luck to you! -- Tim Johnson http://www.alaska-internet-solutions.com http://www.johnsons-web.com From bokchoy@adelphia.net Tue Jan 21 17:24:07 2003 From: bokchoy@adelphia.net (Bob H) Date: Tue Jan 21 17:24:07 2003 Subject: [Tutor] Perl => Python Message-ID: <000101c2c19b$ca1216f0$4b8a3518@olorin> I have this script in Perl that I had help with and I would like to see the Python equivelant: # pragmas use strict; use warnings; # modules use Net::FTP; use File::Copy; # my variables my @list; my @match; my $dir='/public/english_us_canada/antivirus_definitions/norton_antivirus'; my $ftp = Net::FTP->new('ftp.symantec.com', Debug => 0) or die 'Could not connect: $@\n'; $ftp->login('anonymous','iam@updatingnav.com'); $ftp->cwd($dir); @list=$ftp->ls(); # this matches the name only by looking at files # that start with 8 numbers (i.e. 20021203) foreach(@list) { if(m/\d{8}.*x86.exe/) { push(@match,$_) } } if(scalar(@match)) { my $file=$match[$#match]; $ftp->binary(); $ftp->get($file); } $ftp->quit; exit(0); Thanks in advance...! Bob ----- There are only 10 types of people in the world: Those who understand binary and those who don't. From magnus@thinkware.se Tue Jan 21 17:38:05 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Jan 21 17:38:05 2003 Subject: [Tutor] Re: [Tutor] Re: Sorting a dictionary in one line? [programming is hard / Dijkstra's remarks] In-Reply-To: References: <5.1.0.14.0.20030121122802.02c07248@www.thinkware.se> Message-ID: <5.1.0.14.0.20030121232905.02c7dfa8@www.thinkware.se> At 09:49 2003-01-21 -0800, Danny Yoo wrote: >"""Let me conclude. Automatic computers have now been with us for a >quarter of a century. They have had a great impact on our society in Actually Danny, in emails you don't need to triple quote multi line strings, that's only in Python! ;) Occupational disease? Nice quote by the way. Hm... Now we only need to know how to become Very Humble Programmers...and what else we should be. Pragmatic Very Humble Lazy ... -- 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@thinkware.se Tue Jan 21 17:40:04 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Jan 21 17:40:04 2003 Subject: [Tutor] Tkinter headaches In-Reply-To: <0d1a33702191513PCOW057M@blueyonder.co.uk> Message-ID: <5.1.0.14.0.20030121233643.02bf40e8@www.thinkware.se> At 19:00 2003-01-21 +0000, paul butler wrote: >I installed the latest python( a few times ) on NT4, but IDLE >obstinately refuses to appear, You haven't been fooling around with someone else, have you? This happened to me when I installed Ruby. Out it went, and Python was back to normal. (I probably had to clear up some things, but I have supressed all further memories of that incident.) -- 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@thinkware.se Tue Jan 21 18:40:04 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Jan 21 18:40:04 2003 Subject: [Tutor] Perl => Python In-Reply-To: <000101c2c19b$ca1216f0$4b8a3518@olorin> Message-ID: <5.1.0.14.0.20030122000844.02c82948@www.thinkware.se> At 17:23 2003-01-21 -0500, Bob H wrote: >I have this script in Perl that I had help with and I would like to see the >Python equivelant: I don't really understand Perl that well (I am reminded of that every time I look at some code) but I guess you want to download the files matched by the regular expression to a local directory, preserving file names. I'm afraid ftplib isn't very intuitive, with method names like .nlst() and callbacks for recieving files etc. :( But it works...and it's shorter than the Perl script. ;) import ftplib, re site = 'ftp.symantec.com' dir='/public/english_us_canada/antivirus_definitions/norton_antivirus' ftp = ftplib.FTP(site) ftp.login() ftp.cwd(dir) files = ftp.nlst() for fn in re.findall(r'\d{8}.*x86\.exe', "\n".join(files)): print "Fetching", fn, f = file(fn, 'wb') ftp.retrbinary('RETR ' + fn, f.write) # In case of timeout problems, decrease block size from default 8192 # ftp.retrbinary('RETR ' + fn, f.write, 1024) f.close() print 'Done!' ftp.quit() I don't have any "die" on connect. The program will terminate on a failed connect, indicating a socket error. If this isn't user friendly enough, there are a number of further possible errors in the perl script that needs to be improved as well. Every operation can fail. I did add some diagnostic messages though. They can obviously be removed. -- 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 paul@entropia.co.uk Wed Jan 22 03:17:01 2003 From: paul@entropia.co.uk (paul butler) Date: Wed Jan 22 03:17:01 2003 Subject: [Tutor] fooling around trying to find tcl Message-ID: <074b11116081613PCOW035M@blueyonder.co.uk> Dear list > You haven't been fooling around with someone else, have you? > > This happened to me when I installed Ruby. Out it went, and > Python was back to normal. (I probably had to clear up some > things, but I have supressed all further memories of that > incident.) > I swear I've been faithful,( Bruce Eckel expresses my view of RUBY better than I ever could (But good luck to them)) my problems began when I needed to use the PIL library, python could find Image, but little else (kept getting filter not found on .resize etc). So I thought a clean install of python might help. Several installs later, many reboots and still no IDLE. A disk format is looking increasingly attractive. Cheers Paul Butler From alan.gauld@bt.com Wed Jan 22 05:56:01 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed Jan 22 05:56:01 2003 Subject: [Tutor] Database driven web sites with python [Phil and Ale x's Guide to Web Publishing] Message-ID: <7497DCA1C240C042B28F6657ADFD8E0970234D@i2km11-ukbr.domain1.systemhost.net> > http://philip.greenspun.com/panda/ > I second the recommendation but.... > programming language called Tcl/Tk to implement his site, but you can > translate that code to Python pretty easily. If you don't already know Tcl/Tk I think the translation might be challenging. Tcl is a weird kind of language when you first see it! One of the reasons I chose Tcl as a language for my web tutor was that it was so different to most others. IMHO of course, Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From alan.gauld@bt.com Wed Jan 22 06:05:01 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed Jan 22 06:05:01 2003 Subject: [Tutor] Re: [Tutor] Re: Sorting a dictionary in one line? [p rogramming is hard / Dijkstra's remarks] Message-ID: <7497DCA1C240C042B28F6657ADFD8E0970234E@i2km11-ukbr.domain1.systemhost.net> It's a good enough paper but one point of his discourse is flawed: > In computer programming our basic building block has > an associated time grain of less than a microsecond, but our > program may take hours of computation time. I do not know of > any other technology covering a ratio of 10^{10} or more: In fact most technologies can show instances of the same order. For example in Civil engineering bridges and the like may stand for thousands of years but in the event of failure a hairline fracture can rupture in milliseconds. In Electronics the basic unit of tiume is nanoseconds (and increasingly pico seconds) but may electronic systems run for long periods - manufacturing production runs etc, even timers operate over periods of hours or more. Astronomers have even longer timeframe differences, but arguably are not a technmology per se. Computer Scientists seem to have a strange built in belief system whereby, somehow, their problems are significantly different to those in other engineering disciplines. They are not. The only real difference is that CS lacks a complete theoretical basis (pysics etc) with which to perform analyses. But this was true of most traditional engineering disciplines too for many years - think medieval buildings... Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From alan.gauld@bt.com Wed Jan 22 06:17:01 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed Jan 22 06:17:01 2003 Subject: [Tutor] Sorting a dictionary in one line? Message-ID: <7497DCA1C240C042B28F6657ADFD8E0974DA92@i2km11-ukbr.domain1.systemhost.net> > code others have written. One thing I observe is that comments > often do not match the code because code (even with good > design practices) tends to evolve, One reason for this is that the commenting is often bad. It often describes *how the code works* rather than *what* the code does, or *why* the code is there! The excellent book "Code Complete" has much to say on the subject of good commenting and I commend it to every programmer. Example: Here is a bad comment.... # open a file, read the content then extract the third field f = open('pay1232003.txt','r') txt = f.read().split() val = txt[2] f.close() A better, and more robust, comment might say: # extract the salary value from the payments file Of course if I had used better names it would help too: f = open(payment_file,'r') content = f.read().split() salary = content[2] f.close() Good commenting and coding generally is an art as well as a science. Unfortunately a list like this tends not to teach good commenting since we use comments to explain our code samples - which is exactly what you should NOT do in real world code...(unless you are using some dangerous or obscure coding idiom). Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From alan.gauld@bt.com Wed Jan 22 06:20:01 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed Jan 22 06:20:01 2003 Subject: [Tutor] Tkinter headaches Message-ID: <7497DCA1C240C042B28F6657ADFD8E09702350@i2km11-ukbr.domain1.systemhost.net> Did you have an earlier Python installed already(v1.5.1 say?) or even a native Tcl install? If so you may have to search for Tcl/Tk DLL files in your windows\System folders and remove them then reinstall python. This seems to cure the problem. Alan g. From paul@entropia.co.uk Wed Jan 22 06:20:14 2003 From: paul@entropia.co.uk (paul butler) Date: Wed Jan 22 06:20:14 2003 Subject: [Tutor] Tkinter headache Again Message-ID: <0403b4920111613PCOW034M@blueyonder.co.uk> Dear list Moved the tcl directory into LIB and idle reappeared. This is nice, but I remain bewildered as to why or how I could remedy the situation using paths etc Cheers Paul Butler > > After messing about with path: > > %SystemRoot%\system32;%SystemRoot%;c:\Program > Files\Mts;D:\SQLANY\Im5i32;D:\SQLANY\Sys32;D:\SQLANY50\wi > n32;C:\PROGRA~1\COMMON~1\Odbc\FILEMA~1;D:\Executive\;C: > \python22\;c:\Python22\tcl\ > > and > > pythonpath > > C:\Python22\ > ;C:\Python22\Tools\;C:\Python22\DLLs\;C:\Python22\include\;C:\Py > thon22\Lib\;C:\Python22\libs\;C:\Python22\tcl\;C:\Python22\Lib\lib- > tk\;C:\python22\tcl\tcl8.3\ > > I got Tkinter to load > on running the test from a console this was the result > > Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on > win32 Type "help", "copyright", "credits" or "license" for more > information. >>> import Tkinter >>> Tkinter._test() Traceback (most > recent call last): > File "", line 1, in ? > File "C:\Python22\Lib\lib-tk\Tkinter.py", line 3094, in _test > root = Tk() > File "C:\Python22\Lib\lib-tk\Tkinter.py", line 1495, in __init__ > self.tk = _tkinter.create(screenName, baseName, className) > TclError: Can't find a usable init.tcl in the following directories: > {} C:/Python22/lib/tcl8.3 C:/lib/tcl8.3 lib/tcl8.3 > lib/tcl8.3/library > librar > y ../tcl8.3/library > > > > This probably means that Tcl wasn't installed properly. > > >>> From magnus@thinkware.se Wed Jan 22 07:55:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Wed Jan 22 07:55:02 2003 Subject: [Tutor] Sorting a dictionary in one line? In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E0974DA92@i2km11-ukbr.domain1 .systemhost.net> Message-ID: <5.1.0.14.0.20030122124715.02cadc40@www.thinkware.se> At 11:14 2003-01-22 +0000, alan.gauld@bt.com wrote: >A better, and more robust, comment might say: > > # extract the salary value from the payments file > >Of course if I had used better names it would help too: > > f = open(payment_file,'r') > content = f.read().split() > salary = content[2] > f.close() With those well chosen variable names, I don't see that the comment adds anything. Using less descriptive variable names and keeping the comment is not better in my opinion. You can scrap that comment as well. It's redundant. :) The only reason to keep that I see is that it might be faster to read the comment than to read the code, but especially if you reduce the code to salary = open(payment_file,'r').read().split()[2] I feel that it's as easy to read the code as to read the comment. A beginner might not, but a routined python coder will, and what better way to learn than to read code and try to figure out what it means if we don't understand it at once. Getting solutions provided on a silver platter won't make us learn faster, it will only get us used to having someone else provide solutions all the time. We programmers or engineers should not be lazy in *that* way. What I don't really like in this code is the hard coded 2 though. I'd prefer: # The payment file is a text file with whitespace # separated fields positioned like this: id_pos = 0 date_pos = 1 salary_pos = 2 ... salary = open(payment_file,'r').read().split()[salary_pos] In practice, we will probably read more fields from the file, and then we will naturally read the file only once. But this might still be just one statement in Python: id, date, salary = open(payment_file,'r').read().split() Anyway, the lack of distracting noise in Python, makes it possible to write code that can be read with a flow that we associate with reading normal texts. If the code is well written this will further reduce the need for comments. And this in turn makes the code even easier to read... If we feel a need to add comments, we should perhaps first consider rewriting the code. Imagine that you have a section of a function, maybe five or ten lines of code, where you do something tricky that needs to be explained. Then it is likely that these lines of code could be described with a word or short phrase. These lines probably hangs together in some way. Perhaps you should break them out into a separate function. Then they will be reduced to one line, and since you give a very descriptive name to this function, it will become easier to understand the function they were part of... I sometimes write programs by first writing comments, and then filling in the code. In that case it might be a good idea to consider removing some comments when the code is written. Not if they are still helpful...but don't leave them in just because comments are a "good thing". Anyway, I don't program like this as much as I did. With python, the code is sometimes as short as the comments, and now I try to practice XP style test first programming. Then it is the design of unit test cases, and not comments, that drive the programming forward. (But this isn't always so easy to do. Right now I'm doing some ReportLab coding, and how do you write automated tests for PDF file generation?) Comments that aren't helpful just obscure the code. For me, well written Python code reads like a good book. Filled with comments I don't need, and all the kind of syntactic noise most other languages use, it's more like a book where every other word (by word I mean a collection of adjacent letters) is explained (an explanation is some kind of description of something that is intended to make it easier to understand (actually "understand" is a misleading word (you remember what word meant, right?) since it has nothing to do with standing under something, maybe comprehend is better)) in absurdum (In absurdum is actually Latin, and it means something like "to an absurd level"). I assume the previous sentence was easy to understand since I explained it so well, right? Without comments, the sentence ended with "...a book where every other word is explained in absurdum." It was easier to read without comments, right? It certainly happened that I saw an obscure program that didn't make sence, and the first thing I did was to remove all comments. Sometimes is increases the readability of the code quite a lot, and bugs often gets easier to spot. Of course, there is another side to the issue. Even if we agree that comments shouldn't teach programming, but decribe the intent of the code, we could still argue that comments in programs should be there to make it possible for someone who can't program to understand a bit about the code. The customer might want to see what we have done for him. Personally I seriously doubt that people who can't program will be able to draw intelligent conclusions from the code, how ever well commented it is. Of course the customer might request documentation of the program, but should that really be in the form of code comments? I think well documented system test cases, developed with a user of the system, are much more useful in helping the customer to confirm that the program does what is inteded of it. Add to that the concept of doc strings in python, and you will really need very few formal comments (as in #comment). The doc strings are better suited for the kind of documentation that we want plenty of. A description of the intent and usage of each module, class, and function. >Unfortunately a list like this tends not to teach >good commenting since we use comments to explain >our code samples - which is exactly what you should >NOT do in real world code...(unless you are using >some dangerous or obscure coding idiom). Yes, this is a pedagogical problem. I tend to feel more and more that it's a bad thing to demonstrate something, and in the same breath say--you shouldn't do what I do now. (The exception might be experiments that clearly demonstrate the suffering that the "bad" behaviour will cause, such as "Never put your fingers in the power outlet like I do now AAAARGHH"). Trying to raise a son leads me to believe that people (children as well as adults) learn much more from the actions of other people than from their words. Thus, it's probably a good thing *not* to embed explanations of python programming as comments, in this educational context. The explanations can come separated from the code. -- 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 alan.gauld@bt.com Wed Jan 22 08:18:00 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed Jan 22 08:18:00 2003 Subject: [Tutor] Sorting a dictionary in one line? Message-ID: <7497DCA1C240C042B28F6657ADFD8E09702353@i2km11-ukbr.domain1.systemhost.net> > With those well chosen variable names, I don't see > that the comment adds anything. I agree the code is almost seelf decribing, but not quite. More importantly the comment could(should?) be a direct link back to the design documentation soi it serves as a roadmap into the code. On production code for example we will define the design using pseudo code and then that pseudo code will be inserted as comments into the source files. The translation of the pseudo code to real code would be pretty much as shown - about 5-10 lines per line of pseudo code. (Of course our production code is Java/C++ so it is inherently less readable!) > The only reason to keep that I see is that it might > be faster to read the comment than to read the code, but > especially if you reduce the code to > > salary = open(payment_file,'r').read().split()[2] Sorry, I don't think thats fast to read. And only if you are a python programmer. Many of our ops support guys are generic programmers and deal with systems in multiple languages(COBOL/C++/Java/Perl etc) so if they go into a file they like comments they can understand. > What I don't really like in this code is the hard coded 2 though. Yes, I agree, in production code I'd eliminate "magic numbers" as much as possible. > it possible to write code that can be read with a flow > that we associate with reading normal texts. If the code > is well written this will further reduce the need for > comments. And this in turn makes the code even easier > to read... I do agree that much of the normal commenting adds noise, I do also think much python code is undercommented though! self documenting code is much harder to produce that the author often thinks. Its fine for him/her but the follow-on reader might not agree. At the other extreme we have a large COBOL system (about 60 million executable lines!) where there are so few people know how it works that coders are not allowed to remove anything, they must comment it out - including old comments Pythonically this leads to code like this: #### open a file to store the audit results #### audit = open(adt) ### use the existing system file ### audit = GetSysAudit() ## The system file gets deleted so use the original one ## audit = open(adt) # Auditing has been disabled, dont open any files 7 lines in the source which do precisely nothing but are left in 'just in case'... And at worst should only ever really be 2 lines. And yes you've guessed, they don't use CVS.... > I sometimes write programs by first writing comments, and > then filling in the code. In that case it might be a good > idea to consider removing some comments when the code is > written. Not if they are still helpful...but don't leave > them in just because comments are a "good thing". As I said we do that but the comments are from the design docs, in this case they are a good thing because the maintainer who is reading the design can find the associated bit of code using a simple grep/search. This keeps the ISO9000 auditor happy too - traceability being their mantra... > Comments that aren't helpful just obscure the code. Agreed, see the "COBOL" case above. > For me, well written Python code reads like a good > book. But I wouldn't go that far! :-) > Of course, there is another side to the issue. Even > if we agree that comments shouldn't teach programming, > but decribe the intent of the code, we could still > argue that comments in programs should be there to > make it possible for someone who can't program to > understand a bit about the code. The customer might > want to see what we have done for him. Yes, but then explkaining the intent of a block should serve that purpose. In my example the client can see that the next few lines(hopefully separated by whitespace) are about extracting the salary value... No need to worry about the technical nasties of exactly how it happens. > the customer might request documentation of the program, > but should that really be in the form of code comments? Nope, I use lots of notations to describe designs, and some of these Ingive to customers but code is supplied purely on specific request - which frankly, is rare. > Add to that the concept of doc strings in python, > and you will really need very few formal comments Good point, Doc strings are under used but are efectively a type of comment. They certainly should replace the classic type of pre-function comment: ########## # Function Foo # Parameters: a,b,c # This function..... ######### def foo(a,b,c): ..... All the preamble in Python should go in a doc string. Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From blackmariah@shmups.com Wed Jan 22 10:07:01 2003 From: blackmariah@shmups.com (Michael Miller) Date: Wed Jan 22 10:07:01 2003 Subject: [Tutor] Fun with random numbers In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E09702353@i2km11-ukbr.domain1.systemhost.net> References: <7497DCA1C240C042B28F6657ADFD8E09702353@i2km11-ukbr.domain1.systemhost.net> Message-ID: <200301220903.49308.blackmariah@shmups.com> It appears my first post didn't go through. Grrr.... How can I easily generate a bunch of random numbers? For example, 543765843675465436788654365431885431 or something to that effect. I know the answer is staring me in the face somewhere in that module documentation (does that stuff make sense to anyone? ;) ), but for the life of me I can't find it. From magnus@thinkware.se Wed Jan 22 10:33:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Wed Jan 22 10:33:02 2003 Subject: [Tutor] Fun with random numbers In-Reply-To: <200301220903.49308.blackmariah@shmups.com> References: < <7497DCA1C240C042B28F6657ADFD8E09702353@i2km11-ukbr.domain1.systemhost.net> <7497DCA1C240C042B28F6657ADFD8E09702353@i2km11-ukbr.domain1.systemhost.net> Message-ID: <5.1.0.14.0.20030122161806.02cc4ec8@www.thinkware.se> At 09:03 2003-01-22 -0500, Michael Miller wrote: >It appears my first post didn't go through. Grrr.... >How can I easily generate a bunch of random numbers? For example, >543765843675465436788654365431885431 or something to that effect. I know the >answer is staring me in the face somewhere in that module documentation More or less... > (does >that stuff make sense to anyone? ;) Yes >), but for the life of me I can't find >it. "import random" is a start It's probably better if you can describe a little better what you are after. It seems you are after very big numbers. What do you intend to use them for? random.random() will return a random float between 0 and 1. r = random.randrange(x, y) will return a random integer such that x <= r < y. I don't think there is a funktion to generate long integers, but that's easy to fix. Go via a string. For instance if you want a 27 digit random number: >>> print long("%09i" % random.randrange(0,1000000000)+ ... "%09i" % random.randrange(0,1000000000)+ ... "%09i" % random.randrange(0,1000000000)) 502280329152143067453249503 If you have specific demands on random distribution this might not do what you want. As I said, we really need to know what you are after to give a good answer. -- 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 blackmariah@shmups.com Wed Jan 22 10:46:00 2003 From: blackmariah@shmups.com (Michael Miller) Date: Wed Jan 22 10:46:00 2003 Subject: [Tutor] Fun with random numbers In-Reply-To: <5.1.0.14.0.20030122161806.02cc4ec8@www.thinkware.se> References: <" <7497DCA1C240C042B28F6657ADFD8E09702353"@i2km11-ukbr.domain1.systemhost.net> <7497DCA1C240C042B28F6657ADFD8E09702353@i2km11-ukbr.domain1.systemhost.net> <5.1.0.14.0.20030122161806.02cc4ec8@www.thinkware.se> Message-ID: <200301220942.33139.blackmariah@shmups.com> > If you have specific demands on random distribution this > might not do what you want. As I said, we really need to > know what you are after to give a good answer. I'm wanting to create a string of random numbers of a given length. I know how to generate one number, but getting 5 or 15 or 50 at one time is escaping me. I'm messing with some very, excruciatingly trivial "encryption" type things mostly just to have something to do. From francois.granger@free.fr Wed Jan 22 10:54:04 2003 From: francois.granger@free.fr (Fran=?ISO-8859-1?B?5w==?=ois Granger) Date: Wed Jan 22 10:54:04 2003 Subject: [Tutor] Fun with random numbers In-Reply-To: <200301220903.49308.blackmariah@shmups.com> Message-ID: on 22/01/03 15:03, Michael Miller at blackmariah@shmups.com wrote: > It appears my first post didn't go through. Grrr.... > How can I easily generate a bunch of random numbers? For example, > 543765843675465436788654365431885431 or something to that effect. I know the > answer is staring me in the face somewhere in that module documentation (does > that stuff make sense to anyone? ;) ), but for the life of me I can't find > it. The random module ? http://python.org/doc/current/lib/module-random.html -- Le courrier est un moyen de communication. Les gens devraient se poser des questions sur les implications politiques des choix (ou non choix) de leurs outils et technologies. Pour des courriers propres : -- From magnus@thinkware.se Wed Jan 22 13:33:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Wed Jan 22 13:33:01 2003 Subject: [Tutor] Fun with random numbers In-Reply-To: <200301220942.33139.blackmariah@shmups.com> References: <5.1.0.14.0.20030122161806.02cc4ec8@www.thinkware.se> <" <7497DCA1C240C042B28F6657ADFD8E09702353"@i2km11-ukbr.domain1.systemhost.net> <7497DCA1C240C042B28F6657ADFD8E09702353@i2km11-ukbr.domain1.systemhost.net> <5.1.0.14.0.20030122161806.02cc4ec8@www.thinkware.se> Message-ID: <5.1.0.14.0.20030122184105.02cc4d28@www.thinkware.se> At 09:42 2003-01-22 -0500, Michael Miller wrote: >I'm wanting to create a string of random numbers of a given length. I know >how >to generate one number, but getting 5 or 15 or 50 at one time is escaping me. Do you mean 50 numbers of some given size, of do you mean a number with 50 digits. It's not the same thing... I'm sure you can change my code from 27 digits to 50 it you wish. Making it into a function that takes length as a parameter isn't exactly rocket science either... >I'm messing with some very, excruciatingly trivial "encryption" type things >mostly just to have something to do. Encryption is a very tricky subject, and I fear that Python is all too slow to be really useful for real encrytion. Maybe it would be more worthwhile to study some of the already existing encryption libraries for python that are wrappers to C libraries, and to make some useful application that really uses one of them. I think that's the practical way to do crypto with Python. See http://py.vaults.ca/apyllo.py?i=94738404 http://www.post1.com/home/ngps/m2/ http://www.amk.ca/python/code/crypto.html http://eevolved.com/cryptkit/ -- 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 brad.reisfeld@colostate.edu Wed Jan 22 14:16:01 2003 From: brad.reisfeld@colostate.edu (Brad Reisfeld) Date: Wed Jan 22 14:16:01 2003 Subject: [Tutor] Re: Fun with random numbers Message-ID: Michael Miller wrote: > It appears my first post didn't go through. Grrr.... > How can I easily generate a bunch of random numbers? For example, > 543765843675465436788654365431885431 or something to that effect. I know the > answer is staring me in the face somewhere in that module documentation (does > that stuff make sense to anyone? ;) ), but for the life of me I can't find > it. > Hi, As a quick and dirty approach (not concerned with the issues of the 'goodness' or distribution of the pseudo-random numbers generated, or the speed of the code) you could use the following: >> import random >> nl=50 >> long(''.join([random.choice('0123456789') for x in range(nl)])) If 0 is generated at the first 'digit' position, you'll only get nl-1 digits. If you care about this... >> long(random.choice('123456789') + ''.join([random.choice('0123456789') for x in range(nl-1)])) For a more serious approach, see Tim Peters' code at http://www.faqts.com/knowledge_base/view.phtml/aid/4406/fid/546 -Brad From Jmllr891@cs.com Wed Jan 22 17:49:01 2003 From: Jmllr891@cs.com (Jmllr891@cs.com) Date: Wed Jan 22 17:49:01 2003 Subject: [Tutor] capturing screenshots Message-ID: <000801c2c268$97e2b680$58bc8018@ne1.client2.attbi.com> ------=_NextPart_000_0005_01C2C23E.AE8F8F40 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable I have been looking for ways to capture screenshots using Python, but I have= found nothing to help me. I have taken a few looks at the 'os' module, but=20= couldn't find anything that looked helpful, although I probably missed somet= hing. I have tried to find what I need by searching Google and the Python tu= tor archive several times, but to no avail. I'm not looking for a direct answer, just a hint at what I would have to do=20= to capture screenshots in Python. Would I need to do something like simulate= a key press (if that's possible) or is there a function or module somewhere= that I'm just not aware of yet? Also, I'm trying to accomplish this in Windows. Thanks for the help, Joshua Miller ------=_NextPart_000_0005_01C2C23E.AE8F8F40 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
I have been looking for ways to capture scr= eenshots=20 using Python, but I have found nothing to help me. I have taken a few looks=20= at=20 the 'os' module, but couldn't find anything that looked helpful, although I=20 probably missed something. I have tried to find what I need by searching Goo= gle=20 and the Python tutor archive several times, but to no avail.
 
I'm not looking for a direct answer, just a= hint at=20 what I would have to do to capture screenshots in Python. Would I need to=20 do something like simulate a key press (if that's possible) or is there= a=20 function or module somewhere that I'm just not aware of yet?
 
Also, I'm trying to accomplish this in=20 Windows.
 
Thanks for the help,
Joshua=20 Miller
------=_NextPart_000_0005_01C2C23E.AE8F8F40-- From BranimirP@cpas.com Wed Jan 22 19:59:02 2003 From: BranimirP@cpas.com (Branimir Petrovic) Date: Wed Jan 22 19:59:02 2003 Subject: [Tutor] capturing screenshots Message-ID: <33678E78A2DD4D418396703A750048D41A63E6@RIKER> This message is in MIME format. Since your mail reader does not understand this format, some or all of this message may not be legible. ------_=_NextPart_001_01C2C27A.D03702E0 Content-Type: text/plain; charset="iso-8859-1" Since your target platform is Windows, one (and only?) admittedly kludgey way to pull something of this sort would be via free third party COM component - AutoIt.dll. It might help you (to a degree) in dealing with pains emanating from (ahem) lovely, non scriptable, GUI-only aspects of Windows environment. You could 'drive' it (AutoIt.dll) from Python and Mark Hammond's Win23all extensions, activate app you are interested in, then by sending ALT + P or CTRL + P keystrokes you might capture active window or whole desktop bitmap an paste it to the clipboard. Once there - on the clipboard - you have a way with it (Win32all again)... http://www.hiddensoft.com/AutoIt/index.html I doubt very much that proper Python way or suitable module for 'driving' (or interacting with) Windows GUI exists, especially so when even much simpler task like the one Python Expect module tackles (driving/interacting with command line apps/utilities) - does not exist for Windows platform. Branimir -----Original Message----- From: Jmllr891@cs.com [mailto:Jmllr891@cs.com] Sent: Wednesday, January 22, 2003 5:50 PM To: tutor@python.org Subject: [Tutor] capturing screenshots I have been looking for ways to capture screenshots using Python, but I have found nothing to help me. I have taken a few looks at the 'os' module, but couldn't find anything that looked helpful, although I probably missed something. I have tried to find what I need by searching Google and the Python tutor archive several times, but to no avail. I'm not looking for a direct answer, just a hint at what I would have to do to capture screenshots in Python. Would I need to do something like simulate a key press (if that's possible) or is there a function or module somewhere that I'm just not aware of yet? Also, I'm trying to accomplish this in Windows. Thanks for the help, Joshua Miller ------_=_NextPart_001_01C2C27A.D03702E0 Content-Type: text/html; charset="iso-8859-1"
 
Since your target platform is Windows, one (and only?) admittedly kludgey way to pull something of this sort would be via free third party COM component - AutoIt.dll. It might help you (to a degree) in dealing with pains emanating from (ahem) lovely, non scriptable, GUI-only aspects of Windows environment.
 
You could 'drive' it (AutoIt.dll) from Python and Mark Hammond's Win23all extensions, activate app you are interested in, then by sending ALT + P or CTRL + P keystrokes you might capture active window or whole desktop bitmap an paste it to the clipboard. Once there - on the clipboard - you have a way with it (Win32all again)...
 
 
I doubt very much that proper Python way or suitable module for 'driving' (or interacting with) Windows GUI exists, especially so when even much simpler task like the one Python Expect module tackles (driving/interacting with command line apps/utilities) - does not exist for Windows platform.
 
Branimir
 
-----Original Message-----
From: Jmllr891@cs.com [mailto:Jmllr891@cs.com]
Sent: Wednesday, January 22, 2003 5:50 PM
To: tutor@python.org
Subject: [Tutor] capturing screenshots

I have been looking for ways to capture screenshots using Python, but I have found nothing to help me. I have taken a few looks at the 'os' module, but couldn't find anything that looked helpful, although I probably missed something. I have tried to find what I need by searching Google and the Python tutor archive several times, but to no avail.
 
I'm not looking for a direct answer, just a hint at what I would have to do to capture screenshots in Python. Would I need to do something like simulate a key press (if that's possible) or is there a function or module somewhere that I'm just not aware of yet?
 
Also, I'm trying to accomplish this in Windows.
 
Thanks for the help,
Joshua Miller
------_=_NextPart_001_01C2C27A.D03702E0-- From beercanz@hotmail.com Thu Jan 23 00:22:02 2003 From: beercanz@hotmail.com (Guess Who? Me) Date: Thu Jan 23 00:22:02 2003 Subject: [Tutor] Separating recursion, for loops, and while loops Message-ID: I started working on my dice program again, only this time I've decided to split it up - I want to eventually make three entirely separate ways to do the same thing (just for practice's sake) - one with a 'with' loop, one with a 'for' loop, and one with recursion. I have a question about the 'referencing local variable total before assignment', and I'd like some input (ha ha - no pun intended) on what I've done so far, if there is anything I should be doing differently, etc. (The program isn't finished, only the first part of it works, and the second part of it gives me that strange referencing error, even when I put total=0 at the top...well anyway, here is the code). ################ #Dice Roll Program import random #Use for loops, while loops, and recursion, separately, to yield #a dice program. def loop_dice(rolls, sides): if rolls<1: print "If you don't play, you can't win or lose." elif sides<1: print "There are either 0 sides, or infinitely many sides. Trippy." while rolls > 0: value=random.randint(1,sides) rolls=rolls-1 print value def for_dice(rolls, sides): if rolls<1: print "If you don't play, you can't win or lose." elif sides <1: print "There are either 0 sides, or infinitely many sides. Trippy." # I had a problem using rolls because it wasn't in a form that the #for list could swallow, I think, so I made it use the output of the #range #function. rolls=range(1,rolls) for elem in rolls: elem=random.randint(1,sides) value=elem total=value+total #'local variable total referenced before assignment' print total else: print "The end." choice=input("Press 0 to try my (working) while loop code,"\ "press 1 to use the for loop code:") rolls=input("How many rolls would you like to make?") sides=input("How many sides would you like to make?") if choice == 0: print loop_dice(rolls,sides) elif choice == 1: print for_dice(rolls,sides) ################### And one more thing - the first part, loop_dice, outputs things on different lines - is there any way, without using recursion, to add all the numbers together before printing them? And if I am using recursion, same question - can I output add the numbers together and output them? I'm sure I can, I just don't know how, and would appreciate the enlightenment. Oh, and the 'for' statement wouldn't work when I would use the input 'rolls' as a number - was that just in my imagination? http://www.python.org/doc/current/ref/for.html says it can 'iterate over' the following: string, tuple or list. Why would you 'iterate' over a string - isn't a single string just one thing? Or does it mean that it can do operations on a string, and therefore can do operations on a string in a list? Why would you use the for statement for that? Also, what in the world is a tuple? Well...I'm done. I hope the questions aren't too horrible. Thank you for all of the previous help, (I think its starting to show a little! WOOHOO!) ~Travis _________________________________________________________________ Protect your PC - get McAfee.com VirusScan Online http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963 From jjhegde@konark.ncst.ernet.in Thu Jan 23 02:11:48 2003 From: jjhegde@konark.ncst.ernet.in (Jayprasad J. Hegde) Date: Thu Jan 23 02:11:48 2003 Subject: [Tutor] Separating recursion, for loops, and while loops In-Reply-To: References: Message-ID: <20030123070756.GA3367@ncst.ernet.in> hello "Guess who?", I have modified your program to make it work for "while", "for" and the recursive case. All the three have a similar behaviour, unlike the original version, and print out the dice "values" before terminating by printing out the cumulative values ("total"). problem with "while" version: _no_ return value; you are using "print while_dice..." in the main portion of the code My version: returns the total problem with the "for" version: 1. _no_ return value 2. redundancy for a short code e.g. > elem=random.randint(1,sides) > value=elem. I guess, if it helps you understand better you can stick to it. 3. total used on the RHS before "declaring". To avoid this problem you need to say "total = ..." before this statement. I have created a recursive version for you, in case you need some reference. Its open to all for comments. > > And one more thing - the first part, loop_dice, outputs things on different > lines - is there any way, without using recursion, to add all the numbers > together before printing them? you mean _juxtapositioning_ (or putting things on the same line) and not _addition_ don't you? In that case simply put a comma at the end of the print statement e.g. "print value," > > And if I am using recursion, same question - can I output add the numbers > together and output them? I'm sure I can, I just don't know how, and would > appreciate the enlightenment. check out the code. :) You'll find the code below my "signature" section. regards - JJH ps - why the anonymity? -- Human beings were created by water to transport it uphill. (defun JJHdetails () (format t "~&~A~&~A~&~A" "Jayprasad J Hegde, Staff Scientist, KBCS, NCST" "Gulmohar Cross Road 9, Juhu, Mumbai 400049." "tel: +91-22-26201606x373")) ------------------- import random def loop_dice(rolls, sides): if rolls<1: print "If you don't play, you can't win or lose." elif sides<1: print "There are either 0 sides, or infinitely many sides. Trippy." total = 0 while rolls > 0: value=random.randint(1,sides) rolls=rolls - 1 print value, total = total + value print return total def for_dice(rolls, sides): if rolls<1: print "If you don't play, you can't win or lose." elif sides <1: print "There are either 0 sides, or infinitely many sides. Trippy." total = 0 for elem in range (rolls): value=random.randint(1,sides) total= value + total #'local variable total referenced before assignment' print value, print return total def rec_dice (myrolls, mysides): total = 0 if (myrolls >= 0): value = random.randint (1, mysides) print value, total = rec_dice (myrolls - 1, mysides) + value return total choice=input(" 0 == while, 1 == for, 2 == rec:") rolls=input("How many rolls would you like to make?") sides=input("How many sides would you like to make?") if choice == 0: print loop_dice(rolls,sides) elif choice == 1: print for_dice(rolls,sides) elif choice == 2: print print rec_dice (rolls, sides) From p.hartley@spitech.com Thu Jan 23 04:39:01 2003 From: p.hartley@spitech.com (Paul Hartley) Date: Thu Jan 23 04:39:01 2003 Subject: [Tutor] Database driven web sites with python References: Message-ID: <001401c2c2c5$5a8e0d40$ebe710ac@pc7345> I tried the following code from a book - I just wanted a simple web site to test out some ideas and balked at installing Apache or Zope on my PC. It works OK for HTML pages but I can't get CGI scripte to work - I don't know anything about CGI though.. I would like to know how to get cgi scripts to work with this code (what do I put in the htmp page etc. simple steps!! # web.py import os from BaseHTTPServer import HTTPServer from CGIHTTPServer import CGIHTTPRequestHandler # os.chdir("/test/web/html") # Change to web directory! srvraddr = ("", 80) srvrobj = HTTPServer(srvraddr, CGIHTTPRequestHandler) srvrobj.serve_forever() ----- Original Message ----- From: Danny Yoo To: Danny Cc: Sent: Wednesday, January 22, 2003 1:25 AM Subject: Re: [Tutor] Database driven web sites with python [Phil and Alex's Guide to Web Publishing] > > > On Fri, 17 Jan 2003, Danny wrote: > > > Quick and easy question, can you use python to build database driven web > > sites. Thanks ahead of time for everyone help, and have a great > > weekend... > > Out of curiosity, what kind of database-driven web site are you thinking > of building? > > If you haven't seen this already, you may find "Phil and Alex's Guide to > Web Publishing" a useful (and amusing) web book to browse through: > > http://philip.greenspun.com/panda/ > > In particular: > > http://philip.greenspun.com/panda/databases-interfacing > > talks about the basics of writing database-driven sites. He uses a > programming language called Tcl/Tk to implement his site, but you can > translate that code to Python pretty easily. And even with the book's > non-Python focus, it gives a lot of good ideas that you can use to help > build your site. > > > Good luck to you! > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From magnus@thinkware.se Thu Jan 23 04:41:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Thu Jan 23 04:41:02 2003 Subject: [Tutor] capturing screenshots In-Reply-To: <000801c2c268$97e2b680$58bc8018@ne1.client2.attbi.com> Message-ID: <5.1.0.14.0.20030123103555.02c65eb0@www.thinkware.se> At 17:49 2003-01-22 -0500, Jmllr891@cs.com wrote: >I have been looking for ways to capture screenshots using Python, but I >have found nothing to help me. I have taken a few looks at the 'os' >module, but couldn't find anything that looked helpful, although I >probably missed something. I have tried to find what I need by searching >Google and the Python tutor archive several times, but to no avail. Look at Fredrik Lundh's stuff. He's the main imaging wizard of Pythondom. He's the guy who's behind the weather maps we see on TV here in Scandinavia, and his skills go further than weather forcast imaging. http://www.effbot.org/downloads/index.cgi/grabscreen-1.0-20010426.zip As far as I understand from the docs, this grabscreen stuff should be included in PIL now, but I didn't get it to work without this separate download. -- 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 charlie@begeistert.org Thu Jan 23 05:10:00 2003 From: charlie@begeistert.org (Charlie Clark) Date: Thu Jan 23 05:10:00 2003 Subject: [Tutor] Question about connections Message-ID: <20030123110904.1522.7@.1043311993.fake> Dear list, I've got to set up a mail-broadcast system which publishes to a lot (several thousand) of e-mail addresses and was wondering about the possible= problems and bottlenecks as one of the criteria is very rapid publishing to= the addresses. What are the best ways to approach this? Is it "expensive" to set up smtp connections and would it make sense to batch addresses (say several hundred at once)? in bcc: fields? I was thinking of batch publishing to several MTAs at once. Some thing a bit like this very bad pseudo code: msg =3D "You've been spammed" addresses =3D from_db_fetch_many(500) hosts =3D [host1, host2, host3, host4...] host_nr =3D 0 while addresses: =09mail.addHeader("bcc:", addesses) =09host =3D hosts[host_nr] =09smtplib.connect(host) =09smtplib.send("", "me@myhost.com", msg) I'd rather not reinvent the wheel on this and have started looking at Mailman for this but I'm not sure if that is the right thing for a broadcast only list with the addresses probably being held in an external source. Thanx for any suggestions / corrections Charlie From magnus@thinkware.se Thu Jan 23 06:07:05 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Thu Jan 23 06:07:05 2003 Subject: [Tutor] Database driven web sites with python In-Reply-To: <001401c2c2c5$5a8e0d40$ebe710ac@pc7345> References: Message-ID: <5.1.0.14.0.20030123105922.02cb6a18@www.thinkware.se> At 17:54 2003-01-23 +0800, Paul Hartley wrote: >It works OK for HTML pages but I can't get CGI scripte to work - I don't >know anything about CGI though.. If you are planning to actually use the Python web server classes, there is no reason to spawn any new processes for CGI scripts if they are written in Python. You can simply import the python modules you need (or include the code in the same file as the web server stuff) and run it like a normal python program. For an example of this approach (which actually uses os.popen to run windows commands, but that's beside the point) look here: http://www.thinkware.se/cgi-bin/thinki.cgi/PyNetworkCheck CGI - The Common Gateway Interface - will make your web application slower, since the programs have to be started from scratch on each new request. (In the above case it would make no difference, since I have to run slow networking diagnostic commands. There it's more a matter of convenience.) If, on the other hand, you are going to run Python scripts from a web server such as Apache or IIS, you might not have any options, but to use CGI. But then you don't need to bother with the Python web server classes. Using both together sounds a bit odd to me (even if it's supported by Python). -- 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@thinkware.se Thu Jan 23 06:13:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Thu Jan 23 06:13:01 2003 Subject: [Tutor] Question about connections In-Reply-To: <20030123110904.1522.7@.1043311993.fake> Message-ID: <5.1.0.14.0.20030123120634.02cb2aa8@www.thinkware.se> At 11:09 2003-01-23 +0100, Charlie Clark wrote: >I've got to set up a mail-broadcast system which publishes to a lot >(several thousand) of e-mail addresses and was wondering about the possible >problems and bottlenecks as one of the criteria is very rapid publishing to >the addresses. You mean problems such as people being angry because you spammed them? >What are the best ways to approach this? Not to do it? This does not really seem like a Python related question anyway, does it? I'm sure Python could handle it, the question is rather about mail servers, network (and possibly moral and legal issues ;). I'm sure there are more suitable forums for such questions. -- 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 charlie@begeistert.org Thu Jan 23 06:19:09 2003 From: charlie@begeistert.org (Charlie Clark) Date: Thu Jan 23 06:19:09 2003 Subject: [Tutor] Question about connections In-Reply-To: <5.1.0.14.0.20030123120634.02cb2aa8@www.thinkware.se> References: <5.1.0.14.0.20030123120634.02cb2aa8@www.thinkware.se> Message-ID: <20030123121636.2163.9@.1043311993.fake> On 2003-01-23 at 12:12:20 [+0100], Magnus Lycka wrote: > > You mean problems such as people being angry because you spammed them? no, no spam involved. Completely legit mailing to registered users who want to receive it. Sorry, I didn't make this clear enuff initially. > >What are the best ways to approach this? > > Not to do it? > > This does not really seem like a Python related question anyway, does it? > I'm sure Python could handle it, the question is rather about mail > servers, network (and possibly moral and legal issues ;). I'm sure there > are more suitable forums for such questions. Indeed but it seems important how you feed the MTAs I've started looking at how Mailman handles this and will probably start my discussions there. Charlie From Deirdre Hackett" This is a multi-part message in MIME format. ------=_NextPart_000_0050_01C2C2EA.D3F85BC0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable I want to read in infromation from the serial port. The probem is i can = take i the whole line but only want to read it in in lumps of 9 = characters.=20 As in, I want to read the first 9 characters and put that into X, then = read in the next 9 characters and put that into Y... Any advise. =20 Thanks, dee ------=_NextPart_000_0050_01C2C2EA.D3F85BC0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
I want to read in infromation from the = serial port.=20 The probem is i can take i the whole line but only want to read it in in = lumps=20 of 9 characters.
As in, I want to read the first 9 = characters and=20 put that into X, then read in the next 9 characters and put that into=20 Y...
Any advise.    =
Thanks, dee
------=_NextPart_000_0050_01C2C2EA.D3F85BC0-- From dman@dman.ddts.net Thu Jan 23 10:09:01 2003 From: dman@dman.ddts.net (Derrick 'dman' Hudson) Date: Thu Jan 23 10:09:01 2003 Subject: [Tutor] Re: Splitting up the input In-Reply-To: <005301c2c2ea$d7fe53a0$0400a8c0@egbert> References: <005301c2c2ea$d7fe53a0$0400a8c0@egbert> Message-ID: <20030123150827.GA27184@dman.ddts.net> --qDbXVdCdHGoSgWSk Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Thu, Jan 23, 2003 at 02:22:15PM -0000, Deirdre Hackett wrote: | I want to read in infromation from the serial port. The probem is i | can take i the whole line but only want to read it in in lumps of 9 | characters.=20 | As in, I want to read the first 9 characters and put that into X, | then read in the next 9 characters and put that into Y... There are a couple of ways to do that with varying tradeoffs : (assume 'f' is a file object referring to the serial port; if you use windows I can't help with getting that object) line =3D f.readline() X =3D line[:9] Y =3D line[9:18] This will fail (with an IndexError) if the line is too short. Another way is to only read in 9 characters : X =3D f.read(9) Y =3D f.read(9) This will yield different results if the end of the input stream is encountered before 9 characters have been read. It will also count CR and LF as part of the 9 characters. In all cases you need to check the input to make sure you have what you expect to have before proceeding and deal with the situation if something isn't right.=20 HTH, -D --=20 "He is no fool who gives up what he cannot keep to gain what he cannot lose= ." --Jim Elliot =20 http://dman.ddts.net/~dman/ --qDbXVdCdHGoSgWSk Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAj4wBWsACgkQO8l8XBKTpRTIuwCbBn63AAUz2b7dKgzgW6mplxXb htYAoI+N3BzscFOjwolDeS46IWaHfOMc =BbKO -----END PGP SIGNATURE----- --qDbXVdCdHGoSgWSk-- From dman@dman.ddts.net Thu Jan 23 10:23:01 2003 From: dman@dman.ddts.net (Derrick 'dman' Hudson) Date: Thu Jan 23 10:23:01 2003 Subject: [Tutor] Re: Question about connections In-Reply-To: <20030123121636.2163.9@.1043311993.fake> References: <5.1.0.14.0.20030123120634.02cb2aa8@www.thinkware.se> <20030123121636.2163.9@.1043311993.fake> Message-ID: <20030123151634.GB27184@dman.ddts.net> --gj572EiMnwbLXET9 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Thu, Jan 23, 2003 at 12:16:36PM +0100, Charlie Clark wrote: | Indeed but it seems important how you feed the MTAs That can be an important factor. Suppose you feed the MTA a single address at a time. The MTA must then handle each copy of the message as if it is an entirely separate message. If, however, you tell the MTA that the message is being delivered to an entire list of addresses, then for one thing it will have fewer messages on the queue to deal with, and it can optimize the transfer to other hosts by sending the message once with multiple recipients. | I've started looking at how Mailman handles this and will probably | start my discussions there. I recommend using mailman to handle the list and postfix to handle the mail. With my current setup (which only handles small lists so I haven't optimized it) mailman passes the message to the MTA separately for each recipient. It does this because I like the idea of using the return address to identify which list member has delivery problems. The return address looks like "list-name+user=3Ddomain@mydomain". I believe that if I look into using the VERP extension to SMTP then the mailman can inject only a single copy of the message to the MTA and still take advantage of the unique return addresses. The other optimization alternative is to have a single return address and mailman must then try parsing out the message to determine which address had a delivery failure. HTH, -D --=20 The way of a fool seems right to him, but a wise man listens to advice. Proverbs 12:15 =20 http://dman.ddts.net/~dman/ --gj572EiMnwbLXET9 Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAj4wB1IACgkQO8l8XBKTpRSogACfanfQ6RVT7uvFQ2vQf8QRk/R0 ZOIAn0I5SAwoopyYcUGhXD/PzXTeV1rr =vijF -----END PGP SIGNATURE----- --gj572EiMnwbLXET9-- From dyoo@hkn.eecs.berkeley.edu Thu Jan 23 11:13:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Jan 23 11:13:01 2003 Subject: [Tutor] Re: Splitting up the input In-Reply-To: <20030123150827.GA27184@dman.ddts.net> Message-ID: On Thu, 23 Jan 2003, Derrick 'dman' Hudson wrote: > On Thu, Jan 23, 2003 at 02:22:15PM -0000, Deirdre Hackett wrote: | I > want to read in infromation from the serial port. The probem is i | can > take i the whole line but only want to read it in in lumps of 9 | > characters. > > | As in, I want to read the first 9 characters and put that into X, | > then read in the next 9 characters and put that into Y... > > There are a couple of ways to do that with varying tradeoffs : > > (assume 'f' is a file object referring to the serial port; if you use > windows I can't help with getting that object) > > line = f.readline() > X = line[:9] > Y = line[9:18] Hello! It might be a better idea to avoid readline() on a "binary" stream, since there's a chance that there won't be any newlines in the file. In a worse case, if there aren't any newlines in this large file, then Python will waste a lot of effort trying to pull all the characters into memory. The read() method is much safer since we know that we want to pull chunks of 9 bytes (characters) at a time. > This will fail (with an IndexError) if the line is too short. No, the slicing above should not fail. For example, > line = f.readline() > X = line[:9] > Y = line[9:18] Here, Python will assign an empty string to 'Y' if the 'line' is too short for the slice. For example: ### >>> line = "this is a test" >>> x = line[0:20] >>> y = line[20:100] >>> x 'this is a test' >>> y '' ### This is because something like 'line[20:100]' asks Python: "Give me a string containing all the characters between indices 20 and 100". But there are no characters that span, so we get back the empty string. (It's analogous to the "vacuously true" sort of situation that mathematicians run into every so often.) Hope that clarifies things! From op73418@mail.telepac.pt Thu Jan 23 11:39:24 2003 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Thu Jan 23 11:39:24 2003 Subject: [Tutor] Splitting up the input References: <005301c2c2ea$d7fe53a0$0400a8c0@egbert> Message-ID: <003201c2c2fe$a9c44850$b2160dd5@violante> ----- Original Message ----- From: Deirdre Hackett To: tutor@python.org Sent: Thursday, January 23, 2003 2:22 PM Subject: [Tutor] Splitting up the input >I want to read in infromation from the serial port. The probem is i can take i the whole line but only want to read it in in lumps of 9 characters. >As in, I want to read the first 9 characters and put that into X, then read in the next 9 characters and put that into Y... >Any advise. >Thanks, dee I don't know how to get at the serial port, but supposing you can get at it via a file object you can use the new generator facilities in Python 2.2 via (beware: untested code) def get(f, size): buffer = '' while True: #If the buffer is not enough to fulfill request get more from the file. if len(buffer) < size: data = f.read(size) if not data: raise StopIteration buffer += data else: ret, buffer = buffer[:size], buffer[size:] yield ret The function keeps an internal buffer, yielding size bytes at a time. Now you can just do it = get(, 9) And use with it.next() or in a for loop. Hope it helps, G. Rodrigues From dyoo@hkn.eecs.berkeley.edu Thu Jan 23 11:49:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Jan 23 11:49:01 2003 Subject: [Tutor] Database driven web sites with python In-Reply-To: <001401c2c2c5$5a8e0d40$ebe710ac@pc7345> Message-ID: On Thu, 23 Jan 2003, Paul Hartley wrote: > I tried the following code from a book - I just wanted a simple web site > to test out some ideas and balked at installing Apache or Zope on my PC. Hi Paul! Having a Web server on a PC may not be too bad of an idea though, since it'll allow you to play around with web serving. Since Apache's free for download, why not try it out? http://httpd.apache.org/ http://httpd.apache.org/docs-2.0/howto/cgi.html You may find that it's not as difficult as you might expect. And if you do run into problems, Apache has a few resources that you can try out: http://httpd.apache.org/lists.html#http-users > I would like to know how to get cgi scripts to work with this code (what > do I put in the htmp page etc. simple steps!! No problem. Let's take a look. > # web.py > > import os > > from BaseHTTPServer import HTTPServer > > from CGIHTTPServer import CGIHTTPRequestHandler Ok, good, so this gives us access to the CGIHTTPServer class. > # os.chdir("/test/web/html") # Change to web directory! > > srvraddr = ("", 80) > srvrobj = HTTPServer(srvraddr, CGIHTTPRequestHandler) > > srvrobj.serve_forever() (You may run into a small permissions problem here: port 80, the port for http web serving, should be reserved for administrative users. On Unix systems, any port below 1024 can be grabbed by a program only by root, for security reasons. So while you're testing CGI stuff, you might need to run your program on a different port, like '8080'. This warning might not apply on Windows systems though...) Ah! In your line here, when you create the server itself: > srvrobj = HTTPServer(srvraddr, CGIHTTPRequestHandler) you may need to customize the CGIHTTPRequestHandler: by default, it looks for cgi's the '/cgi-bin' and '/htbin' directories, but you may need to extend this if you want CGI's to run in different places. For example, here's a way to customize that class so that whenever a url begins with '/mycgis', Python will treat scripts there as CGI's: ### class CustomCgiHandler(CGIHTTPRequestHandler): cgi_directories = ["/mycgis"] ### Once we have something like this, we can feed this CustomCgiHandler class to our server. Here's an interactive session that shows how this can work: ### [dyoo@tesuque dyoo]$ pwd /home/dyoo [dyoo@tesuque dyoo]$ ls cgi-bin hello.py [dyoo@tesuque dyoo]$ cat cgi-bin/hello.py #!/usr/bin/env python print "Content-type: text/plain\n\n" print "Hello world!" [dyoo@tesuque dyoo]$ cat test_cgi.py from BaseHTTPServer import HTTPServer from CGIHTTPServer import CGIHTTPRequestHandler class CustomCgiHandler(CGIHTTPRequestHandler): cgi_directories = ["/cgi-bin"] def main(): srvraddr = ("", 8888) srvrobj = HTTPServer(srvraddr, CustomCgiHandler) srvrobj.serve_forever() if __name__ == '__main__': main() [dyoo@tesuque dyoo]$ python test_cgi.py & [1] 15919 [dyoo@tesuque dyoo]$ lynx -source http://localhost:8888/cgi-bin/hello.py localhost.localdomain - - [23/Jan/2003 08:44:19] "GET /cgi-bin/hello.py HTTP/1.0" 200 - Hello world! ### That last command using 'lynx' is a Unix program that grabs web resources and dumps them to screen., and the few lines about 'localhost.localdomain' is log information that the server prints out on every request. But at the very bottom, we see the glorious message 'Hello world!", so we know that things are working. Does this work for you? I hope this helps! From alan.gauld@bt.com Thu Jan 23 12:15:57 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu Jan 23 12:15:57 2003 Subject: [Tutor] Separating recursion, for loops, and while loops Message-ID: <7497DCA1C240C042B28F6657ADFD8E0974DA96@i2km11-ukbr.domain1.systemhost.net> > the same thing (just for practice's sake) - one with a 'with' > loop, I assume you mean a while loop... > a 'for' loop, and one with recursion. Good idea. Should be interesting. > def loop_dice(rolls, sides): > while rolls > 0: > value=random.randint(1,sides) > rolls=rolls-1 > print value > > def for_dice(rolls, sides): > rolls=range(1,rolls) > for elem in rolls: I think you mean rolls = range(1,rolls+1) # generates [1...10] Or more pythonically: rolls=range(rolls): # generates [0...9] Or evenb more pythonically: for elem in range(rolls): > elem=random.randint(1,sides) > value=elem > total=value+total > #'local variable total referenced before assignment' You are creating the variable using itself, whioch isn't possible. You need to do total=0 outside the loop. > And one more thing - the first part, loop_dice, outputs > things on different lines - is there any way, without using > recursion, to add all the numbers together before printing them? Either just add them inside the loop or create a list and then add the values later using reduce(operator.add, numbers) But i'd think you might prefer to output the values on a single line by sticking a comma after the print: print value, # comma suppresses the newline > And if I am using recursion, same question - can I output add > the numbers together and output them? Same applies. In the return statement add instead of printing... Or append to a list and then output the result at the end. > Oh, and the 'for' statement wouldn't work when I would use > the input 'rolls' as a number - was that just in my imagination? You need to use range() coz the for loop in python is really a foreach loop and requires a sequence to work on. A number is not a sequence, range makes it into one... > the following: string, tuple or list. Why would you 'iterate' > over a string To process each letter in turn - say to encrypt it? > what in the world is a tuple? Simply a collection of values that you can't change(in Python). Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From alan.gauld@bt.com Thu Jan 23 12:29:01 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu Jan 23 12:29:01 2003 Subject: [Tutor] Splitting up the input Message-ID: <7497DCA1C240C042B28F6657ADFD8E0970235E@i2km11-ukbr.domain1.systemhost.net> > I want to read in infromation from the serial port. To some extent this will epend on your OS and machine architecture. > The probem is i can take i the whole line but only want to read > it in in lumps of 9 characters. Assuming the data arrives in sensible line format then you might be best ton read the line into a buffer and then use slicing to access the data within it. If the data does not naturally arrive as a line then you may need to use the fctl or ioctl functions to read from the serial file decriptor the required number of bytes as they arrive in the buffer. Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From tim@johnsons-web.com Thu Jan 23 13:58:02 2003 From: tim@johnsons-web.com (Tim Johnson) Date: Thu Jan 23 13:58:02 2003 Subject: [Tutor] Article/Code/Python vs. Rebol Message-ID: <20030123190040.GB24149@johnsons-web.com> Hello All: I've written two "columns" for a local 'webzine': It's at http://www.frozen-north-linuxonline.com/ One column is on mailing lists and my part of it is under "Tim's Byte's". Python (and rebol) is mentioned there. The other column is under "Code Corner" (link on right hand side). Content related to "Code Corner" was shared on this list earlier under the thread: Comparative code questions: Python vs. Rebol Enjoy! -- Tim Johnson http://www.alaska-internet-solutions.com http://www.johnsons-web.com From billintucson@yahoo.com Thu Jan 23 16:15:02 2003 From: billintucson@yahoo.com (Bill Gillespie) Date: Thu Jan 23 16:15:02 2003 Subject: [Tutor] How best to create a sharp telemetry log file - from one long string of teletry? Message-ID: <20030123211407.54009.qmail@web11807.mail.yahoo.com> Hi Folks, I want to say thanks to the group for some help I recieved a few months ago in writing a simple GUI in tkinter. The finished gui source code as well as some screen shots of what it looks like is available here: http://www.noao.edu/noao/staff/gillespie/projects/oftc-gui-software-demo.html Now I'm trying to write a nicely formatted log file out of a single string of telemtry that I read of a serial line. The string had 40 different values - numbers such a "120", and titles sucs as "OFT" There are 40 of these seperated by white space. What is the best way to extract just the numerical values from the long string, and then write them into a nicely formatted log file, that will place each numerical value into it's own column? I've learned about the string format codes from Alan's book (page 32) but I do not know where to insert the formatting operation. Nor do I understand the best way to slice up the string and then operate on the slices. Alans shows an exaple that I'd like to apply that I think will give me the format I need - but I dont know where or how to apply it to the 20 number sclices from the string. The format is this: say for the value of 120. '%8.2f' % 120 Here is an example of what I'm trying to do: 1) read single long telemetry string from serial line (using pyserial module) 2) slice string up into seperate segments such as 120, 213, OFT, -8, -311, OCI,etc. Discard all of the non-number segments and keep the numbers. 3) append the new telemetry slices into a new row in the log file, using string foramtting conventions - so that the log file generates even columns even though the number of places and sign values in the telemetry string vary. example target log file: A B C D E 120 -130 -20 30 45 -111 122 32 121 231 3 32 76 -2 -432 Any advice most welcome - and thanks much again to the group for the help a couple of months back. Cheers, Bill __________________________________________________ Do you Yahoo!? Yahoo! Mail Plus - Powerful. Affordable. Sign up now. http://mailplus.yahoo.com From clickron@webtv.net Thu Jan 23 16:35:02 2003 From: clickron@webtv.net (Ron A) Date: Thu Jan 23 16:35:02 2003 Subject: [Tutor] files question Message-ID: <4495-3E305FC8-1767@storefull-2133.public.lawson.webtv.net> This keeps adding to the list each time run it. This is what I get [['1', '2', '3'], ['one', 'two', 'three']] [['1', '2', '3', ''], ['one', 'two', 'three', '']] [['1', '2', '3', '', ''], ['one', 'two', 'three', '', '']] I've been playing with it and it's driving me nuts. I'm sure there are better ways to do this, but I gotta know what I've done wrong. Any help is appreciated. hold =3D [] import string =A0 # OPEN AND READ A FILE def mylist(): =A0=A0=A0 data =3D open('testing.txt', 'r') =A0=A0=A0 while 1: =A0=A0=A0=A0=A0=A0=A0 read_me =3D data.readline() =A0=A0=A0=A0=A0=A0=A0 if read_me =3D=3D '': =A0=A0=A0=A0=A0=A0=A0=A0=A0=A0=A0 break =A0=A0=A0=A0=A0=A0=A0 no_n =3D read_me[:-1] =A0=A0=A0=A0=A0=A0=A0 split_me =3D string.split(no_n, '\t') =A0=A0=A0=A0=A0=A0=A0 hold.append(split_me) =A0=A0=A0 print hold =A0=A0=A0 data.close() =A0 # WRITE BACK TO FILE def saveme(): =A0=A0=A0 data =3D open('testing.txt', 'w') =A0=A0=A0 for x in range(len(hold)): =A0=A0=A0=A0=A0=A0=A0 hold[x].append('\n') =A0=A0=A0=A0=A0=A0=A0 join_up =3D string.join(hold[x], '\t') =A0=A0=A0=A0=A0=A0=A0 data.write(join_up) =A0=A0=A0 data.close =A0 mylist() saveme() Ron A=A0 From drewp@bigasterisk.com Thu Jan 23 17:09:24 2003 From: drewp@bigasterisk.com (Drew Perttula) Date: Thu Jan 23 17:09:24 2003 Subject: [Tutor] files question In-Reply-To: Your message of "Thu, 23 Jan 2003 16:34:00 EST." <4495-3E305FC8-1767@storefull-2133.public.lawson.webtv.net> Message-ID: <200301232207.h0NM7es10991@bang.houseoflove> > This keeps adding to the list each time run it. This is what I get > = > [['1', '2', '3'], ['one', 'two', 'three']] > [['1', '2', '3', ''], ['one', 'two', 'three', '']] > [['1', '2', '3', '', ''], ['one', 'two', 'three', '', '']] > = > # WRITE BACK TO FILE > def saveme(): > =A0=A0=A0 data =3D open('testing.txt', 'w') > =A0=A0=A0 for x in range(len(hold)): ---> =A0=A0=A0=A0=A0=A0=A0 hold[x].append('\n') > =A0=A0=A0=A0=A0=A0=A0 join_up =3D string.join(hold[x], '\t') > =A0=A0=A0=A0=A0=A0=A0 data.write(join_up) > =A0=A0=A0 data.close() The indicated line is adding the newline to the list, which means it'll get a tab to "separate" it from the previous list elements. Instead, remove the indicated line and make the next one something like: join_up =3D string.join(hold[x], '\t')+"\n" Also, I fixed "data.close" (get the close method and do nothing with it- a legal no-op) to "data.close()" (call the close method), although that won't affect the behavior of this little program. -Drew From Janssen@rz.uni-frankfurt.de Thu Jan 23 17:30:01 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Thu Jan 23 17:30:01 2003 Subject: [Tutor] files question In-Reply-To: <4495-3E305FC8-1767@storefull-2133.public.lawson.webtv.net> Message-ID: Hello , i've copied and pasted Ron's code, but it doesn't compile, because the indentation whitespaces arn't spaces nor tabs. It's character number 160. Does anyone know where this characters come from? Ron, could you supply code with real spaces (On a sidenote: you trigger spamassassin's MIME_EXCESSIVE_QP test doe to exessive Quoted-Printable with mails like this)? And also the initially content of testing.txt? On first sight i guess you should say join_up = string.join(hold[x], '\t') join_up = join_up + "\n" # you can do this in one step.. instead of: hold[x].append('\n') # --> ["1","2","3","\n"] join_up = string.join(hold[x], '\t') # --> "1\t2\t3\t\n" did you see what happens? Michael From dyoo@hkn.eecs.berkeley.edu Thu Jan 23 17:58:14 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Jan 23 17:58:14 2003 Subject: [Tutor] Article/Code/Python vs. Rebol [defending Perl] In-Reply-To: <20030123190040.GB24149@johnsons-web.com> Message-ID: [warning: I'm defending Perl in this article. Skip if you have a weak stomach for typeglobs. *grin*] On Thu, 23 Jan 2003, Tim Johnson wrote: > Hello All: I've written two "columns" for a local 'webzine': > It's at > http://www.frozen-north-linuxonline.com/ > > One column is on mailing lists and my part of > it is under "Tim's Byte's". > > Python (and rebol) is mentioned there. Hi Tim, Small corrections: the Perl version of the code needs to make sure '$Var2' is capitalized. This is actually more serious than it looks because if we don't 'use strict', Perl will blissfully use 'undef' as a value for '$VAR2'. Also, the Perl code needs to run in a loop to match the behavior of the Rebol and Python code. I have to take exception on the comment: """ According to the perl programmers that submitted the code, this really can't be done in perl. The best that can be done is an anonymous' function. But this is not meant to "show up" perl. Rebol really sucks at regular expressions and regular expressins are perl's forte. We really should do a Code Corner on regular expressions """ This is not correct at all: there IS a perfectly good way to do it in Perl. ### use strict; for my $i(1..5) { $main::{"h$i"} = sub { $_ = shift @_; print("$_"); }; } h1("hello"); h2("world"); ### It's ugly, but it does work. Whoever you talked to about Perl may need to review their material. *cough* Language comparisons are interesting, but not useful if they misrepresent the languages they compare. If you do more langauge comparisons involving Perl, make sure you talk to folks like the people from perlmonks. http://perlmonks.com/ Ok, enough Perl apologizing; back to Python. *grin* Hope this helps! From clickron@webtv.net Thu Jan 23 18:36:01 2003 From: clickron@webtv.net (Ron A) Date: Thu Jan 23 18:36:01 2003 Subject: [Tutor] files question - thanks Message-ID: <23753-3E3078E5-3090@storefull-2137.public.lawson.webtv.net> It works!!! I knew it had to be something that would be obvious to you guys. Thanks for the help. I can sleep easy tonight. Ron A From Don Arnold" Message-ID: <024501c2c343$d1dc5c20$fa12ba3f@defaultcomp> ----- Original Message ----- From: "Bill Gillespie" To: Sent: Thursday, January 23, 2003 3:14 PM Subject: [Tutor] How best to create a sharp telemetry log file - from one long string of teletry? > Hi Folks, > > I want to say thanks to the group for some help I recieved a few months > ago in writing a simple GUI in tkinter. The finished gui source code as > well as some screen shots of what it looks like is available here: > http://www.noao.edu/noao/staff/gillespie/projects/oftc-gui-software-demo.htm l > > Now I'm trying to write a nicely formatted log file out of a single > string of telemtry that I read of a serial line. > > The string had 40 different values - numbers such a "120", and titles > sucs as "OFT" There are 40 of these seperated by white space. > > What is the best way to extract just the numerical values from the long > string, and then write them into a nicely formatted log file, that will > place each numerical value into it's own column? > Almost guaranteed to not be the 'best' way, but maybe something like this would work? inputStr = '12 abc -12.3 c d 14.7 -45 qw 34dkdk 92' numList = [] formatList = [] for item in inputStr.split(): try: if str(item).find('.') > -1: numList.append(float(item)) formatList.append('%10.2f ') else: numList.append((int(item))) formatList.append('%10d ') except: pass resultStr = ''.join(formatList) % tuple(numList) print resultStr >>> 12 -12.30 14.70 -45 92 HTH, Don From dman@dman.ddts.net Thu Jan 23 22:41:48 2003 From: dman@dman.ddts.net (Derrick 'dman' Hudson) Date: Thu Jan 23 22:41:48 2003 Subject: [Tutor] Re: Splitting up the input In-Reply-To: References: <20030123150827.GA27184@dman.ddts.net> Message-ID: <20030124034004.GA2297@dman.ddts.net> --u3/rZRmxL6MmkK24 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Thu, Jan 23, 2003 at 08:11:58AM -0800, Danny Yoo wrote: | On Thu, 23 Jan 2003, Derrick 'dman' Hudson wrote: | > On Thu, Jan 23, 2003 at 02:22:15PM -0000, Deirdre Hackett wrote: | I | > | want to read in infromation from the serial port. The probem is i=20 | > | can take i the whole line but only want to read it in in lumps of | > | 9 characters. | > | > | As in, I want to read the first 9 characters and put that into X, | > | then read in the next 9 characters and put that into Y... | > | > There are a couple of ways to do that with varying tradeoffs : | > | > (assume 'f' is a file object referring to the serial port; if you use | > windows I can't help with getting that object) | > | > line =3D f.readline() | > X =3D line[:9] | > Y =3D line[9:18] | It might be a better idea to avoid readline() on a "binary" stream, since | there's a chance that there won't be any newlines in the file. I agree here. It all depends on the data itself. On my last co-op I had to write a daemon to read SMDR log info from the serial port. SMDR is the log format the Lucent phone switch generated. It was a plain-text format suitable to feed directly into a line printer (80 character lines, new header every 66 lines). Instead of spewing pages of hard-copy logs on the floor, I wrote a daemon to read the data (using readline() since it was ASCII) and split it up into the columns for insertion into a database. That text happened to fall into a strict columnar layout, so "extract 9 characters, then another 9 characters" can be sensible even for text data. If you are reading a binary data stream, however, I agree that using read() directly is better. | > This will fail (with an IndexError) if the line is too short. |=20 | No, the slicing above should not fail. For example, Oops, my bad. I was assuming (without testing) that it would fail the same as indexing does. The non-failure might really be a failure in disguise if you don't ever want to get the empty string. Never forget to over-check the validity of the input! | This is because something like 'line[20:100]' asks Python: "Give me a | string containing all the characters between indices 20 and 100". But | there are no characters that span, so we get back the empty string. | (It's analogous to the "vacuously true" sort of situation that | mathematicians run into every so often.) It's reasonable behavior, IMO, and in many cases is probably much nicer than an exception. =20 -D --=20 Do not pay attention to every word people say, or you may hear your servant cursing you -- for you know in your heart that many times you yourself have cursed others. Ecclesiastes 7:21-22 =20 http://dman.ddts.net/~dman/ --u3/rZRmxL6MmkK24 Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAj4wtZQACgkQO8l8XBKTpRRz7gCfb7aomcv77wVoNgz4STNttnE3 jgYAnA3a4I7DvYRBYSIh7vPo0MyBCkgz =gxLN -----END PGP SIGNATURE----- --u3/rZRmxL6MmkK24-- From gus.tabares@verizon.net Thu Jan 23 22:46:48 2003 From: gus.tabares@verizon.net (Gus Tabares) Date: Thu Jan 23 22:46:48 2003 Subject: [Tutor] Renaming files Message-ID: <1043380228.22416.4.camel@blackbetty> Hello, I'm trying to rename files that have endings as such: blah.mp3.bunchofchars . I'm trying to strip off the extra chars and just have *.mp3. The files were fed into a list via the os.listdir() function. The searching I've done so far has come up empty. Should I be using the string module for something like this or is this a simple slice operation I'm missing? Any help is greatly appreciated. Thanks, Gus From johnca@ourpla.net Fri Jan 24 00:26:02 2003 From: johnca@ourpla.net (John Abbe) Date: Fri Jan 24 00:26:02 2003 Subject: [Tutor] Objectifying code Message-ID: Okay, i've read the syntax for coding objects in Python, but i'm new to using objects, and looking for your support on how to put them into use. If you'd like to help, please take a look at my GroupOwnedDatabase and suggest some ways of object-ifying it (it will grow, and want some kind of modularization), and/or reading that might help me learn how to do this. Thanks! Life, John -- All you /\/\ John Abbe "If you don't like the news, need \ / CatHerder go out and make some of your own." is... \/ http://ourpla.net/john/ --Wes Nisker From lumbricus@gmx.net Fri Jan 24 04:20:02 2003 From: lumbricus@gmx.net (lumbricus@gmx.net) Date: Fri Jan 24 04:20:02 2003 Subject: [Tutor] Renaming files References: <1043380228.22416.4.camel@blackbetty> Message-ID: <9179.1043399925@www1.gmx.net> Hi! > Hello, > > I'm trying to rename files that have endings as such: > blah.mp3.bunchofchars . I'm trying to strip off the extra chars and just strip() os.path.basename() os.rename() etc. > Thanks, > Gus Greetings,J"o! -- sigfault +++ GMX - Mail, Messaging & more http://www.gmx.net +++ NEU: Mit GMX ins Internet. Rund um die Uhr für 1 ct/ Min. surfen! From magnus@thinkware.se Fri Jan 24 05:15:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Fri Jan 24 05:15:01 2003 Subject: [Tutor] Renaming files In-Reply-To: <1043380228.22416.4.camel@blackbetty> Message-ID: <5.1.0.14.0.20030124103434.02cb2bf0@www.thinkware.se> At 22:50 2003-01-23 -0500, Gus Tabares wrote: > I'm trying to rename files that have endings as such: >blah.mp3.bunchofchars . I'm trying to strip off the extra chars and just >have *.mp3. The files were fed into a list via the os.listdir() >function. The searching I've done so far has come up empty. Should I be >using the string module for something like this or is this a simple >slice operation I'm missing? Any help is greatly appreciated. You can certainly use os.rename as J"o suggested, but I don't know what he wants .strip for, it removes whitespace, and os.path.basename strips off the part of a path that precedes a file name, and you don't get that from os.listdir, so that's not very useful here either. On the other hand, os.path.splitext *might* be right... >>> import os >>> help(os.path.splitext) Help on function splitext in module ntpath: splitext(p) Split the extension from a pathname. Extension is everything from the last dot to the end. Return (root, ext), either part may be empty. It depends a little on whether we know that there are stuff after .mp3 or not. If the a file might actually end with '.mp3', we don't want *that* extension removed. Also, if there are dots in the string *after* '.mp3.' we still want ALL of it removed. I'd feel safer looking explicitly for .mp3 in the name in his case. Let's experiment a bit... >>> name = "blah.mp3.bunchofchars" >>> end = '.mp3' >>> name.find(end) 4 >>> len(end) 4 >>> #Hm... >>> print name[:name.find(end)+len(end)] blah.mp3 >>> for name in ['blaha.mp3', 'sdffg.mp3.sdf', 'not.an.mp.3', 'x.mp3.x.y']: ... print "Find trick", name[:name.find(end)+len(end)] ... print "Splitext", os.path.splitext(name)[0] ... Find trick blaha.mp3 Splitext blaha Find trick sdffg.mp3 Splitext sdffg.mp3 Find trick not Splitext not.an.mp Find trick x.mp3 Splitext x.mp3.x So: Find trick blaha.mp3 Splitext blaha In this case os.path.splitext removed .mp3. Bad! Find trick sdffg.mp3 Splitext sdffg.mp3 Both ok. Find trick not Splitext not.an.mp Both messed up files that don't contain .mp3 at all. :( Find trick x.mp3 Splitext x.mp3.x os.path.splitext failed here too... Hm... It seems the find version is more robust, but it will just return the first three characters if there is no '.mp3' in the file name. If we got the data from "os.listdir('*.mp3*') I guess that's ok, but if we want both belt and suspenders we might add a check for that. >>> for name in ['blaha.mp3', 'sdffg.mp3.sdf', 'not.an.mp.3', 'x.mp3.x.y']: ... newName = name[:name.find(end)+len(end)] ... if newName.endswith('.mp3'): ... print "Ok, put this in os.rename:", newName ... else: ... print "No, I don't like this name:", newName ... Ok, put this in os.rename: blaha.mp3 Ok, put this in os.rename: sdffg.mp3 No, I don't like this name: not Ok, put this in os.rename: x.mp3 The newName.endswith('.mp3') check seems to fit our purposes very well. If we really feel that os.listdir SHOULD only have given us file names containing .mp3, we might want to turn this into an assert: >>> for name in ['blaha.mp3', 'sdffg.mp3.sdf', 'not.an.mp.3', 'x.mp3.x.y']: ... newName = name[:name.find(end)+len(end)] ... assert newName.endswith('.mp3') ... print "Ok, put this in os.rename:", newName ... Ok, put this in os.rename: blaha.mp3 Ok, put this in os.rename: sdffg.mp3 Traceback (most recent call last): File "", line 3, in ? AssertionError I'm sure you can loop over os.listdir(something) and exchange the print for os.rename(name, newName)... Oh yes, one more thing. This won't work of course: for name in os.listdir('/some/path/to/wherever/*.mp3*'): ... os.rename(name, newName) os.rename won't know what directory you pointed at in os.listdir... Obvious but easy to miss. It's probably easiest to do. os.chdir('/some/path/to/wherever/') for name in os.listdir('*.mp3*'): ... Another option would obviously be to use good old regular expressions. >>> names = "\n".join(['blaha.mp3', 'sdffg.mp3.sdf', 'not.an.mp.3', 'x.mp3.x.y']) >>> import re >>> re.findall(r'(.*\.mp3)', names) ['blaha.mp3', 'sdffg.mp3', 'x.mp3'] -- 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 =?ISO-8859-1?B?YW50b25tdWhpbiDt4CByYW1ibGVyLnJ1?= Fri Jan 24 06:12:43 2003 From: =?ISO-8859-1?B?YW50b25tdWhpbiDt4CByYW1ibGVyLnJ1?= (=?ISO-8859-1?B?YW50b25tdWhpbiDt4CByYW1ibGVyLnJ1?=) Date: Fri Jan 24 06:12:43 2003 Subject: [Tutor] files question In-Reply-To: <4495-3E305FC8-1767@storefull-2133.public.lawson.webtv.net> References: <4495-3E305FC8-1767@storefull-2133.public.lawson.webtv.net> Message-ID: <14814856832.20030124141019@rambler.ru> Hello Ron, Friday, January 24, 2003, 12:34:00 AM, you wrote: RA> hold =3D [] RA> import string RA> =A0 RA> # OPEN AND READ A FILE RA> def mylist(): RA> =A0=A0=A0 data =3D open('testing.txt', 'r') RA> =A0=A0=A0 while 1: RA> =A0=A0=A0=A0=A0=A0=A0 read_me =3D data.readline() RA> =A0=A0=A0=A0=A0=A0=A0 if read_me =3D=3D '': RA> =A0=A0=A0=A0=A0=A0=A0=A0=A0=A0=A0 break RA> =A0=A0=A0=A0=A0=A0=A0 no_n =3D read_me[:-1] RA> =A0=A0=A0=A0=A0=A0=A0 split_me =3D string.split(no_n, '\t') RA> =A0=A0=A0=A0=A0=A0=A0 hold.append(split_me) RA> =A0=A0=A0 print hold RA> =A0=A0=A0 data.close() RA> =A0 Maybe, this function could be improved: for read_me in open(testing.txt', 'r'): if read_me =3D=3D '': break And if you use empty line to mark end of a file, you can get rid of it: for read_me in open(testing.txt', 'r'): no_n =3D read_me[:-1] etc... This loop will terminate at the end of a file. --=20 Best regards, anton mailto:antonmuhin@rambler.ru From alan.gauld@bt.com Fri Jan 24 06:22:42 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri Jan 24 06:22:42 2003 Subject: [Tutor] How best to create a sharp telemetry log file - from one long string of teletry? Message-ID: <7497DCA1C240C042B28F6657ADFD8E0974DA98@i2km11-ukbr.domain1.systemhost.net> Hi Bill, > Now I'm trying to write a nicely formatted log file out of a single > string of telemtry that I read of a serial line. > The string had 40 different values - numbers such a "120", and titles > sucs as "OFT" There are 40 of these seperated by white space. You don't say whether these come in a predetermined sequence that is repeatable. If it is a fixed set then you can use syring slicing to extract the digits: field1 = strng[4:9] #or whateve. Beterr to define these external to the slicing: # field name = (start,length) field1 = (4,5) field2 = (13,3) etc... Then you can slice like: f1 = strng[field1[0]:field1[0]+field1[1]] f1 = int(f1) # if you need them as numbers rather than numeric strings etc > place each numerical value into it's own column? > > I've learned about the string format codes from Alan's book (page 32) Thats the best solution, just define the line format in terms of field specifiers: fmt = "%12s%3d%7d%7s%8.2f\n" Then in a loop create each line output.write(headingStrings) # report header for lines in buffer: getFields() # assume uses slicing as above result = fmt % (f1,f2,f3....) output.write(result) > say for the value of 120. > > '%8.2f' % 120 This will print " 120.00" Is that what you want? If its not a floating pint value a %8d might be better. Finally if the string is non deterministic in its numeric content you might be better using a regular expression and a findall() call to get a list of the strings. Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From lumbricus@gmx.net Fri Jan 24 07:11:01 2003 From: lumbricus@gmx.net (lumbricus@gmx.net) Date: Fri Jan 24 07:11:01 2003 Subject: [Tutor] Renaming files References: <5.1.0.14.0.20030124103434.02cb2bf0@www.thinkware.se> Message-ID: <25903.1043410214@www1.gmx.net> Hi! > At 22:50 2003-01-23 -0500, Gus Tabares wrote: > > I'm trying to rename files that have endings as such: > >blah.mp3.bunchofchars . I'm trying to strip off the extra chars and just > >have *.mp3. The files were fed into a list via the os.listdir() > >function. The searching I've done so far has come up empty. Should I be > >using the string module for something like this or is this a simple > >slice operation I'm missing? Any help is greatly appreciated. > > You can certainly use os.rename as J"o suggested, but I don't know > what he wants .strip for, it removes whitespace, Errhm - split! I meant split > and os.path.basename > strips off the part of a path that precedes a file name, and you don't Yes, I mixed that up with the Unix-command basename, which can be used to strip off the file-suffix. Thanks and Greets, J"o! -- -- sigfault +++ GMX - Mail, Messaging & more http://www.gmx.net +++ NEU: Mit GMX ins Internet. Rund um die Uhr für 1 ct/ Min. surfen! From shalehperry@attbi.com Fri Jan 24 10:39:14 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Fri Jan 24 10:39:14 2003 Subject: [Tutor] Objectifying code In-Reply-To: References: Message-ID: <200301240738.19620.shalehperry@attbi.com> On Thursday 23 January 2003 20:33, John Abbe wrote: > Okay, i've read the syntax for coding objects in Python, but i'm new > to using objects, and looking for your support on how to put them > into use. If you'd like to help, please take a look at my > GroupOwnedDatabase > and suggest some ways of object-ifying it (it will grow, and want > some kind of modularization), and/or reading that might help me learn > how to do this. > > Thanks! Life, > John Dunno, after reading the code I am not but so sure objects are the right=20 solution. There is some disagreement out in the world but I find that objects get m= e one=20 of two things: * joining data with methods to act on it and thereby making maintenance e= asier * hiding implementations to allow more plug and play style code and thus making trying out alternate solutions easier Your PrintPerson seemed the most likely candidate for wrapping into a cla= ss=20 followed by the authentication mechanism. If find that sitting down and=20 writing out the data (nouns) in my code and then defining the actions (ve= rbs)=20 tends to point out places where OO would be nice or convince me that=20 functions are good enough. As a side critique there is a cgi module in Python which implements some = of=20 what you have perhaps you should consider using it instead. From jeff@ccvcorp.com Fri Jan 24 12:39:34 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Fri Jan 24 12:39:34 2003 Subject: [Tutor] Renaming files References: <5.1.0.14.0.20030124103434.02cb2bf0@www.thinkware.se> Message-ID: <3E317A0C.6090702@ccvcorp.com> Magnus Lycka wrote: > > [...] If we got the data from "os.listdir('*.mp3*') [...] As a minor correction, os.listdir() won't do wildcard expansion -- the argument to os.listdir() must be an existing directory. If you want to check for files matching a wildcard pattern, then you need to use glob.glob() instead. (Unix calls this wildcard expansion 'globbing', and the module was named after that...) I'm sure that Magnus knows this and just accidentally misspoke (er, mistyped), but figured I'd mention this so that someone trying this code wouldn't be puzzled by the error messages... :) Jeff Shannon Technician/Programmer Credit International From magnus@thinkware.se Fri Jan 24 13:44:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Fri Jan 24 13:44:02 2003 Subject: [Tutor] Objectifying code In-Reply-To: <200301240738.19620.shalehperry@attbi.com> References: Message-ID: <5.1.0.14.0.20030124181208.02cffed8@www.thinkware.se> At 07:38 2003-01-24 -0800, Sean 'Shaleh' Perry wrote: >Dunno, after reading the code I am not but so sure objects are the right >solution. To be honest, I didn't bother reading through the code well enough to understand what it did. This is partly because I'm in a hurry, and partly because it's written in a way that is difficult to read. I would suggest that you use the normal convention of python code, instead of writing something looking like an overgrown bat-file. ;) In other words, use the standard idiom of if __name__ == '__main__': main() in the end, make a main() function that captures the main abstractions of the program, so that people can read that function (which is hopefully note more than a screenful) and understand what it's all about. You don't need classes for this, you can use well named functions. I'm sure that it's reasonable to divide most of the main code in chunks that logacally form an abstraction, or a step in your processing if you like. Hopefully there won't be too many vaiables that go beyond the boundries of these blocks. If there aren't terribly many shared variables, it's not very difficult to make these chunks into separate functions. Actually, if there are a lot of shared data, that might be a reason to use one or several classes instead, since class instances can remember their data (in attributes) between method calls, but remember that a class should capture one abstraction. I would also suggest that you remove all the big strings from the main body of the code. They completely mess up the readability that python normally provides. Let's have a look at a piece of code: elif 'edit' in Args: # Edit a record for entry in lankaDB: if entry['firstname'] + entry['lastname'] == Args['edit']: print """

Editing %s %s's record

First name:
Last name:
Phone:
E-mail:
Address:
Comments:
Password: (must match old password)

""" % (entry['firstname'], entry['lastname'], cgiaddr, entry['firstname'], entry['lastname'], entry['firstname'], entry['lastname'], entry['phone'], entry['email'], entry['address'], entry['comments']) print """
Or, change %s %s's password:

Old password:
New password:
New password: (just to be sure we get it right)

""" % (entry['firstname'], entry['lastname'], cgiaddr, entry['firstname'], entry['lastname']) print """
Or, delete:

Password: (must match old password)

""" % (cgiaddr, entry['firstname'], entry['lastname'], entry['firstname'], entry['lastname']) Here, it's completely hopeless to follow the flow of the code. At least for me. Has the if statement ended yet? The for-loop? I don't know, I can't make myself try to follow this without giving it an overhaul. This big string I'd make into a global variable. Not because it's so global in nature, but because it's a small program and I want this big chunk of HTML away from the flow of the code. Maybe I'd even put it in a separate file and import it? recordEditForm = """

Editing %(firstname)s %)(lastname)s's record

First name:
Last name:
Phone:
E-mail:
Address:
Comments:
Password: (must match old password)


Or, change %(firstname)s %(lastname)s's password:

Old password:
New password:
New password: (just to be sure we get it right)


Or, delete:

Password: (must match old password)

""" The only thing left in the part of the program where I cut out this section would be: elif 'edit' in Args: # Edit a record for entry in lankaDB: if entry['firstname'] + entry['lastname'] == Args['edit']: print recordEditForm % (entry + {'cgiaddr': cgiaddr}) This is easier to read, isn't it? We don't have to worry about HTML form layout and program flow at the same time. The indentation is helpful in suggesting a structure, and the use of string % dict instead of string % tuple both cleans up the print statement and makes it much easier to modify and review the HTML forms. -- 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 calveg@accessus.net Sat Jan 25 16:00:04 2003 From: calveg@accessus.net (Gary Calvert) Date: Sat Jan 25 16:00:04 2003 Subject: [Tutor] Very basic help Message-ID: <000101c2c4b4$9f8ab420$b789cecf@VAIO> This is a multi-part message in MIME format. ------=_NextPart_000_0002_01C2C482.54F04420 Content-Type: text/plain; charset="us-ascii" Content-Transfer-Encoding: quoted-printable I am an IT student that is taking a Python programming class and I am = having some difficulty. This class is a math based programming class that = requires all math problems to be solved in Python. My last assignment requires writing a module and running all of the calculations in the module. I = have attached the code that I have written can anyone help. This is very = basic, I am just beginning the class. =20 ------=_NextPart_000_0002_01C2C482.54F04420 Content-Type: text/plain; name="overtimemod.py" Content-Transfer-Encoding: 7bit Content-Disposition: attachment; filename="overtimemod.py" #overtime module def wage(x,y): return x * y def overtime(x,y): return x * y def gross(x,y): return x + y ------=_NextPart_000_0002_01C2C482.54F04420 Content-Type: text/plain; name="9-20.py" Content-Transfer-Encoding: 7bit Content-Disposition: attachment; filename="9-20.py" #Problem 9-20 import overtimemod rate = float(input("Enter your hourly wage\n")) time = float(input("Enter number of hours straight time worked\n")) overtime = float(input("Enter number of over time hours worked\n")) multiplier = float(input("Enter your over time multiplier\n")) x = overtime(rate,multiplier) y = gross(overtime,rate) z = wage(time,rate) print "Your straight wage is",z print "Your overtime is",x print "Your gross pay is",y ------=_NextPart_000_0002_01C2C482.54F04420-- From shalehperry@attbi.com Sat Jan 25 17:28:05 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Sat Jan 25 17:28:05 2003 Subject: [Tutor] Very basic help In-Reply-To: <000101c2c4b4$9f8ab420$b789cecf@VAIO> References: <000101c2c4b4$9f8ab420$b789cecf@VAIO> Message-ID: <200301251427.05860.shalehperry@attbi.com> On Saturday 25 January 2003 12:59, Gary Calvert wrote: > I am an IT student that is taking a Python programming class and I am > having some difficulty. This class is a math based programming class t= hat > requires all math problems to be solved in Python. My last assignment > requires writing a module and running all of the calculations in the > module. I have attached the code that I have written can anyone help.=20 > This is very basic, I am just beginning the class. when asking for help on the list it is good form to tell us what you need= help=20 with. Is there a syntax issue? Odd exception you were not expecting? O= r=20 are you just unhappy with a piece of code and want a better solution? From python@jaydorsey.com Sat Jan 25 17:41:02 2003 From: python@jaydorsey.com (Jay Dorsey) Date: Sat Jan 25 17:41:02 2003 Subject: [Tutor] Very basic help In-Reply-To: <000101c2c4b4$9f8ab420$b789cecf@VAIO> References: <000101c2c4b4$9f8ab420$b789cecf@VAIO> Message-ID: <3E331259.5040707@jaydorsey.com> The first thing I see you need to fix is the references to your imported functions from the overtimemod module. In your 9-20.py file, since you imported overtimemod (instead of "from overtimemod import *" - which you wouldn't want to do now anyways since you call one of your variables the same name as one of the functions from yoru module - "overtime"), you need to prefix all of your function calls with the name of the module (overtimemod.) See below for an example. You may want to check your functions as well - I ran the program after I made the changes below, but the results didn't look correct (I'm no math major though). Hope this helps, jay Gary Calvert wrote: >#Problem 9-20 >import overtimemod >rate = float(input("Enter your hourly wage\n")) >time = float(input("Enter number of hours straight time worked\n")) >overtime = float(input("Enter number of over time hours worked\n")) >multiplier = float(input("Enter your over time multiplier\n")) > >x = overtimemod.overtime(rate,multiplier) >y = overtimemod.gross(overtime,rate) >z = overtimemod.wage(time,rate) >print "Your straight wage is",z >print "Your overtime is",x >print "Your gross pay is",y > > From idiot1@netzero.net Sun Jan 26 02:14:02 2003 From: idiot1@netzero.net (Kirk Bailey) Date: Sun Jan 26 02:14:02 2003 Subject: [Tutor] making money Message-ID: <3E338A78.9090107@netzero.net> ok, we all like a joke. I have an idea that will help me make money. I will a modify an existing script just a bit. It will reference a fortunecookie file, and a banner rotation file. It will output a webpage with a tasteful portrait of Alfred E Newmann in frame, with a cracked quote under it. Above this will be a banner. Want a new cookie? Click reload, up comes another, and a new banner. Boy, will this get alot of banner impressions! We could do this with assorted images of Monty Python and quotes from the show, whatever, it lends itself to adaptation. Anyone want to talk about this sillyness a little? -- end Respectfully, Kirk D Bailey Owner HowlerMonkey Email Services Company: http://www.howlermonkey.net/ Inventor of TinyList MLM list server: http://www.tinylist.org/ Consulting Lunatic: http://www.sacredelectron.org/ Remember: it is an ill wind that blows no minds. Fnord. From dyoo@hkn.eecs.berkeley.edu Sun Jan 26 14:59:03 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Jan 26 14:59:03 2003 Subject: [Tutor] Very basic help [we don't do homework / module usage] In-Reply-To: <000101c2c4b4$9f8ab420$b789cecf@VAIO> Message-ID: On Sat, 25 Jan 2003, Gary Calvert wrote: > I am an IT student that is taking a Python programming class and I am > having some difficulty. This class is a math based programming class > that requires all math problems to be solved in Python. > > My last assignment requires writing a module and running all of the > calculations in the module. I have attached the code that I have > written can anyone help. Hi Gary, This is a somewhat sensitive issue for us: we are not supposed to help with homework assignments. At the very least, you should not just send us code on us, and ask us for help --- it makes it sound like you just want us to do your homework! Forgive me for stating it that bluntly. You may not have implied us to do your work in your question, but without telling us more, it's possible for us to assume the worse. You need to tell us approximately where you are getting stuck, and what parts appear to be working for you, what error messages you've gotten, and what you suspect might be the problem. These questions are not useless: they are very crucial for us since we'll have a better idea of what's going on in your head. We'll still be limited to what we can help you with, but at least we'll be better equipped to point you toward resources that directly address your questions, rather than just spout something generic that might be less helpful for you. In the absence of information, I've got to spout. I did take a look at your code; it looks fairly reasonable. Were you having problems with the 'import' of your module, or with the use of the functions in the module? What have you read about modules so far? There a section in Mark Pilgrim's "Dive into Python" tutorial that might help you: http://diveintopython.org/fileinfo_fromimport.html as well as a chapter about modules in the Official Python Tutorial: http://www.python.org/doc/tut/node8.html Both may be useful in showing you how to use modules. If you run into any problems, or if there's points which seem turgid and confused, please feel free to ask questions on Python-tutor; we'd be happy to chat and try to clear the air. From maillist@kuwest.de Sun Jan 26 15:02:00 2003 From: maillist@kuwest.de (Jens Kubieziel) Date: Sun Jan 26 15:02:00 2003 Subject: [Tutor] reading 2nd line Message-ID: <20030126174922.GB1163@kubieziel.de> Hi, I have here several text files, where I want to read second line of each file and no idea how to do it. Those files are csv-files exported from MS Excel and have following format: date,open,high,low,close,sales 01-01-03,11.23,11.24,10.66,10.87,678537 On a shell I would write: head -n 2 $FILE | tail -n 1 Can you give me a hint on this? If I read those line, I want to read out the close price (10.87). My current solution looks like: >>> line = "01-01-03,11.23,11.24,10.66,10.87,678537" >>> single = line.split(",") >>> print single[4] Is there a better solution? -- Jens Kubieziel mailto:jens@kubieziel.de Adultery: Putting yourself in someone else's position. From dyoo@hkn.eecs.berkeley.edu Sun Jan 26 15:49:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Jan 26 15:49:02 2003 Subject: [Tutor] reading 2nd line In-Reply-To: <20030126174922.GB1163@kubieziel.de> Message-ID: On Sun, 26 Jan 2003, Jens Kubieziel wrote: > I have here several text files, where I want to read second line of each > file and no idea how to do it. Those files are csv-files exported from > MS Excel and have following format: > > date,open,high,low,close,sales > 01-01-03,11.23,11.24,10.66,10.87,678537 > > On a shell I would write: > head -n 2 $FILE | tail -n 1 > > Can you give me a hint on this? Hi Jens, Yes, you may want to look at the function 'open()', which gives us a file object, as well as the 'readline()' method of a file object: http://www.python.org/doc/lib/built-in-funcs.html#l2h-44 http://www.python.org/doc/lib/bltin-file-objects.html#l2h-165 These two tools should allow you to get the second line of a file. > If I read those line, I want to read out the close price (10.87). My > current solution looks like: > > >>> line = "01-01-03,11.23,11.24,10.66,10.87,678537" > >>> single = line.split(",") > >>> print single[4] > > Is there a better solution? For simple files, string splitting will work. However, there is a specialized third-party Python module that does CSV files: http://www.object-craft.com.au/projects/csv/ which handles subtleties like having commas within fields; you may want to use this in favor of simple string splitting. Good luck to you! From magnus@thinkware.se Sun Jan 26 16:44:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Sun Jan 26 16:44:01 2003 Subject: [Tutor] Very basic help In-Reply-To: <000101c2c4b4$9f8ab420$b789cecf@VAIO> Message-ID: <5.1.0.14.0.20030126041401.02c4bac0@www.thinkware.se> At 14:59 2003-01-25 -0600, Gary Calvert wrote: >9-20.py Hi Gary. Python files can be loaded into other python programs as modules as you know. This requires that the main part of the file name (the part before .py) can be a python identifier. 9-20 is a numerical expression with the value -11. so it's not a permitted name in python. A python identifier can only contain A-Z, a-z, 0-9 and _, and it can't begin with a digit. NineToTwenty.py or _9to20.py etc will do, but 9-20.py can't be used as a module. Maybe you didn't intend that, but I still think it is a good practice to use file names that are legal identifiers for all python source code. Who knows, you might be in the python interpreter and want to import your file to test it interactively. Apart from the restrictions concerning character set, and initial digit, you can't use reserved names such as 'if', 'for' and 'class' as module (or variable) names. -- 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@thinkware.se Sun Jan 26 16:51:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Sun Jan 26 16:51:01 2003 Subject: [Tutor] reading 2nd line In-Reply-To: References: <20030126174922.GB1163@kubieziel.de> Message-ID: <5.1.0.14.0.20030126224247.02c6bcf0@www.thinkware.se> At 12:48 2003-01-26 -0800, Danny Yoo wrote: >Yes, you may want to look at the function 'open()' Or "file()" which is now the preferred name. >For simple files, string splitting will work. However, there is a >specialized third-party Python module that does CSV files: > > http://www.object-craft.com.au/projects/csv/ Actually, there are at least three: ASC, CSV and DSV. The others can be found at: http://tratt.net/laurie/python/asv/ and http://python-dsv.sf.net CSV is fastest though, being implemented in C. Might be the simplest to use as well. -- 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 ahimsa@onetel.net.uk Sun Jan 26 17:00:02 2003 From: ahimsa@onetel.net.uk (ahimsa) Date: Sun Jan 26 17:00:02 2003 Subject: [Tutor] rockpaperscissors Message-ID: <1043618266.20752.28.camel@localhost.localdomain> Hey Gang So many of you were very helpful last time around I wanted to pick your brains on the following: I have enclosed some code for the game 'Rock, Paper, Scissors'. The idea for doing this in Python was drawn from Tim Wilson's lessons for the Henry Sibley school ( http://isd197.org/sibley/cs/icp/ ), but I have run aground on a couple of aspects: 1. I'm sure that there must be a more elegant way of writing this code, so any suggestions would be useful, if only for aesthetic purposes. 2. I was wanting to include a way of counting the number of wins for the computer and for the user. This might follow on 'naturally' from a more elegant code lay-out, but I've tried as many ways as I can think of but can't figure a way to get that in. FWIW, I must say that playing around with Python is *great* fun - so unless someone really objects or thinks it inappropriate (in which case, please tell me) I'd like to continue to forward odd bits of programming to this list for input and advice, suggestions, and so on. Much obliged. Anyway, here's the code (the type-setting will probably be messed up). All the best Andrew %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%: begin # Rock, Paper, Scissors: print "Rock, Paper, Scissors" # Initialisation phase: import random # module import to randomise computer's # selection counter = 0 # game counter def item( a ): # locally defined function to convert if a == 1: # random.randrange( ) into user-friendly words return "Rock" elif a == 2: return "Paper" elif a == 3: return "Scissors" def results( b, c ): # locally defined function to output results if b == c: # relative to computer's selection return "That's a tie" elif ( b == "Rock" and c == "Paper" ): return "%s covers %s. Computer wins." % ( c, b ) elif ( b == "Rock" and c == "Scissors" ): return "%s breaks %s. You win." % ( b, c ) elif ( b == "Paper" and c == "Rock" ): return "%s covers %s. You win." % ( b, c ) elif ( b == "Paper" and c == "Scissors" ): return "%s cut %s. Computer wins." % ( c, b ) elif ( b == "Scissors" and c == "Rock" ): return "%s breaks %s. Computer wins." % ( c, b ) elif ( b == "Scissors" and c == "Paper" ): return "%s cut %s. You win." % ( b, c ) # Processing phase: while counter < 3: # only want to run the game three times x = random.randrange( 1, 4 ) print print "Rock (1), Paper (2), or Scissors (3)" print y = int( raw_input( "Make a selection: " ) ) # invite user's input print "You selected %s and the Computer selected %s" % (item( y ), item( x ) ) print results( item( y ), item( x )) # output results counter += 1 # move counter up 1 'click' print "Hit ENTER to return to the prompt" # basic way of exiting program %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%: end -- ________________________%%%%%%%%%%%%%%%%%____________________________ Proudly sent using Ximian Evolution 1.2.1 on a Linux Red Hat 8.0 box. From shalehperry@attbi.com Sun Jan 26 18:04:04 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Sun Jan 26 18:04:04 2003 Subject: [Tutor] rockpaperscissors In-Reply-To: <1043618266.20752.28.camel@localhost.localdomain> References: <1043618266.20752.28.camel@localhost.localdomain> Message-ID: <200301261503.27257.shalehperry@attbi.com> On Sunday 26 January 2003 13:59, ahimsa wrote: FYI, this game is also referred to as "ro sham bo" (various spellings). > > 1. I'm sure that there must be a more elegant way of writing this code, > so any suggestions would be useful, if only for aesthetic purposes. > 2. I was wanting to include a way of counting the number of wins for th= e > computer and for the user. This might follow on 'naturally' from a more > elegant code lay-out, but I've tried as many ways as I can think of but > can't figure a way to get that in. > what you have here is a classic programming "mistake". You are combining= two=20 problems in one function and as a result have loss your flexibility. The function results() both determines who wins *AND* is responsible for=20 reporting this data. Here is where you went wrong. If you had separated= =20 this the print step would be rather simple. Splitting the function would= =20 also let you reimplement this program as a server for a distributed netwo= rk=20 play version. What you find is that splitting functions so they only do one thing (same= with=20 classes and their methods) you can mix and match functions for bigger and= =20 better programs. I would have made a "who won" function and a separate "print output funct= ion". The print output is much simpler because it just has to say "noun verb no= un, X=20 wins over Y". You could also store the strings in a dictionary/list to make the lookup = a=20 little cleaner. objects[] =3D (("paper", "covers"), ("rock", "breaks"), ("scissors", "cut= ")) This is very common in games where the object list can grow and grow like= role=20 playing games. > FWIW, I must say that playing around with Python is *great* fun - so > unless someone really objects or thinks it inappropriate (in which case= , > please tell me) I'd like to continue to forward odd bits of programming > to this list for input and advice, suggestions, and so on. That is why this list exists. However please send the code as an attachm= ent=20 that way various people's email programs do not reformat or munge the cod= e. =20 Many people read email in a mailer which uses TTF fonts and this makes co= de=20 reading difficult because the lines do not line up how they would in a fi= xed=20 point code editor. Since Python is indentation sensitive this is even more important. From magnus@thinkware.se Sun Jan 26 18:08:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Sun Jan 26 18:08:02 2003 Subject: [Tutor] rockpaperscissors In-Reply-To: <1043618266.20752.28.camel@localhost.localdomain> Message-ID: <5.1.0.14.0.20030126234945.02bf8a28@www.thinkware.se> At 21:59 2003-01-26 +0000, ahimsa wrote: >while counter < 3: # only want to run the game three times ... > counter += 1 # move counter up 1 'click' Here it fits with... numberOfTries = 3 for counter in range(numberOfTries): > y = int( raw_input( "Make a selection: " ) ) # invite user's input You could do: y = input("Make a selection: ")) But you have a bit more control with raw_input and int. For the algorithm, this little session might give some ideas: >>> winners = {'scissors': 'rock', 'paper': 'scissors', 'rock': 'paper'} >>> def whoWon(a, b): ... if winners[a] == b: ... print b, "wins over", a ... elif winners[b] == a: ... print a, "wins over", b ... else: ... print "A draw, try again" ... >>> whoWon('rock', 'scissors') rock wins over scissors >>> whoWon('rock', 'paper') paper wins over rock >>> whoWon('rock', 'rock') A draw, try again Maybe whoWon should instead take a tuple of (name, choice)? -- 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 GREENDAY31087@aol.com Sun Jan 26 20:06:02 2003 From: GREENDAY31087@aol.com (GREENDAY31087@aol.com) Date: Sun Jan 26 20:06:02 2003 Subject: [Tutor] why wont this code run? Message-ID: <110.1f259c3f.2b65dfc1@aol.com> --part1_110.1f259c3f.2b65dfc1_boundary Content-Type: text/plain; charset="US-ASCII" Content-Transfer-Encoding: 7bit class Map: def __init__(self): self.__grid={} # Don't assume global startroom def addRoom(self, room, x, y): if self.__grid.has_key((x,y)): raise KeyError, "Location occupied" self.__grid[(x, y)] = room def getRoom(self, x, y): return self.__grid[(x, y)] def getLocation(self, room): for coord, aRoom in self.__grid.items(): if room == aRoom: return coord raise KeyError class Room: def __init__(self, map, x=0, y=0): self.__map = map map.addRoom(self, x, y) def dig(direction): --part1_110.1f259c3f.2b65dfc1_boundary Content-Type: text/html; charset="US-ASCII" Content-Transfer-Encoding: 7bit class Map:
         def __init__(self):
             self.__grid={} # Don't assume global startroom
         def addRoom(self, room, x, y):
             if self.__grid.has_key((x,y)):
                 raise KeyError, "Location occupied"
             self.__grid[(x, y)] = room
         def getRoom(self, x, y):
             return self.__grid[(x, y)]
         def getLocation(self, room):
             for coord, aRoom in self.__grid.items():
                 if room == aRoom:
                     return coord
             raise KeyError
   
    class Room:
         def __init__(self, map, x=0, y=0):
             self.__map = map
             map.addRoom(self, x, y)
         def dig(direction):
--part1_110.1f259c3f.2b65dfc1_boundary-- From Don Arnold" Message-ID: <041d01c2c5a4$17a394a0$a610ba3f@defaultcomp> ----- Original Message ----- From: GREENDAY31087@aol.com To: tutor@python.org Sent: Sunday, January 26, 2003 7:05 PM Subject: [Tutor] why wont this code run? class Map: def __init__(self): self.__grid={} # Don't assume global startroom def addRoom(self, room, x, y): if self.__grid.has_key((x,y)): raise KeyError, "Location occupied" self.__grid[(x, y)] = room def getRoom(self, x, y): return self.__grid[(x, y)] def getLocation(self, room): for coord, aRoom in self.__grid.items(): if room == aRoom: return coord raise KeyError class Room: def __init__(self, map, x=0, y=0): self.__map = map map.addRoom(self, x, y) def dig(direction): [---- my reply ----] Well, the code won't make it past the parsing stage because Room.dig() is broken: it has no body. Even if you give this method a body of 'pass', you'll still have problems because its first parameter isn't 'self' (or some equivalent). So, change it to: def dig(self, direction): pass and you should be ready to roll. If you run your code now, you shouldn't get any errors. Of course, all you've done at this point is define 2 classes, so you won't see anything going on until you add some driver logic that does something with the classes: if __name__ == '__main__': theMap = Map() room1 = Room(theMap) room2 = Room(theMap,1,1) room3 = Room(theMap,1,2) for somelocation in [room1, room2, room3]: print theMap.getLocation(somelocation) >>> (0, 0) (1, 1) (1, 2) >>> HTH, Don From jjhegde@konark.ncst.ernet.in Mon Jan 27 02:34:01 2003 From: jjhegde@konark.ncst.ernet.in (Jayprasad J. Hegde) Date: Mon Jan 27 02:34:01 2003 Subject: [Tutor] reading 2nd line In-Reply-To: <20030126174922.GB1163@kubieziel.de> References: <20030126174922.GB1163@kubieziel.de> Message-ID: <20030127073026.GE278@ncst.ernet.in> --sm4nu43k4a2Rpi4c Content-Type: text/plain; charset=us-ascii Content-Disposition: inline hello Jens, On Sun, Jan 26, 2003 at 06:49:22PM +0100, Jens Kubieziel wrote: > I have here several text files, where I want to read second line of each > file and no idea how to do it. Those files are csv-files exported from MS > Excel and have following format: > date,open,high,low,close,sales > 01-01-03,11.23,11.24,10.66,10.87,678537 > Is there a better solution? I have attached a very simple code which can either extract the "close" field directly for the second line, or extract only the second line (you'll have to uncomment the relevant code for that) This would work in for CSV docs in the following manner: cat inputCSVfile | python tp2.py Whether this is a good solution or not would probably depend on its usage. Hope this helps. regards - JJH -- QOTD: If you're looking for trouble, I can offer you a wide selection. (defun JJHdetails () (format t "~&~A~&~A~&~A" "Jayprasad J Hegde, Staff Scientist, KBCS, NCST" "Gulmohar Cross Road 9, Juhu, Mumbai 400049." "tel: +91-22-26201606x373")) --sm4nu43k4a2Rpi4c Content-Type: text/plain; charset=us-ascii Content-Disposition: attachment; filename="tp2.py" import sys REQUIRED_ENTRY = 2 #0,1,2,3,4,5 POSITION_CLOSE = 4 myfile = sys.stdin entries = myfile.read ().splitlines () ### if you want to print only the second line ## then uncomment this line .. and comment the code following it ## print entries [REQUIRED_ENTRY - 1] ## else use this to extract the "close" field directly req = entries [REQUIRED_ENTRY - 1].split (',') print req [POSITION_CLOSE] --sm4nu43k4a2Rpi4c-- From magnus@thinkware.se Mon Jan 27 04:35:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Jan 27 04:35:02 2003 Subject: [Tutor] reading 2nd line In-Reply-To: <20030127073026.GE278@ncst.ernet.in> References: <20030126174922.GB1163@kubieziel.de> <20030126174922.GB1163@kubieziel.de> Message-ID: <5.1.0.14.0.20030127100955.02c05570@www.thinkware.se> At 13:00 2003-01-27 +0530, Jayprasad J. Hegde wrote: >I have attached a very simple code I'd suggest pasting small snippets of code into the mail body instead of making attachments. That makes life easier for most of us. >entries = myfile.read ().splitlines () This means that you read the entire file into a string, and then split it into lines. A more convenient way to do that would be to use myfile.readlines(), but it's still not a very good idea. If we don't want more than the second line, there is no reason to read past that. The file might be big... So I'd do: filename = ... myfile = file(filename) myfile.readline() # Read first line and drop result secondLine = myfile.readline() myfile.close() This will be much faster than to read a big file. Particularly if we work with many files, as in: import glob closePos = 4 # Process close value in second line of all files # with .csv extension in current folder. for fn in glob.glob('*.csv'): f = file(fn) f.readline() line2 = f.readline() process(fn, line2.split(',')[closePos]) f.close() If we have 100 files with 100 lines each, we will now read 200 lines totally, instead of 10,000 lines if we had used .read() or .readlines(). I assume the "process" function needs the file name as well as the close value in this case to figure out what stock it was. -- 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@thinkware.se Mon Jan 27 07:50:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Jan 27 07:50:02 2003 Subject: [Tutor] reading 2nd line In-Reply-To: <20030127122903.GA1086@ncst.ernet.in> References: <5.1.0.14.0.20030127100955.02c05570@www.thinkware.se> <20030126174922.GB1163@kubieziel.de> <20030126174922.GB1163@kubieziel.de> <5.1.0.14.0.20030127100955.02c05570@www.thinkware.se> Message-ID: <5.1.0.14.0.20030127134144.02c23b20@www.thinkware.se> At 17:59 2003-01-27 +0530, Jayprasad J. Hegde wrote: > a question about file (). Has it been introduced from Python 2.3 onwards? No, it's in 2.2 as well. It's really part of the type/class unification. Now you can use type names as constructors. >>> int('5') 5 >>> int(5) 5 >>> float('5') 5.0 >>> file('c:/autoexec.bat') You can also subclass types now: >>> class NonNegInt(int): ... def __init__(self, val): ... if int(val) < 0: ... raise ValueError, 'Negative value!' ... super(int, self).__init__(val) ... >>> print NonNegInt(5) 5 >>> print NonNegInt(-5) Traceback (most recent call last): File "", line 1, in ? File "", line 4, in __init__ ValueError: Negative value! >>> print NonNegInt(0) 0 >>> a = NonNegInt(5) >>> print '*' * a ***** -- 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 alan.gauld@bt.com Mon Jan 27 08:54:01 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Jan 27 08:54:01 2003 Subject: [Tutor] rockpaperscissors Message-ID: <7497DCA1C240C042B28F6657ADFD8E0974DA9D@i2km11-ukbr.domain1.systemhost.net> > I have enclosed some code for the game 'Rock, Paper, Scissors'. > 1. I'm sure that there must be a more elegant way of writing > this code, Its not too bad given the size of the problem. You can of course build on all sorts of extra sophistication, but its gardly worth it IMHO. > so any suggestions would be useful, if only for aesthetic purposes. One area that might be more e;egant is to drive the results() function from a data structure: # results is a dictionary of dictionaries outcomes = ["Scissors cuts Paper", "Paper wraps Rock", "Rock smashes Scissors"] winners = ["Drawn game", "Computer won", "You won"] results = { 1: { 2: outcomes[1] + winners[1], 3: outcomes[2] + winners[2] }, 2: { 1: outcomes[1] + winners[2], 3: outcomes[0] + winners[1]}, 3: { 1: outcomes[2] + winners[1], 2: outcomes[0] + winners[2]} } Now your function just becomes a case of looking up the dictionary and printing the result. But its not that much prettier and only saves a tiny bit of maintenance effort. > 2. I was wanting to include a way of counting the number of > wins for the computer and for the user. There are 3 outcomes - Computer Wins, User wins, or draw. You can return that from the return function by making the return value a tuple containing the result code and result string. Represent that with 0,1,2 - which coincidentally(!) are the indices of the winners string list above, making translation easy... Then use a line in the loop like: if result[0] == -1: draw += 1 elif result[0] == 0: computer += 1 else user += 1 HTH, Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From alan.gauld@bt.com Mon Jan 27 09:00:03 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Jan 27 09:00:03 2003 Subject: [Tutor] why wont this code run? Message-ID: <7497DCA1C240C042B28F6657ADFD8E09702369@i2km11-ukbr.domain1.systemhost.net> This message is in MIME format. Since your mail reader does not understand this format, some or all of this message may not be legible. ------_=_NextPart_001_01C2C604.21DB8A80 Content-Type: text/plain; charset="iso-8859-1" What actually happens? Error codes and output are always helpful... -----Original Message----- From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of GREENDAY31087@aol.com Sent: 27 January 2003 01:05 To: tutor@python.org Subject: [Tutor] why wont this code run? class Map: def __init__(self): self.__grid={} # Don't assume global startroom def addRoom(self, room, x, y): if self.__grid.has_key((x,y)): raise KeyError, "Location occupied" self.__grid[(x, y)] = room def getRoom(self, x, y): return self.__grid[(x, y)] def getLocation(self, room): for coord, aRoom in self.__grid.items(): if room == aRoom: return coord raise KeyError class Room: def __init__(self, map, x=0, y=0): self.__map = map map.addRoom(self, x, y) def dig(direction): The class TRoom doewsn't align with the class Map. The dig method is undefined. There are only 2 class definitions, you never create instances, so its hard to know what you think the code will do if it were to "run". Alan G. ------_=_NextPart_001_01C2C604.21DB8A80 Content-Type: text/html; charset="iso-8859-1"
What actually happens? Error codes and output are always helpful...
-----Original Message-----
From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of GREENDAY31087@aol.com
Sent: 27 January 2003 01:05
To: tutor@python.org
Subject: [Tutor] why wont this code run?

class Map:
         def __init__(self):
             self.__grid={} # Don't assume global startroom
         def addRoom(self, room, x, y):
             if self.__grid.has_key((x,y)):
                 raise KeyError, "Location occupied"
             self.__grid[(x, y)] = room
         def getRoom(self, x, y):
             return self.__grid[(x, y)]
         def getLocation(self, room):
             for coord, aRoom in self.__grid.items():
                 if room == aRoom:
                     return coord
             raise KeyError
   
    class Room:
         def __init__(self, map, x=0, y=0):
             self.__map = map
             map.addRoom(self, x, y)
         def dig(direction):
 
The class TRoom doewsn't align with the class Map.
The dig method is undefined.
There are only 2 class definitions, you never create instances, so its hard to
know what you think the code will do if it were to "run".
 
Alan G.
------_=_NextPart_001_01C2C604.21DB8A80-- From Deirdre Hackett" This is a multi-part message in MIME format. ------=_NextPart_000_0049_01C2C619.564A7F00 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi there,=20 Thanks for all the advice the last time. Worked out great! I want to now put my 3 integer values into an array but it will not let = me do data[0] =3D int(x2string) data[1] =3D int(y2string).... etc instead I have to data =3D (int(x2string), int(y2string), int(z2string)) and this is only a tuple in which the size cannot be changed. Can you create an array that you can append values to it. You cannot = append vales to a tuple - its size is static. Not a big deal, but would like to know for the future. Thanks Deirdre =20 ------=_NextPart_000_0049_01C2C619.564A7F00 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hi there,
Thanks for all the advice the last = time. Worked out=20 great!
 
I want to now put my 3 integer values = into an array=20 but it will not let me do
 
data[0] =3D int(x2string)
data[1] =3D int(y2string).... = etc
 
instead I have to
data =3D (int(x2string), int(y2string), int(z2string))
 
and this is only a tuple in which the size cannot be changed.
 
Can you create an array that you can append values to it. You = cannot append=20 vales to a tuple - its size is static.
 
Not a big deal, but would like to know for the future.
Thanks
Deirdre
 
 
------=_NextPart_000_0049_01C2C619.564A7F00-- From =?ISO-8859-1?B?YW50b25tdWhpbiDt4CByYW1ibGVyLnJ1?= Mon Jan 27 12:13:01 2003 From: =?ISO-8859-1?B?YW50b25tdWhpbiDt4CByYW1ibGVyLnJ1?= (=?ISO-8859-1?B?YW50b25tdWhpbiDt4CByYW1ibGVyLnJ1?=) Date: Mon Jan 27 12:13:01 2003 Subject: [Tutor] Arrays and tuples In-Reply-To: <006701c2c61a$1915bea0$0400a8c0@egbert> References: <006701c2c61a$1915bea0$0400a8c0@egbert> Message-ID: <18421766819.20030127201141@rambler.ru> Hello Deirdre, Monday, January 27, 2003, 6:32:44 PM, you wrote: DH> Hi there, DH> Thanks for all the advice the last time. Worked out great! DH> I want to now put my 3 integer values into an array but it will not let me do DH> data[0] = int(x2string) DH> data[1] = int(y2string).... etc DH> instead I have to DH> data = (int(x2string), int(y2string), int(z2string)) DH> and this is only a tuple in which the size cannot be changed. DH> Can you create an array that you can append values to it. You cannot append vales to a tuple - its size is static. As I understand your problem, you forgot to define a variable. The code below should work: myArray = {} # Define an array myArray[0] = int("123") .... BTW, it's not an array, but a dictionary. If speed is crucial for your application, glance at arrays from Numeric. -- Best regards, anton mailto:antonmuhin@rambler.ru From churmtom@hotmail.com Mon Jan 27 12:16:00 2003 From: churmtom@hotmail.com (Tom Churm) Date: Mon Jan 27 12:16:00 2003 Subject: [Tutor] Import Statement Differences Message-ID: i'm running python 2.2.2 and i'm very confused because this works: from time import * formattedTimeNow = strftime("%H:%M:%S - %a, %d %b %y", localtime(time()) ) print formattedTimeNow but this results in an error: import time formattedTimeNow = strftime("%H:%M:%S - %a, %d %b %y", localtime(time()) ) print formattedTimeNow ==> NameError: name 'strftime' is not defined what's the difference between the two import statements? --tom _________________________________________________________________ The new MSN 8: advanced junk mail protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From ramrom@earthling.net Mon Jan 27 12:21:02 2003 From: ramrom@earthling.net (Bob Gailer) Date: Mon Jan 27 12:21:02 2003 Subject: [Tutor] Arrays and tuples In-Reply-To: <006701c2c61a$1915bea0$0400a8c0@egbert> Message-ID: <5.2.0.9.0.20030127101145.02dc2f60@66.28.54.253> --=======7D8E3D26======= Content-Type: multipart/alternative; x-avg-checked=avg-ok-38A765EE; boundary="=====================_10683001==.ALT" --=====================_10683001==.ALT Content-Type: text/plain; x-avg-checked=avg-ok-38A765EE; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 03:32 PM 1/27/2003 +0000, Deirdre Hackett wrote: >I want to now put my 3 integer values into an array but it will not let me do "will not let me" is woefully uninformative. Please always tell us what happens? Do you get an error? Does the computer hang? Do you get unexpected results? What do you mean by array? What do you want to do with it? Native python does not have arrays in the sense of other languages. It has lists, tuples, dictionaries for storing array-like things. If you want a list, instead of: >>> data = (int(x2string), int(y2string), int(z2string)) do: >>> data = [int(x2string), int(y2string), int(z2string)] or if you want elememt assignment initialize the list: >>> data = [0]*n # where n is the number of elements you want. then you can >>> data[0] = int(x2string) >>> data[1] = int(y2string).... etc Also check out the array capabilities in the array module and in numPy. I have recently written a class that supports arrays stored as lists of lists, and provides (at the moment) for 1 and 2 dimensional arrays, to be extended soon to higher dimensions. It allows for subscripting in the form array[row, col]. There is no requirement that all elements be the same type. Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=====================_10683001==.ALT Content-Type: text/html; x-avg-checked=avg-ok-38A765EE; charset=us-ascii Content-Transfer-Encoding: 8bit At 03:32 PM 1/27/2003 +0000, Deirdre Hackett wrote:
I want to now put my 3 integer values into an array but it will not let me do

"will not let me" is woefully uninformative. Please always tell us what happens? Do you get an error? Does the computer hang? Do you get unexpected results?

What do you mean by array? What do you want to do with it? Native python does not have arrays in the sense of other languages. It has lists, tuples, dictionaries for storing array-like things. If you want a list, instead of:
>>> data = (int(x2string), int(y2string), int(z2string))
do:
>>> data = [int(x2string), int(y2string), int(z2string)]
or if you want elememt assignment initialize the list:
>>> data = [0]*n # where n is the number of elements you want.
then you can
>>> data[0] = int(x2string)
>>> data[1] = int(y2string).... etc

Also check out the array capabilities in the array module and in numPy.

I have recently written a class that supports arrays stored as lists of lists, and provides (at the moment) for 1 and 2 dimensional arrays, to be extended soon to higher dimensions. It allows for subscripting in the form array[row, col]. There is no requirement that all elements be the same type.

Bob Gailer
mailto:ramrom@earthling.net
303 442 2625
--=====================_10683001==.ALT-- --=======7D8E3D26======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-38A765EE Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.445 / Virus Database: 250 - Release Date: 1/21/2003 --=======7D8E3D26=======-- From ATrautman@perryjudds.com Mon Jan 27 12:45:02 2003 From: ATrautman@perryjudds.com (Alan Trautman) Date: Mon Jan 27 12:45:02 2003 Subject: [Tutor] Import Statement Differences Message-ID: <0BA95581EDA7D611841B00A0C9AD25DD2B5998@mail.pjinet.com> Tom, Your issue is with the way items are named based on the way they are imported into the working program. Read the namespaces section on the Python website for more info (it quire clear and this is a model example). >from time import * >formattedTimeNow = strftime("%H:%M:%S - %a, %d %b %y", localtime(time()) ) >print formattedTimeNow from * import * all of the time function into the current namespace and then they can be called without explicit reference to the module from which they came. This sort of means (don't pick on me for generalizing please) they are added to the standard library in this program/module and can be called without explicit calls to the module. This however: >import time >formattedTimeNow = strftime("%H:%M:%S - %a, %d %b %y", localtime(time()) ) >print formattedTimeNow Needs the know where to find the functions you are calling so you explicitly tell Python where to look. (i.e. time.[function name). import time formattedTimeNow = time.strftime("%H:%M:%S - %a, %d %b %y", time.localtime(time.time()) ) print formattedTimeNow IMO opinion except for very simple items explicit is better because it is easier to trace after the program is complete and you should never run into problems with 2 modules having functions of the same name. In addition the Python documentation I seem to recall says the shames thing. HTH, Alan -----Original Message----- From: Tom Churm [mailto:churmtom@hotmail.com] Sent: Monday, January 27, 2003 11:15 AM To: tutor@python.org Subject: [Tutor] Import Statement Differences i'm running python 2.2.2 and i'm very confused because this works: from time import * formattedTimeNow = strftime("%H:%M:%S - %a, %d %b %y", localtime(time()) ) print formattedTimeNow but this results in an error: import time formattedTimeNow = strftime("%H:%M:%S - %a, %d %b %y", localtime(time()) ) print formattedTimeNow ==> NameError: name 'strftime' is not defined what's the difference between the two import statements? --tom _________________________________________________________________ The new MSN 8: advanced junk mail protection and 2 months FREE* http://join.msn.com/?page=features/junkmail _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From alan.gauld@bt.com Mon Jan 27 13:04:24 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Jan 27 13:04:24 2003 Subject: [Tutor] Arrays and tuples Message-ID: <7497DCA1C240C042B28F6657ADFD8E09702372@i2km11-ukbr.domain1.systemhost.net> > I want to now put my 3 integer values into an array but it will not let me do > > data[0] = int(x2string) > data[1] = int(y2string).... etc data = [] # create empty list data.append(int(x2string)) data.append(int(y2string)) etc... > Can you create an array that you can append values to it. Exactly so, as shown above. You might find my Raw Materials chapter useful in the web tutor... Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From dyoo@hkn.eecs.berkeley.edu Mon Jan 27 13:45:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Jan 27 13:45:01 2003 Subject: [Tutor] Import Statement Differences In-Reply-To: Message-ID: On Mon, 27 Jan 2003, Tom Churm wrote: > i'm running python 2.2.2 and i'm very confused because this works: > > from time import * > formattedTimeNow = strftime("%H:%M:%S - %a, %d %b %y", localtime(time()) ) > print formattedTimeNow Hi Tom, The 'from time import *' statement will take everything that's in the 'time' module, and dump all of it on our feet. That is, when we see something like: > from time import * it's actually doing a lot of stuff; it's almost equivalent to: ### import time accept2dyear = time.accept2dyear altzone = time.altzone asctime = time.asctime clock = time.clock ctime = time.ctime daylight = time.daylight # etc... ### Try doing a dir() before and after a 'from time import *', and you'll see a large increase of variables being dumped in after the 'from time import *'. This indiscriminant dump is one reason why using 'from foo import *' isn't usually a good idea, as it's a bit messy since it makes dir()ing our variables more difficult. If we're interested, we can look at: http://www.python.org/doc/tut/node8.html#SECTION008410000000000000000 which talks more about this. > but this results in an error: > > import time > formattedTimeNow = strftime("%H:%M:%S - %a, %d %b %y", localtime(time()) ) > print formattedTimeNow > > ==> NameError: name 'strftime' is not defined > > what's the difference between the two import statements? The second version does not pull everything out of 'time': it just makes the module 'time' itself available to us. To get at time's 'strftime' function, we have to go through 'time' first: ### import time formattedTimeNow = time.strftime("%H:%M:%S - %a, %d %b %y", localtime(time()) ) print formattedTimeNow ### This form, using a straight import, has the advantage that when we see something like: time.strftime("%H:%M:%S - %a, %d %b %y", localtime(time()) ) we can read from the statement that 'strftime' belongs to the 'time' module by inspection. When we start using a lot of modules, being able to see which functions belong to which modules can be really helpful. By the way, we can pull specific functions out of a module by using an assignment: ### import time strftime = time.strftime ### and from that point forward, 'strftime' will stand for the 'strftime' function in the 'time' module. Hope this helps! From dyoo@hkn.eecs.berkeley.edu Mon Jan 27 13:54:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Jan 27 13:54:01 2003 Subject: [Tutor] Arrays and tuples In-Reply-To: <006701c2c61a$1915bea0$0400a8c0@egbert> Message-ID: On Mon, 27 Jan 2003, Deirdre Hackett wrote: > I want to now put my 3 integer values into an array but it will not let > me do > > data[0] = int(x2string) > data[1] = int(y2string).... etc > > instead I have to > data = (int(x2string), int(y2string), int(z2string)) > > and this is only a tuple in which the size cannot be changed. > > Can you create an array that you can append values to it. You cannot > append vales to a tuple - its size is static. Instead of using a tuple, you may want to use a Python list: unlike a traditional array, it can expand as long as we tell it to. ### >>> people = [] >>> people.append('gamma') >>> people.append('helm') >>> people ['gamma', 'helm'] >>> people.append('johnson') >>> people.append('vissides') >>> people ['gamma', 'helm', 'johnson', 'vissides'] >>> people.pop(-1) 'vissides' >>> people ['gamma', 'helm', 'johnson'] ### The session above shows that we can even 'pop()' off pieces out of our list if we want. We can learn more about lists by looking at: http://www.python.org/doc/tut/node7.html#SECTION007100000000000000000 By the way, you might want to be careful about the word "array": arrays are traditionally used to say that we want a container of fixed size, so "appending to an array" is an oxymoron in certain circumstances. *grin* Good luck! From ahimsa@onetel.net.uk Mon Jan 27 14:14:01 2003 From: ahimsa@onetel.net.uk (ahimsa) Date: Mon Jan 27 14:14:01 2003 Subject: [Tutor] rockpaperscissors In-Reply-To: <200301261503.27257.shalehperry@attbi.com> References: <1043618266.20752.28.camel@localhost.localdomain> <200301261503.27257.shalehperry@attbi.com> Message-ID: <1043694547.20752.62.camel@localhost.localdomain> On Sun, 2003-01-26 at 23:03, Sean 'Shaleh' Perry wrote: > what you have here is a classic programming "mistake". You are combining two > problems in one function and as a result have loss your flexibility. That's what I dig about this list: you folk are *really* helpful. Thank you. > The function results() both determines who wins *AND* is responsible for > reporting this data. Here is where you went wrong. If you had separated > this the print step would be rather simple. Splitting the function would > also let you reimplement this program as a server for a distributed network > play version. OK you lost me about the "distributed network play version", but no doubt I'll pick that up at some point. I *do* get your point about splitting the function up: I think that I was believing that doing it the way I did it was parsimonious - but evidently not. > What you find is that splitting functions so they only do one thing (same with > classes and their methods) you can mix and match functions for bigger and > better programs. You are right Sean, and y'know now that I reflect on this I can kick myself because I had just finished reading about the wisdom of designing a function to do one thing really well (which, if I'm not mistaken is also locally referred to in Linux circles as the 'Unix Way'?), and then to add one function to reference another function in a kind of 'daisy-chain' linkage. Having made the error, I can begin to get a clearer sense of both what not doing it looks like as well as the wisdom of doing it properly. > I would have made a "who won" function and a separate "print output function". > The print output is much simpler because it just has to say "noun verb noun, X > wins over Y". Hmmm - I'll think about that for a while. I might do it like that also, but want to think it over a bit first. > You could also store the strings in a dictionary/list to make the lookup a > little cleaner. > > objects[] = (("paper", "covers"), ("rock", "breaks"), ("scissors", "cut")) > > This is very common in games where the object list can grow and grow like role > playing games. Now I like that idea. Haven't reached the section in my work books that deal with Dictionaries in depth, but might be worthwhile to work on it a bit more this weekend. Neat idea - that does appeal to me aesthetically. > That is why this list exists. However please send the code as an attachment > that way various people's email programs do not reformat or munge the code. > Many people read email in a mailer which uses TTF fonts and this makes code > reading difficult because the lines do not line up how they would in a fixed > point code editor. Fair enough - I guess as a regular text file should suffice. > Since Python is indentation sensitive this is even more important. Agreed. And thanks :-) That was useful to me. Andrew -- ahimsa From ahimsa@onetel.net.uk Mon Jan 27 14:15:04 2003 From: ahimsa@onetel.net.uk (ahimsa) Date: Mon Jan 27 14:15:04 2003 Subject: [Tutor] rockpaperscissors In-Reply-To: <5.1.0.14.0.20030126234945.02bf8a28@www.thinkware.se> References: <5.1.0.14.0.20030126234945.02bf8a28@www.thinkware.se> Message-ID: <1043694879.20756.69.camel@localhost.localdomain> Hello Magnus On Sun, 2003-01-26 at 23:07, Magnus Lycka wrote: > For the algorithm, this little session might give some ideas: > > >>> winners = {'scissors': 'rock', 'paper': 'scissors', 'rock': 'paper'} > >>> def whoWon(a, b): > ... if winners[a] == b: > ... print b, "wins over", a > ... elif winners[b] == a: > ... print a, "wins over", b > ... else: > ... print "A draw, try again" > ... > >>> whoWon('rock', 'scissors') > rock wins over scissors > >>> whoWon('rock', 'paper') > paper wins over rock > >>> whoWon('rock', 'rock') > A draw, try again > > Maybe whoWon should instead take a tuple of (name, choice)? So you are suggesting a dictionary where the key pairs are the win-lose pairs (i.e. 'scissors' broken by 'rock', etc). Sean also suggested a dictionary approach, and again I must say that it does give a really nice neat look to the code, and is easy to read too. Thank you for your suggestion; I am certainly more inclined to try to use that approach. All the best Andrew -- ahimsa From ahimsa@onetel.net.uk Mon Jan 27 14:25:05 2003 From: ahimsa@onetel.net.uk (ahimsa) Date: Mon Jan 27 14:25:05 2003 Subject: [Tutor] rockpaperscissors In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E0974DA9D@i2km11-ukbr.domain1.systemhost.net> References: <7497DCA1C240C042B28F6657ADFD8E0974DA9D@i2km11-ukbr.domain1.systemhost.net> Message-ID: <1043695387.20750.79.camel@localhost.localdomain> Hello Alan On Mon, 2003-01-27 at 12:57, alan.gauld@bt.com wrote: > Its not too bad given the size of the problem. You can of course > build on all sorts of extra sophistication, but its gardly worth > it IMHO. It is functional, but only just. The code is messy and long-winded and as both Sean and Magnus have already suggested, designing a smaller function to do the task is just better a programming tactic. > One area that might be more e;egant is to drive the results() function > from a data structure: > > # results is a dictionary of dictionaries > outcomes = ["Scissors cuts Paper", "Paper wraps Rock", "Rock smashes > Scissors"] > winners = ["Drawn game", "Computer won", "You won"] > results = { 1: { 2: outcomes[1] + winners[1], > 3: outcomes[2] + winners[2] }, > 2: { 1: outcomes[1] + winners[2], > 3: outcomes[0] + winners[1]}, > 3: { 1: outcomes[2] + winners[1], > 2: outcomes[0] + winners[2]} > } > > Now your function just becomes a case of looking up the dictionary > and printing the result. But its not that much prettier and only > saves a tiny bit of maintenance effort. Hmmm ... It took me a while but I think that I can follow what you're suggesting here. No offence, but it still looks a little clumsy or awkward, which is one of the things I didn't feel satisfied about with the example code I presented ... that and also because I couldn't add the score counter to it. > There are 3 outcomes - Computer Wins, User wins, or draw. > You can return that from the return function by making the > return value a tuple containing the result code and result > string. > > Represent that with 0,1,2 - which coincidentally(!) are the > indices of the winners string list above, making translation > easy... This is true enough ... coincidentally??? ;-) > Then use a line in the loop like: > > if result[0] == -1: draw += 1 > elif result[0] == 0: computer += 1 > else user += 1 This bottom section might do the trick actually, so I'm going to file this part away along with a couple of the other suggestions and play around with it some more and see what I can get to work. Thanks for your suggestion Alan. Best wishes Andrew -- ahimsa From nixonron@yahoo.com Mon Jan 27 14:58:06 2003 From: nixonron@yahoo.com (Ron Nixon) Date: Mon Jan 27 14:58:06 2003 Subject: [Tutor] newbie search and replace Message-ID: <20030127195622.97080.qmail@web20309.mail.yahoo.com> --0-899984948-1043697382=:96837 Content-Type: text/plain; charset=us-ascii I have a file with several thousand address in it with different spellings of "st", "street" "road", "rd" "lane", "ln" I want to go in a standardize all the spellings. The file looks like this below 100 Broad Street 50 Apple LN 24 Dirckson St. 439 Bullock RD 342 Nash Road I tried something like this addr = open('c://address.txt') import string addr = open('c://address.txt') addrN = addr.readlines() addrN.replace('LN', 'Lane') I got an error message back. Can someone tell me what am I doing wrong here and how to correct the problem to get the results I want? Ron --------------------------------- Do you Yahoo!? Yahoo! Mail Plus - Powerful. Affordable. Sign up now --0-899984948-1043697382=:96837 Content-Type: text/html; charset=us-ascii

I have a file with several thousand address in it with different spellings of "st", "street" "road", "rd" "lane", "ln"

I want to go in a standardize all the spellings. The file looks like this below

 

100 Broad Street

50 Apple LN

24 Dirckson St.

439 Bullock RD

342 Nash Road

I tried something like this

addr = open('c://address.txt')

import string
addr = open('c://address.txt')
addrN = addr.readlines()
addrN.replace('LN', 'Lane')

I got an error message back. Can someone tell me what am I doing wrong here and how to correct the problem to get the results I want?

 

Ron



Do you Yahoo!?
Yahoo! Mail Plus - Powerful. Affordable. Sign up now --0-899984948-1043697382=:96837-- From glingl@aon.at Mon Jan 27 15:13:02 2003 From: glingl@aon.at (Gregor Lingl) Date: Mon Jan 27 15:13:02 2003 Subject: [Tutor] newbie search and replace References: <20030127195622.97080.qmail@web20309.mail.yahoo.com> Message-ID: <3E3592C8.5070302@aon.at> Ron Nixon schrieb: > I have a file with several thousand address in it with different > spellings of "st", "street" "road", "rd" "lane", "ln" > > I want to go in a standardize all the spellings. The file looks like > this below > > > > 100 Broad Street > > 50 Apple LN > > 24 Dirckson St. > > 439 Bullock RD > > 342 Nash Road > > I tried something like this > > addr = open('c://address.txt') > > import string > addr = open('c://address.txt') > addrN = addr.readlines() > addrN.replace('LN', 'Lane') > > I got an error message back. Can someone tell me what am I doing wrong > here and how to correct the problem to get the results I want? > > > The readlines() method outputs a list of strings, whereas replace() is a string-method. If you used addr.read() instead, which reads in the content of the file as a string, the replace()-method should work. HTH; Gregor > Ron > > > ------------------------------------------------------------------------ > Do you Yahoo!? > Yahoo! Mail Plus > - > Powerful. Affordable. Sign up now > From Jmllr891@cs.com Mon Jan 27 15:26:00 2003 From: Jmllr891@cs.com (Jmllr891@cs.com) Date: Mon Jan 27 15:26:00 2003 Subject: [Tutor] Simple wxPython Question Message-ID: <001001c2c642$497f0ec0$58bc8018@ne1.client2.attbi.com> ------=_NextPart_000_000D_01C2C618.5FA5A080 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable I was wondering if it is possible to change the default font that is used fo= r menus in wxPython. I have tried doing it with the wxFont widget, but all I= get is an error message. I've gone through the documentation and couldn't find what I was looking for= , although I probably missed something (there's quite a few widgets to read=20= about). Anyway, thanks in advance! Joshua Miller ------=_NextPart_000_000D_01C2C618.5FA5A080 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
I was wondering if it is possible to change= the=20 default font that is used for menus in wxPython. I have tried doing it with=20= the=20 wxFont widget, but all I get is an error message.
 
I've gone through the documentation an= d=20 couldn't find what I was looking for, although I probably missed something=20 (there's quite a few widgets to read about).
 
Anyway, thanks in advance!
Joshua Miller
------=_NextPart_000_000D_01C2C618.5FA5A080-- From cooll@bol.com.br Mon Jan 27 15:43:02 2003 From: cooll@bol.com.br (Rodrigo) Date: Mon Jan 27 15:43:02 2003 Subject: [Tutor] Problem with entrys with python and Tix Message-ID: <20030127174211.6d61478d.cooll@bol.com.br> I have wrote a simple class in python to use tix to create a window, my idea is make possible open variuos instances of this window with a variation(a var inside the class will handle a database value that will allow to create diferent tables in diferente windows) but the problem is that i can not retry the information on the entrys , i have tryed it in may ways but it did not worked, i`m sending the source of the class so you can help me. class nc: def __init__(self,conta): self.__jn=Tix.Tk() nmconta=Tix.StringVar() self.__tpconta=Tix.StringVar() frm1=Tix.Frame(self.__jn,border='3',relief='ridge') frm1.pack(side='top',fill='both',expand='1') lb1 = Tix.Label(frm1,text="Nome:") lb2 = Tix.Label(frm1,text="Tipo:") self.__ent= Tix.Entry(frm1,textvariable=nmconta) tp =Tix.ComboBox(frm1,variable=self.__tpconta) tp.insert(Tix.END,"Entrada") tp.insert(Tix.END,"Saida") tp.insert(Tix.END,"Movimentacao") lb1.pack(side='top') self.__ent.pack(side='top',fill='x') lb2.pack(side='top') tp.pack(side='top',fill='x') frm2=Tix.Frame(self.__jn,border='4',relief='ridge') frm2.pack(side='top',expand='1',fill='both') bt1=Tix.Button(frm2,relief='ridge',command=self.cancelar,text='Cancel') bt2=Tix.Button(frm2,relief='ridge',command=self.ok,text='Ok') bt2.pack(side='left',fill='x') bt1.pack(side='left',fill='x') def ok(self): if(tkMessageBox.askyesno("Controler:Nova Conta","Confirma criacao da conta?")): # try: # print(self.__nmconta.get()) #sql1="Create table "+nome_conta.get()+"(data date,descricao char(250),valor float(10,2),sinal char(1))" #sql2="Insert into contas values("+self.__nmconta.get()+","+self.__tpconta.get()+")" tkMessageBox.showinfo("",nmconta) #tkMessageBox.showinfo("",sql2) #self.__jn.destroy(); # except: # tkMessageBox.showerror("Controler:Nova conta","Erro criando conta") def cancelar(self): self.__jn.wm_title("Oi") ######### From Sean Abrahams Mon Jan 27 16:01:01 2003 From: Sean Abrahams (Sean Abrahams) Date: Mon Jan 27 16:01:01 2003 Subject: [Tutor] Import and Execute Modules in List Message-ID: <59-2120858812.20030127130309@sfsu.edu> I'm developing an application where I want the user to define a list of modules they want to use and then the application then takes that list and loads those modules. As a test, I did this: ------------------------------------ >>> a = ['cgi','Cookie','sys','re'] >>> b = len(a) >>> for counter in range(b): ... import a[counter] File "", line 2 import a[counter] ^ SyntaxError: invalid syntax ------------------------------------ Obviously, this doesn't work, and I don't want to use an if-else statement. Thanks, --Sean From dyoo@hkn.eecs.berkeley.edu Mon Jan 27 16:21:04 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Jan 27 16:21:04 2003 Subject: [Tutor] Import and Execute Modules in List In-Reply-To: <59-2120858812.20030127130309@sfsu.edu> Message-ID: On Mon, 27 Jan 2003, Sean Abrahams wrote: > I'm developing an application where I want the user to define a list of > modules they want to use and then the application then takes that list > and loads those modules. > > As a test, I did this: > > ------------------------------------ > >>> a = ['cgi','Cookie','sys','re'] > >>> b = len(a) > >>> for counter in range(b): > ... import a[counter] > File "", line 2 > import a[counter] > ^ > SyntaxError: invalid syntax > ------------------------------------ > > Obviously, this doesn't work, and I don't want to use an if-else > statement. Hi Sean, The 'import' statement is slightly special: it doesn't take strings, but names of the module that's going to be imported. So we have to take a sligthly different approach. To do what you want is slightly trickier, but not by too much. We can use the builtin '__import__' function, and combine that with some globals() fiddling. For example: ### [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. >>> module_names = ['random', 'unittest', 'bisect'] >>> for m in module_names: ... globals()[m] = __import__(m) ... >>> dir() ['__builtins__', '__doc__', '__name__', 'bisect', 'm', 'module_names', 'random', 'unittest'] ### (By the way, I've simplified the for-loop code a little more by iterating directly on the names of the modules, rather than their respective numeric indices.) For more information on those two functions --- __import__() and globals() --- we can look at: http://www.python.org/doc/lib/built-in-funcs.html#l2h-2 http://www.python.org/doc/lib/built-in-funcs.html#l2h-24 I hope this helps! From nixonron@yahoo.com Mon Jan 27 16:26:15 2003 From: nixonron@yahoo.com (Ron Nixon) Date: Mon Jan 27 16:26:15 2003 Subject: [Tutor] newbie search and replace In-Reply-To: <3E3592C8.5070302@aon.at> Message-ID: <20030127212539.86768.qmail@web20304.mail.yahoo.com> --0-1037896305-1043702739=:84062 Content-Type: text/plain; charset=us-ascii Gregor Lingl wrote:Ron Nixon schrieb: > I have a file with several thousand address in it with different > spellings of "st", "street" "road", "rd" "lane", "ln" > > I want to go in a standardize all the spellings. The file looks like > this below > > > > 100 Broad Street > > 50 Apple LN > > 24 Dirckson St. > > 439 Bullock RD > > 342 Nash Road > > I tried something like this > > addr = open('c://address.txt') > > import string > addr = open('c://address.txt') > addrN = addr.readlines() > addrN.replace('LN', 'Lane') > > I got an error message back. Can someone tell me what am I doing wrong > here and how to correct the problem to get the results I want? > > > The readlines() method outputs a list of strings, whereas replace() is a string-method. If you used addr.read() instead, which reads in the content of the file as a string, the replace()-method should work. HTH; Gregor > Ron > > > ------------------------------------------------------------------------ > Do you Yahoo!? > Yahoo! Mail Plus > - > Powerful. Affordable. Sign up now > _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor Gregor and Tim Thanks Ron --------------------------------- Do you Yahoo!? Yahoo! Mail Plus - Powerful. Affordable. Sign up now --0-1037896305-1043702739=:84062 Content-Type: text/html; charset=us-ascii

 

 Gregor Lingl <glingl@aon.at> wrote:

Ron Nixon schrieb:

> I have a file with several thousand address in it with different
> spellings of "st", "street" "road", "rd" "lane", "ln"
>
> I want to go in a standardize all the spellings. The file looks like
> this below
>
>
>
> 100 Broad Street
>
> 50 Apple LN
>
> 24 Dirckson St.
>
> 439 Bullock RD
>
> 342 Nash Road
>
> I tried something like this
>
> addr = open('c://address.txt')
>
> import string
> addr = open('c://address.txt')
> addrN = addr.readlines()
> addrN.replace('LN', 'Lane')
>
> I got an error message back. Can someone tell me what am I doing wrong
> here and how to correct the problem to get the results I want?
>
>
>
The readlines() method outputs a list of strings, whereas replace() is a
string-method.
If you used addr.read() instead, which reads in the content of the file
as a string, the
replace()-method should work.


HTH; Gregor


> Ron
>
>
> ------------------------------------------------------------------------
> Do you Yahoo!?
> Yahoo! Mail Plus
> -
> Powerful. Affordable. Sign up now
>






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

Gregor and Tim

 

Thanks

 

Ron



Do you Yahoo!?
Yahoo! Mail Plus - Powerful. Affordable. Sign up now --0-1037896305-1043702739=:84062-- From nsis5@allstate.com Mon Jan 27 16:41:02 2003 From: nsis5@allstate.com (Sison, Nick) Date: Mon Jan 27 16:41:02 2003 Subject: [Tutor] Python 2.2.1 - RedHat 8 distro Message-ID: <4DF4786A05BDCA4BA5AC00431981688001005F03@a0001-xpo0113-s.hodc.ad.allstate.com> Greetings, I just installed the Rhat 8 distro on my machine and found that Python 2.2.1 seems to be installed as a default. I can't get Idle to work though. Is there something I'm missing? Can anyone direct me to a site that addresses this issue? Thanks in advance...!! ps. I do find the Idle files but when I start ./idle.py, I get a traceback call....I didn't copy it exactly but if memory serves it seems like it doesn't see some of the modules. I am thinking that I need to adjust the ENV (path)? Would this be a good assumption? Nick From Sean Abrahams Mon Jan 27 16:43:01 2003 From: Sean Abrahams (Sean Abrahams) Date: Mon Jan 27 16:43:01 2003 Subject: Re[2]: [Tutor] Import and Execute Modules in List In-Reply-To: References: Message-ID: <197-2118368125.20030127134440@sfsu.edu> Danny, Pefect =). Thank you! --Sean Monday, January 27, 2003, 1:20:33 PM, you wrote: DY> On Mon, 27 Jan 2003, Sean Abrahams wrote: >> I'm developing an application where I want the user to define a list of >> modules they want to use and then the application then takes that list >> and loads those modules. >> >> As a test, I did this: >> >> ------------------------------------ >> >>> a = ['cgi','Cookie','sys','re'] >> >>> b = len(a) >> >>> for counter in range(b): >> ... import a[counter] >> File "", line 2 >> import a[counter] >> ^ >> SyntaxError: invalid syntax >> ------------------------------------ >> >> Obviously, this doesn't work, and I don't want to use an if-else >> statement. DY> Hi Sean, DY> The 'import' statement is slightly special: it doesn't take strings, but DY> names of the module that's going to be imported. So we have to take a DY> sligthly different approach. DY> To do what you want is slightly trickier, but not by too much. We can use DY> the builtin '__import__' function, and combine that with some globals() DY> fiddling. For example: DY> ### DY> [dyoo@tesuque dyoo]$ python DY> Python 2.2.1 (#1, Sep 3 2002, 14:52:01) DY> [GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-112)] on linux2 DY> Type "help", "copyright", "credits" or "license" for more information. >>>> module_names = ['random', 'unittest', 'bisect'] >>>> for m in module_names: DY> ... globals()[m] = __import__(m) DY> ... >>>> dir() DY> ['__builtins__', '__doc__', '__name__', 'bisect', 'm', DY> 'module_names', 'random', 'unittest'] DY> ### DY> (By the way, I've simplified the for-loop code a little more by iterating DY> directly on the names of the modules, rather than their respective numeric DY> indices.) DY> For more information on those two functions --- __import__() and globals() DY> --- we can look at: DY> http://www.python.org/doc/lib/built-in-funcs.html#l2h-2 DY> http://www.python.org/doc/lib/built-in-funcs.html#l2h-24 DY> I hope this helps! DY> _______________________________________________ DY> Tutor maillist - Tutor@python.org DY> http://mail.python.org/mailman/listinfo/tutor From hall@ouhep1.nhn.ou.edu Mon Jan 27 16:45:15 2003 From: hall@ouhep1.nhn.ou.edu (Isaac Hall) Date: Mon Jan 27 16:45:15 2003 Subject: [Tutor] Python 2.2.1 - RedHat 8 distro In-Reply-To: <4DF4786A05BDCA4BA5AC00431981688001005F03@a0001-xpo0113-s.hodc.ad.allstate.com> Message-ID: Hi Nick, As far as I know, on a linux box there is no need to run Idle. I have been running python on RH 7.2 (and earlier) for 3 years now, and never used idle until the other day when I installed python on my windows box. You can get an interactive interpreter like idle simply by opening a shell window and typing 'python' in at the command line. (no arguments!) I think this should answer your questions. Ike On Mon, 27 Jan 2003, Sison, Nick wrote: > > Greetings, > > I just installed the Rhat 8 distro on my machine and found that Python 2.2.1 > seems to be installed as a default. I can't get Idle to work though. Is > there something I'm missing? Can anyone direct me to a site that addresses > this issue? Thanks in advance...!! > > ps. I do find the Idle files but when I start ./idle.py, I get a traceback > call....I didn't copy it exactly but if memory serves it seems like it > doesn't see some of the modules. I am thinking that I need to adjust the > ENV (path)? Would this be a good assumption? > > Nick > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- From magnus@thinkware.se Mon Jan 27 17:50:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Jan 27 17:50:02 2003 Subject: [Tutor] Arrays and tuples In-Reply-To: <006701c2c61a$1915bea0$0400a8c0@egbert> Message-ID: <5.1.0.14.0.20030127232720.02c8e258@www.thinkware.se> At 15:32 2003-01-27 +0000, Deirdre Hackett wrote: >I want to now put my 3 integer values into an array but it will not let me do > >data[0] = int(x2string) >data[1] = int(y2string).... etc As others have told you, the typical Python structure to use when arrays are used in other languages is a list. But while l = []; l.append(x); l.append(y) is certainly a common construct, you can also initialize with values, which you tried to do... >instead I have to >data = (int(x2string), int(y2string), int(z2string)) You are so close here. Just use [] instead of the outer (). t = (1, 2) l = [1, 2] d = {1: 2, 'a':'b'} Here, t is a tuple, l is a list, and d is a dictionary. As you noted, tuples are immutable. Dictionaries differ from lists and tuples in that they have arbitrary (well almost) keys. In this case, both t[1], l[1] and d[1] will return the same value: 2. Now you might understand why you could not simply do: data[0] = something There is no way for python to know whether you are trying to put something into a list or a dictionary here. Actually, there are a number of other types of objects as well, which use the x[n] notation. Anyway, there IS actually an array type in python as well. It's helpful if you want to restrict a list-like object to certain types of values. >>> import array >>> help(array) ... >>> a = array.array('i') >>> type(a) >>> a.append(1) >>> a.append(2) >>> a.append('r') Traceback (most recent call last): File "", line 1, in ? TypeError: an integer is required >>> print a array('i', [1, 2]) >>> for i in a: ... print i ... 1 2 >>> a = array.array('f') >>> a.append(1) >>> a.append(2) >>> a.append('r') Traceback (most recent call last): File "", line 1, in ? TypeError: bad argument type for built-in operation >>> print a array('f', [1.0, 2.0]) >>> for i in a: ... print i ... 1.0 2.0 But just as with lists, you must use append (or insert etc) to make it bigger, you can't do this: >>> a[2] = 7 Traceback (most recent call last): File "", line 1, in ? IndexError: array assignment index out of range -- 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@thinkware.se Mon Jan 27 18:09:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Jan 27 18:09:02 2003 Subject: [Tutor] Import Statement Differences In-Reply-To: References: Message-ID: <5.1.0.14.0.20030127235331.02c926b0@www.thinkware.se> At 10:44 2003-01-27 -0800, Danny Yoo wrote: >The 'from time import *' statement will take everything that's in the >'time' module, and dump all of it on our feet. A middleground between 'import time' and 'from time import *' is to write 'from time import strftime, localtime'. This means that you just type 'localtime()' instead of 'time.localtime()' when you use it, but you still don't clog your namespace with any unexpected names. I still suggest that you use "import time" though. As you code, you will probably realize that you need to use time.time() and time.clock() etc as well, and then you will need to go back to the beginning of your program to add more functions to the "from time import ..." line. This will be disruptive for your programming. No flow there... Also, when you read a program, seeing 'time.accept2dyear' is much more informative than just seeing 'accept2dyear'. In the second case, there is no way you can know from the code where 'accept2dyear' came from. In the first case it's clear that it's from the time module. Sometimes it might be obvious where a function or class belongs, but far from always. Typing "time.localtime()" is not so horribly long, but what if your module name is called MyHomemadeOracleNineDatabaseAdapter? import MyHomemadeOracleNineDatabaseAdapter conn = MyHomemadeOracleNineDatabaseAdapter.conn(connectstring) cur = ... Yuk! This time we MUST use from MyHomemadeOracleNineDatabaseAdapter import * right? No, no, no! Just use the "as" part of the import statement! import MyHomemadeOracleNineDatabaseAdapter as db conn = db.conn(connectstring) cur = ... -- 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 wheelcrdan@hotmail.com Mon Jan 27 18:17:01 2003 From: wheelcrdan@hotmail.com (Danny) Date: Mon Jan 27 18:17:01 2003 Subject: Fw: [Tutor] Database driven web sites with python [Phil and Alex's Guide to Web Publishing] Message-ID: ----- Original Message ----- From: "Danny Yoo" To: "Danny" Cc: Sent: Tuesday, January 21, 2003 10:25 AM Subject: Re: [Tutor] Database driven web sites with python [Phil and Alex's Guide to Web Publishing] > > > On Fri, 17 Jan 2003, Danny wrote: > > > Quick and easy question, can you use python to build database driven web > > sites. Thanks ahead of time for everyone help, and have a great > > weekend... > > Out of curiosity, what kind of database-driven web site are you thinking > of building? > > If you haven't seen this already, you may find "Phil and Alex's Guide to > Web Publishing" a useful (and amusing) web book to browse through: > > http://philip.greenspun.com/panda/ > > In particular: > > http://philip.greenspun.com/panda/databases-interfacing > > talks about the basics of writing database-driven sites. He uses a > programming language called Tcl/Tk to implement his site, but you can > translate that code to Python pretty easily. And even with the book's > non-Python focus, it gives a lot of good ideas that you can use to help > build your site. > > > Good luck to you! > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor Hello everyone! :) The kind of site i was building is really simple idea. They want to add to a all ready existing site... They want to add a page that they can log into. Then go to a another page. Which is a database that lists their clients for them.. So they can be any where, and know where who their clients are. I recomended it to be database driven.. Because they can easily update it, without having to know any code. "I know how to sell a page thats what I do for a living. :) :)" But I'm really tring to learn to program so I can build and sell a web page. So I can make more $$$ :) :) :).. Hope everyone had a great day, and thanks to everyone responded to my emails.. Danny Dudleston > From glingl@aon.at Mon Jan 27 18:24:10 2003 From: glingl@aon.at (Gregor Lingl) Date: Mon Jan 27 18:24:10 2003 Subject: [Tutor] Arrays and tuples References: <5.1.0.14.0.20030127232720.02c8e258@www.thinkware.se> Message-ID: <3E35BFA3.6000201@aon.at> Magnus Lycka schrieb: > At 15:32 2003-01-27 +0000, Deirdre Hackett wrote: > >> I want to now put my 3 integer values into an array but it will not >> let me do >> >> data[0] = int(x2string) >> data[1] = int(y2string).... etc > > > But while > l = []; l.append(x); l.append(y) > is certainly a common construct, you can also initialize > with values, which you tried to do... > >> instead I have to >> data = (int(x2string), int(y2string), int(z2string)) > Sometimes you may encounter a situation, where you know the length of an array but NOT the order in which values will be put into that array. In this situation you may use an approach similar to the following one: >>> data = [None] * 4 >>> data [None, None, None, None] >>> data[2] = 4.25 >>> data [None, None, 4.25, None] >>> data[0] = 1 >>> data [1, None, 4.25, None] Sincerely, Gregor From magnus@thinkware.se Mon Jan 27 18:26:00 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Jan 27 18:26:00 2003 Subject: [Tutor] Simple wxPython Question In-Reply-To: <001001c2c642$497f0ec0$58bc8018@ne1.client2.attbi.com> Message-ID: <5.1.0.14.0.20030128002230.02c862b8@www.thinkware.se> At 15:25 2003-01-27 -0500, Jmllr891@cs.com wrote: >I was wondering if it is possible to change the default font that is used >for menus in wxPython. I have tried doing it with the wxFont widget, but >all I get is an error message. If I remember correctly, a similar question was recently up on the wxPython-users mailing list. That's really be proper forum for this question, but search the archives first. -- 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@thinkware.se Mon Jan 27 18:37:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Jan 27 18:37:01 2003 Subject: [Tutor] newbie search and replace In-Reply-To: <3E3592C8.5070302@aon.at> References: <20030127195622.97080.qmail@web20309.mail.yahoo.com> Message-ID: <5.1.0.14.0.20030128002502.02c5f0c0@www.thinkware.se> At 21:12 2003-01-27 +0100, Gregor Lingl wrote: >>addrN.replace('LN', 'Lane') >The readlines() method outputs a list of strings, whereas replace() is a >string-method. >If you used addr.read() instead, which reads in the content of the file as >a string, the >replace()-method should work. But beware! Remember that ALL occurences of LN etc will be replaced. And it's case sensitive. >>> "First Liston St".replace('st', 'street') 'Firstreet Listreeton St' Oops! Regular expressions might be a better choice. >>> import re >>> stPat = re.compile(r'\bst\b', re.IGNORECASE) >>> stPat.sub('Street', "First Liston St") 'First Liston Street' But to use re well, you need some study and practice. See the python library reference. -- 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 glingl@aon.at Mon Jan 27 18:50:01 2003 From: glingl@aon.at (Gregor Lingl) Date: Mon Jan 27 18:50:01 2003 Subject: [Tutor] newbie search and replace References: <20030127195622.97080.qmail@web20309.mail.yahoo.com> <5.1.0.14.0.20030128002502.02c5f0c0@www.thinkware.se> Message-ID: <3E35C5A5.3080202@aon.at> Magnus Lycka schrieb: > > But to use re well, you need some study and practice. See > the python library reference. > > And also the very well written Regular Expression HOWTO at http://www.amk.ca/python/howto/ Gregor From Sean Abrahams Mon Jan 27 19:01:02 2003 From: Sean Abrahams (Sean Abrahams) Date: Mon Jan 27 19:01:02 2003 Subject: [Tutor] Web Programming Resources Message-ID: <189-2110056968.20030127160311@sfsu.edu> Thanks to this list I just found: "Philip and Alex's Guide to Web Publishing" http://philip.greenspun.com/panda/index.html Something I wish I would have found four years ago. As a young web developer I have seriously been lacking a Mentor. I've been going it on my own for a year now and have yearned for an experienced programmer to show me the ropes. Thus, I was hoping some of you on this list would share the books/resources that have changed the way you program, and more specifically, for the web. I can't be thankful enough that I finally signed up for this list, and look forward to learning each and every day from the posts. So you don't forget ;), what books/resources do you find essential to your programming (specifically web programming in my case) and learning/usage of it? I would definitely put "Philip and Alex's Guide to Web Publishing" on my list. Thanks, --Sean From Janssen@rz.uni-frankfurt.de Mon Jan 27 20:08:13 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Mon Jan 27 20:08:13 2003 Subject: [Tutor] newbie search and replace In-Reply-To: <5.1.0.14.0.20030128002502.02c5f0c0@www.thinkware.se> Message-ID: Hi all, to avoid nasty regular expressions, one can split the file into "words" (defined as character[s] between spaces - now you needn't check for word-boundaries via regexp) and check for every word if a abbrevation-fullstring-dictionary has the word as a key: 1. read file with readlines (--> list of lines) 2. split every line into "words". Omit newlines 3. check for each word in lowercase if the dictionary has it as a key. If yes change it (i.e. overwrite the word with the fullstring from the dictionary). 4. join the words back to lines. 5. write list of lines back to file. This approach has the advantages of avoiding regexps, possibly being faster (could be, but I don't know), being more readable, because the abbrevation-fullstring definitions sits in the dictionary and arn't scattered through the code. On the other hand, the code itself is more comlicate than simple read(), xxx times of re.sub() and write(). Perhaps, you have solved your task just a few minutes after first response from the list, how knows? regards Michael On Tue, 28 Jan 2003, Magnus Lycka wrote: > But to use re well, you need some study and practice. See > the python library reference. From shalehperry@attbi.com Mon Jan 27 20:32:02 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Mon Jan 27 20:32:02 2003 Subject: [Tutor] rockpaperscissors In-Reply-To: <1043694547.20752.62.camel@localhost.localdomain> References: <1043618266.20752.28.camel@localhost.localdomain> <200301261503.27257.shalehperry@attbi.com> <1043694547.20752.62.camel@localhost.localdomain> Message-ID: <200301271731.10861.shalehperry@attbi.com> On Monday 27 January 2003 11:09, ahimsa wrote: > > What you find is that splitting functions so they only do one thing (= same > > with classes and their methods) you can mix and match functions for > > bigger and better programs. > > You are right Sean, and y'know now that I reflect on this I can kick > myself because I had just finished reading about the wisdom of designin= g > a function to do one thing really well (which, if I'm not mistaken is > also locally referred to in Linux circles as the 'Unix Way'?), and then > to add one function to reference another function in a kind of > 'daisy-chain' linkage. Having made the error, I can begin to get a > clearer sense of both what not doing it looks like as well as the wisdo= m > of doing it properly. > One of my college professors explained this as: when you go to write a function write a comment in front of it explaining= its=20 purpose to someone else. If you find yourself using the word 'and' more = than=20 once it is probably doing too much. I find that to be a little simplistic but generally sums up the idea well= =2E =20 While I do not comment my code like that I find the thought process can b= e=20 quite useful. From magnus@thinkware.se Mon Jan 27 20:50:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Jan 27 20:50:01 2003 Subject: [Tutor] newbie search and replace In-Reply-To: References: <5.1.0.14.0.20030128002502.02c5f0c0@www.thinkware.se> Message-ID: <5.1.0.14.0.20030128023853.02ce5e20@www.thinkware.se> At 02:07 2003-01-28 +0100, Michael Janssen wrote: >to avoid nasty regular expressions, one can split the file into "words" >(defined as character[s] between spaces - now you needn't check for >word-boundaries via regexp) and check for every word if a >abbrevation-fullstring-dictionary has the word as a key: But this is not the same as a regular expression word boundry. A word in RE is a sequence of alphanumeric characters and underscore. So, there are other word boundries than whitespace. This means that both "Hill St." and "Hill St" will be found by re.compile(r'\bst\b', re.IGNORECASE). If we want to eat up a possible trailing space, change it to re.compile(r'\bst\b\.?', re.IGNORECASE) >>> stPat = re.compile(r'\bst\b', re.IGNORECASE) >>> stPat.sub('Street', "First Liston St.") 'First Liston Street.' >>> stPat = re.compile(r'\bst\b\.?', re.IGNORECASE) >>> stPat.sub('Street', "First Liston St") 'First Liston Street' >>> stPat.sub('Street', "First Liston St.") 'First Liston Street' Once a problem reaches a certain level of complexity, and I think tidying natural language texts are a problem at that level, using too simple tools will just lead to very complicated, or failing, solutions. (Or both.) The power of RE means that it takes some time to learn, but in many situations, it's worth it. -- 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 Janssen@rz.uni-frankfurt.de Mon Jan 27 22:16:55 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Mon Jan 27 22:16:55 2003 Subject: [Tutor] newbie search and replace In-Reply-To: <5.1.0.14.0.20030128023853.02ce5e20@www.thinkware.se> Message-ID: On Tue, 28 Jan 2003, Magnus Lycka wrote: > But this is not the same as a regular expression word boundry. > A word in RE is a sequence of alphanumeric characters and > underscore. So, there are other word boundries than whitespace. [snip] > Once a problem reaches a certain level of complexity, and I > think tidying natural language texts are a problem at that > level, using too simple tools will just lead to very > complicated, or failing, solutions. (Or both.) > > The power of RE means that it takes some time to learn, but > in many situations, it's worth it. My first concern was that many global subtitions over a long string would last a long time. But I know: never optimize your code before the obvious attempt has proven inefficiency (On a sidenote: my favourite programm stucks most the runtime computing RE's where perl aequivalents have done the job already - it's terrible subjective, but I believe python's RE slow). Thanks for spotting the details of regular expression's "\b". Michael > > > -- > 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 llazarre@yahoo.com Mon Jan 27 23:39:02 2003 From: llazarre@yahoo.com (Levy Lazarre) Date: Mon Jan 27 23:39:02 2003 Subject: [Tutor] Python and Tcl/Tk Message-ID: <20030128043730.12746.qmail@web40413.mail.yahoo.com> Greetings to all, Is anybody in this list familiar with Tcl/Tk? How does it compare to Python as a scripting language? Any areas where Tcl would be superior to Python? Please comment. Thanks, Levy Lazarre __________________________________________________ Do you Yahoo!? Yahoo! Mail Plus - Powerful. Affordable. Sign up now. http://mailplus.yahoo.com From dman@dman.ddts.net Tue Jan 28 00:01:02 2003 From: dman@dman.ddts.net (Derrick 'dman' Hudson) Date: Tue Jan 28 00:01:02 2003 Subject: [Tutor] Re: Sending Break in Telnet In-Reply-To: <46FEE020BCB4D3118C5800508B55C92801361151@SFOEXCHANGE> References: <46FEE020BCB4D3118C5800508B55C92801361151@SFOEXCHANGE> Message-ID: <20030128050026.GA4678@dman.ddts.net> --T4sUOijqQbZv57TR Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Wed, Jan 15, 2003 at 06:21:54PM -0800, Pankaj Mittal wrote: | Hi |=20 | I am developing a python program that connects to a server using telnet. | When I use the unix telnet I have to send=20 | telnet . This has to be followed by sending a "^]" | chartacter and then with "send break" on receiving a "telnet>" prompt.=20 | But when I try to send \035(equivalent of '^]', it does not work. How does your python program make the connection? Typing ^] is specific to the 'telnet' program. That is merely a way of indicating that you (the user at the keyboard) want the telnet program itself to respond to you, rather than sending the keys on to the remote machine. | Also I tried to send '\377\363'(255 and 243 - code as in RFC | document). I'm not sure, but possibly that character sequence must occur in a specific location in the telnet data stream. I'm not familiar with the intricacies of the telnet protocol and I don't have the RFCs handy, nor the time at the moment to read through them. However, I suspect that if you reread the RFC and if you use a packet sniffer like tcpdump or ethereal to compare the two sessions you'll find the difference. It is completely possible to match the (snipped) example session using python code and not using the 'telnet' program. HTH, -D --=20 Whoever gives heed to instruction prospers, and blessed is he who trusts in the Lord. Proverbs 16:20 =20 http://dman.ddts.net/~dman/ --T4sUOijqQbZv57TR Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAj42DmoACgkQO8l8XBKTpRSNRQCeLbnJh3yja4Sz6xCtVjl/pHJF 1DkAnRK6Ud2iBIs7tNSDC5r0gtkI3J28 =+826 -----END PGP SIGNATURE----- --T4sUOijqQbZv57TR-- From dyoo@hkn.eecs.berkeley.edu Tue Jan 28 00:12:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Jan 28 00:12:01 2003 Subject: [Tutor] Python and Tcl/Tk In-Reply-To: <20030128043730.12746.qmail@web40413.mail.yahoo.com> Message-ID: On Mon, 27 Jan 2003, Levy Lazarre wrote: > Greetings to all, > > Is anybody in this list familiar with Tcl/Tk? How does it compare to > Python as a scripting language? Any areas where Tcl would be superior to > Python? Please comment. Hi Levy, I ran into the following humongous web page that compares Tcl/Tk against other languages: http://www.icemcfd.com/tcl/comparison.html I got very tired after reading a few pages. *grin* But you're welcome to browse through it; there's actually quite a lot of good stuff in there. Good luck! From idiot1@netzero.net Tue Jan 28 01:20:02 2003 From: idiot1@netzero.net (Kirk Bailey) Date: Tue Jan 28 01:20:02 2003 Subject: [Tutor] making money References: <3E338A78.9090107@netzero.net> Message-ID: <3E362101.2050904@netzero.net> ok. Be advised that I routinely pack heat. Michael Miller wrote: >>Anyone want to talk about this sillyness a little? > > > Sure. Meet me behind the 7-11 at midnight tomorrow. I'll be the one with the > baseball bat. ;) Sad thing is, it would probably work. Make sure you put a > popup or five on every new page. > > Michael > > -- end Respectfully, Kirk D Bailey Owner HowlerMonkey Email Services Company: http://www.howlermonkey.net/ Inventor of TinyList MLM list server: http://www.tinylist.org/ Consulting Lunatic: http://www.sacredelectron.org/ Remember: it is an ill wind that blows no minds. Fnord. From ahimsa@onetel.net.uk Tue Jan 28 03:07:03 2003 From: ahimsa@onetel.net.uk (ahimsa) Date: Tue Jan 28 03:07:03 2003 Subject: [Tutor] rockpaperscissors In-Reply-To: <200301271731.10861.shalehperry@attbi.com> References: <1043618266.20752.28.camel@localhost.localdomain> <200301261503.27257.shalehperry@attbi.com> <1043694547.20752.62.camel@localhost.localdomain> <200301271731.10861.shalehperry@attbi.com> Message-ID: <1043741155.20752.229.camel@localhost.localdomain> On Tue, 2003-01-28 at 01:31, Sean 'Shaleh' Perry wrote: > One of my college professors explained this as: > > when you go to write a function write a comment in front of it explaining its > purpose to someone else. If you find yourself using the word 'and' more than > once it is probably doing too much. > > > I find that to be a little simplistic but generally sums up the idea well. > While I do not comment my code like that I find the thought process can be > quite useful. I agree - that is a useful little reminder. Thanks :-) -- ahimsa From magnus@thinkware.se Tue Jan 28 06:49:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Jan 28 06:49:01 2003 Subject: [Tutor] Python and Tcl/Tk In-Reply-To: <20030128043730.12746.qmail@web40413.mail.yahoo.com> Message-ID: <5.1.0.14.0.20030128113357.02b61ac8@www.thinkware.se> At 20:37 2003-01-27 -0800, Levy Lazarre wrote: >Is anybody in this list familiar with Tcl/Tk? How does >it compare to Python as a scripting language? Any >areas where Tcl would be superior to Python? Please >comment. Tcl and Python are fairly different languages. Python is a language you can grow with. You can start small, and your project can grow in python. The language scales well. Tcl is only intended for small tasks and to glue larger programs (written in C or whatever) together. Either as an alternative to unix scripts, or to provide a GUI for a text based application. Don't expect to use Tcl beyond that scope. It needs to live in symbiosis with another language, where the "real" programs are written. You can do everything Tcl can in Python, but not vice versa. Even as a glue language for C programs, Python is much stronger, since Python has much more advanced data structures. I haven't really tried, but it seems to me that using Tcl to interface to programs where you need to access and communicate with complex data structures would be a little like trying to build model airplanes with thick wool mittens... On the other hand, I think Tcl is smaller, which might be a good thing on a palmtop or in an embedded appliance etc. If you search amazon for tcl books, you will find that all (?) books fall into one of these categories: * Published earlier than year 2000, maybe first ed in 1994. * Out of print. * Promised update of old book that is not yet available. A fading star? For very simple tasks for beginners, or as a user macro language Tcl might have a strength in its very simple syntax, and very simple data structures--every variable is a string. For people who have programmed in something like Basic, Java, C, Pascal etc, Python will probably look more familiar though. But as soon as things get a little more complex, programming in Tcl starts to be an uphill battle. Programmers start to invent their own syntax and data structures to an extent where other people will have to make an effort to understand construct that would have been trivial had they been implemented in for instance Python. -- 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 alan.gauld@bt.com Tue Jan 28 07:13:04 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Jan 28 07:13:04 2003 Subject: [Tutor] Python 2.2.1 - RedHat 8 distro Message-ID: <7497DCA1C240C042B28F6657ADFD8E09702378@i2km11-ukbr.domain1.systemhost.net> > As far as I know, on a linux box there is no need to run > Idle. There's no *need* but many folks like to because it gives them some nice features over a shell python prompt: 1) syntax colouring(even at the >>> prompt) 2) a graphical debugger 3) tooltips for function parameters 4) some nice inspection tools(class and path browsers) Alan G. (Voting on the pro-IDLE side for a change!) From alan.gauld@bt.com Tue Jan 28 10:27:01 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Jan 28 10:27:01 2003 Subject: [Tutor] Python at C++ conference Message-ID: <7497DCA1C240C042B28F6657ADFD8E0974DAA2@i2km11-ukbr.domain1.systemhost.net> I just got an invite to the "Association of C and C++ users"(ACCU) annual conference. Interestingly days 1 & 2 feature a Python stream with such luminaries as Guido, Alex Martelli and Duncan Booth and Andy Koenig giving talks covering both Python and Jython. Since my company doesn't, as a rule, allow attendance at such events is anyone else on the list attending who can give a report? More details: http://www.accuconference.co.uk/ Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From alan.gauld@bt.com Tue Jan 28 10:50:34 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Jan 28 10:50:34 2003 Subject: [Tutor] newbie search and replace Message-ID: <7497DCA1C240C042B28F6657ADFD8E09702381@i2km11-ukbr.domain1.systemhost.net> > My first concern was that many global subtitions over a long > string would last a long time. True but probably less time with a well designed RE than with multiple string searches with lots of safety checks. > stucks most the runtime computing RE's where perl > aequivalents have done the job already - it's terrible subjective, > but I believe python's RE slow). The C versions are pretty good, they are slower than Perl mainly because they are not builtin to the language but apart from module overhead they are not that much slower. I think Python's bad reputation for REs is largely based on the original regex module written in Python. Dirt sticks, even after its been cleaned off sometimes! Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From alan.gauld@bt.com Tue Jan 28 10:50:49 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Jan 28 10:50:49 2003 Subject: [Tutor] Python and Tcl/Tk Message-ID: <7497DCA1C240C042B28F6657ADFD8E09702382@i2km11-ukbr.domain1.systemhost.net> > Is anybody in this list familiar with Tcl/Tk? How does > it compare to Python as a scripting language? Any > areas where Tcl would be superior to Python? Please > comment. Slightly. Its usually shorter than Python for short programs. As the program size increases the difference diminishes and then swaps in Python's favour - in my experience. You can compare the two on my web tutor which uses Tcl in the basics section as a comparison to Python and also a very short example of Tk in my GUI topic. www.scriptics.com is/was Tcl's home site. I find Tcl interesting conceptually in much the same way I find Lisp and Smalltalk interesting. Fun to play with but I never seem to actually use them for anything big... Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From alan.gauld@bt.com Tue Jan 28 11:04:04 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Jan 28 11:04:04 2003 Subject: [Tutor] Python and Tcl/Tk Message-ID: <7497DCA1C240C042B28F6657ADFD8E09702383@i2km11-ukbr.domain1.systemhost.net> Oooh, I have to jump to Tcl's defence here :-) > Tcl and Python are fairly different languages. That's true, Tcl is unlike most languages in that it is command based and all operations consist of a single "line" - even when that line spans several physical lines! > Tcl is only intended for small tasks and to glue larger > programs (written in C or whatever) together. Not entirely true, the latest versions of Tcl can scale to quite large projects now it has OO and module support. But I do still favour Python for that role. > It needs to live in symbiosis with another language, where > the "real" programs are written. Not at all true. there are many standalone Tcl scripts around, most famously expect. > You can do everything Tcl can in Python This isn't true. In Tcl irts easy to redefine the bahaviour of the language at a level Python can't approach - redefine how the if statement works, or a while loop etc. Whether doing such things is wise is another matter entirely! Self modifying code is also easier to write in TCL - and the same caveat applies! > really tried, but it seems to me that using Tcl to interface > to programs where you need to access and communicate with > complex data structures would be a little like trying to build > model airplanes with thick wool mittens... Not sure why you think that. Tcl can handle complex structures pretty well. Certainly C unions and structs are handled OK. And classes map to Tcl classes. > On the other hand, I think Tcl is smaller, which might be > a good thing on a palmtop or in an embedded appliance etc. Much smaller. > If you search amazon for tcl books, you will find that all (?) > books fall into one of these categories: Too true, finding good Tcl books is not hard but there are few of them and the language is tending to outpace the authors. (But the same is true of Python book currency) > A fading star? A niche player... > simple data structures--every variable is a string. No longer true, and Tcl does have native compilation (and Java byte code support) in its favour too (as does Python via Jython and py2exe etc). > who have programmed in something like Basic, Java, C, Pascal > etc, Python will probably look more familiar though. This is definitely true. Tcl is downright weird the first time you encounter it - and the second! > in Tcl starts to be an uphill battle. Programmers start to invent > their own syntax and data structures Which is the Tcl idiom. In that regard its a bit like Lisp which also encourages a fine grained functional approach. I definitely prefer Python,, especially for big projects but Tcl is alive and well and very powerful for some things. In its niche (an embedded extensible macro language) it is still the best tool around IMHO. Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From ramrom@earthling.net Tue Jan 28 11:24:01 2003 From: ramrom@earthling.net (Bob Gailer) Date: Tue Jan 28 11:24:01 2003 Subject: [Tutor] rockpaperscissors In-Reply-To: <1043741155.20752.229.camel@localhost.localdomain> References: <200301271731.10861.shalehperry@attbi.com> <1043618266.20752.28.camel@localhost.localdomain> <200301261503.27257.shalehperry@attbi.com> <1043694547.20752.62.camel@localhost.localdomain> <200301271731.10861.shalehperry@attbi.com> Message-ID: <5.2.0.9.0.20030128090815.02e812c0@66.28.54.253> --=======3BF65911======= Content-Type: text/plain; x-avg-checked=avg-ok-2D7674C4; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit Here's a "minimalist" version of rockpaperscissors: import random score = [0,0,0] for i in range(3): play = random.randint(0,2), random.randint(0,2) outcome = [2,1,0,2,1][play[0] - play[1] + 2] print '-'.join([['rock', 'scissors', 'paper'][p] for p in play]), ['tie', 'player 1 wins', 'player 2 wins'][outcome] score[outcome] += 1 print 'player 1-%s ties=%s player 2=%s' % tuple(score) Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======3BF65911======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-2D7674C4 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.445 / Virus Database: 250 - Release Date: 1/21/2003 --=======3BF65911=======-- From glingl@aon.at Tue Jan 28 12:13:03 2003 From: glingl@aon.at (Gregor Lingl) Date: Tue Jan 28 12:13:03 2003 Subject: [Tutor] rockpaperscissors References: <200301271731.10861.shalehperry@attbi.com> <1043618266.20752.28.camel@localhost.localdomain> <200301261503.27257.shalehperry@attbi.com> <1043694547.20752.62.camel@localhost.localdomain> <200301271731.10861.shalehperry@attbi.com> <5.2.0.9.0.20030128090815.02e812c0@66.28.54.253> Message-ID: <3E36BA2B.6050403@aon.at> Bob Gailer schrieb: > Here's a "minimalist" version of rockpaperscissors: > > import random > score = [0,0,0] > for i in range(3): > play = random.randint(0,2), random.randint(0,2) > outcome = [2,1,0,2,1][play[0] - play[1] + 2] > print '-'.join([['rock', 'scissors', 'paper'][p] for p in play]), > ['tie', 'player 1 wins', 'player 2 wins'][outcome] > score[outcome] += 1 > print 'player 1-%s ties=%s player 2=%s' % tuple(score) > I think the last line should read: print 'ties=%s player 1=%s player 2=%s\n' % tuple(score) Isn't it? Moreover, if you would agree the following to be even more minimalstic, you could replace line #5 by: outcome = (play[1]-play[0]) % 3 If you now wonder, why this yields the same output, you may feel that there's something slightly uncomfortable with "minimalistic" solutions like this. Sincerely, Gregor From PMittal@Ceon.com Tue Jan 28 12:59:01 2003 From: PMittal@Ceon.com (Pankaj Mittal) Date: Tue Jan 28 12:59:01 2003 Subject: [Tutor] RE: Sending Break in Telnet Message-ID: <46FEE020BCB4D3118C5800508B55C9280136116A@SFOEXCHANGE> Hi Derrick You are absolutely correct ^} is just to indicate the telnet client to got to a mode where some commands can be send like break. I read the RFC document and came to know about the break sequence. I was unable to send this as in Python 2.0.1 the telnet class escapes the special character i.e. decimal 255. So I found that I can directly use the public socket variable when I need to send this special characters as there is no other write function in telnet class. So Once I did that I was able to send special characters and everything worked. Thanks for you help Pankaj -----Original Message----- From: Derrick 'dman' Hudson [mailto:dman@dman.ddts.net] Sent: Monday, January 27, 2003 9:00 PM To: 'tutor@python.org' Cc: Pankaj Mittal Subject: Re: Sending Break in Telnet On Wed, Jan 15, 2003 at 06:21:54PM -0800, Pankaj Mittal wrote: | Hi | | I am developing a python program that connects to a server using telnet. | When I use the unix telnet I have to send | telnet . This has to be followed by sending a "^]" | chartacter and then with "send break" on receiving a "telnet>" prompt. | But when I try to send \035(equivalent of '^]', it does not work. How does your python program make the connection? Typing ^] is specific to the 'telnet' program. That is merely a way of indicating that you (the user at the keyboard) want the telnet program itself to respond to you, rather than sending the keys on to the remote machine. | Also I tried to send '\377\363'(255 and 243 - code as in RFC | document). I'm not sure, but possibly that character sequence must occur in a specific location in the telnet data stream. I'm not familiar with the intricacies of the telnet protocol and I don't have the RFCs handy, nor the time at the moment to read through them. However, I suspect that if you reread the RFC and if you use a packet sniffer like tcpdump or ethereal to compare the two sessions you'll find the difference. It is completely possible to match the (snipped) example session using python code and not using the 'telnet' program. HTH, -D -- Whoever gives heed to instruction prospers, and blessed is he who trusts in the Lord. Proverbs 16:20 http://dman.ddts.net/~dman/ From Janssen@rz.uni-frankfurt.de Tue Jan 28 13:28:01 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Tue Jan 28 13:28:01 2003 Subject: [Tutor] regexp are fast - was: newbie search and replace In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E09702381@i2km11-ukbr.domain1.systemhost.net> Message-ID: On Tue, 28 Jan 2003 alan.gauld@bt.com wrote: > > My first concern was that many global subtitions over a long > > string would last a long time. > > True but probably less time with a well designed RE than with > multiple string searches with lots of safety checks. I've played a bit with "findall", rewritten the core of a script of mine, which I've written throughout the summer within twenty minutes, made it far more stable and voila: even incredibly faster than my first attempt (at least factor 2 with first try): What I've learned this afternoon and last night is: re's findall over a large string is much faster than many single string or re-operations while iterating line by line over a file. Yes, well designed RE's are fast. Michael [me - yesterday] > > stucks most the runtime computing RE's where perl > > aequivalents have done the job already - it's terrible subjective, > > but I believe python's RE slow). okey, I've changed my opinion about this :-) "You learn more, and the language scales up" > > The C versions are pretty good, they are slower than Perl mainly > because they are not builtin to the language but apart from module > overhead they are not that much slower. I think Python's bad reputation > for REs is largely based on the original regex module written in > Python. Dirt sticks, even after its been cleaned off sometimes! > > Alan g. > Author of the Learn to Program website > http://www.freenetpages.co.uk/hp/alan.gauld/ > From tim@johnsons-web.com Tue Jan 28 17:20:02 2003 From: tim@johnsons-web.com (Tim Johnson) Date: Tue Jan 28 17:20:02 2003 Subject: [Tutor] HTTP_REFERER Issues Message-ID: <20030128222426.GY16215@johnsons-web.com> Hello All: I'm using python for a cgi script, but I believe this is a language independant issue: Ideally, my script will check for the HTTP_REFERER, and provide content only if it matches a 'hard-coded' variable. This script will be 'activated' through a link created from (probably) dynamic content provided by another cgi program. Is there a way to guarantee the the Referring Document will indeed provide the HTTP_REFERER environment variable to my cgi script? If this question is not appropriate for this mailing list, than I hope that you will forgive me and perhaps someone will point me in the right direction. Regards -- Tim Johnson http://www.alaska-internet-solutions.com http://www.johnsons-web.com From magnus@thinkware.se Tue Jan 28 17:59:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Jan 28 17:59:01 2003 Subject: [Tutor] Python and Tcl/Tk In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E09702383@i2km11-ukbr.domain1 .systemhost.net> Message-ID: <5.1.0.14.0.20030128200648.0298bce0@www.thinkware.se> At 16:00 2003-01-28 +0000, alan.gauld@bt.com wrote: >Oooh, I have to jump to Tcl's defence here :-) Good! I rarely meet Tclers these days. > > Tcl is only intended for small tasks and to glue larger > > programs (written in C or whatever) together. > >Not entirely true, the latest versions of Tcl can scale to >quite large projects now it has OO and module support. >But I do still favour Python for that role. If you say so... but it was John Osterhout who wrote that: "I think that Stallman's objections to Tcl may stem largely from one aspect of Tcl's design that he either doesn't understand or doesn't agree with. This is the proposition that you should use *two* languages for a large software system: one, such as C or C++, for manipulating the complex internal data structures where performance is key, and another, such as Tcl, for writing small-ish scripts that tie together the C pieces and are used for extensions." He wrote that in 1994 though. Maybe he changed his mind later? Or was his statement then just his feeble defence for Tcl shortcomings until he had repaired them? A brief review of Tcl scalabilty and related problems would be interesting. > > It needs to live in symbiosis with another language, where > > the "real" programs are written. > >Not at all true. there are many standalone Tcl scripts >around, most famously expect. I'd say that expect is a perfect example of what I meant. Expect is used to provide access to other programs. It's as glue as it gets! Sorry if I was unclear. > > You can do everything Tcl can in Python > >This isn't true. In Tcl irts easy to redefine the bahaviour >of the language at a level Python can't approach - redefine >how the if statement works, or a while loop etc. Whether >doing such things is wise is another matter entirely! > >Self modifying code is also easier to write in TCL - and >the same caveat applies! I was unclear again. Sorry. What I meant to say was that if there is a problem where tcl can provide a solution, python can be used to provide a solution as well. I didn't mean that you would do it in an equally weird way. ;) I'll make a reservation for embedded use where space is an important factor. Python might be too big for some applications. This ability to redefine the way the language works is a mixed blessing to put it mildly. > > really tried, but it seems to me that using Tcl to interface > > to programs where you need to access and communicate with > > complex data structures would be a little like trying to build > > model airplanes with thick wool mittens... > >Not sure why you think that. Tcl can handle complex structures >pretty well. Certainly C unions and structs are handled OK. >And classes map to Tcl classes. It seems Tcl has evolved a bit since I last looked at it. I thought OO features like classes only existed in extensions like [incr Tcl]. As far as I understand these extensions might cause compatibility problems with other Tcl/Tk libraries since they change the language, introducing scopes. I have this vague memory of horror stories from people who tried to use [incr Tk] widgets in applications that previously were "classic" Tcl/Tk apps. But I guess it's difficult to make *any* firm statement about features in a language where you can change how the basic building blocks behave in runtime. > > On the other hand, I think Tcl is smaller, which might be > > a good thing on a palmtop or in an embedded appliance etc. > >Much smaller. The ActiveTcl package at ActiveState isn't so terribly small though. But I assume that includes a lot that you can strip out. Although that is true about Python as well. So, how small does it get? Can it run in a PDA? With classes and stuff? Or are we back to stripped and/or old versions? >Too true, finding good Tcl books is not hard but there are few >of them and the language is tending to outpace the authors. >(But the same is true of Python book currency) You don't need to develop the language a lot to outpace the book authors if the newest books are four years old. Roughly 30 books about Python have been published after 1999. Regarding Python, version 2.3 doesn't change as much as the previous releases did, so it might be time for the authors to catch up now... But there ARE Python books that are fairly current, covering version 2.2. The 3rd edition of the Welch book covers 8.2 though... Not too bad I guess, but if you don't want t brick, and look for O'Reilly book for instance, I think you get something like 8.0 which as fairly dated. > > A fading star? > >A niche player... So how do you judge the vitality of the Tcl community today? Compared to Python? I seems python's growth is beginning to flatten out. But I think there is a chance that it will make another surge. For Tcl it seems to be downhill to me, like Delphi and soon Visual Basic. Not quite like Fortran, COBOL and good old ADA, but it'll come... In the middle of the 90's Tcl/Tk got a lot of attention--it was a cool way to build Unix GUIs, and Sun obviously showed a lot of interest. Now, I don't hear a lot about it. I just notice that it's alive from the fact that new Python versions use newer Tcl versions for Tkinter. Today, the mainstream is all involved in Java, C++ and C#. The volume in free development tools is in Perl and PHP, with Python and Ruby as the slightly cooler and smarter options, and the little Lisp community is just like the good old HP calculator freaks in school. They will never die... >Tcl does have native compilation (and >Java byte code support) in its favour too (as does Python >via Jython and py2exe etc). Is this real native compilation to machine code, or is it py2exe style cheating? >Which is the Tcl idiom. In that regard its a bit like Lisp >which also encourages a fine grained functional approach. Do you think this is good? >In its niche (an embedded extensible macro language) it is >still the best tool around IMHO. Right, this is actually another niche than the glue and Tk GUIs I mentioned. Assuming we are in a normal computer, with a resonable amount of money, what is the main advantage with Tcl compared to Python? Python swims in this water too, you know... ;) There is a list of top ten reasons to use Tcl at http://www.tcl.tk/advocacy/top10.html It has headlines as listed below. It's curious that Python and Tcl seem so similar when you look at those headlines, and are still very different languages, with a big difference in scope in my opinion. 1. Rapid development All they say here could as well have been said about Python. See http://www.ipd.uka.de/~prechelt/Biblio/jccpprt_computer2000.pdf for an objective comparision. In that study, Python and Tcl programs were more or less equally fast to develop, with just a slight advantage for Python, but the Tcl programs used much more memory and ran slower. 2. Graphical user interfaces With Tcl, you only have Tk and it's extensions. It seems Tix might be getting somewhere, but it still seems to me that wxPython has much more features than Tk + Tix and others. 3. Cross-platform applications I think there is a draw here. 4. Extensible applications This is what Alan mentions above. Python can obviously do this as well. I can't judge the respective merits of either approach. In all honesty I never even did this with Python. 5. Flexible integration Python works as glue, just as Tcl does. There are even Python programs that work more or less like expect. I don't think they work under Windows though, but does expect? 6. Ready for the enterprise Here they claim that Tcl is the only scripting language with "all the facilities needed for enterprise applications, which include internationalization, thread safety, cross-platform portability, great GUI capabilities, embeddability, Internet support, and database access." Funny... What is it that python doesn't have here? Python is no speed daemon, but Tcl is worse. Does Tcl have application development frameworks like Zope or Twisted? Are there business libraries/toolkits etc like 4Suite, ReportLab etc in Tcl/Tk? 7. Testing I've certainly used Python a lot for this. It works very well here in my opinion. 8. Easy to learn Hm... I've heard that about Python. 9. Network-aware applications "No platform has easier to use networking facilities than Tcl." So, why are Zope and Twisted written in Python? Where are the big Tcl network killer applications hiding? 10. The Tcl community I can't compare the helpfulness or professionalism of these two communities, but I know about the Python one... If we look at the free software community, Freshmeat lists almost 900 Python projects and a little over 300 Tcl projects. At sourceforge there are 600 Tcl projects and 2100 Python projects. So, despite an longer time, a period of fame in big business and a much earlier inroad into the business world, it seems Python is much bigger today. 11 BONUS: It's free! Very unique! ;) -- 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 tim@johnsons-web.com Tue Jan 28 20:49:02 2003 From: tim@johnsons-web.com (Tim Johnson) Date: Tue Jan 28 20:49:02 2003 Subject: [Tutor] Python and Tcl/Tk/more In-Reply-To: <5.1.0.14.0.20030128200648.0298bce0@www.thinkware.se> References: <7497DCA1C240C042B28F6657ADFD8E09702383@i2km11-ukbr.domain1.systemhost.net> <5.1.0.14.0.20030128200648.0298bce0@www.thinkware.se> Message-ID: <20030129015258.GZ16215@johnsons-web.com> Hello (My two cents worth): I moved from a primarily C/C++ development platform 3 years ago in the direction of primarily rebol and secondarily python. Rebol is hugely productive and in terms of 'raw' productivity, I truly believe that it runs rings around python. Like TCL, it has a small footprint and control structures are themselves functions, rather than immutable part of the language syntax. What's more, is likely that rebol has many more features than TCL (from what I gather from this thread). So why may you ask am I starting to implement python modules into my 'mostly-rebol' projects? The answer is for one thing, I think that python will scale better, and is more 'disciplined' IMHO. Also python interacts well with many non-proprietory resources, while rebol is more proprietory (comparing compression resources and graphic interfaces, as an example) My partner programs in perl. Although there are little similarities in syntax, perl and rebol are 'looser' (my terms) and with each "there are many ways to do one thing". The corrolary of this is that, where it seems to take me longer to write python code, it is more likely to do just what I want it to do. So as my works grows, it is likely that python will play a larger and larger role. It is possible that I will be writing rebol programs that write out python code as input. I think that one sells onself short if one focuses on one and only one programming language. Besides there are many times that a single project that I work on has many processes and communication between those processes is being done in a 'cross-platform' and 'cross-language' medium. It is thus, less critical that I must use only one language source. And programming languages have a way of informing one other, it enriches my life to be acquainted with a larger number of them. Regards. * Magnus Lycka [030128 14:10]: > At 16:00 2003-01-28 +0000, alan.gauld@bt.com wrote: > >Oooh, I have to jump to Tcl's defence here :-) > > Good! I rarely meet Tclers these days. > > >> Tcl is only intended for small tasks and to glue larger > >> programs (written in C or whatever) together. > > > >Not entirely true, the latest versions of Tcl can scale to > >quite large projects now it has OO and module support. > >But I do still favour Python for that role. > > If you say so... but it was John Osterhout who wrote that: > > "I think that Stallman's objections to Tcl may stem largely > from one aspect of Tcl's design that he either doesn't > understand or doesn't agree with. This is the proposition > that you should use *two* languages for a large software > system: one, such as C or C++, for manipulating the complex > internal data structures where performance is key, and another, > such as Tcl, for writing small-ish scripts that tie together > the C pieces and are used for extensions." > > He wrote that in 1994 though. Maybe he changed his mind > later? Or was his statement then just his feeble defence > for Tcl shortcomings until he had repaired them? > > A brief review of Tcl scalabilty and related problems would > be interesting. > > >> It needs to live in symbiosis with another language, where > >> the "real" programs are written. > > > >Not at all true. there are many standalone Tcl scripts > >around, most famously expect. > > I'd say that expect is a perfect example of what I meant. > Expect is used to provide access to other programs. It's > as glue as it gets! Sorry if I was unclear. > > >> You can do everything Tcl can in Python > > > >This isn't true. In Tcl irts easy to redefine the bahaviour > >of the language at a level Python can't approach - redefine > >how the if statement works, or a while loop etc. Whether > >doing such things is wise is another matter entirely! > > > >Self modifying code is also easier to write in TCL - and > >the same caveat applies! > > I was unclear again. Sorry. What I meant to say was that if > there is a problem where tcl can provide a solution, python > can be used to provide a solution as well. I didn't mean that > you would do it in an equally weird way. ;) > > I'll make a reservation for embedded use where space is > an important factor. Python might be too big for some > applications. > > This ability to redefine the way the language works is a > mixed blessing to put it mildly. > > >> really tried, but it seems to me that using Tcl to interface > >> to programs where you need to access and communicate with > >> complex data structures would be a little like trying to build > >> model airplanes with thick wool mittens... > > > >Not sure why you think that. Tcl can handle complex structures > >pretty well. Certainly C unions and structs are handled OK. > >And classes map to Tcl classes. > > It seems Tcl has evolved a bit since I last looked at it. I > thought OO features like classes only existed in extensions > like [incr Tcl]. As far as I understand these extensions might > cause compatibility problems with other Tcl/Tk libraries since > they change the language, introducing scopes. I have this vague > memory of horror stories from people who tried to use [incr Tk] > widgets in applications that previously were "classic" Tcl/Tk > apps. > > But I guess it's difficult to make *any* firm statement about > features in a language where you can change how the basic > building blocks behave in runtime. > > >> On the other hand, I think Tcl is smaller, which might be > >> a good thing on a palmtop or in an embedded appliance etc. > > > >Much smaller. > > The ActiveTcl package at ActiveState isn't so terribly small > though. But I assume that includes a lot that you can strip out. > Although that is true about Python as well. > > So, how small does it get? Can it run in a PDA? With classes > and stuff? Or are we back to stripped and/or old versions? > > >Too true, finding good Tcl books is not hard but there are few > >of them and the language is tending to outpace the authors. > >(But the same is true of Python book currency) > > You don't need to develop the language a lot to outpace the > book authors if the newest books are four years old. Roughly > 30 books about Python have been published after 1999. Regarding > Python, version 2.3 doesn't change as much as the previous > releases did, so it might be time for the authors to catch up > now... > > But there ARE Python books that are fairly current, covering > version 2.2. The 3rd edition of the Welch book covers 8.2 > though... Not too bad I guess, but if you don't want t brick, > and look for O'Reilly book for instance, I think you get > something like 8.0 which as fairly dated. > > >> A fading star? > > > >A niche player... > > So how do you judge the vitality of the Tcl community today? > Compared to Python? I seems python's growth is beginning to > flatten out. But I think there is a chance that it will make > another surge. > > For Tcl it seems to be downhill to me, like Delphi and soon > Visual Basic. Not quite like Fortran, COBOL and good old ADA, > but it'll come... > > In the middle of the 90's Tcl/Tk got a lot of attention--it > was a cool way to build Unix GUIs, and Sun obviously showed > a lot of interest. Now, I don't hear a lot about it. I just > notice that it's alive from the fact that new Python versions > use newer Tcl versions for Tkinter. > > Today, the mainstream is all involved in Java, C++ and C#. > The volume in free development tools is in Perl and PHP, with > Python and Ruby as the slightly cooler and smarter options, > and the little Lisp community is just like the good old HP > calculator freaks in school. They will never die... > > >Tcl does have native compilation (and > >Java byte code support) in its favour too (as does Python > >via Jython and py2exe etc). > > Is this real native compilation to machine code, or is it > py2exe style cheating? > > >Which is the Tcl idiom. In that regard its a bit like Lisp > >which also encourages a fine grained functional approach. > > Do you think this is good? > > >In its niche (an embedded extensible macro language) it is > >still the best tool around IMHO. > > Right, this is actually another niche than the glue and > Tk GUIs I mentioned. > > Assuming we are in a normal computer, with a resonable amount > of money, what is the main advantage with Tcl compared to > Python? Python swims in this water too, you know... ;) > > There is a list of top ten reasons to use Tcl at > http://www.tcl.tk/advocacy/top10.html > > It has headlines as listed below. It's curious that Python and > Tcl seem so similar when you look at those headlines, and are > still very different languages, with a big difference in scope > in my opinion. > > 1. Rapid development > > All they say here could as well have been said about Python. See > http://www.ipd.uka.de/~prechelt/Biblio/jccpprt_computer2000.pdf > for an objective comparision. In that study, Python and Tcl > programs were more or less equally fast to develop, with just > a slight advantage for Python, but the Tcl programs used much > more memory and ran slower. > > 2. Graphical user interfaces > > With Tcl, you only have Tk and it's extensions. It seems Tix > might be getting somewhere, but it still seems to me that > wxPython has much more features than Tk + Tix and others. > > 3. Cross-platform applications > > I think there is a draw here. > > 4. Extensible applications > > This is what Alan mentions above. Python can obviously do > this as well. I can't judge the respective merits of either > approach. In all honesty I never even did this with Python. > > 5. Flexible integration > > Python works as glue, just as Tcl does. There are even Python > programs that work more or less like expect. I don't think > they work under Windows though, but does expect? > > 6. Ready for the enterprise > > Here they claim that Tcl is the only scripting language with > "all the facilities needed for enterprise applications, which > include internationalization, thread safety, cross-platform > portability, great GUI capabilities, embeddability, Internet > support, and database access." Funny... > > What is it that python doesn't have here? > > Python is no speed daemon, but Tcl is worse. Does Tcl have > application development frameworks like Zope or Twisted? > > Are there business libraries/toolkits etc like 4Suite, > ReportLab etc in Tcl/Tk? > > 7. Testing > > I've certainly used Python a lot for this. It works very > well here in my opinion. > > 8. Easy to learn > > Hm... I've heard that about Python. > > 9. Network-aware applications > > "No platform has easier to use networking facilities than > Tcl." So, why are Zope and Twisted written in Python? > Where are the big Tcl network killer applications hiding? > > 10. The Tcl community > > I can't compare the helpfulness or professionalism of > these two communities, but I know about the Python one... > > If we look at the free software community, Freshmeat > lists almost 900 Python projects and a little over 300 > Tcl projects. At sourceforge there are 600 Tcl projects > and 2100 Python projects. So, despite an longer time, > a period of fame in big business and a much earlier > inroad into the business world, it seems Python is much > bigger today. > > 11 BONUS: It's free! > > Very unique! ;) > > > -- > 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 > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Tim Johnson http://www.alaska-internet-solutions.com http://www.johnsons-web.com From BranimirP@cpas.com Tue Jan 28 23:17:01 2003 From: BranimirP@cpas.com (Branimir Petrovic) Date: Tue Jan 28 23:17:01 2003 Subject: [Tutor] Zip-ing files/folders - collecting opinions Message-ID: <33678E78A2DD4D418396703A750048D41A6406@RIKER> Hi All, I am trying to put together somethin' littl' in Python that would do archiving of potentially large files and/or large folder structures on Windows platform. WinZip and its command line add-on (wzzip.exe) works fine up to 4 GB size limit, therefore can't do what I'd like it to do... My archiving script must be able to compress large 10 GB+ Oracle dump files (among other things). Other option I considered, and is still in 'game', is gzip.exe - GNU's port for Win32. It works like a charm on large files and it can be 'driven' via popen. But... But gzip compresses files one by one in place, leaving behind N *.gz files if folder had N files for compressing. Moreover gzip leaves directories intact - it does not 'know' how to put everything (folders AND files) in one big archive file (like wzzip can). Oh, by the way - I've discovered (preferred - hard way) that GNU's tar port for Win32 breaks down upon reaching 2 GB boundary!? Therefore tar-ing everything together prior to gzip-ing on Windows platform does not work for my purpose either. Puthon's zipfile standard library seems to be fine - performance is close to gzip.exe's plus it can do additional trick - it can add multiple files in one archive which is a mixed blessing since gunzip.exe does not know how to deal with these (should someone unsuspectingly try to unzip it using gunzip.exe). But like gzip - Python's zipfile library seems not to be able do deal with folders. It can not compress whole folder structure in one large archive. My questions are: a) Am I missing something with zipfile library, may be it can compress/uncompress folder structure in one large zip file? b) Should I rather 'close the nose' and do it gzip.exe's way - M folders with up to N *.gz files in each after popen returns (and rest assured that gunzip can always recursively un-zip them)? c) Add all files found in each folder to archive and end up with just one large zip file in each folder (keeping the folder structure intact, and deleting source files), use WinZip for de-archiving (or Python in rare cases when individual archived file expands over 4 GB limit)? If I missed something obvious, or if you have better idea or approach, please let me know. Branimir From Simon.Wittber@perth.maptek.com.au Tue Jan 28 23:34:02 2003 From: Simon.Wittber@perth.maptek.com.au (Simon Wittber (Maptek)) Date: Tue Jan 28 23:34:02 2003 Subject: [Tutor] Zip-ing files/folders - collecting opinions Message-ID: <10F0E58C0018054484E329DC494C4D7F01BD58@mexper1> This is a multi-part message in MIME format. ------_=_NextPart_001_01C2C74F.61349F94 Content-Type: text/plain; charset="us-ascii" Content-Transfer-Encoding: quoted-printable >I am trying to put together somethin' littl' in Python=20 >that would do archiving of potentially large files and/ >or large folder structures on Windows platform.=20 I'm not sure my idea or approach is any better, but it is quite nifty! It's a small program which zips up a directory structure into an python program. You then run the generated python program to expand the tree. Have a look, you might get some more ideas. Sw. ------_=_NextPart_001_01C2C74F.61349F94 Content-Type: application/octet-stream; name="com.py" Content-Transfer-Encoding: base64 Content-Description: com.py Content-Disposition: attachment; filename="com.py" I0NvcHlyaWdodCAyMDAyIFNpbW9uIFdpdHRiZXINCiNzaW1vbndpdHRiZXJAaG90bWFpbC5jb20N Cg0KI1RoaXMgcHJvZ3JhbSBpcyBmcmVlIHNvZnR3YXJlOyB5b3UgY2FuIHJlZGlzdHJpYnV0ZSBp dCBhbmQvb3IgbW9kaWZ5DQojaXQgdW5kZXIgdGhlIHRlcm1zIG9mIHRoZSBHTlUgR2VuZXJhbCBQ dWJsaWMgTGljZW5zZSBhcyBwdWJsaXNoZWQgYnkNCiN0aGUgRnJlZSBTb2Z0d2FyZSBGb3VuZGF0 aW9uOyBlaXRoZXIgdmVyc2lvbiAyIG9mIHRoZSBMaWNlbnNlLCBvcg0KIyhhdCB5b3VyIG9wdGlv bikgYW55IGxhdGVyIHZlcnNpb24uDQoNCiNUaGlzIHByb2dyYW0gaXMgZGlzdHJpYnV0ZWQgaW4g dGhlIGhvcGUgdGhhdCBpdCB3aWxsIGJlIHVzZWZ1bCwNCiNidXQgV0lUSE9VVCBBTlkgV0FSUkFO VFk7IHdpdGhvdXQgZXZlbiB0aGUgaW1wbGllZCB3YXJyYW50eSBvZg0KI01FUkNIQU5UQUJJTElU WSBvciBGSVRORVNTIEZPUiBBIFBBUlRJQ1VMQVIgUFVSUE9TRS4gIFNlZSB0aGUNCiNHTlUgR2Vu ZXJhbCBQdWJsaWMgTGljZW5zZSBmb3IgbW9yZSBkZXRhaWxzLg0KDQojWW91IHNob3VsZCBoYXZl IHJlY2VpdmVkIGEgY29weSBvZiB0aGUgR05VIEdlbmVyYWwgUHVibGljIExpY2Vuc2UNCiNhbG9u ZyB3aXRoIHRoaXMgcHJvZ3JhbTsgaWYgbm90LCB3cml0ZSB0byB0aGUgRnJlZSBTb2Z0d2FyZQ0K I0ZvdW5kYXRpb24sIEluYy4sIDU5IFRlbXBsZSBQbGFjZSwgU3VpdGUgMzMwLCBCb3N0b24sIE1B ICAwMjExMS0xMzA3ICBVU0ENCg0KaW1wb3J0IGJhc2U2NA0KaW1wb3J0IHpsaWINCmltcG9ydCBv cw0KaW1wb3J0IG9zLnBhdGgNCmltcG9ydCBzeXMNCg0KaWYgbGVuKHN5cy5hcmd2KSAhPSAyOg0K CXByaW50ICJDb21wcmVzc2VzIGEgZGlyZWN0b3J5IHN0cnVjdHVyZSBpbnRvIGEgcHl0aG9uIHBy b2dyYW0uXG5cblVzYWdlOiAiICsgc3lzLmFyZ3ZbMF0gKyAiIDxkaXJlY3Rvcnk+Ig0KCXN5cy5l eGl0KDApDQppZiBub3Qgb3MucGF0aC5pc2Rpcihvcy5wYXRoLmFic3BhdGgoc3lzLmFyZ3ZbMV0p KToNCglwcmludCBzeXMuYXJndlsxXSArICIgaXMgbm90IGEgZGlyZWN0b3J5LiINCglzeXMuZXhp dCgwKQ0KDQpjb2RlID0gIiIiDQppbXBvcnQgYmFzZTY0DQppbXBvcnQgemxpYg0KaW1wb3J0IG9z DQppbXBvcnQgb3MucGF0aA0KaW1wb3J0IHN5cw0KIiIiDQoNCmZvbGRlciA9IHN5cy5hcmd2WzFd DQoNCm91dGZpbGVuYW1lID0gZm9sZGVyICsgIi5jb21wcmVzc2VkLnB5Ig0Kb3V0ZmlsZSA9IGZp bGUoInRlbXAuIiArIG91dGZpbGVuYW1lLCAidyIpDQoNCm91dGZpbGUud3JpdGUoY29kZSkNCg0K Zm9sZGVycyA9IHt9DQoNCmRlZiB3YWxrZXIoYXJnLCBkaXJuYW1lLCBuYW1lcyk6DQoJZ2xvYmFs IGZvbGRlcnMNCglmb2xkZXJzW2Rpcm5hbWVdID0gbmFtZXMNCgkNCm9zLnBhdGgud2Fsayhmb2xk ZXIsIHdhbGtlciwgTm9uZSkNCg0KZm9sZGVybGlzdCA9IGZvbGRlcnMua2V5cygpDQpmb2xkZXJs aXN0LnNvcnQoKQ0KZm9yIGYgaW4gZm9sZGVybGlzdDoNCglwYXRoID0gb3MucGF0aC5qb2luKGYp DQoJcGF0aCA9IHBhdGgucmVwbGFjZSgiXFwiLCAiLyIpDQoJb3V0ZmlsZS53cml0ZSgicHJpbnQg XCIiICsgcGF0aCArICJcIlxuIikNCglvdXRmaWxlLndyaXRlKCJ0cnk6XG5cdG9zLm1rZGlyKFwi XCJcIiIgKyAgcGF0aCArICJcIlwiXCIpXG5leGNlcHQgT1NFcnJvcjpcblx0cHJpbnQgXCJhbHJl YWR5IGV4aXN0cy5cIlxuXHRzeXMuZXhpdCgxKVxuIikNCg0KZm9yIGYgaW4gZm9sZGVybGlzdDoN Cglmb3IgbiBpbiBmb2xkZXJzW2ZdOg0KCQljdXJyZW50RmlsZW5hbWUgPSBvcy5wYXRoLmpvaW4o ZiwgbikNCgkJaWYgb3MucGF0aC5pc2ZpbGUob3MucGF0aC5hYnNwYXRoKGN1cnJlbnRGaWxlbmFt ZSkpOg0KCQkJcHJpbnQgY3VycmVudEZpbGVuYW1lIA0KCQkJY3VycmVudEZpbGUgPSBmaWxlKG9z LnBhdGguYWJzcGF0aChjdXJyZW50RmlsZW5hbWUpLCAicmIiKQ0KCQkJZGF0YSA9IGN1cnJlbnRG aWxlLnJlYWQoKQ0KCQkJZGF0YSA9IHpsaWIuY29tcHJlc3MoZGF0YSwgOSkNCgkJCWRhdGEgPSBi YXNlNjQuZW5jb2Rlc3RyaW5nKGRhdGEpDQoJCQlwYXRoID0gb3MucGF0aC5qb2luKGN1cnJlbnRG aWxlbmFtZSkNCgkJCXBhdGggPSBwYXRoLnJlcGxhY2UoIlxcIiwgIi8iKQ0KCQkJb3V0ZmlsZS53 cml0ZSgicHJpbnQgXCIiICsgcGF0aCArICJcIlxuIikNCgkJCW91dGZpbGUud3JpdGUoImZpbGUo XCIiICsgcGF0aCArICJcIiwgXCJ3YlwiKS53cml0ZSh6bGliLmRlY29tcHJlc3MoYmFzZTY0LmRl Y29kZXN0cmluZyhcIlwiXCIiICsgZGF0YSAgKyAiXCJcIlwiKSkpXG4iKQ0KCQkJY3VycmVudEZp bGUuY2xvc2UoKQ0KDQpvdXRmaWxlLmNsb3NlKCkNCmluZmlsZSA9IGZpbGUoInRlbXAuIiArIG91 dGZpbGVuYW1lKQ0KZGF0YSA9IGluZmlsZS5yZWFkKCkNCmluZmlsZS5jbG9zZSgpDQpvcy51bmxp bmsoInRlbXAuIiArIG91dGZpbGVuYW1lKQ0KZGF0YSA9IGJhc2U2NC5lbmNvZGVzdHJpbmcoemxp Yi5jb21wcmVzcyhkYXRhLCA5KSkNCg0KY29kZWRmaWxlID0gZmlsZShvdXRmaWxlbmFtZSwgIndi IikNCmNvZGVkZmlsZS53cml0ZSgiIiJpbXBvcnQgYmFzZTY0DQppbXBvcnQgemxpYg0KIiIiKQ0K Y29kZWRmaWxlLndyaXRlKCJleGVjKHpsaWIuZGVjb21wcmVzcyhiYXNlNjQuZGVjb2Rlc3RyaW5n KFwiXCJcIiIgKyBkYXRhICsgIlwiXCJcIikpKVxuIikNCg0KDQoNCg0K ------_=_NextPart_001_01C2C74F.61349F94-- From j.ezequiel@spitech.com Wed Jan 29 02:57:02 2003 From: j.ezequiel@spitech.com (Justin Ezequiel) Date: Wed Jan 29 02:57:02 2003 Subject: [Tutor] string parsing Message-ID: <01C2C7AE.E98D8C80@pc7486> I guess this is not the right place for this question but I do not know where else to ask. You've all been very helpful. Can anyone point me to a more appropriate forum? I need ideas on how to (begin to) programmatically identify elements of a bibliographic reference. By elements, I mean authors/editors, their names (givenname, surname, suffix), article/chapter titles, book/journal titles, date of publication, volume number, start and end page numbers, publisher name and publisher location, etc. Has anyone done something similar? Do you know others who have? Can you point me to discussions on the web on the subject if there are? examples of bibliographic entries we get: (I modified the names and some of the titles) Ezequiel III JG, Garcia EA. Identifying elements of a bibliographic reference. J Nerv Ment Dis. 1990;178:123-40. Justin G. Ezequiel and Edna A. Garcia, Pattern Matching, 2nd ed., John Wiley & Sons, 1982. J. Ezequiel III, et al., Mater. Sci. Eng. A 328-329 (1997) 157. J.G. Ezequiel and E.A. Garcia. Modelling and Enactment of Whatever. In J. Garcia Ezequiel, editor, Application and Theory of Whatever 2001, volume 123 of Lecture Notes in Whatever, pages 11-15. Springer-Verlag, Berlin, 1993. From alan.gauld@bt.com Wed Jan 29 06:09:01 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed Jan 29 06:09:01 2003 Subject: [Tutor] Python and Tcl/Tk Message-ID: <7497DCA1C240C042B28F6657ADFD8E0974DAA4@i2km11-ukbr.domain1.systemhost.net> > If you say so... but it was John Osterhout who wrote that: > > that you should use *two* languages for a large software I think that is still Ousterhouts view but there are plenty of Tcl'ers who are going the dedicated Tcl route. > later? Or was his statement then just his feeble defence > for Tcl shortcomings until he had repaired them? Ousterhout is not the sole owner of Tcl to the extent that Guido is for Python. He owns the core language but because that can be changed in Tcl its easy for add on facilities to be crafted in by "entyhusiastic amateurs"... BLT would be a good example. > I'd say that expect is a perfect example of what I meant. > Expect is used to provide access to other programs. It's > as glue as it gets! Sorry if I was unclear. OK, but expect is a tool for robotically driving other programs not interacting at the code level which is what I thought you meant. Sun also have a bnch of networking/server admin tools written in pure Tcl, but many of them drive other tools under the hood so in the real worlds I might concede this one :-) > > > You can do everything Tcl can in Python > I was unclear again. Sorry. What I meant to say was that if > there is a problem where tcl can provide a solution, python > can be used to provide a solution as well. In the sense that any Turing complete language can do so, yes. In that respect anything that Python can do can be done in vim macro language too - and I don't mean with Python built in as the macro language (have we ever mentioned that feature of vim before?) > >Not sure why you think that. Tcl can handle complex structures > >pretty well. Certainly C unions and structs are handled OK. > >And classes map to Tcl classes. > > It seems Tcl has evolved a bit since I last looked at it. In the last 3 or 4 years Tcl has leapt forward. I think it was the move to 8.x which was even more radical than Pythons jump to 2.x. > thought OO features like classes only existed in extensions > like [incr Tcl]. There are two main Tcl OOP extensions, and yes that is how they are implemented. The code looks very much like a C++ class definition but is, of course, just a single line of Tcl... > cause compatibility problems with other Tcl/Tk libraries since > they change the language, introducing scopes. I didn't say there were no issues! Just that the mechanisms are there and lots of experience to help use them. > memory of horror stories from people who tried to use [incr Tk] > widgets in applications that previously were "classic" Tcl/Tk > apps. I wouldn't use [incr Tk] personally, Tk already is in what Ousterhout calls an OO style and trying to wrap one OO paradigm inside another, different one, spounds like a really bad idea to me. But [incr Tcl] (which, for non Tcl'ers, is a Tcl joke on C++ since it means the same syntactically) I've used [incr Tcl] without problems. > >Much smaller. > > The ActiveTcl package at ActiveState isn't so terribly small Yeah but has oodles of tools/extensions. Raw Tcl is only a few hundred kilobytes if all you want to do is embed it - see the tcl80.dll file that ships with python. > Although that is true about Python as well. Yes but its still bigger at the minimal level. > So, how small does it get? Can it run in a PDA? Easily, but then so can Python, see the Palm version... > Or are we back to stripped and/or old versions? Not old versions but obviously the more extensions you add the bigger it gets. > So how do you judge the vitality of the Tcl community today? > Compared to Python? Like I say its a niche. Those who have settled for Tcl are actively using and developing it. Take a look at the traffic on c.l.tcl But I suspect Python is more active and probably has more users nowadays. > For Tcl it seems to be downhill to me, like Delphi and soon > Visual Basic. Delphi is actually growing again due to Kylix. But that will be short term I fear. VB, I suspect, is here for the long haul - unless Bill G leaves Microsoft! > a lot of interest. Now, I don't hear a lot about it. Yes, it has settled into its niche. It has about 4 years advantage over Python so maybe in 4 years time Python will stabilize in a similar fashion. It also was radical in its day as being the first language designed fron the ground up to be embedded as glue inside another language application. I suspect the history books will recognise Tcl mainly for its innovation factor than for any long term staying power. > Today, the mainstream is all involved in Java, C++ and C#. And COBOL - still more programmers using COBOL than any other language... > Python and Ruby as the slightly cooler and smarter options, There are certainly far more active Tcl'ers than active Rubyists. > and the little Lisp community is just like the good old HP > calculator freaks in school. They will never die... Indeed, and Smalltalk, and aybe someday Tcl... > >Tcl does have native compilation (and > Is this real native compilation to machine code, or is it > py2exe style cheating? I don't know, I suspect the latter. I don't see how you could genuinly compile Tcl to machine code without an amazingly intelligent optimiser. But the key thing it does is convert types from strings etc and does seem to give much more of a speed up than py2exe achieves. I think its a combination of Pythons bytecode compiler and py2exe - but thats guesswork based on observed results not any inside knowlredge. > >Which is the Tcl idiom. In that regard its a bit like Lisp > >which also encourages a fine grained functional approach. > > Do you think this is good? I don't think its bad, its just another way of working. Forth did exactly the same. In fact, thinking about it, I'd say Tcl is like a modern version of Forth. Probably the best description I can come up with. > > of money, what is the main advantage with Tcl compared to > Python? Python swims in this water too, you know... ;) Tcl is, in my experience, easier than Python to embed. But not that much easier. Its comparative and subjective. If you have already done it with Python and not woith Tcl then you might get the opposite result! > There is a list of top ten reasons to use Tcl at > http://www.tcl.tk/advocacy/top10.html Yes, an old list and hardly objective :-) The Ruby gang have a similar list on their web site... > programs that work more or less like expect. I don't think > they work under Windows though, but does expect? expect does work in Win32 yes. > Python is no speed daemon, but Tcl is worse. This is true, Tcl is slow. > Does Tcl have application development frameworks like Zope or Twisted? I wouldn't be surprised but thats not how I use Tcl so I haven't looked. > Are there business libraries/toolkits etc like 4Suite, > ReportLab etc in Tcl/Tk? There are certainly numerical processing libraries like PyNum etc. Dunno about the others mentioned. > 8. Easy to learn > > Hm... I've heard that about Python. Python is *much* easier to learn than Tcl. Tcl has some really obscure rules about what gets executed when. Thesecare necessary because of its single line/command philosophy but it forces beginners(and experts!) to think like the interpreter. This is not a good learning environment - unless you are learning about language interpreters! In summary, Tcl is good for a small set of problems. For an even smaller subset it may even be better than Python. But I see no compelling reason for anyone to learn Tcl other than that it offers an interesting alternative style of programming. The same is true of Lisp or Smalltalk. Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From alan.gauld@bt.com Wed Jan 29 06:19:01 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed Jan 29 06:19:01 2003 Subject: [Tutor] Python and Tcl/Tk/more Message-ID: <7497DCA1C240C042B28F6657ADFD8E0970238C@i2km11-ukbr.domain1.systemhost.net> > I think that one sells onself short if one focuses > on one and only one programming language. I totally agree (and I suspect Magnus does too!). I have never worked on a paying project that was implemented in only one language. Most have at least 3, and one had 12 different programming languages being used across a team of >150 developers located in 6 cities in 3 countries... Alan G. From magnus@thinkware.se Wed Jan 29 06:54:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Wed Jan 29 06:54:02 2003 Subject: [Tutor] string parsing In-Reply-To: <01C2C7AE.E98D8C80@pc7486> Message-ID: <5.1.0.14.0.20030129105954.02bd2e80@www.thinkware.se> At 15:55 2003-01-29 +0800, Justin Ezequiel wrote: >I need ideas on how to (begin to) programmatically identify >elements of a bibliographic reference. If you get them on the free form given below, I don't honestly think it's possible to identify these elements programmatically in a reliable way. I think you *might* end up as a case for J Nerv Ment Dis. if you try! ;) But what do you mean by "(begin to)". Did you have something semi-manual in mind? It's obviously possible to make guesses. You can recognize years for instance. As you parse (more or less manually) you will build up a knowledge of names for publishers, journals and authors. These could be used to guess what elements certain character sequences belong to. I've had a similar "machine-learning" idea for translation. I could probably patent what's coming now, but I place it in the public domain. Software patents are evil. Really! I see some kind of GUI application where different elements are marked with different background colours etc. Green for author, yellow for title, blue for publisher or whatever. From start, the application is pretty clueless. You manually mark the relevant parts of the bibliography by for instance typing a key (a for author, t for title etc) and cliking on the relevant part, which will then be coloured accordingly. As you work, the program will remember things like: Garcia is a name, 1997 is a year, Pattern Matching is a title. The next time you see an entry with Garcia, it will be marked green. If this happens to be a book about Garcia, you will have to press t and click on Garcia to correct this. Obviously you can preload the program with some knowledge, like 1000 to 2100 being years, Smith, Jones and van Rossum being names, Springer Verlag being a publisher etc. When the computer program is trying to match stuff, it will begin with the longest sequences it can remember, and then try with shorter. If it finds the same word in several categories in the database, it will suggest the category where it occurs more often. This would certainly be faster than to type everything in from scratch, or to cut and paste from a text to some kind of database form. I can well imagine that you will have a dual view though. On the left, you have your free format entry, and on the right, you have a form, like in a database application, with labels and text entry fields that are updated as you click in the free form. You could also edit the form directly, but that would put the free text and the form out of sych I guess... >examples of bibliographic entries we get: >(I modified the names and some of the titles) > >Ezequiel III JG, Garcia EA. Identifying elements of a >bibliographic reference. J Nerv Ment Dis. 1990;178:123-40. > >Justin G. Ezequiel and Edna A. Garcia, Pattern Matching, 2nd >ed., John Wiley & Sons, 1982. > >J. Ezequiel III, et al., Mater. Sci. Eng. A 328-329 (1997) >157. > >J.G. Ezequiel and E.A. Garcia. Modelling and Enactment of >Whatever. In J. Garcia Ezequiel, editor, Application and >Theory of Whatever 2001, volume 123 of Lecture Notes in >Whatever, pages 11-15. Springer-Verlag, Berlin, 1993. A better option might be to take those who give you these lists into an elevator, stop it between floors, and ask them in a very soft and sweet voice if they could consider using a bibliographic tool such as BibTex or EndNote instead of giving you that "free" format. Don't forget to bring a baseball bat. The laws of Thermodynamics have to be considered after all. I'm sure the authors of that text has a low enthropy view of this to start with. They have well structured information, and know very well that Springer Verlag is a publisher of scientific journals, Berlin is a location (where Springer is in this case) etc. They raise the enthropy by removing this informations. Why? Why don't they reorder the letters in the words as well? Verler Springag isn't much worse than what they did! OK, there is a plan B as well. I'm not sure the citations are as bad as you seem to claim. Where do you get these from? I assume it's from scientific publications. They don't all have a common format, but each Journal is usually consistent in the format that is used for their citations. Of course, if you scan paper to plain text, you might raise the enthropy even more by removing cues like whether texts is bold etc. Still, by knowing the bibliographic entry format for a certain publication, you will know in what order fields will occur. The problem is that you don't know where one field ends and the next begins, or which fields are applicable for this very entry... If you had just had some kind of field separators... -- 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@thinkware.se Wed Jan 29 09:15:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Wed Jan 29 09:15:02 2003 Subject: [Tutor] Python and Tcl/Tk/more In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E0970238C@i2km11-ukbr.domain1 .systemhost.net> Message-ID: <5.1.0.14.0.20030129130532.02bad9a8@www.thinkware.se> At 11:17 2003-01-29 +0000, alan.gauld@bt.com wrote: > > I think that one sells onself short if one focuses > > on one and only one programming language. > >I totally agree (and I suspect Magnus does too!). Sure! But I have to admit that I have done very little in other languages that Python the last two years, and when I have to, I typically get disappointed about the other tools. For instance I had to do some Perl. Great I though, I did Perl before I found Python, but it used to be fun. It's not such a different bird compared to Python, just more arcane syntax etc... Unfortunately I wasn't wearing the Camel book, and after five years of absence, I didn't have a clue about how to dereference values in a list of lists. :( None of the Perl "hackers" at that location had ever done such "magic" either. They just stared at me. For those who haven't done Perl, I just wanted to do something like: l = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] for m in l: for n in m: print n This involves some special incantations called dereferencing in Perl. The "Camel Book" by Larry Wall spends three pages explaining the common mistakes in such an advanced feat. Seriously! These pages are full of this-that-seems-correct- won't-work-but-that-dangerous-looking-code-works-and-is- more-efficient... There is no way you can guess how to do this right based on simple Perl experience where you have used lists, but never nested them inside each other. I'm not joking! Some time ago, I help a physician with an Excel application. Some VBA ought to be trivial. After all, the big "secret" is that you use the macro recording feature of Excel to produce most of the code for you, and then you just modify what you need, and tie things together, calling functions from buttons etc. The problem is that a lot of code ran once, and then choked on the second attempt! In some cases this was probably because of contexts issues. A piece of code might work in Excel 2000 every time, but in Excel 97 it will only work if a certain worksheet in the workbook is active, even though the worksheet is explicitly addressed in the code, and the docs make no mention of activating the sheet, and even though it worked regardless of what sheet was active, when you replay the recorded macro (that was just moved to another function). There are also glaring differences between the docs and how things works in real life. The docs consitently use Worksheets("Sheet 1"), but if you type that, Excel doesn't know what you are after, you have to type Sheets("Sheet 1"). Also, in the middle of typing, if you leave the line unfinshed to copy some text from another line, you will get a captive dialog that tells you that your code is in error. Doh! For some problems, the error message alternated between two completely different and both unhelpful messages on every other run. Sometimes, VBA complained that it couldn't find the methods I wanted in range objects. Have you heard about classes suddenly dropping methods in other languages? Maybe it actually failed to find the right object, but it said things like "The Range object doesn't have a Sort attribute". When I run into these things I feel so happy about Python. I certanly don't hesitate to use C, C++ or SQL where it's useful, and some Java at times. I don't worry about editing shell scripts, but if I have to write new script I will write them in Python almost all the time. PHP has really boomed, and become much bigger than Python, but I must admit, that if I find an interesting applications that is implemented in PHP (or Perl) I will take another look to see if there is something good enough implemented in Python. I might do some more MS Office / VBA work, but it's not a preference. I had a look at Ruby, but left it alone. I'm thinking about trying to learn OCaml, partly because I use an application called GeneWeb written in that language. Hm... I guess I'll have a look at Rebol. I've been put off by the fact that it's proprietary, but taking a peek can't hurt, can it? >I have never worked on a paying project that was implemented >in only one language. Most have at least 3, Really? Well, if you do relational databases you will at least have SQL and one more I guess. C++, Java and SQL is a fairly common trio I guess. And if you integrate with an old system, some COBOL is likely to be involved as well I guess... >and one >had 12 different programming languages being used >across a team of >150 developers located in 6 cities >in 3 countries... How convenient... ;) -- 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 Deirdre Hackett" This is a multi-part message in MIME format. ------=_NextPart_000_00CE_01C2C7B1.C22D9060 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable I want to use pickle module import pickle =20 f =3D open('/Python22/testing3.txt', 'w') data =3D [23,34,34] pickle.dump(data,f) I want to write data to the file testing3.txt. =20 I tried f.write(data) but you are only allowed to write strings to the = file and it said in the documentation that pickle was the way to do it. Not sure where to go here. Thanks=20 Dee ------=_NextPart_000_00CE_01C2C7B1.C22D9060 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
I want to use pickle = module
 
import=20 pickle
   =20
f =3D = open('/Python22/testing3.txt',=20 'w')
 
data =3D=20 [23,34,34]
 
pickle.dump(data,f)
 
I want to write data = to=20 the file testing3.txt.
 
I tried = f.write(data) but=20 you are only allowed to write strings to the file and it said in the=20 documentation that pickle was the way to do it.
 
Not sure where to go here.
 
Thanks
Dee
------=_NextPart_000_00CE_01C2C7B1.C22D9060-- From BranimirP@cpas.com Wed Jan 29 11:19:03 2003 From: BranimirP@cpas.com (Branimir Petrovic) Date: Wed Jan 29 11:19:03 2003 Subject: [Tutor] Zip-ing files/folders - collecting opinions Message-ID: <33678E78A2DD4D418396703A750048D41A6408@RIKER> > -----Original Message----- > From: Simon Wittber (Maptek) > > I'm not sure my idea or approach is any better, but it is quite nifty! > Clever and cute little program indeed, thanks for sharing it! > It's a small program which zips up a directory structure into > an python program. You then run the generated python program to expand the tree. > > Have a look, you might get some more ideas. > > Sw. > Having a good look at your script I can now see possible use for zlib. Bare bone documentation coming with zlib is not overly helpful in figuring out how's (and why's) of putting it to good use (but this can be said with equal accuracy for most of documentation coming with std. lib. modules)... It also helped me stop fighting/resisting the idea of having many individually zipped files inside preserved folder structure. Python's zipfile module does this quite well, and with a small effort I can replicate folder structure on different location as a part of archiving process. In cases when in-place archiving is desirable - GNU's gzip 'driven' via Python script would be the way to go. Optionally, if resulting archive is smaller than 4 GB, WinZip's command line utility wzzip.exe can be used to coalesce everything into one large archive file, and that's it. Thanks for help. Branimir From Janssen@rz.uni-frankfurt.de Wed Jan 29 11:53:02 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Wed Jan 29 11:53:02 2003 Subject: [Tutor] Pickle Module In-Reply-To: <00d101c2c7b1$d507eb40$0400a8c0@egbert> Message-ID: On Wed, 29 Jan 2003, Deirdre Hackett wrote: > pickle.dump(data,f) > > I want to write data to the file testing3.txt. you have done it already. Perhaps you need to close the file again in order to write cached data to disk (f.close()) or do this directly via f.flush() To read the data, you need another file-object in read-mode: f = open("testing3.txt","r") data = pickle.load(f) Michael From bigal@geosci.uchicago.edu Wed Jan 29 12:19:25 2003 From: bigal@geosci.uchicago.edu (Alistair McGowan) Date: Wed Jan 29 12:19:25 2003 Subject: [Tutor] Control flow Message-ID: --============_-1168261878==_ma============ Content-Type: text/plain; charset="us-ascii" ; format="flowed" Dear All, I am trying to modify a resampling program so that I can resample without replacement. I am an old BASIC hand, so what I want to do is at the point where tally is assessed to see if that draw has already been made. If tally>0 I want to go back to the line n = random.randint(0,10) # calls random interger to get sample and try to draw a sample that I haven't picked before. This would be done with a goto in ye olden days, but I am not having much joy figuring out what I need to do in Python to handle this control flow. Thanks in advance, Al McGowan import random import array arr=[] pc1 = [] pc2 = [] pc3= [] TR = [] inp = open ("pc.tab","r") #read line into array for line in inp.readlines(): line = line.strip() # get rid of \n nums = line.split() # separate the characters nums = map(float,nums) # convert to floats for n in nums: arr.append(n) for estimate in range (0,10): # starts the cycle of reps pc1 = [] pc2 = [] pc3= [] jack = [] for sample in range (0,10): #samples the appropriate number of genera n = random.randint(0,10) # calls random interger to get sample #m=n, run through jack, if good go on if not back to sample tally = jack.count (m) if tally>0: print "go" jack.append(n) #write to jacknife check file x = n*3 #gets around spread of data in array a= arr[x] #grab appropriate data for pc1 b = arr [x+1]#grab appropriate data for pc2 c = arr [x+2] #grab appropriate data for pc3 pc1.append(a) #write sample to file pc2.append(b) #write sample to file pc3.append(c) #write sample to file trmax1 = max (pc1) trmin1 = min (pc1) trmax2 = max (pc2) trmin2 = min (pc2) trmax3 = max (pc3) trmin3 = min (pc3) one = trmax1 - trmin1 two = trmax2 - trmin2 three = trmax3 - trmin3 final = one+two+three #print estimate #print final print jack[0:] #print pc1 [0:] #print pc2 [0:] #print pc3 [0:] -- Alistair J. McGowan Department of Geophysical Sciences, University of Chicago Chicago IL 60637 Phone: 773-795-1170 Fax: 773-702-9505 "Hope is a duty from which paleontologists are exempt." David Quammen 'It's not if, it's when and how bad." Richard Keeling --============_-1168261878==_ma============ Content-Type: text/html; charset="us-ascii" Control flow
Dear All,
                I am trying to modify a resampling program so that I can resample without replacement. I am an old BASIC hand, so what I want to do is at the point where tally is assessed to see if that draw has already been made. If tally>0 I want to go back to the line

n = random.randint(0,10)        # calls random interger to get sample

and try to draw a sample that I haven't picked before. This would be done with a goto in ye olden days, but I am not having much joy figuring out what I need to do in Python to handle this control flow.
        Thanks in advance,
                                Al McGowan

import  random
import array
arr=[]
pc1 = []
pc2 = []
pc3= []
TR = []
inp = open ("pc.tab","r")
 #read line into array
for line in inp.readlines():
    line = line.strip()        # get rid of \n
    nums = line.split()  # separate the characters
    nums = map(float,nums)     # convert to floats
    for n in nums: arr.append(n)
for estimate in range (0,10):        # starts the cycle of  reps
    pc1 = []
        pc2 = []
        pc3= []
jack = []
       for sample in range (0,10):     #samples the appropriate number of genera
                n = random.randint(0,10)        # calls random interger to get sample
                #m=n, run through jack, if good go on if not back to sample
                tally = jack.count (m)
          if tally>0:
                     print "go"
              jack.append(n) #write to jacknife check file
            x = n*3 #gets around spread of data in array
            a= arr[x]       #grab appropriate data for pc1
          b = arr [x+1]#grab appropriate data for pc2
             c = arr [x+2] #grab appropriate data for pc3
            pc1.append(a) #write sample to file
             pc2.append(b) #write sample to file
             pc3.append(c) #write sample to file
     trmax1  = max (pc1)
     trmin1 = min (pc1)
      trmax2  = max (pc2)
     trmin2 = min (pc2)
      trmax3  = max (pc3)
     trmin3 = min (pc3)
      one = trmax1 - trmin1
   two = trmax2 - trmin2
   three = trmax3 - trmin3
final = one+two+three
   #print estimate
#print final
    print jack[0:]
#print pc1 [0:]
#print pc2 [0:]
#print pc3 [0:]
-- 
Alistair J. McGowan
Department of Geophysical Sciences,
University of Chicago
Chicago
IL 60637

Phone: 773-795-1170
Fax: 773-702-9505

"Hope is a duty from which paleontologists are exempt."
                           David Quammen

'It's not if, it's when and how bad."
                              Richard Keeling
--============_-1168261878==_ma============-- From denis@charternavgps.ie Wed Jan 29 12:22:07 2003 From: denis@charternavgps.ie (Denis Hanley) Date: Wed Jan 29 12:22:07 2003 Subject: [Tutor] Array Message-ID: <001601c2c7ba$e893a5b0$0701a8c0@gozzy> This is a multi-part message in MIME format. ------=_NextPart_000_0013_01C2C7BA.E772CC60 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Dear All, what I need to do is create an Array. Input Information into the Array = on the fly and then output my data in this format: LineData =3D array[x1 y1, x2 y2, x3 y3, etc] Line x1 y1 x2 y2 Line x2 y2 x3 y3 Line x3 y3 x4 y4 etc. The problem is I do not know how to do this as I am very new to Python. = Any assistance will be greatly appreciated. Denis Hanley IT & GIS Software Support Manager CharterNav GPS Ltd tel: ++353 214832990/1 fax: ++ 353 21 4832992 after hours support: ++ 353 21 4375164 or ++353 86 833 9303 denis@charternavgps.ie www.charternavgps.ie GPS House, Church Bay Road, Crosshaven, Co. Cork, Ireland ------=_NextPart_000_0013_01C2C7BA.E772CC60 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Dear All,
 
what I need to do is create an = Array.  Input=20 Information into the Array on the fly and then output my data in this=20 format:
 
LineData =3D array[x1 y1, x2 y2, x3 y3, = etc]
 
Line x1 y1  x2 y2
Line x2 y2 x3 y3
Line x3 y3 x4 y4
 
 
etc.
 
 
The problem is I do not know how to do = this as I am=20 very new to Python.  Any assistance will be greatly=20 appreciated.
 
 
Denis Hanley
IT & GIS Software = Support=20 Manager
CharterNav GPS Ltd
 
tel: ++353 214832990/1
fax: ++ 353 = 21=20 4832992
after hours support: ++ 353 21 4375164 or ++353 86 833 = 9303
denis@charternavgps.ie
www.charternavgps.ie
 
GPS House,
Church Bay=20 Road,
Crosshaven,
Co. Cork, Ireland
------=_NextPart_000_0013_01C2C7BA.E772CC60-- From magnus@thinkware.se Wed Jan 29 12:38:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Wed Jan 29 12:38:02 2003 Subject: [Tutor] Zip-ing files/folders - collecting opinions In-Reply-To: <10F0E58C0018054484E329DC494C4D7F01BD58@mexper1> Message-ID: <5.1.0.14.0.20030129095851.02bafd58@www.thinkware.se> At 12:32 2003-01-29 +0800, Simon Wittber (Maptek) wrote: >It's a small program which zips up a directory structure into an python >program. You then run the generated python program to expand the tree. Cute! >... >codedfile.write("exec(zlib.decompress(base64.decodestring(\"\"\"" + data + >"\"\"\")))\n") Note that exec is a statement, not a function. The kosher way to write exec statements (as print statements) is without parenthesis. codedfile.write("exec zlib.decompress(base64.decodestring(\"\"\"" + data + "\"\"\"))\n") I'm curious to hear how this works with 4 GB files... That will be a big string. -- 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@hkn.eecs.berkeley.edu Wed Jan 29 12:49:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Jan 29 12:49:01 2003 Subject: [Tutor] string parsing In-Reply-To: <01C2C7AE.E98D8C80@pc7486> Message-ID: On Wed, 29 Jan 2003, Justin Ezequiel wrote: > I guess this is not the right place for this question but I > do not know where else to ask. > > You've all been very helpful. > > Can anyone point me to a more appropriate forum? > > I need ideas on how to (begin to) programmatically identify > elements of a bibliographic reference. > > By elements, I mean authors/editors, their names (givenname, surname, > suffix), article/chapter titles, book/journal titles, date of > publication, volume number, start and end page numbers, publisher name > and publisher location, etc. Hi Justin, There is a project called the Freely Extensible Biomedical Record Linkage (FEBRL) which uses Hidden Markov Models to parse through address records: http://sourceforge.net/projects/febrl http://datamining.anu.edu.au/software/febrl/febrldoc/manual.html It uses some sophisticated models to match text to fields in a record. I can imagine that this software can be applied toward bibliographic entries as well! I haven't played with Febrl yet, but I'm planning to when I have more time. I hope this helps! From dyoo@hkn.eecs.berkeley.edu Wed Jan 29 13:00:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Jan 29 13:00:02 2003 Subject: [Tutor] Pickle Module In-Reply-To: Message-ID: > On Wed, 29 Jan 2003, Deirdre Hackett wrote: > > > pickle.dump(data,f) > > > > I want to write data to the file testing3.txt. Hi Deirdre, The reason pickle.dump() takes in a file as its second argument is because pickle.dump() itself will call f.write() with a stringified version of data. So there's no need to call f.write() ourselves: that's the detail that pickle is supposed to handle for us. By the way, if you haven't seen it already, you may find Patrick O'Brian's tutorial on object persistance (pickling) really useful: http://www-106.ibm.com/developerworks/linux/library/l-pypers.html?dwzone=linux Good luck to you! From dyoo@hkn.eecs.berkeley.edu Wed Jan 29 13:09:28 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Jan 29 13:09:28 2003 Subject: [Tutor] Array In-Reply-To: <001601c2c7ba$e893a5b0$0701a8c0@gozzy> Message-ID: On Wed, 29 Jan 2003, Denis Hanley wrote: > Dear All, > > what I need to do is create an Array. Input Information into the Array > on the fly and then output my data in this format: > > LineData = array[x1 y1, x2 y2, x3 y3, etc] > > Line x1 y1 x2 y2 > Line x2 y2 x3 y3 > Line x3 y3 x4 y4 Hi Denis, Python supports a more flexible data structure called the "List" that we can use to collect a bunch of data: http://www.python.org/doc/tut/node5.html#SECTION005140000000000000000 http://www.python.org/doc/tut/node7.html#SECTION007100000000000000000 Lists support on-the-fly appending, so they should be suitable for the task you're describing. Once you have your points stored in a List, it shouldn't be too bad to iterate between adjacent pairs and print out the Line descriptions you want. Try going through some of the List examples in the links above. If you run into problems, please feel free to send a holler on Tutor; we'll be happy to help! From jeff@ccvcorp.com Wed Jan 29 13:17:05 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Wed Jan 29 13:17:05 2003 Subject: [Tutor] Array References: <001601c2c7ba$e893a5b0$0701a8c0@gozzy> Message-ID: <3E3818FB.6070900@ccvcorp.com> Denis Hanley wrote: > what I need to do is create an Array. Input Information into the > Array on the fly and then output my data in this format: > > LineData = array[x1 y1, x2 y2, x3 y3, etc] > > Line x1 y1 x2 y2 > Line x2 y2 x3 y3 > Line x3 y3 x4 y4 What other languages do with Arrays, Python typically does with lists. (There's some differences, and Python does actually have an Array module, but a list is usually the best translation.) It looks like in each 'slot' in your list, you have an (x,y) coordinate pair. The Python structure to use for this would typically be a tuple. So you would have a list of 2-element tuples as your basic data structure. LineData = [ (x1,y1), (x2,y2), (x3,y3), (x4,y4) ] Now, you want to proceed through that list, showing tuples in pairs. A normal for loop in Python will iterate over a sequence one-at-a-time, but that's not quite what we want. We need the index that we're at, so that we can also get the *next* element of the list -- each iteration, we want to show element N and element N+1. This means that we're going to iterate len(LineData) - 1 times, because the last element won't have a next element to pair with. We can use the range() function to generate a sequence of indexes that'll fit our needs, and then use a for loop to iterate over that sequence of indexes. Lists start indexing at 0, and range() defaults to starting its generated sequence at 0, so that works out very conveniently. Let's try it out. >>> LineData = [ (1,2), (3,4), (5,6), (7,8), (9,0) ] >>> for n in range( len(LineData)-1 ): ... print "Line %d: %s %s" % (n+1, LineData[n], LineData[n+1]) ... Line 1: (1, 2) (3, 4) Line 2: (3, 4) (5, 6) Line 3: (5, 6) (7, 8) Line 4: (7, 8) (9, 0) >>> Hope this helps! Jeff Shannon Technician/Programmer Credit International From dyoo@hkn.eecs.berkeley.edu Wed Jan 29 13:27:23 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Jan 29 13:27:23 2003 Subject: [Tutor] Control flow In-Reply-To: Message-ID: On Wed, 29 Jan 2003, Alistair McGowan wrote: > I am trying to modify a resampling program so that I can resample > without replacement. I am an old BASIC hand, so what I want to do is at > the point where tally is assessed to see if that draw has already been > made. If tally>0 I want to go back to the line > > n = random.randint(0,10) # calls random interger to get sample Hi Alistair, I see... Ok, let's look at that block of code: ### n = random.randint(0,10) tally = jack.count (m) if tally > 0: print "go" else: ## ??? how to "goto"? ### What we'd like to do is repeat this block of code until we finally get a positive tally. We can do this by using a "while" loop: ### while 1: n = random.randint(0, 10) tally = jack.count(m) if tally > 0: print "go" break ## <--- break out of the infinite loop ### This loop has the effect of GOing back TO the beginning of the call to random.randint(), and captures the idea of waiting till we get a positive tally. By the way, we can give a descriptive "name" this block by making a "subroutine" function: ### def getPositiveTally(): while 1: n = random.randint(0, 10) tally = jack.count(m) if tally > 0: print "go" break return tally, n ### The effect of this is that we can then use it in the original code like this: ### ... # samples the appropriate number of genera for sample in range (0,10): tally, n = getPositiveTally() jack.append(n) # write to jacknife check file x = n*3 # gets around spread of data in array ... ### which simplifies the code a little bit. The tutorials at: http://python.org/doc/Newbies.html should all have sections on using 'while' loops. Please feel free to ask more questions about them! For a historical perspective, here's a link to the article "Go To Statement Considered Harmful", which was one of the defining papers pushing for alternative ways of controlling control flow: http://www.acm.org/classics/oct95/ Good luck! From dyoo@hkn.eecs.berkeley.edu Wed Jan 29 13:30:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Jan 29 13:30:02 2003 Subject: [Tutor] Control flow In-Reply-To: Message-ID: On Wed, 29 Jan 2003, Danny Yoo wrote: > By the way, we can give a descriptive "name" this block by making a > "subroutine" function: > > ### > def getPositiveTally(): > while 1: > n = random.randint(0, 10) > tally = jack.count(m) > if tally > 0: > print "go" > break > return tally, n > ### Doh. I goofed again. I meant to write: ### def getPositiveTally(): while 1: n = random.randint(0, 10) tally = jack.count(m) if tally > 0: print "go" break return tally, n ### Sorry about that! Aside: I think one reason I goofed like that was because I was thinking of the alternative definition: ### def getPositiveTally(): while 1: n = random.randint(0, 10) tally = jack.count(m) if tally > 0: print "go" return tally, n ### and somehow, maybe, I "averaged" the indentation of both solutions... I dunno. *grin* From magnus@thinkware.se Wed Jan 29 13:35:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Wed Jan 29 13:35:02 2003 Subject: [Tutor] Array In-Reply-To: <001601c2c7ba$e893a5b0$0701a8c0@gozzy> Message-ID: <5.1.0.14.0.20030129192646.02bdb268@www.thinkware.se> At 17:21 2003-01-29 +0000, Denis Hanley wrote: >what I need to do is create an Array. If you tell us what you want to achieve, we'll tell *you* what you need to create! ;) >LineData = array[x1 y1, x2 y2, x3 y3, etc] >>> lineData = [ (1,2), (3,4), (5, 6) ] >Line x1 y1 x2 y2 >Line x2 y2 x3 y3 >Line x3 y3 x4 y4 >>> pos = 0 >>> while pos < len(lineData) -1: ... print "Line", lineData[pos], lineData[pos + 1] ... pos = pos + 1 ... Line (1, 2) (3, 4) Line (3, 4) (5, 6) -- 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 BranimirP@cpas.com Wed Jan 29 13:44:02 2003 From: BranimirP@cpas.com (Branimir Petrovic) Date: Wed Jan 29 13:44:02 2003 Subject: [Tutor] Zip-ing files/folders - collecting opinions Message-ID: <33678E78A2DD4D418396703A750048D41A640C@RIKER> > -----Original Message----- > From: Magnus Lycka [mailto:magnus@thinkware.se] > Sent: January 29, 2003 12:36 PM > To: Simon Wittber (Maptek); Branimir Petrovic; tutor@python.org > Subject: RE: [Tutor] Zip-ing files/folders - collecting opinions > > > At 12:32 2003-01-29 +0800, Simon Wittber (Maptek) wrote: > >It's a small program which zips up a directory structure > into an python > >program. You then run the generated python program to expand > the tree. > > Cute! > > >... > I'm curious to hear how this works with 4 GB files... That > will be a big string. > This would probably be the longest Python program ever ;-) There is also minor issue to be fixed, namely this: outfile = file("temp." + outfilename, "w") will not work as is on Windows platform since 'outfilename' will contain no-no characters (colon after vol. name like C:), but is trivial to fix. I am wary of reading humungous 4 GB++ files in RAM, all in one large 'slurp', but the idea of bonding Python script with data is brilliant. No way to misplace re-assembling code, all needed is there - all the time. Cookbook worthy recipe! Branimir From magnus@thinkware.se Wed Jan 29 13:58:03 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Wed Jan 29 13:58:03 2003 Subject: [Tutor] Zip-ing files/folders - collecting opinions In-Reply-To: <33678E78A2DD4D418396703A750048D41A6406@RIKER> Message-ID: <5.1.0.14.0.20030129194714.02c66ea8@www.thinkware.se> At 23:19 2003-01-28 -0500, Branimir Petrovic wrote: >My archiving script must be able to compress large >10 GB+ Oracle dump files (among other things). Can't you convince Oracle to spew out more and smaller files instead? 10GB files aren't so funny to play with. Another option is to split the file as you read it, and save compressed parts. chunksize = 100000000 f = file('oracle.dump', 'rb') i = 0 while 1: data = f.read(chunksize) if not data: break myWriteToZipFile(data, 'mydump_%04i.zip' % i) To restore, you'd just do: fileNames=glob.glob('mydump*.zip') fileNames.sort() f = file('restored.dump', 'rb') for fn in fileNames: data = myUnZipFromFile(fn) w.write(data) -- 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 BranimirP@cpas.com Wed Jan 29 14:23:01 2003 From: BranimirP@cpas.com (Branimir Petrovic) Date: Wed Jan 29 14:23:01 2003 Subject: [Tutor] Zip-ing files/folders - collecting opinions Message-ID: <33678E78A2DD4D418396703A750048D41A640D@RIKER> > -----Original Message----- > From: Magnus Lycka [mailto:magnus@thinkware.se] > Sent: January 29, 2003 1:56 PM > To: Branimir Petrovic; 'tutor@python.org' > Subject: Re: [Tutor] Zip-ing files/folders - collecting opinions > > > At 23:19 2003-01-28 -0500, Branimir Petrovic wrote: > >My archiving script must be able to compress large > >10 GB+ Oracle dump files (among other things). > > Can't you convince Oracle to spew out more and smaller > files instead? 10GB files aren't so funny to play > with. > Oracle can be persuaded to export parts, instead of the 'whole thing', but then simplicity in approach is lost, and new fear - didn't I forget some important piece - becomes menacing presence. > Another option is to split the file as you read it, > and save compressed parts. Splitting the file into smaller chucks would work, but only for those with the re-assembling script (or knowledge of how the splitting came to be). I was not very explicit in my post on this, but I always knew (therefore never said so;) that I'd prefer un-zipping to be as generic as possible. Joe Sixpack, the 'care taker' with our customer, should be able to unzip what I zipped once he is told over the phone how to, without overloading his grey stuff by calling uncalled for names (like Python). GNU's Win32 port with gzip/gunzip stands proud for this particular task, and so does Python with ability to produce archives in this widely accepted format. Branimir From magnus@thinkware.se Wed Jan 29 20:09:15 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Wed Jan 29 20:09:15 2003 Subject: [Tutor] Python and Tcl/Tk In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E0974DAA4@i2km11-ukbr.domain1 .systemhost.net> Message-ID: <5.1.0.14.0.20030130012532.02c11b70@www.thinkware.se> At 11:07 2003-01-29 +0000, alan.gauld@bt.com wrote: > > For Tcl it seems to be downhill to me, like Delphi and soon > > Visual Basic. > >Delphi is actually growing again due to Kylix. But that will >be short term I fear. I think so too... >VB, I suspect, is here for the long haul - unless Bill G leaves >Microsoft! I don't know... VB 1 was released in 1991, and VB 6 in 1998. Almost one new version per year. I guess there is some kind of VB.NET now, but it seems to me that the development of VB has slowed down quite a bit. And BG has been known to shift lane. Once upon a time, he spoke highly of Microsofts Smalltalk for OS/2. That was to be the next big thing. And of course, we have OS/2... And internet... And Java... Bill has no holy cows. It all started with BASIC but I doubt that he's sentimental. Let's look at the VB versions VB 1 1991 VB 2 1992 1 yr VB 3 1993 1 yr VB 4 1995 2 yrs VB 5 1997 2 yrs VB 6 1998 1 yr VB 7/.NET 2002 4 yrs since previous version... There might be a new Visual Studio in 2003, and perhaps a new version number for VB, but I doubt that much will change except pure Dotnet updates that must be integrated in VB.NET. I don't know, but I suspect VB and CSharp will aquire more and more of each other. VB will become more CSharpish, and CSharp will become more and more relaxed as all MS tools. Instead of flagging errors, they try to guess what you meant. It's the antithesis of Python's "When in doubt, refuse the temptation to guess". Anyone who developed C++ with Visual Studio for deployment on Solaris etc knows what I mean. (No it was not my idea, but I was well paid, so I won't complain...) I would imagine that C# will be the next VB, but perhaps I'm wrong. With it's Java roots, it's rather object-oriented, and that might be to difficult to grasp for many? But when Office etc is fully Dotnet enabled, VBA will be replaced by Dotnet, and you can write macros and whatever in any Dotnet capable language. At that point I imagine VB will be given little further attention. After 40 years, it's about time for BASIC to retire... -- 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 j.ezequiel@spitech.com Thu Jan 30 00:57:07 2003 From: j.ezequiel@spitech.com (Justin Ezequiel) Date: Thu Jan 30 00:57:07 2003 Subject: FW: [Tutor] string parsing Message-ID: <01C2C866.FFA02560@pc7486> -----Original Message----- From: Ezequiel, Justin=20 Sent: Thursday, January 30, 2003 1:47 PM To: 'Magnus Lycka'; 'Danny Yoo[dyoo@hkn.eecs.berkeley.edu]' Cc: 'tutor@python.org' Subject: Re: [Tutor] string parsing Thanks to Magnus and Danny! Thanks to Magnus for the ideas! I will definitely give them a lot of thought and consideration. Here's a little more information on what I need. This project is for converting the full text of author-submitted = documents (including bibliographic references) to XML before = publication. Tagging of references is one part of our process that takes up lots of = time. This covers more than 200+ scientific journals and authors do not always = follow the format of the respective journal as reformatting is handled = by the typesetters. Thanks to Danny for pointing me to FEBRL! I will surely look at this after I get current work out of the way. From glidedon Thu Jan 30 02:26:01 2003 From: glidedon (glidedon) Date: Thu Jan 30 02:26:01 2003 Subject: [Tutor] Variables in Os Path ? Message-ID: <0003b56e95a4d563_mailit@mail.c-zone.net> Hi list, Newbie here, What am I doing wrong here ? When I try to insert my variable "file_name" into the path to open a file I get the error at bottom. The path is correct if I insert the acutal file name . BTW this on a BeOS system, if you don't recognise the path format :-) TIA Don import os /snip/ file_query = raw_input( ' Do you have a log already started ? : y/n ' ) if file_query in ( 'y', 'Y', 'Yes' ): file_name = raw_input ( ' Enter file name : ') file = open('/boot/home/py/file_name' , 'r') history_list = file.readlines() file.close() for eachline in history_list: print eachline, /snip/ Traceback (most recent call last): File "/boot/home/py/IOFile/File_Query.py", line 11, in ? file = open('/boot/home/py/filename' , 'r') IOError: [Errno -2147459069] No such file or directory: '/boot/home/py/ filename' From francois.granger@free.fr Thu Jan 30 02:32:02 2003 From: francois.granger@free.fr (Francois Granger) Date: Thu Jan 30 02:32:02 2003 Subject: [Tutor] Variables in Os Path ? In-Reply-To: <0003b56e95a4d563_mailit@mail.c-zone.net> References: <0003b56e95a4d563_mailit@mail.c-zone.net> Message-ID: At 23:24 -0800 29/01/2003, in message [Tutor] Variables in Os Path ?, glidedon wrote: >Hi list, > >Newbie here, What am I doing wrong here ? When I try to insert my variable >"file_name"[...] > file_name = raw_input ( ' Enter file name : ') > file = open('/boot/home/py/file_name' , 'r') file = open('/boot/home/py/' + file_name , 'r') # concatenate a string literal and a variable -- Recently using MacOSX....... From dyoo@hkn.eecs.berkeley.edu Thu Jan 30 02:40:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Jan 30 02:40:02 2003 Subject: [Tutor] Variables in Os Path ? In-Reply-To: <0003b56e95a4d563_mailit@mail.c-zone.net> Message-ID: On Wed, 29 Jan 2003, glidedon wrote: > Hi list, > > Newbie here, What am I doing wrong here ? When I try to insert my variable > "file_name" into the path to open a file I get the error at bottom. The path > is correct if I insert the acutal file name . BTW this on a BeOS system, if > you don't recognise the path format :-) Hi Glidedon, Let's take a look: > file_name = raw_input ( ' Enter file name : ') > file = open('/boot/home/py/file_name' , 'r') ^^^^^^^^^ Python has no way of knowing if you literally meant to open a file named 'file_name'. We as humans know that we want to "fill in" that place with the value named by that 'file_name' variable, but Python can't read minds yet. *grin* We have to be more explicit and spell it out to our program. We can fix your problem by joining the literal part of the string, that '/boot/home/py/' part, with the value of file_name. If we look at: http://www.python.org/doc/tut/node5.html#SECTION005120000000000000000 we can browse through till we see something about "concatenation": with concatenation, we should be able to fix the code. By the way, there's a specialized function for attaching a path string to a file, by using the 'os.path.join()' function: http://www.python.org/doc/lib/module-os.path.html#l2h-1288 which would probably be a desirable way to form the full file name, since it handles platform-dependent issues for us. Good luck! From alan.gauld@bt.com Thu Jan 30 06:47:02 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu Jan 30 06:47:02 2003 Subject: [Tutor] Python and Tcl/Tk Message-ID: <7497DCA1C240C042B28F6657ADFD8E09702394@i2km11-ukbr.domain1.systemhost.net> > I don't know... VB 1 was released in 1991, and VB 6 in 1998. > Almost one new version per year. I guess there is some kind > of VB.NET now, Yes and in between we got lkots of VBA and VBScript releases. But VB.NET is a major release with completely unified class libraries, full inheritance/polymorphism in its OOP capability etc. I hesitate to say so but VB.NET is not a bad language for just getting things done... > has no holy cows. It all started with BASIC but I doubt that > he's sentimental. I dunno, its the one project Bill takes a very personal interest in, its what he iuses for his own programming - and he still does quite a bit by all accounts! > VB 6 1998 1 yr > VB 7/.NET 2002 4 yrs since previous version... But all the ASP stuff and uunified VBA was in that period too. > I don't know, but I suspect VB and CSharp will aquire more and > more of each other. Thats true, and of course in .NET they both compile down to the same bytecodes. You can even write one module in VB and another in C# and link them together seamlessly. But I don't see C# ever appearing as a macxro language in Office 2005 or whatever, VB is the end user programming environment, C# is the developers tool. I do expect to see Managed C++ gradually disappearing off the Microsoft radar except as a niche server side tool. > wrong. With it's Java roots, it's rather object-oriented, and > that might be to difficult to grasp for many? Exactly, too much for the end users, and not 'natural English' enough for corporate America. > But when Office etc is fully Dotnet enabled, VBA will be replaced > by Dotnet, and you can write macros and whatever in any Dotnet > capable language. Absolutely but as you said earlier, the normal way for end users is to record macros then enhance them, and I suspect the macro recorder will still be spitting out VBA.NET rather than C# for a long time to come. Alan g. From charlie@begeistert.org Thu Jan 30 11:39:02 2003 From: charlie@begeistert.org (Charlie Clark) Date: Thu Jan 30 11:39:02 2003 Subject: [Tutor] Checking for valid e-mails Message-ID: <20030130173840.4137.9@.1043915775.fake> Dear list, I have a bundle of e-mail addresses to check for validity and have come across a Python class which does this but not well enuff. I have found some perl code which is better but I'm having trouble translating some of the perl expressions. The Python stuff is at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66439/index_txt It is a module with a single class which comes with some built in patterns and the ability to make custom patterns. The built in e-mail test doesn't catch things like spaces or @@ and other things. The perl stuff is at http://aspn.activestate.com/ASPN/Cookbook/Rx/Recipe/68432/index_txt This seems to catch pretty much everything but it's perl and I'm not sure what !~ and =~ do I've started work on making custom definitions based on the perl source like this sv1 = StringValidator("joe@testmail.com") sv1.definePattern("test1", "^[0-9a-zA-Z\.\-\_]+\@[0-9a-zA-Z\.\-]+$") sv1.definePattern("test2", "^[^0-9a-zA-Z]|[^0-9a-zA-Z]$") if not sv1.isValidForPattern("test1"): print sv1.validateString, " has invalid characters in the name" elif not sv1.isValidForPattern("test1"): print sv1.validateString, " doesn't start or end with alpha or num" else: print sv1.validateString, "is valid" Here test1 works as it should. I think !~ translates to matches. test2 doesn't work here as it rejects pretty much all addresses. I'd expect it to work differently because it uses =~ but haven't quite worked out how. I'll carry on experimenting! Thanx for any pointers. Charlie From BranimirP@cpas.com Thu Jan 30 13:17:37 2003 From: BranimirP@cpas.com (Branimir Petrovic) Date: Thu Jan 30 13:17:37 2003 Subject: [Tutor] Checking for valid e-mails Message-ID: <33678E78A2DD4D418396703A750048D41A641B@RIKER> http://www.interclasse.com/scripts/EMailValidatorCLS.php > -----Original Message----- > From: Charlie Clark [mailto:charlie@begeistert.org] > Sent: January 30, 2003 11:39 AM > To: tutor@python.org > Subject: [Tutor] Checking for valid e-mails > > > Dear list, > > I have a bundle of e-mail addresses to check for validity and > have come > across a Python class which does this but not well enuff. I > have found some > perl code which is better but I'm having trouble translating > some of the > perl expressions. You have to keep on mind that: - E-mail validation is NOT a trivial matter (see RFC2822 for full set of rules to see what you are up against), Proper validation would respect all pattern rules imposed by governing RFC, and would also check and validate the domain part (against the list of valid and registered domains). - Even if valid pattern wise - and if target domain exists, and if mail host for the domain is 'there' and responds, there is absolutely no guarantee that that particular user/mailbox exists as well, and that's what effectively kills the purpose of doing it too seriously. Because it is so hard to do it properly, and ultimately futile on the account of the above point, solutions you can find 'out there' are in the range of either completely broken to 'almost working'... If you are in mood for a chuckle, see the 'pure' regexp solution (compliant with now obsolete RFC822): http://www.foad.org/~abigail/Perl/url3.regex If 'almost there' (good enough) is what would please you, you can have a look at this JScript: http://www.interclasse.com/scripts/EMailValidatorCLS.php that I've done some time ago, before 'seeing the light' (discovering Python). The same thing can be done in Python better and closer to the specs, but I do not think that effort in this direction is worthwhile after all. Branimir From micforster@yahoo.com Thu Jan 30 17:40:03 2003 From: micforster@yahoo.com (Mic Forster) Date: Thu Jan 30 17:40:03 2003 Subject: [Tutor] cellular automaton Message-ID: <20030130223936.24010.qmail@web13401.mail.yahoo.com> Does anyone have ready access to a cellular automaton script in Python? I have a script in Basic but not Python. Thanks for any help..... __________________________________________________ Do you Yahoo!? Yahoo! Mail Plus - Powerful. Affordable. Sign up now. http://mailplus.yahoo.com From BranimirP@cpas.com Thu Jan 30 17:43:00 2003 From: BranimirP@cpas.com (Branimir Petrovic) Date: Thu Jan 30 17:43:00 2003 Subject: FW: [Tutor] Checking for valid e-mails Message-ID: <33678E78A2DD4D418396703A750048D41A6421@RIKER> > -----Original Message----- > From: Charlie Clark [mailto:charlie@begeistert.org] > Sent: January 30, 2003 11:39 AM > To: tutor@python.org > Subject: [Tutor] Checking for valid e-mails > > > Dear list, > > I have a bundle of e-mail addresses to check for validity and > have come > across a Python class which does this but not well enuff. I > have found some > perl code which is better but I'm having trouble translating > some of the > perl expressions. You have to keep on mind that: - E-mail validation is NOT a trivial matter (see RFC2822 for full set of rules to see what you are up against), Proper validation would respect all pattern rules imposed by governing RFC, and would also check and validate the domain part (against the list of valid and registered domains). - Even if valid pattern wise - and if target domain exists, and if mail host for the domain is 'there' and responds, there is absolutely no guarantee that that particular user/mailbox exists as well, and that's what effectively kills the purpose of doing it too seriously. Because it is so hard to do it properly, and ultimately futile on the account of the above point, solutions you can find 'out there' are in the range of either completely broken to 'almost working'... If you are in mood for a chuckle, see the 'pure' regexp solution (compliant with now obsolete RFC822): http://www.foad.org/~abigail/Perl/url3.regex If 'almost there' (good enough) is what would please you, you can have a look at this JScript: http://www.interclasse.com/scripts/EMailValidatorCLS.php that I've done some time ago, before 'seeing the light' (discovering Python). The same thing can be done in Python better and closer to the specs, but I do not think that effort in this direction is worthwhile after all. Branimir From glingl@aon.at Thu Jan 30 18:23:01 2003 From: glingl@aon.at (Gregor Lingl) Date: Thu Jan 30 18:23:01 2003 Subject: [Tutor] cellular automaton References: <20030130223936.24010.qmail@web13401.mail.yahoo.com> Message-ID: <3E39B3CC.9000508@aon.at> Mic Forster schrieb: >Does anyone have ready access to a cellular automaton >script in Python? I have a script in Basic but not >Python. Thanks for any help..... > > Are you interested in a small "Lifegame"-script? Or are you searching for something more general or more elaborated? Gregor >__________________________________________________ >Do you Yahoo!? >Yahoo! Mail Plus - Powerful. Affordable. Sign up now. >http://mailplus.yahoo.com > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From Sean Abrahams Thu Jan 30 19:09:47 2003 From: Sean Abrahams (Sean Abrahams) Date: Thu Jan 30 19:09:47 2003 Subject: [Tutor] Stopping program execution Message-ID: <31178548468.20030130160745@sfsu.edu> I have a web script that checks to see if the user has a session cookie. If not, I want to display a page saying 'no session found, please login. yadda yadda yadda', and not execute the rest of the script. Thing is, I check for the session cookie through a separate module. import session id = session.checkSession() # for example If there is a session, the id is returned, otherwise the error message is printed. Right now, I have the error message printing fine, but it continues to execute the rest of the script, which is not the behavior I'm looking for. How do I halt the script when it detects no session? Or, is there a better way to do this? def sessionCheck(session): try: id = session["id"] return id except KeyError, e: print "content-type: text/html" print print "No session found." # Stop script Thanks, --Sean From magnus@thinkware.se Thu Jan 30 19:43:09 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Thu Jan 30 19:43:09 2003 Subject: [Tutor] Stopping program execution In-Reply-To: <31178548468.20030130160745@sfsu.edu> Message-ID: <5.1.0.14.0.20030131013115.02c74e00@www.thinkware.se> At 16:07 2003-01-30 -0800, Sean Abrahams wrote: >I have a web script that checks to see if the user has a session >cookie. If not, I want to display a page saying 'no session found, >please login. yadda yadda yadda', and not execute the rest of the >script. Thing is, I check for the session cookie through a separate >module. > >import session >id = session.checkSession() ># for example > >If there is a session, the id is returned, otherwise the error message >is printed. > >Right now, I have the error message printing fine, but it continues to >execute the rest of the script, which is not the behavior I'm looking >for. If session.checkSession() returns without providing a return value, it will be the same as "return None" This means that the calling script could for instance do id = session.checkSession() if id is None: # There is no ongoing session for this client. Abort! raise SystemExit >def sessionCheck(session): > try: > id = session["id"] > > return id > except KeyError, e: > print "content-type: text/html" > print > print "No session found." > > # Stop script You can do: raise SystemExit here instead. In general, I think you should put all your code in functions. Indent your main code four spaces, and make it look like this: def main(): [The code that is now always run, except imports and possibly some globals needed by other functions.] if __name__ == '__main__': main() This style is more pythonic, and it will make it easier to structure the code further. It will also enable you to simply do "return" in main() instead of "raise SystemExit". -- 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 shalehperry@attbi.com Thu Jan 30 19:54:39 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Thu Jan 30 19:54:39 2003 Subject: [Tutor] Checking for valid e-mails In-Reply-To: <20030130173840.4137.9@.1043915775.fake> References: <20030130173840.4137.9@.1043915775.fake> Message-ID: <200301301653.18697.shalehperry@attbi.com> On Thursday 30 January 2003 08:38, Charlie Clark wrote: > > The perl stuff is at > http://aspn.activestate.com/ASPN/Cookbook/Rx/Recipe/68432/index_txt > > This seems to catch pretty much everything but it's perl and I'm not su= re > what !~ and =3D~ do > $foo =3D~ /pattern/ is roughly equivalent to re.search(pattern, foo) !~ means does not match it is analogous to the relationship between =3D=3D= and !=3D. From magnus@thinkware.se Thu Jan 30 21:40:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Thu Jan 30 21:40:02 2003 Subject: [Tutor] Re: you may regret that comment Magnus!! In-Reply-To: <20030130223705.23615.qmail@web13401.mail.yahoo.com> References: <5.1.0.14.0.20030129192646.02bdb268@www.thinkware.se> Message-ID: <5.1.0.14.0.20030131014117.02c090f0@www.thinkware.se> Hi, it seems your mail didn't reach the mailing list. I don't know if the Word attachment caused rejection, or if the subject line triggered some flame-war filter! ;) Anyway, maybe it would be better if you could put the image on some web location, and just post a URL with your mail. Obviously, this algorithm is written in an unstructured way, completely violating everything Dijkstra and others have said, so it would be easier to code without a lot of thinking in a language that supported GOTO, such as BASIC or C. I don't think it's a big issue though. The problem is that the flow chart is not a description of the problem, it's a suggested solution, and a solution made up with an idea that the tool will look different from the one we use: Python. The same basic algorithm could be described differently (well, much smarter) and then be much easier to find a structured solution for. For instance, loops with j = j + 1 just before j > jM, and i = i + 1 just before i > nsp are simply for loops in disguise. Also, the needlessly crossing path makes it more difficult to see the structured solution. These kinds of problems are fairly common. We'll have to twist it a bit. Personally I'd just look at the flow chart and code. I have some trouble distinguishing between 1 (one) and l (ell) in the picture. Could you clarify that? Roughly, your structure should be #init things for j in range(2, jM+1): x = rnd() if x < ...: abund.append(1) else: cum[l or 1?] = ... for i in range(l+1 or 2?, nsp+1): cum[i] = ... i = 1 or l??? while x >= cum[i]: i += 1 abund[i] += 1 ? Also, nsp could be a function, instead of a variable etc. At 14:37 2003-01-30 -0800, Mic Forster wrote: >--- Magnus Lycka wrote: > > If you tell us what you want to achieve, we'll tell > > *you* what you need to create! ;) > > > > >I wasn't going to burden anyone with this but, well, >Magnus I just couldn't turn down your offer. Attached >is an algorithm I want to convert into Python. Any >advice? > >Cheers, >Mic Forster -- 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 micforster@yahoo.com Thu Jan 30 21:43:12 2003 From: micforster@yahoo.com (Mic Forster) Date: Thu Jan 30 21:43:12 2003 Subject: [Tutor] cellular automaton In-Reply-To: <3E39B3CC.9000508@aon.at> Message-ID: <20030131024232.57329.qmail@web13406.mail.yahoo.com> --- Gregor Lingl wrote: > Are you interested in a small "Lifegame"-script? Or > are you > searching for something more general or more > elaborated? > Gregor > Gregor, It's an area that I am really finding interesting. So what ever you may have would be greatly appreciated. Mic __________________________________________________ Do you Yahoo!? Yahoo! Mail Plus - Powerful. Affordable. Sign up now. http://mailplus.yahoo.com From micforster@yahoo.com Thu Jan 30 21:50:02 2003 From: micforster@yahoo.com (Mic Forster) Date: Thu Jan 30 21:50:02 2003 Subject: [Tutor] Re: you may regret that comment Magnus!! In-Reply-To: <5.1.0.14.0.20030131014117.02c090f0@www.thinkware.se> Message-ID: <20030131024915.21480.qmail@web13402.mail.yahoo.com> --- Magnus Lycka wrote: >I have some trouble distinguishing between 1 (one) >and l (ell) in the picture. Could you clarify that? Thanks for your help, Magnus. They are all ones in the algorithm; there are no ells. I thought the algorithm was rather elaborate and could be simplified. Again, thanks for the pointer.... __________________________________________________ Do you Yahoo!? Yahoo! Mail Plus - Powerful. Affordable. Sign up now. http://mailplus.yahoo.com From magnus@thinkware.se Thu Jan 30 22:21:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Thu Jan 30 22:21:01 2003 Subject: [Tutor] Re: you may regret that comment Magnus!! In-Reply-To: <20030131024915.21480.qmail@web13402.mail.yahoo.com> References: <5.1.0.14.0.20030131014117.02c090f0@www.thinkware.se> Message-ID: <5.1.0.14.0.20030131041545.02c8fd60@www.thinkware.se> At 18:49 2003-01-30 -0800, Mic Forster wrote: >--- Magnus Lycka wrote: > >I have some trouble distinguishing between 1 (one) > >and l (ell) in the picture. Could you clarify that? > >Thanks for your help, Magnus. They are all ones in the >algorithm; there are no ells. Ok. Then I imagine it's something like below. >I thought the algorithm >was rather elaborate and could be simplified. I still don't have a clue what it does... :) But the main loop is only 12 lines of code. from random import random as rnd # This only works in newer Python versions... class growList(list): '''A list that does as in Perl: Grows when we assign to new indices. I.e. x[1] = 5 will work if x was previously empty.''' def __setitem__(self, i, val): while i >= len(self): self.append(None) list.__setitem__(self, i, val) def __getitem__(self, i): 'Return 0 for unused slots' if i < len(self): return list.__getitem__(self, i) else: return 0 abund = growList() abund[1] = 1 cumul = growList() jM = 10 theta = 5 def nsp(): '''Number of species must be the same as the size of the abundence list (I guess). Note that first position is unused to match the 1-based algorithm syntax.''' return len(abund) - 1 for j in range(2, jM + 1): x = rnd() if x < (theta / float(theta + j - 1)): abund.append(1) else: cumul[1] = abund[1] / float(j-1) for i in range(2, nsp()+1): cumul[i] = cumul[i-1] + abund[i] / float(j-1) i = 1 while x >= cumul[i]: i += 1 abund[i] += 1 print "Abund", abund[1:] print "Cumulative", cumul[1:] -- 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 llazarre@yahoo.com Fri Jan 31 00:16:14 2003 From: llazarre@yahoo.com (Levy Lazarre) Date: Fri Jan 31 00:16:14 2003 Subject: [Tutor] Checking a file size before moving it Message-ID: <20030131051457.3280.qmail@web40411.mail.yahoo.com> Hello to all, I am writing a Python script that is intended to move some files from directory A to directory B on a server. Users copy the files to directory A once daily. The Python script is triggered by a scheduler and sweeps the directory for the files every 15 minutes. Obviously, I need to check that a file has been completely written before attempting to move it. On the Unix platform, I use the following scheme to ascertain that a file is no longer being written: stat the file and get its size(size1) sleep for 10 seconds stat the file again and get its size(size2) if size2 == size1 proceed with the move operation This works fine in Unix but I am not sure sleep works OK in Win32 since I had some problems in the past doing something similar with VB6. The timer would sometimes trigger at the same time the files were being copied and incomplete files were moved to the target directory. Can anybody suggest a different way of checking if the copy operation has been completed? Thanks, Levy Lazarre __________________________________________________ Do you Yahoo!? Yahoo! Mail Plus - Powerful. Affordable. Sign up now. http://mailplus.yahoo.com From jsc@rock-tnsc.com Fri Jan 31 00:48:01 2003 From: jsc@rock-tnsc.com (Jethro Cramp) Date: Fri Jan 31 00:48:01 2003 Subject: [Tutor] Renaming files In-Reply-To: <1043380228.22416.4.camel@blackbetty> References: <1043380228.22416.4.camel@blackbetty> Message-ID: <200301242209.23666.jsc@rock-tnsc.com> As an interesting aside. If you the characters after mp3 contained more than one period and you were sure that .mp3. (or even just mp3) appeared only once you could do something like this: >>> filename = "name.mp3.something.else" >>> stem = string.split(filename, "mp3", 1) >>> print stem ['name.', '.something.else'] >>> filename = stem[0]+"mp3" >>> print filename name.mp3 >>> Regards, Jethro From jay@jaydorsey.com Fri Jan 31 00:48:16 2003 From: jay@jaydorsey.com (Jay Dorsey) Date: Fri Jan 31 00:48:16 2003 Subject: [Tutor] Very basic help In-Reply-To: <000101c2c4b4$9f8ab420$b789cecf@VAIO> References: <000101c2c4b4$9f8ab420$b789cecf@VAIO> Message-ID: <3E330D5B.5000803@jaydorsey.com> The first thing I see you need to fix is the references to your imported functions from the overtimemod module. In your 9-20.py file, since you imported overtimemod (instead of "from overtimemod import *" - which you wouldn't want to do now anyways since you call one of your variables the same name as one of the functions from yoru module - "overtime"), you need to prefix all of your function calls with the name of the module (overtimemod.) See below for an example. You may want to check your functions as well - I ran the program after I made the changes below, but the results didn't look correct (I'm no math major though). Hope this helps, jay >#Problem 9-20 >import overtimemod >rate = float(input("Enter your hourly wage\n")) >time = float(input("Enter number of hours straight time worked\n")) >overtime = float(input("Enter number of over time hours worked\n")) >multiplier = float(input("Enter your over time multiplier\n")) > >x = overtimemod.overtime(rate,multiplier) >y = overtimemod.gross(overtime,rate) >z = overtimemod.wage(time,rate) >print "Your straight wage is",z >print "Your overtime is",x >print "Your gross pay is",y > > From mjcluster@earthlink.net Fri Jan 31 00:48:35 2003 From: mjcluster@earthlink.net (Mike Cluster) Date: Fri Jan 31 00:48:35 2003 Subject: [Tutor] can't run script Message-ID: <004b01c2c724$0931bd80$9b29b73f@MichaelCluster> This is a multi-part message in MIME format. ------=_NextPart_000_0048_01C2C6E0.F8AA9CE0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable I am new to both programming and python, but I've been able to work in = interactive mode and make some progress. However I am unable to save and "run = script"- every time I try I get an "invalid syntax" error message. None of the = tutorials seem to address this or anticipate it as a problem.????????????? mike ------=_NextPart_000_0048_01C2C6E0.F8AA9CE0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
 
I am new to both programming and = python, but=20 I've been able to work in interactive
mode and make some progress. However = I am unable=20 to save and "run script"-
every time I try I get an = "invalid=20 syntax" error message. None of the tutorials
seem to address this or anticipate = it as a=20 problem.?????????????
mike
------=_NextPart_000_0048_01C2C6E0.F8AA9CE0-- From Alberto.Mantovani@bologna.marelli.it Fri Jan 31 00:48:51 2003 From: Alberto.Mantovani@bologna.marelli.it (Mantovani Alberto) Date: Fri Jan 31 00:48:51 2003 Subject: [Tutor] pythonwin Message-ID: <098A62EB12AED611B60000D0B723F98E0512E9@exbologna.bologna.marelli.it> Hi, working with Pythonwin I've noted that if you launch a script a first time and then you modify and relaunch it, the script that goes in ecxecution is alwais the first one that you launch. To execute the modify script you have to exit and to enter from pythonwin. This could be annoying, so my question is: 1) Is there some method or some script to avoid this? I have found the manner to delete the module if it is imported with but not if it is imported with . 2) Is it possible to run automatically a my python script when I launch the pythonwin? If this was possible I could, at the start, to save all module imported in pythonwin () and when I want to clear the namespace to delete the new module imported best regards Mantovani Alberto Magneti Marelli Powertrain S.p.A. Software Testing Dept. Via del Timavo, 33 - 40134 Bologna (ITALY) Tel.: +39 051 615 7152 Fax.: +39 051 617 7782 Alberto.Mantovani@bologna.marelli.it From dyoo@hkn.eecs.berkeley.edu Fri Jan 31 00:59:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Jan 31 00:59:01 2003 Subject: [Tutor] Re: you may regret that comment Magnus!! [Word attachments == bad] In-Reply-To: <5.1.0.14.0.20030131014117.02c090f0@www.thinkware.se> Message-ID: On Fri, 31 Jan 2003, Magnus Lycka wrote: > Hi, it seems your mail didn't reach the mailing list. > I don't know if the Word attachment caused rejection, > or if the subject line triggered some flame-war > filter! ;) Hello! Mailman automatically caught it and prompted the admins to take a look. Mic, I had to reject the post because it was way too large. To get around this, you may just want to do a cut-and-paste of the code directly into the email, so that it appears in the body of the post. There's one major problem with sending code as a Microsoft Word attachment: 1. It's Word. *grin* But seriously speaking, this limits your audience to people who are running on a system that has Microsoft Word. It excludes people who are running on systems that don't have Word installed. There's also the matter of the attachment being much too large to send to the list. But the major problem is compatibility: we want to allow people to see your question in as widespread a way as possible, and Word is not a good medium from a compatibility standpoint. Plain text is a better medium, so let's use that instead. Just wanted to give a straight explanation why your post hadn't appeared on Tutor. Sorry about the inconvenience! From dyoo@hkn.eecs.berkeley.edu Fri Jan 31 01:04:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Jan 31 01:04:02 2003 Subject: [Tutor] can't run script In-Reply-To: <004b01c2c724$0931bd80$9b29b73f@MichaelCluster> Message-ID: On Tue, 28 Jan 2003, Mike Cluster wrote: > I am new to both programming and python, but I've been able to work in > interactive mode and make some progress. However I am unable to save and > "run script"- every time I try I get an "invalid syntax" error message. Hi Mike, When Python says "Invalid syntax", it means that the program doesn't quite know what to make of it. *grin* But don't worry; that's what we're here for. We need to see what you've typed to better understand the problem. Can you cut and paste your program and send it to the Tutor list? You can copy it directly into the email body: we can take a look and see what's going on. Also, there should have been a few lines of error message right above the "Invalid syntax" part --- can you send those lines over as well? > None of the tutorials seem to address this or anticipate it as a > problem.????????????? mike I wrote a tutorial on IDLE that does mention that SyntaxErrors can happen: http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/ As you learn more of the language, syntax errors will be easier to figure out. Since you're new to the language, please feel free to show us on the Tutor list; we'll be happy to interpret the errors for you. Good luck! From dyoo@hkn.eecs.berkeley.edu Fri Jan 31 01:08:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Jan 31 01:08:02 2003 Subject: [Tutor] cellular automaton In-Reply-To: <3E39B3CC.9000508@aon.at> Message-ID: On Fri, 31 Jan 2003, Gregor Lingl wrote: > Mic Forster schrieb: > > >Does anyone have ready access to a cellular automaton script in Python? > >I have a script in Basic but not Python. Thanks for any help..... > > > > > Are you interested in a small "Lifegame"-script? Or are you searching > for something more general or more elaborated? Hi Mic, A while back, I did write a small program that simulated "Rule 100" of one of Steven Wolfram's cellular automata. Here's a link to that message: http://mail.python.org/pipermail/tutor/2002-September/017256.html I think it's a cute script; it's probably a bit longer than it needs to be, but it should be fairly easy to read. Does this help? Best of wishes to you! From micforster@yahoo.com Fri Jan 31 01:29:02 2003 From: micforster@yahoo.com (Mic Forster) Date: Fri Jan 31 01:29:02 2003 Subject: [Tutor] cellular automaton In-Reply-To: Message-ID: <20030131062808.52899.qmail@web13402.mail.yahoo.com> yes that's the sort of thing I'm after. perhaps i'll also grab a copy of Wolfram's book....been meaning to for a while now --- Danny Yoo wrote: > > > On Fri, 31 Jan 2003, Gregor Lingl wrote: > > > Mic Forster schrieb: > > > > >Does anyone have ready access to a cellular > automaton script in Python? > > >I have a script in Basic but not Python. Thanks > for any help..... > > > > > > > > Are you interested in a small "Lifegame"-script? > Or are you searching > > for something more general or more elaborated? > > Hi Mic, > > A while back, I did write a small program that > simulated "Rule 100" of one > of Steven Wolfram's cellular automata. Here's a > link to that message: > > > http://mail.python.org/pipermail/tutor/2002-September/017256.html > > I think it's a cute script; it's probably a bit > longer than it needs to > be, but it should be fairly easy to read. Does this > help? > > > Best of wishes to you! > __________________________________________________ Do you Yahoo!? Yahoo! Mail Plus - Powerful. Affordable. Sign up now. http://mailplus.yahoo.com From dyoo@hkn.eecs.berkeley.edu Fri Jan 31 03:55:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Jan 31 03:55:01 2003 Subject: [Tutor] can't run script (fwd) Message-ID: Hi Mike, (side note: when you reply, make sure tutor@python.org is also in the reply; that way, even if I get mauled by a large rat, you'll still have a good chance of getting answers from the rest of the group) Let's look at the code you attached: ### code Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. IDLE 0.8 -- press F1 for help print "hello world" print "Here are 10 numbers" for i in range(10): print i print "I'm done" ### And here's the error message you sent me: ### File "C:\Python22\hello128.py", line 1 Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 ^ SyntaxError: invalid syntax ### Ah ha! You'll need to drop the first few lines there from your program. Those lines, """ Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. IDLE 0.8 -- press F1 for help """ are part of the "greeting" that Python gives you when it starts up: they are not actual program lines. That's why Python's pointing to the first greeting line: it's saying "these are not program statements." If you clean up your program, it should look like: ### print "hello world" print "Here are 10 numbers" for i in range(10): print i print "I'm done" ### Try that; you should get better results with it. Hope this helps! ---------- Forwarded message ---------- Date: Fri, 31 Jan 2003 00:20:37 -0800 From: Mike Cluster To: Danny Yoo Subject: Re: [Tutor] can't run script Danny, Thanks for answering. Here are the files. mike -----Original Message----- From: Danny Yoo To: Mike Cluster Cc: tutor@python.org Date: Thursday, January 30, 2003 10:03 PM Subject: Re: [Tutor] can't run script > > >On Tue, 28 Jan 2003, Mike Cluster wrote: > >> I am new to both programming and python, but I've been able to work in >> interactive mode and make some progress. However I am unable to save and >> "run script"- every time I try I get an "invalid syntax" error message. > >Hi Mike, > >When Python says "Invalid syntax", it means that the program doesn't quite >know what to make of it. *grin* But don't worry; that's what we're here >for. > > >We need to see what you've typed to better understand the problem. Can >you cut and paste your program and send it to the Tutor list? You can >copy it directly into the email body: we can take a look and see what's >going on. Also, there should have been a few lines of error message right >above the "Invalid syntax" part --- can you send those lines over as well? > > >> None of the tutorials seem to address this or anticipate it as a >> problem.????????????? mike > >I wrote a tutorial on IDLE that does mention that SyntaxErrors can >happen: > > http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/ > >As you learn more of the language, syntax errors will be easier to figure >out. Since you're new to the language, please feel free to show us on the >Tutor list; we'll be happy to interpret the errors for you. > > >Good luck! > From charlie@begeistert.org Fri Jan 31 04:08:03 2003 From: charlie@begeistert.org (Charlie Clark) Date: Fri Jan 31 04:08:03 2003 Subject: [Tutor] re: Checking e-mail addresses In-Reply-To: <20030131054835.24881.64741.Mailman@mail.python.org> References: <20030131054835.24881.64741.Mailman@mail.python.org> Message-ID: <20030131100734.689.2@.1044002776.fake> On 2003-01-31 at 06:48:35 [+0100], tutor-request@python.org wrote: > You have to keep on mind that:=20 >=20 > - E-mail validation is NOT a trivial matter=20 I know but they do help. I'm tidying up a list of addresses for a=20 newsletter and there are lots of typos and things in there - over a=20 thousand invalid addresses so anything that helps is good. I used to run=20 the system myself and manually correct addresses or remove them when they=20 bounced but that was a few years ago... =20 > If you are in mood for a chuckle, see the 'pure' regexp solution=20 > (compliant with now obsolete RFC822): >=20 > http://www.foad.org/~abigail/Perl/url3.regex aaagh! I'm allergic to perl wow. It's amazing how "perverted" people's brains can get. That looks like=20 compiled code! =20 > If 'almost there' (good enough) is what would please you, you can have a=20 > look at this JScript: >=20 > http://www.interclasse.com/scripts/EMailValidatorCLS.php Thanx, I've looked at it briefly. I think it would take *me* a long time to=20 transpose it to Python. If we could take this off-list and you could help=20 me I'll make and release the Python version. =20 > that I've done some time ago, before 'seeing the light' (discovering=20 > Python). The same thing can be done in Python better and closer to the=20 > specs, but I do not think that effort in this direction is worthwhile=20 > after all. I think this is a moot point. I like to catch errors as early as possible=20 providing the work required to do this isn't enuff to get you me a PhD=20 (actually I'd need a BSc beforehand ;-). Catching typos can be very useful=20 and I would guess a good solution will catch over 90% of most addresses=20 which works for me. Charlei --=20 Charlie Clark Helmholtzstr. 20 D=FCsseldorf D- 40215 Tel: +49-211-938-5360 From charlie@begeistert.org Fri Jan 31 04:40:14 2003 From: charlie@begeistert.org (Charlie Clark) Date: Fri Jan 31 04:40:14 2003 Subject: [Tutor] Checking telephone numbers: re or strings Message-ID: <20030131103945.821.5@.1044002776.fake> Dear list, I've got a list of telphone numbers for SMS delivery and have a similar problem as with my e-mail list: there's a lot of junk it which I've got to try and tidy up. One of the problems is that the numbers are international access codes, country codes, network codes and number all rolled into one, ie: numbers = ['+491787826226', '1721545662', '001745648324'] I've managed to "normalise" the numbers and remove the "+", "++" and "00" at the beginning and I would like to identify and remove the country access code so it can be stored separately. Given a list of the country codes: access ={'America':'1', 'Germany':'49', 'Ireland':'353'....} what is the best way of checking to see if a country code is there and removing it? I've come up with two different approaches to this and would like to hear comments and possibly alternatives. The first one attempts to build up a country code from the start of the phone number and compare this with the list of values in the codes dictionary. for number in numbers: access = codes.values() code = "" for i in range(4): if number[:i] in access: number = number[i:] code = number[:i] break store(number, code) # store is a call to a database the other approach checks for a match of an access code at the beginning of a number import re for number in numbers: for code in codes: if re.search("^" + code, number): number = re.sub("^" + code, "", number) break else: code = "" store(number, code) Apart from the fact that I'm not very sure if the regular expression is correct this is definitely more processor intensive as possibly all of the codes have to be tried on each number before exiting. I also wasn't sure as to whether to use "break" or not: this takes me out of the current loop, doesn't it? Charlie From dyoo@hkn.eecs.berkeley.edu Fri Jan 31 05:08:28 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Jan 31 05:08:28 2003 Subject: [Tutor] Checking telephone numbers: re or strings In-Reply-To: <20030131103945.821.5@.1044002776.fake> Message-ID: On Fri, 31 Jan 2003, Charlie Clark wrote: > I've got a list of telphone numbers for SMS delivery and have a similar > problem as with my e-mail list: there's a lot of junk it which I've got > to try and tidy up. One of the problems is that the numbers are > international access codes, country codes, network codes and number all > rolled into one, ie: > > numbers = ['+491787826226', '1721545662', '001745648324'] > > I've managed to "normalise" the numbers and remove the "+", "++" and > "00" at the beginning and I would like to identify and remove the > country access code so it can be stored separately. > > Given a list of the country codes: > access ={'America':'1', 'Germany':'49', 'Ireland':'353'....} > what is the best way of checking to see if a country code is there and > removing it? Hi Charlie, Out of curiosity, is it ever possible for two country codes to "conflict"? That is, is it ever possible that something like this might happen? access = {'America':'1', ..., 'Pythonia' : '123'} Just wondering. > I've come up with two different approaches to this and would like to > hear comments and possibly alternatives. > > The first one attempts to build up a country code from the start of the > phone number and compare this with the list of values in the codes > dictionary. > > for number in numbers: > access = codes.values() > code = "" > for i in range(4): > if number[:i] in access: > number = number[i:] > code = number[:i] > break > store(number, code) # store is a call to a database This works. We can speed things up slightly. We don't actually need to do: access = codes.values() because, in recent versions of Python, it's perfectly ok to check for things inside dictionaries by using 'in': ### >>> digits = {'zero': 0, 'one':1, 'two':2, 'three' : 3, 'four':4, ... 'five': 5, 'six':6, 'seven':7, 'eight':8, 'nine':9} >>> 'zero' in digits 1 >>> 'twenty' in digits 0 ### and the lookup check for key membership is much faster than scanning for membership in a list. In your code, 'access' is a dictionary that maps countries to their respective country codes. If you make a reversed map --- that is, country codes to countries --- you may find parts of your program easier to do. > the other approach checks for a match of an access code at the beginning of > a number > > import re > > for number in numbers: > for code in codes: > if re.search("^" + code, number): > number = re.sub("^" + code, "", number) > break > else: > code = "" > store(number, code) > > > Apart from the fact that I'm not very sure if the regular expression is > correct this is definitely more processor intensive as possibly all of > the codes have to be tried on each number before exiting. Yes, the loop might be a bit expensive. However, we can improve the situation: what about constructing a large regular expression out of all those country codes? ### >>> prefixes = ['1', '49', '353'] >>> import re >>> pattern = re.compile('|'.join(prefixes)) >>> >>> numbers = ['491787826226', '1721545662', '001745648324'] >>> for n in numbers: ... print n, pattern.match(n).group(0) ... 491787826226 49 1721545662 1 001745648324 Traceback (most recent call last): File "", line 2, in ? AttributeError: 'NoneType' object has no attribute 'group' ### Ok, the last one didn't work out because the regular expression didn't match against '001745648324', but that's a situation we can properly detect, if we write a little more code. I think this approach --- compiling a regular expression at runtime --- should still be pretty darn fast, since we avoid doing loops over individual regular expressions. There are other techniques we can use to make this go even faster, but let's see how far the standard regular expressions can take us. From dyoo@hkn.eecs.berkeley.edu Fri Jan 31 05:18:39 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Jan 31 05:18:39 2003 Subject: [Tutor] re: Checking e-mail addresses [Mailman and email validation] In-Reply-To: <20030131100734.689.2@.1044002776.fake> Message-ID: [about writing a email address validator] > If we could take this off-list and you could help me I'll make and > release the Python version. Hi Charlie, I know that there's got to be something in Mailman, the Mailing List Manager, http://www.list.org/ that must do some initial validation of email addresses: Mailman has a utility that allows for a batch of users to become subscribed (it's 'bin/addmembers'), and in the process of mass subscription, Mailman culls out a list of addresses that are definitely "wrong". If you have the Mailman source code handly, you can take a look at 'Mailman/Utils.py:ValidateEmail'. The responsible code is actually quite short, but it does weird stuff. (os.path.join()? What is THAT doing in there? *grin*) Here's what it looks like on a system of mine: ### _badchars = re.compile('[][()<>|;^,]') def ValidateEmail(str): """Verify that the an email address isn't grossly invalid.""" # Pretty minimal, cheesy check. We could do better... if not str: raise Errors.MMBadEmailError if _badchars.search(str) or str[0] == '-': raise Errors.MMHostileAddress if string.find(str, '/') <> -1 and \ os.path.isdir(os.path.split(str)[0]): # then raise Errors.MMHostileAddress user, domain_parts = ParseEmail(str) # this means local, unqualified addresses, are no allowed if not domain_parts: raise Errors.MMBadEmailError if len(domain_parts) < 2: raise Errors.MMBadEmailError ### But they know that it's a hack: they even say that they should do better! So if you write an improved version of an email validator, the Mailman folks should be very interested in it. *grin* Good luck! From fredm@smartypantsco.com Fri Jan 31 05:19:02 2003 From: fredm@smartypantsco.com (Alfred Milgrom) Date: Fri Jan 31 05:19:02 2003 Subject: [Tutor] Checking a file size before moving it In-Reply-To: <20030131051457.3280.qmail@web40411.mail.yahoo.com> Message-ID: <5.1.0.14.0.20030131210503.00a92830@192.168.1.1> OK - I note that no-one has ventured any suggestions, so here is a start from someone who knows nothing about file systems! I assume that there is no simple way to tell if a file is being accessed. One suggestion would be to look at the timestamp. Since you sweep every 15 minutes, ignore ay files that have been created since the last sweep, but transfer only those files that were created more than 15 minutes earlier. Another suggestion might be to copy the files rather than moving them, and at the end of the operation check whether the size of the files is the same. If yes, you can remove the file from Directory A. I'm sure there's a better way out there than waiting 10 seconds! HTH, Fred Milgrom At 09:14 PM 30/01/03 -0800, you wrote: >Hello to all, > >I am writing a Python script that is intended to move >some files from directory A to directory B on a >server. Users copy the files to directory A once >daily. The Python script is triggered by a scheduler >and sweeps the directory for the files every 15 >minutes. Obviously, I need to check that a file has >been completely written before attempting to move it. >On the Unix platform, I use the following scheme to >ascertain that a file is no longer being written: > >stat the file and get its size(size1) >sleep for 10 seconds >stat the file again and get its size(size2) >if size2 == size1 proceed with the move operation > >This works fine in Unix but I am not sure sleep works >OK in Win32 since I had some problems in the past >doing something similar with VB6. The timer would >sometimes trigger at the same time the files were >being >copied and incomplete files were moved to the target >directory. > >Can anybody suggest a different way of checking if the >copy operation has been completed? > >Thanks, >Levy Lazarre From charlie@begeistert.org Fri Jan 31 05:21:02 2003 From: charlie@begeistert.org (Charlie Clark) Date: Fri Jan 31 05:21:02 2003 Subject: [Tutor] Checking telephone numbers: re or strings In-Reply-To: References: Message-ID: <20030131111914.1084.6@.1044002776.fake> > Hi Charlie, >=20 > Out of curiosity, is it ever possible for two country codes to=20 > "conflict"? That is, is it ever possible that something like this might=20 > happen? >=20 > access =3D {'America':'1', ..., 'Pythonia' : '123'} >=20 > Just wondering. apparently not because this might cause an error when dialling the number +1-234-712-4667 may be a valid number in North America for all I know but=20 it would rooted to Pythonia. So we don't have to worry about that problem. =20 > This works. We can speed things up slightly. We don't actually need to=20 > do: >=20 > access =3D codes.values() >=20 > because, in recent versions of Python, it's perfectly ok to check for=20 > things inside dictionaries by using 'in': mm, I've heard of this. Which version did it come in? I've kind of got used=20 to the explicit calls to keys(), values() and items() =20 > ### > >>> digits =3D {'zero': 0, 'one':1, 'two':2, 'three' : 3, 'four':4, > ... 'five': 5, 'six':6, 'seven':7, 'eight':8, 'nine':9} > >>> 'zero' in digits > 1 > >>> 'twenty' in digits > 0 > ### >=20 > and the lookup check for key membership is much faster than scanning for=20 > membership in a list.=20 agreed > In your code, 'access' is a dictionary that maps countries to their=20 > respective country codes. If you make a reversed map --- that is,=20 > country codes to countries --- you may find parts of your program easier=20 > to do. Yes, I know. It's constructed from the database where the numbers are=20 stored as numbers but as I have convert them into a string for the match I=20 can use them as keys. =20 > Yes, the loop might be a bit expensive. However, we can improve the=20 > situation: what about constructing a large regular expression out of all=20 > those country codes? Good idea! What about it? ;-) Lack of experience. =20 > ### > >>> prefixes =3D ['1', '49', '353'] > >>> import re > >>> pattern =3D re.compile('|'.join(prefixes)) > >>> > >>> numbers =3D ['491787826226', '1721545662', '001745648324'] for n in=20 > >>> numbers: > ... print n, pattern.match(n).group(0) > ... > 491787826226 49 > 1721545662 1 > 001745648324 > Traceback (most recent call last): > File "", line 2, in ? > AttributeError: 'NoneType' object has no attribute 'group' ### =20 > Ok, the last one didn't work out because the regular expression didn't=20 > match against '001745648324', but that's a situation we can properly=20 > detect, if we write a little more code. Yes, that was the raw list. I've already written something to detect the=20 "00" at the beginning as this is just an access code for international=20 dialling outside of North America. However, there will be other cases of=20 none matches which means I need to catch those errors and give them an=20 empty code. =20 > I think this approach --- compiling a regular expression at runtime ---=20 > should still be pretty darn fast, since we avoid doing loops over=20 > individual regular expressions. Sounds good to me. I'll give a try. =20 > There are other techniques we can use to make this go even faster, but=20 > let's see how far the standard regular expressions can take us. No need to over-optimise! There are only a couple of thousand numbers. If=20 my expensive loop method only takes a minute. Thanx for helping me understand re's a bit better! Charlie --=20 Charlie Clark Helmholtzstr. 20 D=FCsseldorf D- 40215 Tel: +49-211-938-5360 From charlie@begeistert.org Fri Jan 31 05:36:03 2003 From: charlie@begeistert.org (Charlie Clark) Date: Fri Jan 31 05:36:03 2003 Subject: [Tutor] Checking telephone numbers: re or strings In-Reply-To: References: Message-ID: <20030131113509.1191.7@.1044002776.fake> On 2003-01-31 at 11:05:14 [+0100], Danny Yoo wrote: > Ok, the last one didn't work out because the regular expression didn't=20 > match against '001745648324', but that's a situation we can properly=20 > detect, if we write a little more code. >=20 >=20 > I think this approach --- compiling a regular expression at runtime ---=20 > should still be pretty darn fast, since we avoid doing loops over=20 > individual regular expressions. >=20 > There are other techniques we can use to make this go even faster, but=20 > let's see how far the standard regular expressions can take us. So I've done the tests: string based solution =3D 3.94 secs regex based solution =3D 2.84 secs Thanx Danny! Charlie --=20 Charlie Clark Helmholtzstr. 20 D=FCsseldorf D- 40215 Tel: +49-211-938-5360 From charlie@begeistert.org Fri Jan 31 05:45:02 2003 From: charlie@begeistert.org (Charlie Clark) Date: Fri Jan 31 05:45:02 2003 Subject: [Tutor] re: Checking e-mail addresses [Mailman and email validation] In-Reply-To: References: Message-ID: <20030131114447.1276.8@.1044002776.fake> On 2003-01-31 at 11:17:46 [+0100], Danny Yoo wrote: > Here's what it looks like on a system of mine: > > ### > _badchars = re.compile('[][()<>|;^,]') cound you explain this? the characters [, ], (, ), <, > are not allowed? neither are ";" and ","? > def ValidateEmail(str): > """Verify that the an email address isn't grossly invalid.""" # > Pretty minimal, cheesy check. We could do better... if not str: > raise Errors.MMBadEmailError > if _badchars.search(str) or str[0] == '-': > raise Errors.MMHostileAddress > if string.find(str, '/') <> -1 and \ > os.path.isdir(os.path.split(str)[0]): > # then > raise Errors.MMHostileAddress > user, domain_parts = ParseEmail(str) > # this means local, unqualified addresses, are no allowed if not > domain_parts: > raise Errors.MMBadEmailError > if len(domain_parts) < 2: > raise Errors.MMBadEmailError > ### > But they know that it's a hack: they even say that they should do better! > So if you write an improved version of an email validator, the Mailman > folks should be very interested in it. *grin* It's an awful hack - even I can understand it! But thanx for the tip. I'm already trying to contact them re. InterfaceTemplate but the dev list is moderated. I'll give it a try! As Branimir has already pointed out it's probably impossible to have a completely reliable solution but making a list with probable errors can make life a lot easier. Charlie From blackmariah@shmups.com Fri Jan 31 05:54:01 2003 From: blackmariah@shmups.com (Michael Miller) Date: Fri Jan 31 05:54:01 2003 Subject: [Tutor] Getting hex value of pixels In-Reply-To: <200301242209.23666.jsc@rock-tnsc.com> References: <1043380228.22416.4.camel@blackbetty> <200301242209.23666.jsc@rock-tnsc.com> Message-ID: <200301310451.14329.blackmariah@shmups.com> I'm using PIL to build an ASCII art generator. Silly, but I'm learning here. ;) It will take an input image, get the value of each pixel, then output an HTML file with random characters that have the color of each pixel. Sorry if that doesn't make much sense. I need to get the hexadecimal value of each pixel's color, but I'm having no luck doing so. hex() returns normal hexadecimal numbers, not those used for HTML colors (of course). The getpixel() method of PIL returns the RGB values. How can I go about getting the hex value of each pixel's color? Thanks in advance. Michael From alan.gauld@bt.com Fri Jan 31 06:00:10 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri Jan 31 06:00:10 2003 Subject: [Tutor] can't run script Message-ID: <7497DCA1C240C042B28F6657ADFD8E097023A0@i2km11-ukbr.domain1.systemhost.net> This message is in MIME format. Since your mail reader does not understand this format, some or all of this message may not be legible. ------_=_NextPart_001_01C2C917.94F04400 Content-Type: text/plain; charset="iso-8859-1" You don't say how you are saving your script, but it sounds like you are trying to save an interactive session in IDLE as a script? You can't do that because it will include all the >>> prompts etc. You need to create the script in a new window(File->New) and save from there. This is covered (briefly) in my tutorial and also in Danny's intro to IDLE. Same principle applies if you use Pythonwin. Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ PS A nice enhancement to both IDEs would be a "Save As Script" feature for the shell windows... -----Original Message----- From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of Mike Cluster Sent: 28 January 2003 23:22 To: tutor@python.org Subject: [Tutor] can't run script I am new to both programming and python, but I've been able to work in interactive mode and make some progress. However I am unable to save and "run script"- every time I try I get an "invalid syntax" error message. None of the tutorials seem to address this or anticipate it as a problem.????????????? mike ------_=_NextPart_001_01C2C917.94F04400 Content-Type: text/html; charset="iso-8859-1"
You don't say how you are saving your script, but it sounds like you are trying
to save an interactive session in IDLE as a script? You can't do that because
it will include all the >>> prompts etc.
 
You need to create the script in a new window(File->New) and save from there.
 
This is covered (briefly) in my tutorial and also in Danny's intro to IDLE.
 
Same principle applies if you use Pythonwin.
 
Alan g.
Author of the Learn to Program website
http://www.freenetpages.co.uk/hp/alan.gauld/
 
PS
A nice enhancement to both IDEs would be a "Save As Script" feature for the shell windows...
-----Original Message-----
From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of Mike Cluster
Sent: 28 January 2003 23:22
To: tutor@python.org
Subject: [Tutor] can't run script

 
I am new to both programming and python, but I've been able to work in interactive
mode and make some progress. However I am unable to save and "run script"-
every time I try I get an "invalid syntax" error message. None of the tutorials
seem to address this or anticipate it as a problem.?????????????
mike
------_=_NextPart_001_01C2C917.94F04400-- From alan.gauld@bt.com Fri Jan 31 06:02:02 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri Jan 31 06:02:02 2003 Subject: [Tutor] Checking a file size before moving it Message-ID: <7497DCA1C240C042B28F6657ADFD8E097023A1@i2km11-ukbr.domain1.systemhost.net> > On the Unix platform, I use the following scheme to > ascertain that a file is no longer being written: > > stat the file and get its size(size1) > sleep for 10 seconds > stat the file again and get its size(size2) > if size2 == size1 proceed with the move operation I'm pretty sure theres a better way that doesn't involve sleep at all, but I can't think what it is right now! > This works fine in Unix but I am not sure sleep works > OK in Win32 since I had some problems in the past > doing something similar with VB6. sleep() works OK, it doesn't use the Win32 timer event mechanism that VB uses. > Can anybody suggest a different way of checking if the > copy operation has been completed? I'm thinking about it :-) Alan g From =?ISO-8859-1?B?YW50b25tdWhpbiDt4CByYW1ibGVyLnJ1?= Fri Jan 31 06:08:11 2003 From: =?ISO-8859-1?B?YW50b25tdWhpbiDt4CByYW1ibGVyLnJ1?= (=?ISO-8859-1?B?YW50b25tdWhpbiDt4CByYW1ibGVyLnJ1?=) Date: Fri Jan 31 06:08:11 2003 Subject: [Tutor] can't run script In-Reply-To: <004b01c2c724$0931bd80$9b29b73f@MichaelCluster> References: <004b01c2c724$0931bd80$9b29b73f@MichaelCluster> Message-ID: <374569370.20030131140733@rambler.ru> Hello Mike, Wednesday, January 29, 2003, 2:21:46 AM, you wrote: MC> I am new to both programming and python, but I've been able to work in interactive MC> mode and make some progress. However I am unable to save and "run script"- MC> every time I try I get an "invalid syntax" error message. None of the tutorials MC> seem to address this or anticipate it as a problem.????????????? MC> mike Take a look at saved file: you should find a lot of >>> there. They are prompts of interpreter and lead to syntax error of Python. Several examples: In interpreter: >>> a = 0 0 >>> print a + 1 1 In .py a = 0 print a + 1 HTH -- Best regards, antonmuhin mailto:antonmuhin@rambler.ru From magnus@thinkware.se Fri Jan 31 07:40:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Fri Jan 31 07:40:02 2003 Subject: [Tutor] Getting hex value of pixels In-Reply-To: <200301310451.14329.blackmariah@shmups.com> References: <200301242209.23666.jsc@rock-tnsc.com> <1043380228.22416.4.camel@blackbetty> <200301242209.23666.jsc@rock-tnsc.com> Message-ID: <5.1.0.14.0.20030131132854.02c79d78@www.thinkware.se> At 04:51 2003-01-31 -0500, Michael Miller wrote: >... output an >HTML file with random characters that have the color of each pixel. Sorry if >that doesn't make much sense. I need to get the hexadecimal value of each >pixel's color, but I'm having no luck doing so. hex() returns normal >hexadecimal numbers, not those used for HTML colors (of course). The >getpixel() method of PIL returns the RGB values. How can I go about getting >the hex value of each pixel's color? Hex values aren't different than decimal values, they are just presented differently... I guess you want something like this: >>> "#%02X%02X%02X" % (55, 200, 255) '#37C8FF' I'm assuming you have a tuple with (red, green, blue)... -- 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 blackmariah@shmups.com Fri Jan 31 07:57:01 2003 From: blackmariah@shmups.com (Michael Miller) Date: Fri Jan 31 07:57:01 2003 Subject: [Tutor] Getting hex value of pixels In-Reply-To: <5.1.0.14.0.20030131132854.02c79d78@www.thinkware.se> References: <200301242209.23666.jsc@rock-tnsc.com> <5.1.0.14.0.20030131132854.02c79d78@www.thinkware.se> Message-ID: <200301310653.34012.blackmariah@shmups.com> > Hex values aren't different than decimal values, they are just > presented differently... I guess you want something like this: > >>> "#%02X%02X%02X" % (55, 200, 255) > > '#37C8FF' > Okay, now would you mind explaining how that works? LOL Messing with it I see that just using "%02X" % (55) produces the expected output of 37. What is "%02X" doing, anyway? Thanks a lot for helping out. From magnus@thinkware.se Fri Jan 31 08:12:03 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Fri Jan 31 08:12:03 2003 Subject: [Tutor] Getting hex value of pixels In-Reply-To: <200301310653.34012.blackmariah@shmups.com> References: <5.1.0.14.0.20030131132854.02c79d78@www.thinkware.se> <200301242209.23666.jsc@rock-tnsc.com> <5.1.0.14.0.20030131132854.02c79d78@www.thinkware.se> Message-ID: <5.1.0.14.0.20030131140049.02d593a8@www.thinkware.se> At 06:53 2003-01-31 -0500, Michael Miller wrote: >Okay, now would you mind explaining how that works? LOL Messing with it I see >that just using "%02X" % (55) produces the expected output of 37. What is >"%02X" doing, anyway? Thanks a lot for helping out. I guess I need to put this in my sig... Read the Library reference chapter 2 every so often... http://www.python.org/doc/current/lib/builtin.html In this case, specifically http://www.python.org/doc/current/lib/typesseq-strings.html I'm sure someone else can point to tutorials that explain this with more examples. In short: % => Now comes a formatting instruction 0 => Fill up with zeroes 2 => Use two positions X => show as heXadecimal with capital A-F. -- 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@thinkware.se Fri Jan 31 08:18:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Fri Jan 31 08:18:01 2003 Subject: [Tutor] pythonwin In-Reply-To: <098A62EB12AED611B60000D0B723F98E0512E9@exbologna.bologna.m arelli.it> Message-ID: <5.1.0.14.0.20030131141107.02d56048@www.thinkware.se> At 15:45 2003-01-29 +0100, Mantovani Alberto wrote: >Hi, >working with Pythonwin I've noted that if you launch a script a first time >and then you modify and relaunch it, the script that goes in ecxecution is >alwais the first one that you launch. To execute the modify script you have >to exit and to enter from pythonwin. This could be annoying, so my >question is: > >1) Is there some method or some script to avoid this? import X ... reload(X) >I have found the manner to delete the module if it is imported with >but not if it is imported with . Yet another reason to avoid the from...syntax. You may find that nothing beats the command line in the end. COMMAND.COM stinks, but with a better OS, you might find the command line very useful. CMD.EXE (in NT and derivates) is already much better, just enable tab completion. It's not as good as unix shells of cource. But they are available for Windows too... You can even survive with COMMAND.COM if you have to, as long as you run DOSKEY /I before you start working... -- 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 blackmariah@shmups.com Fri Jan 31 08:25:03 2003 From: blackmariah@shmups.com (Michael Miller) Date: Fri Jan 31 08:25:03 2003 Subject: [Tutor] Getting hex value of pixels In-Reply-To: <5.1.0.14.0.20030131140049.02d593a8@www.thinkware.se> References: <5.1.0.14.0.20030131132854.02c79d78@www.thinkware.se> <5.1.0.14.0.20030131140049.02d593a8@www.thinkware.se> Message-ID: <200301310720.35365.blackmariah@shmups.com> On Friday 31 January 2003 08:09 am, Magnus Lycka wrote: > I guess I need to put this in my sig... > > Read the Library reference chapter 2 every so often... > http://www.python.org/doc/current/lib/builtin.html > > In this case, specifically > http://www.python.org/doc/current/lib/typesseq-strings.html > > I'm sure someone else can point to tutorials that explain this > with more examples. > > In short: > % => Now comes a formatting instruction > 0 => Fill up with zeroes > 2 => Use two positions > X => show as heXadecimal with capital A-F. Even if you did put it in your sig, it wouldn't have helped me much. If it wasn't for your short explanation there I wouldn't understand anything on that page. But since you included it, everything makes sense. Thanks a lot for all the help again. Michael Miller From magnus@thinkware.se Fri Jan 31 08:29:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Fri Jan 31 08:29:01 2003 Subject: [Tutor] Checking a file size before moving it In-Reply-To: <5.1.0.14.0.20030131210503.00a92830@192.168.1.1> References: <20030131051457.3280.qmail@web40411.mail.yahoo.com> Message-ID: <5.1.0.14.0.20030131134013.02ce9938@www.thinkware.se> At 21:15 2003-01-31 +1000, Alfred Milgrom wrote: >Another suggestion might be to copy the files rather than moving them, and >at the end of the operation check whether the size of the files is the >same. If yes, you can remove the file from Directory A. I think both this and the sleep version might cause lost data if the computer system is slow. Why don't you just try to open the file? At least in Win2000 you get an IOError if you try to open a file that it being written. I assume that something like opening in append more would yield an error in any OS, if open in read while writing is permitted. something like: for fn in glob.glob('*'): try: f = file(fn) f.close() however_you_do_the_copying except IOError: print fn, 'is busy?' See also http://www.python.org/doc/current/lib/os-fd-ops.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 alan.gauld@bt.com Fri Jan 31 08:58:09 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri Jan 31 08:58:09 2003 Subject: [Tutor] Checking a file size before moving it Message-ID: <7497DCA1C240C042B28F6657ADFD8E0974DAA9@i2km11-ukbr.domain1.systemhost.net> > I assume that there is no simple way to tell if a file is > being accessed. OK, I'm at work now with access to my Unix books... The fcntl function allows you to get a lock. If the file is already locked you get that lock back. Within the lock structure you can read the user and process IDs. If they aint your own then the file is already locked by another user 0- and you know which one! Itrs a wee bit of processing but you can wrap it as a function easily enough and it will be much faster than 10 seconds! The good news is that there is an fcntl module in Python (which uses the FCNTL module to define the needed constants). F_GETLK is one of these and the function apparently returns a flock structure...which I can't see the definition of... The C definition is a struct: struct { short l_type; short l_whence; short l_start; short l_len; short l_sysid; short l_pid; } >From previous practice I'd guess in Python its a tuple with the same set of values in the same order... The bad news is that fcntl only seems to exist in Unix. For Windows you probably can find something similar in Mark Hammonds win32 stuff... But you need to hunt the Win32 docs for that I'm afraid. Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From python@jaydorsey.com Fri Jan 31 12:30:18 2003 From: python@jaydorsey.com (Jay Dorsey) Date: Fri Jan 31 12:30:18 2003 Subject: [Tutor] Running a process/script as another user Message-ID: <3E3AB232.2040504@jaydorsey.com> I have a python script that I"m executing via cgi. the process that exceutes the script doesn't have access to do what I need it to do (automate some CVS tasks). Is there anyway to switch to a differnet non-root user so I can execute these commands as the user with the proper permissions (using os.system())? This is on a *nix box. Any help or pointers would be appreciated. jay From dman@dman.ddts.net Fri Jan 31 15:02:22 2003 From: dman@dman.ddts.net (Derrick 'dman' Hudson) Date: Fri Jan 31 15:02:22 2003 Subject: [Tutor] Re: Running a process/script as another user In-Reply-To: <3E3AB232.2040504@jaydorsey.com> References: <3E3AB232.2040504@jaydorsey.com> Message-ID: <20030131200007.GA26497@dman.ddts.net> --2fHTh5uZTiUOsy+g Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Fri, Jan 31, 2003 at 12:28:18PM -0500, Jay Dorsey wrote: | I have a python script that I"m executing via cgi. the process that=20 | exceutes the script doesn't have access to do what I need it to do=20 | (automate some CVS tasks). I recommend using suexec. It will run the cgi script as you, instead of as the web server's uid. | Is there anyway to switch to a differnet=20 | non-root user so I can execute these commands as the user with the=20 | proper permissions (using os.system())? This is on a *nix box. setuid(), seteuid(). (probably in the os module) Watch out for security holes in your script! -D --=20 How to shoot yourself in the foot with Java: =20 You find that Microsoft and Sun have released incompatible class libraries both implementing Gun objects. You then find that although there are plenty of feet objects implemented in the past in many other languages, you cannot get access to one. But seeing as Java is so cool, you don't care and go around shooting anything else you can find. (written by Mark Hammond) =20 http://dman.ddts.net/~dman/ --2fHTh5uZTiUOsy+g Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAj461ccACgkQO8l8XBKTpRRPYwCfTAo2qqDZVMukoJ4e9xfjzAHj vO4AoIwytuC+deiy8XwOPO6V6ZycZ2/9 =xDXC -----END PGP SIGNATURE----- --2fHTh5uZTiUOsy+g--