From dyoo@hkn.eecs.berkeley.edu Fri Nov 1 03:18:01 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Nov 1 03:18:01 2002 Subject: [Tutor] How to use Numeric / where's the documentation? In-Reply-To: <000901c28133$53c17de0$f2937ad5@oemcomputer> Message-ID: [forwarding back to tutor] On Thu, 31 Oct 2002, Alex Gillis wrote: > > Yes, thankyou very much, hopefully one day I'll be able to answer > > other people's questions and repay the tutor list. No problem! If you see a question that you'd like to comment on or answer, just charge ahead; there's no certification required. *grin* > Where do you find out info like this, I can look in the libraries to > find what functions are available and a short description of what they > do. The "Numeric" module is an outside extension of Python, so its documentation isn't known by IDLE, nor by the standard library documentation at: http://python.org/doc/lib However, there's good news: the Numeric Python page itself has a pretty good tutorial that you can browse through. Here it is: http://www.pfdubois.com/numpy/html2/numpy.html There's also some built in help() that we can use in a snap; it's a little sparse, but if we're trying to remember what parameter a function takes in, the help() function is often useful. For example, try out: ### >>> help(Numeric.zeros) ### at the interactive prompt, and you should get some sligthly useful information from it. Another good one is: ### >>> help(Numeric) ### which gives an overview of the functions you can play with in Numeric Python. Numeric Python is meant to give Python some specialized matrix-handling features, similar to those of the Matlab programming language, so it may feel a little different from standard Python programming. Give it some time; there's just a few main functions and concepts in Numeric, and you should do fine. Also, if documentation isn't enough, you're always welcome to ask questions on the Tutor list; we'll be happy to listen to your questions. I hope this helps answer some of your questions. Good luck! From dyoo@hkn.eecs.berkeley.edu Fri Nov 1 03:30:02 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Nov 1 03:30:02 2002 Subject: [Tutor] Visiting a URL In-Reply-To: Message-ID: On Thu, 31 Oct 2002, John Abbe wrote: > I've got a newbie question -- i'm looking at altering PikiePikie to > notify weblogs.com when my weblog updates. I could get all involved in > XML-RPC, but it's doable through a plain URL. How do i visit a URL in > Python? Hi John, Do you mean retrieving the contents of the URL resource? If so, there's a nice module called 'urllib' that allows us to open URLs as if they were files. http://python.org/doc/lib/module-urllib.html There's an example near the bottom that you can try out, and if you have problems, please feel free to contact the Tutor list again. There's also a nice set of modules to take the "signature" of a string in an efficient way, so that, rather than having to save an exact snapshot of a page, you can just store a shorter signature, and do signature comparison to see if changes have occurred. Here's a link to one of these signature digest modules: http://python.org/doc/lib/module-hmac.html Hmmm... on second thought, using that hmac module might be overkill, but it's still useful to know that it exists. *grin* Good luck! From magnus@thinkware.se Fri Nov 1 05:49:08 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Fri Nov 1 05:49:08 2002 Subject: [Tutor] Re: compute class name In-Reply-To: References: <16449291856.20021031232657@publisher.de> Message-ID: <5.1.0.14.0.20021101114404.0314f3f0@www.thinkware.se> At 17:18 2002-10-31 -0800, Emile van Sebille wrote: >Ulrich Wisser: > > I would like to create new object instances, but compute the > > class name. Simple example > t = globals()[name]() This is certainly safer than to use eval() that I mentioned, at least if the string can be changed outside the control of the programmer. It's still not perfect though. Someone who could change the string could still be able to execute unexpected things defined in the global namespace. The best option might be to register the classes that are to be dynamically invoked in a dict, and to invoke them from that dict. >>> classDict = {} >>> class A: ... pass ... >>> class B: ... pass ... >>> for klass in [A, B]: ... classDict[klass.__name__] = klass ... >>> print classDict['A']() <__main__.A instance at 0x0165FE10> >>> print classDict['B']() <__main__.B instance at 0x00F2AA28> >>> print classDict['X']() Traceback (most recent call last): File "", line 1, in ? KeyError: X -- 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 fuad4python@yahoo.com Fri Nov 1 06:16:07 2002 From: fuad4python@yahoo.com (=?iso-8859-1?q?fuad=20python?=) Date: Fri Nov 1 06:16:07 2002 Subject: [Tutor] make python easy to use Message-ID: <20021101111551.45283.qmail@web10901.mail.yahoo.com> --0-1171653694-1036149351=:44540 Content-Type: text/plain; charset=iso-8859-1 Content-Transfer-Encoding: 8bit dear python-ers, i am a beginner even in python and in programming language. i had used python just for two weeks but i feel it is easier to learn than others. i am looking for any visual python in order to be able to use python more and more easier. anyone can help me please.....!!! __a beginner python__ --------------------------------- Get a bigger mailbox -- choose a size that fits your needs. --0-1171653694-1036149351=:44540 Content-Type: text/html; charset=iso-8859-1 Content-Transfer-Encoding: 8bit

dear python-ers,

i am a beginner even in python and in programming language. i had used python just for two weeks but i feel it is easier to learn than others. i am looking for any visual python in order to be able to use python more and more easier. anyone can help me please.....!!!

__a beginner python__



Get a bigger mailbox -- choose a size that fits your needs.
--0-1171653694-1036149351=:44540-- From fuad4python@yahoo.com Fri Nov 1 06:24:02 2002 From: fuad4python@yahoo.com (=?iso-8859-1?q?fuad=5Ffor=5Fpython?=) Date: Fri Nov 1 06:24:02 2002 Subject: [Tutor] trigonometry in python Message-ID: <20021101112312.46202.qmail@web10901.mail.yahoo.com> --0-681955999-1036149792=:45794 Content-Type: text/plain; charset=iso-8859-1 Content-Transfer-Encoding: 8bit dear python-er, when i import math module to count the value of for example sin(30), why the value is not 0.5 ? i used this syntax : import math math.sin(30) the result value is not 0.5, what happened ? anyone can help me ? __a beginner python__ --------------------------------- Get a bigger mailbox -- choose a size that fits your needs. --0-681955999-1036149792=:45794 Content-Type: text/html; charset=iso-8859-1 Content-Transfer-Encoding: 8bit

dear python-er,

when i import math module to count the value of for example sin(30), why the value is not 0.5 ? i used this syntax :

import math

math.sin(30)

the result value is not 0.5, what happened ? anyone can help me ?

 

__a beginner python__



Get a bigger mailbox -- choose a size that fits your needs.
--0-681955999-1036149792=:45794-- From yduppen@xs4all.nl Fri Nov 1 07:23:01 2002 From: yduppen@xs4all.nl (Yigal Duppen) Date: Fri Nov 1 07:23:01 2002 Subject: [Tutor] trigonometry in python References: <20021101112312.46202.qmail@web10901.mail.yahoo.com> Message-ID: <007101c281a1$45d91e90$0d01a8c0@YDD> > when i import math module to count the value of for example sin(30), why the value is not 0.5 ? i used this syntax : > the result value is not 0.5, what happened ? anyone can help me ? Hi, There are two reasons you get a different value than you expected. The first is that there are two(*) ways to look at trig. You can count angles in degrees and you can count them in radians. The trig functions in math work in radians, not in degrees. So the correct approach is to first convert your angle in degrees to radians. >>> def toRadians(degrees): >>> return degrees * ((2 * math.pi) / 360) ... >>> math.sin(toRadians(30)) 0.49999999999999994 Much better! However, we're still not getting 0.5 This is where the second reason comes into play. As you might know, there is an infinite amount of real numbers. However, due to computer constraints there is only a limited amount of real numbers that can be represented on a computer. Therefore, Python often gives you an /approximation/ of the correct value. I hope this helps. YDD -- http://yduppen.xs4all.nl From yduppen@xs4all.nl Fri Nov 1 07:30:02 2002 From: yduppen@xs4all.nl (Yigal Duppen) Date: Fri Nov 1 07:30:02 2002 Subject: [Tutor] trigonometry in python In-Reply-To: <007101c281a1$45d91e90$0d01a8c0@YDD> References: <20021101112312.46202.qmail@web10901.mail.yahoo.com> <007101c281a1$45d91e90$0d01a8c0@YDD> Message-ID: <200211011329.40936.yduppen@xs4all.nl> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 > The first is that there are two(*) ways to look at trig.=20 Forgot to expand the (*). *) Actually, there are more than two ways to look at trig. However, degre= es=20 and radians are the most common. YDD - --=20 http://www.xs4all.nl/~yduppen -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE9wnO0LsKMuCf5EdwRAon2AKCTyGT/R+RP2gzA8v7KMUKycDj24wCg8Ocv 5tx+abgtWYHXMvRs+mRLODI=3D =3DTP3I -----END PGP SIGNATURE----- From magnus@thinkware.se Fri Nov 1 07:40:02 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Fri Nov 1 07:40:02 2002 Subject: [Tutor] trigonometry in python In-Reply-To: <20021101112312.46202.qmail@web10901.mail.yahoo.com> Message-ID: <5.1.0.14.0.20021101133415.03153840@www.thinkware.se> At 11:23 2002-11-01 +0000, fuad_for_python wrote: >math.sin(30) > >the result value is not 0.5, what happened ? anyone can help me ? Beacause the trigonometric functions use the only sane measure for angles: radians. >>> import math >>> print math.sin(30/180.*math.pi) 0.5 This is not a python issue. I suggest you ask some mathematics teacher about the reasons for using radians. My personal opinion is that the use of degrees should be confined to navigation, and kept out of mathematics. ;) It's just like using inches and pounds instead of the metric system. You will have to use a lot of absurd constants in your calculations if you use degrees in any advanced mathematics. For instance, with radians, small values of an angle x will make x == sin(x) == tan(x) (almost). >>> x = 1e-6 >>> print math.sin(x) 1e-006 >>> print math.tan(x) 1e-006 This has all sorts of consequences on simplifying calculations. What's the derivate of atan(x) 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 magnus@thinkware.se Fri Nov 1 07:44:01 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Fri Nov 1 07:44:01 2002 Subject: [Tutor] trigonometry in python In-Reply-To: <007101c281a1$45d91e90$0d01a8c0@YDD> References: <20021101112312.46202.qmail@web10901.mail.yahoo.com> Message-ID: <5.1.0.14.0.20021101134645.030eab68@www.thinkware.se> At 13:21 2002-11-01 +0100, Yigal Duppen wrote: >The first is that there are two(*) ways to look at trig. You can count >angles in degrees and you can count them in radians. In other words, the wrong way and the right way! ;) >0.49999999999999994 > >Much better! > >However, we're still not getting 0.5 >This is where the second reason comes into play. As you might know, there is >an infinite amount of real numbers. However, due to computer constraints >there is only a limited amount of real numbers that can be represented on a >computer. Therefore, Python often gives you an /approximation/ of the >correct value. Using the "print" statement usually fixes this. For more about floating point problems, see the tutorial: http://www.python.org/doc/current/tut/node14.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 magnus@thinkware.se Fri Nov 1 07:49:02 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Fri Nov 1 07:49:02 2002 Subject: [Tutor] make python easy to use In-Reply-To: <20021101111551.45283.qmail@web10901.mail.yahoo.com> Message-ID: <5.1.0.14.0.20021101135029.03152ba0@www.thinkware.se> At 11:15 2002-11-01 +0000, fuad python wrote: >i am a beginner even in python and in programming language. i had used >python just for two weeks but i feel it is easier to learn than others. i >am looking for any visual python in order to be able to use python more >and more easier. anyone can help me please.....!!! I'm not sure you are after. What do you expect that this "Visual Python" would do? Help you write graphical user interfaces like Visual Basic? Indicate syntax errors and show what you could type after a . or ( ? What are you using today? -- 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 James.Alexander.McCarney@Cognicase.com Fri Nov 1 12:08:19 2002 From: James.Alexander.McCarney@Cognicase.com (McCarney, James Alexander) Date: Fri Nov 1 12:08:19 2002 Subject: [Tutor] make python easy to use Message-ID: <23FD7B1A77E8D211BCB900001D108C02023FCAB4@camelot> Hmm Visual Python... How about it Guido ? ;-) We could call it CheeseShop... It's very VERY runny, sir. . i >am looking for any visual python in order to be able to use python more >and more easier. anyone can help me please.....!!! From magnus@thinkware.se Fri Nov 1 12:52:02 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Fri Nov 1 12:52:02 2002 Subject: [Tutor] make python easy to use In-Reply-To: <23FD7B1A77E8D211BCB900001D108C02023FCAB4@camelot> Message-ID: <5.1.0.14.0.20021101185603.02a0a728@www.thinkware.se> At 12:07 2002-11-01 -0500, McCarney, James Alexander wrote: >Hmm Visual Python... How about it Guido ? ;-) We could call it CheeseShop... >It's very VERY runny, sir. Activestate has a Python plugin for Visual Studio .NET called Visual Python. See http://www.activestate.com/Products/Visual_Python/?_x=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 dyoo@hkn.eecs.berkeley.edu Fri Nov 1 14:21:01 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Nov 1 14:21:01 2002 Subject: [Tutor] make python easy to use In-Reply-To: <5.1.0.14.0.20021101135029.03152ba0@www.thinkware.se> Message-ID: > >i am a beginner even in python and in programming language. i had used > >python just for two weeks but i feel it is easier to learn than others. > >i am looking for any visual python in order to be able to use python > >more and more easier. anyone can help me please.....!!! Hi Fuad, By "visual", I'm assuming that you're looking for a gui-building tool, something like Microsoft's Visual Basic. A "visual" interface is not necessarily easier to learn; there are times when text interfaces are more appropriate for a task. It might actually be an advantage not to use such a visual tool, so that you can concentrate more on how the language itself works. That being said, there are some nice visually-oriented tools that you might find useful. Pythoncard is one of the main projects that try to make GUI building simple: http://pythoncard.sourceforge.net/ I'd still recommend, though, getting a more concrete feeling for the Python language itself before using these tools; I think PythonCard's graphical tools assume that the user already has some basic Python knowledge. Perhaps someone can correct me on this one? Good luck! From Bryan.Weingarten@watchguard.com Fri Nov 1 14:49:03 2002 From: Bryan.Weingarten@watchguard.com (Bryan Weingarten) Date: Fri Nov 1 14:49:03 2002 Subject: [Tutor] X_OK Message-ID: <7381838783da528be503f1ddd72e725d3dc2da82@watchguard.com> 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_01C281DF.7B42F130 Content-Type: text/plain; charset="iso-8859-1" can someone please explain to me why import os os.access('C:\WINNT\notepad.exe', os.X_OK) always return a 0 on a windows executable file? i thought this was a cross-platform function. i was expecting a 1 on windows. now i have to guard this function with "if not windows" logic. thanks, bryan ------_=_NextPart_001_01C281DF.7B42F130 Content-Type: text/html; charset="iso-8859-1"
can someone please explain to me why
 
import os
os.access('C:\WINNT\notepad.exe', os.X_OK)
 
always return a 0 on a windows executable file?  i thought this was a cross-platform function.  i was expecting a 1 on windows.  now i have to guard this function with "if not windows" logic.
 
thanks,
 
bryan
------_=_NextPart_001_01C281DF.7B42F130-- From alan.gauld@bt.com Fri Nov 1 16:49:02 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri Nov 1 16:49:02 2002 Subject: [Tutor] trigonometry in python Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C9F3@mbtlipnt02.btlabs.bt.co.uk> 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_01C281F0.11DBD930 Content-Type: text/plain; charset="iso-8859-1" > when i import math module to count the value of for example sin(30), why the value is not 0.5 ? Pytho, in common with most programming languages uses radians for the angle not degrees. To convert degrees to radians multiply by pi/180 So 30 degrees = pi/6 radians. The constant value of pi can be found in the math module: import math angle = (30 * math.PI)/180 print math.sin(angle) Alan G ------_=_NextPart_001_01C281F0.11DBD930 Content-Type: text/html; charset="iso-8859-1"
 >  when i import math module to count the value of for example sin(30), why the value is not 0.5 ?  
 
Pytho, in common with most programming languages uses radians for the
angle not degrees. To convert degrees to radians multiply by pi/180
 
So 30 degrees = pi/6 radians.
 
The constant value of pi can be found in the math module:
 
import math
angle = (30 * math.PI)/180
print math.sin(angle)
 
Alan G
------_=_NextPart_001_01C281F0.11DBD930-- From ramrom@earthling.net Fri Nov 1 17:33:03 2002 From: ramrom@earthling.net (Bob Gailer) Date: Fri Nov 1 17:33:03 2002 Subject: [Tutor] X_OK In-Reply-To: <7381838783da528be503f1ddd72e725d3dc2da82@watchguard.com> Message-ID: <5.1.0.14.0.20021101153012.03ad7ef0@66.28.54.253> --=====================_18998728==_.ALT Content-Type: text/plain; charset="us-ascii"; format=flowed At 11:47 AM 11/1/2002 -0800, Bryan Weingarten wrote: >can someone please explain to me why > >import os >os.access('C:\WINNT\notepad.exe', os.X_OK) > >always return a 0 on a windows executable file? Try os.access('C:\\WINNT\\notepad.exe', os.X_OK) Remember that a single \ in a string literal is an escape character. It takes \\ to represent \. Bob Gailer 170 Forsythe Rd Nederland CO 80466 303-442-2625 --=====================_18998728==_.ALT Content-Type: text/html; charset="us-ascii" At 11:47 AM 11/1/2002 -0800, Bryan Weingarten wrote:

can someone please explain to me why
 
import os
os.access('C:\WINNT\notepad.exe', os.X_OK)
 
always return a 0 on a windows executable file? 

Try os.access('C:\\WINNT\\notepad.exe', os.X_OK)

Remember that a single \ in a string literal is an escape character. It takes \\ to represent \.

Bob Gailer
170 Forsythe Rd
Nederland CO 80466
303-442-2625 --=====================_18998728==_.ALT-- From idiot1@netzero.net Sat Nov 2 00:29:02 2002 From: idiot1@netzero.net (Kirk Bailey) Date: Sat Nov 2 00:29:02 2002 Subject: [Tutor] password request form Message-ID: <3DC3627C.C27D7B0F@netzero.net> Working on a password reminder service for list owners. http://www.tinylist.org/cgi-bin/TLpassword1.py first part works, I'm working on second script. it's due for release with 1.6.0, with a few other goodies. List creation and deletion on the web is also on the back burner, simmering nicely. When done, it will be a complete list service in a can, all web administered. Hmmm, should I include banner rotation features for the web management pages? hmmm... Discussion? -- end Respectfully, Kirk D Bailey +---------------------"Thou Art Free." -Eris-----------------------+ | http://www.howlermonkey.net mailto:highprimate@howlermonkey.net | | KILL spam dead! http://www.scambusters.org/stopspam/#Pledge | | http://www.tinylist.org +--------+ mailto:grumpy@tinylist.org | +------------------Thinking| NORMAL |Thinking----------------------+ +--------+ --------------------------------------------- Introducing NetZero Long Distance 1st month Free! Sign up today at: www.netzerolongdistance.com From emile@fenx.com Sat Nov 2 10:42:01 2002 From: emile@fenx.com (Emile van Sebille) Date: Sat Nov 2 10:42:01 2002 Subject: [Tutor] Re: pausing time and perform on exit References: <000a01c28142$a96c31e0$06e5a8ac@chuck> Message-ID: > Kyle Babich: > > Also how would I tell the program to do something when the program is > exited > > by having the window closed to the computer shut down (anything with > the > > user manually typing 'quit' into the program)? I don't even know > where to > > begin with this. This is even easier -- it's built in! ActivePython 2.2.1 Build 222 (ActiveState Corp.) based on Python 2.2.1 (#34, Apr 15 2002, 09:51:39) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import atexit >>> def myexitfunc():print 'inmyexittfunc' ... >>> atexit.register(myexitfunc) >>> ^Z inmyexittfunc F:\Python22> -- Emile van Sebille emile@fenx.com --------- From rob@zoism.org Sat Nov 2 11:52:02 2002 From: rob@zoism.org (Rob Brown-Bayliss) Date: Sat Nov 2 11:52:02 2002 Subject: [Tutor] should this cause a syntax error? Message-ID: <1036255924.9478.5.camel@caspian.everglade> Hi, I spent bout an hour scratching my head tryng to find why a class was misbehaving, then I found a typo. self.some_value == FALSE rather than the correct self.some_value = FALSE Shouldn't the first one have caused a syntax error as it was not in an if or while loop etc? -- * Rob Brown-Bayliss * ================= * zoism.org From johnca@ourpla.net Sat Nov 2 12:09:01 2002 From: johnca@ourpla.net (John Abbe) Date: Sat Nov 2 12:09:01 2002 Subject: [Tutor] Visiting a URL In-Reply-To: References: Message-ID: At 12:29 AM -0800 on 2002-11-01, Danny Yoo typed: >On Thu, 31 Oct 2002, John Abbe wrote: > > I've got a newbie question -- i'm looking at altering PikiePikie to >> notify weblogs.com when my weblog updates. I could get all involved in >> XML-RPC, but it's doable through a plain URL. How do i visit a URL in >> Python? > >Hi John, > >Do you mean retrieving the contents of the URL resource? If so, there's a >nice module called 'urllib' that allows us to open URLs as if they were >files. > > http://python.org/doc/lib/module-urllib.html Very cool. Thanks! Even that may be a little overkill. All i need to do is visit the URL; i don't need the response. On second thought, maybe not a bad idea to get the results and check for errors, but still curious. >There's also a nice set of modules to take the "signature" of a string in >an efficient way, so that, rather than having to save an exact snapshot of >a page, you can just store a shorter signature, and do signature >comparison to see if changes have occurred. Here's a link to one of these >signature digest modules: > > http://python.org/doc/lib/module-hmac.html > >Hmmm... on second thought, using that hmac module might be overkill, but >it's still useful to know that it exists. *grin* Thanks again -- although wouldn't using ETags or Last-Modified headers be more efficient? (i guess it counts on the server to do the right thing) 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://www.ourpla.net/john/ --Wes Nisker From magnus@thinkware.se Sat Nov 2 12:24:01 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Sat Nov 2 12:24:01 2002 Subject: [Tutor] should this cause a syntax error? In-Reply-To: <1036255924.9478.5.camel@caspian.everglade> Message-ID: <5.1.0.14.0.20021102181745.043a56b8@www.thinkware.se> At 05:52 2002-11-03 +1300, Rob Brown-Bayliss wrote: >self.some_value == FALSE >Shouldn't the first one have caused a syntax error as it was not in an >if or while loop etc? No, you are allowed to put expressions in your code, even if you don't take care of the return value. It's common that you don't care about the results of expressions. Not exactly _that_ expression maybe, but in other cases. Although, if self.some_value is an instance of a class that has implemented __eq__ or __cmp__ you might want to use a side effect but not care about return values in this case. Do you think it should be illegal to write: my_function(x, y) instead of return_value_I_dont_care_about = my_function(x, y) or should this be illegal: f1(x,y) or f2(x,y,z) The latter uses the lazy evaluation in Python to make sure that f2 is only called if f1 returns a value which is equivalent of false. But you might have intended: x = f1(x,y) or f2(x,y,z) Where should Python draw the line? In the Computer Programming For Everybody (CP4E) project, Guido had planned different language levels in Python, where syntax which *could* be intentional but was probably a mistake would give syntax error. I don't know if your case would be an example of 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 emile@fenx.com Sat Nov 2 12:25:03 2002 From: emile@fenx.com (Emile van Sebille) Date: Sat Nov 2 12:25:03 2002 Subject: [Tutor] Re: should this cause a syntax error? References: <1036255924.9478.5.camel@caspian.everglade> Message-ID: Rob Brown-Bayliss: > self.some_value == FALSE > > rather than the correct > > self.some_value = FALSE > > Shouldn't the first one have caused a syntax error as it was not in an > if or while loop etc? > No. The result of the comparison was simply not bound. This might more commonly be found on a return line, and on a line by itself is certainly suspect. -- Emile van Sebille emile@fenx.com --------- From lumbricus@gmx.net Sat Nov 2 12:30:04 2002 From: lumbricus@gmx.net (lumbricus@gmx.net) Date: Sat Nov 2 12:30:04 2002 Subject: [Tutor] should this cause a syntax error? References: <1036255924.9478.5.camel@caspian.everglade> Message-ID: <1571.1036258153@www6.gmx.net> Hi! > Hi, I spent bout an hour scratching my head tryng to find why a class > was misbehaving, then I found a typo. > > self.some_value == FALSE > > rather than the correct > > self.some_value = FALSE > > Shouldn't the first one have caused a syntax error as it was not in an > if or while loop etc? Why should it? It is a correct expression (yet redundant) If you throw away its value it is your problem. Sometimes you do this intentionally, because you just need the side effect of a statement. HTH, J"o! -- Wir beschliessen etwas, stellen das dann in den Raum und warten dann einige Zeit ab, was passiert. Wenn es dann kein grosses Geschrei gibt und keine Aufstaende, weil die meisten gar nicht begreifen, was da beschlossen wurde, dann machen wir weiter - Schritt fuer Schritt, bis es kein Zurueck mehr gibt. -- J-C Juncker +++ 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 Sat Nov 2 14:06:09 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Sat Nov 2 14:06:09 2002 Subject: [Tutor] should this cause a syntax error? In-Reply-To: <1036255924.9478.5.camel@caspian.everglade> Message-ID: <5.1.0.14.0.20021102200752.02abb178@www.thinkware.se> At 05:52 2002-11-03 +1300, Rob Brown-Bayliss wrote: >Shouldn't the first one have caused a syntax error as it was not in an >if or while loop etc? Have you tried PyChecker? Maybe it would give a warning about such a construct. (If it doesn't, that could be a suggested feature.) There are certainly some unbound expressions that are normal, like lonely function calls, and perhaps expressions with and/or, but I suppose a lonely == will typically be an error. -- 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 rob@zoism.org Sat Nov 2 14:16:02 2002 From: rob@zoism.org (Rob Brown-Bayliss) Date: Sat Nov 2 14:16:02 2002 Subject: [Tutor] should this cause a syntax error? In-Reply-To: <5.1.0.14.0.20021102200752.02abb178@www.thinkware.se> References: <5.1.0.14.0.20021102200752.02abb178@www.thinkware.se> Message-ID: <1036264522.10165.5.camel@caspian.everglade> On Sun, 2002-11-03 at 08:10, Magnus Lycka wrote: > Have you tried PyChecker? Maybe it would give > a warning about such a construct. (If it doesn't, > that could be a suggested feature.) There are > certainly some unbound expressions that are > normal, like lonely function calls, and perhaps > expressions with and/or, but I suppose a lonely > == will typically be an error. No I a havn't tried it. I'm not really a fan of ides and things like that (but do like GUI builders). I have changed my text editor to highlight the == so that they now stand out a bit more. -- * Rob Brown-Bayliss * ================= * zoism.org From rnd@onego.ru Sat Nov 2 14:56:10 2002 From: rnd@onego.ru (Roman Suzi) Date: Sat Nov 2 14:56:10 2002 Subject: [Tutor] make python easy to use In-Reply-To: <20021101111551.45283.qmail@web10901.mail.yahoo.com> Message-ID: On Fri, 1 Nov 2002, [iso-8859-1] fuad python wrote: >dear python-ers, > >i am a beginner even in python and in programming language. i had used python >just for two weeks but i feel it is easier to learn than others. i am looking >for any visual python in order to be able to use python more and more easier. Hmmm... I know no way to PROGRAM easier than to write code in the text editor. Visual things are good for building GUI (graphical user interfaces). In other words, being a passenger is easier than driving. >anyone can help me please.....!!! > >__a beginner python__ > > > > >--------------------------------- >Get a bigger mailbox -- choose a size that fits your needs. > Sincerely yours, Roman Suzi -- rnd@onego.ru =\= My AI powered by Linux RedHat 7.3 From dyoo@hkn.eecs.berkeley.edu Sat Nov 2 17:18:02 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Nov 2 17:18:02 2002 Subject: [Tutor] should this cause a syntax error? [does pychecker work?] In-Reply-To: <1036264522.10165.5.camel@caspian.everglade> Message-ID: On 3 Nov 2002, Rob Brown-Bayliss wrote: > On Sun, 2002-11-03 at 08:10, Magnus Lycka wrote: > > > Have you tried PyChecker? Maybe it would give a warning about such a > > construct. (If it doesn't, that could be a suggested feature.) There > > are certainly some unbound expressions that are normal, like lonely > > function calls, and perhaps expressions with and/or, but I suppose a > > lonely == will typically be an error. > > No I a havn't tried it. I'm not really a fan of ides and things like > that (but do like GUI builders). I have changed my text editor to > highlight the == so that they now stand out a bit more. PyChecker is not an IDE, but a kind of source-code analysis that tries to pick out common Python mistakes. I'm personally curious to see what PyChecker will say on that '==' code. And bcause I've actually never used PyChecker before, this will be fun for me. *grin* Let's see what happens... ### dyoo@coffeetable:~$ cat test.py print "this is a test" 1 == 1 print "did something trigger?" dyoo@coffeetable:~$ pychecker test.py Processing test... this is a test did something trigger? Warnings... test.py:2: Statement appears to have no effect ### Wow! That's very nice! So yes, this PyChecker utility will point out suspicious looking code. We can grab PyChecker here: http://pychecker.sourceforge.net/ From shalehperry@attbi.com Sat Nov 2 17:48:01 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Sat Nov 2 17:48:01 2002 Subject: [Tutor] should this cause a syntax error? [does pychecker work?] In-Reply-To: References: Message-ID: <200211021446.33191.shalehperry@attbi.com> On Saturday 02 November 2002 14:16, Danny Yoo wrote: > > Warnings... > > test.py:2: Statement appears to have no effect > ### > > > Wow! That's very nice! So yes, this PyChecker utility will point out > suspicious looking code. We can grab PyChecker here: > > http://pychecker.sourceforge.net/ > and especially handy because this is as close to compile time checks as y= ou=20 can get. If that statement had been in a rarely used function who knows = how=20 long that bug could have survived. From arosado@softhome.net Sat Nov 2 19:25:02 2002 From: arosado@softhome.net (Andres Rosado) Date: Sat Nov 2 19:25:02 2002 Subject: [Tutor] Re: Killing Buttons! (in Tk) Message-ID: <5.1.0.14.0.20021102202702.00bfaca8@mail.softhome.net> At 12:00 PM 10/28/2002 -0500, you wrote: >Now that I have buttons created - and working, how do I get rid of them? >In the application, the buttons change based on the function. Do I just >destroy the widget? If so, how? Or do I have to disable and hide the >buttons? Anyone have an example?? widget.grid_forget() if you're using the grid layout. -- Andres Rosado Email: andresr@despammed.com ICQ: 66750646 Homepage: http://andres980.tripod.com/ What's the use of a good quotation if you can't change it? -- Dr. Who From graumann@its.caltech.edu Sat Nov 2 21:36:02 2002 From: graumann@its.caltech.edu (Johannes Graumann) Date: Sat Nov 2 21:36:02 2002 Subject: [Tutor] Directory operation: why so darn slow? In-Reply-To: <20021102170005.30773.36047.Mailman@mail.python.org> References: <20021102170005.30773.36047.Mailman@mail.python.org> Message-ID: <20021102183721.2110b114.graumann@its.caltech.edu> --=.BICYX0?v2xFmzg Content-Type: text/plain; charset=US-ASCII Content-Transfer-Encoding: 7bit Hello, I have a class that spits out a dictionary ('contrast.data()') and I have two major problems with it: 1) the operation represented by the snippet below is ridiculisly slow (didn't use to be - before I had a several level deep dictionary) - is there anything I can do about that? repres_filtered = {} for dataset in contrast.data()['conform'].keys(): seqcov_count = 0 for element in contrast.data()['conform'][dataset]['seqcov']: if re.match(r"\d+",element): seqcov_count = seqcov_count + 1 if not seqcov_count < repres: repres_filtered[dataset]=contrast.data()['conform'][dataset] 2) does the fact that the dictionary is created by the class imply that I can not change it (delete it)? I would prefer to do something like for dataset in contrast.data()['conform'].keys(): seqcov_count = 0 for element in contrast.data()['conform'][dataset]['seqcov']: if re.match(r"\d+",element): seqcov_count = seqcov_count + 1 if not seqcov_count < repres: del contrast.data()['conform'][dataset] Thanks for any hint! Joh --=.BICYX0?v2xFmzg Content-Type: application/pgp-signature -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.0 (GNU/Linux) iD8DBQE9xIv8JSKujSMUwjMRAuj8AKCcseQN7878SJRhEjBzKyZgRc96JwCaAkA0 nTwfPnEdx/aRuhYrn4BjwHA= =H52X -----END PGP SIGNATURE----- --=.BICYX0?v2xFmzg-- From mongo57a@comcast.net Sat Nov 2 21:37:04 2002 From: mongo57a@comcast.net (andy surany) Date: Sat Nov 2 21:37:04 2002 Subject: [Tutor] Re: Killing Buttons! (in Tk) Message-ID: <002c01c282e2$283cfae0$2502a8c0@emily.ewndsr01.nj.comcast.net> Thanks. I ended up using "destroy". -----Original Message----- From: Andres Rosado To: tutor@python.org Date: Saturday, November 02, 2002 7:25 PM Subject: [Tutor] Re: Killing Buttons! (in Tk) >At 12:00 PM 10/28/2002 -0500, you wrote: >>Now that I have buttons created - and working, how do I get rid of them? >>In the application, the buttons change based on the function. Do I just >>destroy the widget? If so, how? Or do I have to disable and hide the >>buttons? Anyone have an example?? > >widget.grid_forget() if you're using the grid layout. > > >-- >Andres Rosado >Email: andresr@despammed.com >ICQ: 66750646 >Homepage: http://andres980.tripod.com/ > >What's the use of a good quotation if you can't change it? > -- Dr. Who > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From Jmllr891@cs.com Sat Nov 2 21:38:02 2002 From: Jmllr891@cs.com (Jmllr891@cs.com) Date: Sat Nov 2 21:38:02 2002 Subject: [Tutor] Need Help with Pygame & Icons Message-ID: --part1_a5.2fc3a54a.2af5e5dd_boundary Content-Type: text/plain; charset="US-ASCII" Content-Transfer-Encoding: 7bit I need help with using my own custom icons when turning my Python scripts into Windows executables. I'm using Windows ME and so the build process doesn't use the icons I specify. Is there anything I can do OTHER than changing the icon to a shortcut to the .exe file? This method is insufficient. --part1_a5.2fc3a54a.2af5e5dd_boundary Content-Type: text/html; charset="US-ASCII" Content-Transfer-Encoding: 7bit I need help with using my own custom icons when turning my Python scripts into Windows executables. I'm using Windows ME and so the build process doesn't use the icons I specify. Is there anything I can do OTHER than changing the icon to a shortcut to the .exe file? This method is insufficient. --part1_a5.2fc3a54a.2af5e5dd_boundary-- From lbrannma@cablespeed.com Sat Nov 2 23:49:01 2002 From: lbrannma@cablespeed.com (Lance) Date: Sat Nov 2 23:49:01 2002 Subject: [Tutor] PYTHONPATH environment variable Message-ID: <000701c282f4$a0f13a70$3212eb42@MYNEWBOX> Hi All, I added a directory to the end of my PYTHONPATH environment variable (running on Windoze XP). When print sys.path, the added directory is not at the end. Instead the Python installation directory is at the end. My understanding is that Python looks for files in PYTHONPATH order. How can I put something at the end and ensure it will truly be at the end? Thanks, Lance From lbrannma@cablespeed.com Sun Nov 3 00:10:02 2002 From: lbrannma@cablespeed.com (Lance) Date: Sun Nov 3 00:10:02 2002 Subject: [Tutor] PYTHONSTARTUP in PythonWin Message-ID: <000b01c282f7$9fedf3e0$3212eb42@MYNEWBOX> Hi, I'm running a recent PythonWin. I set my PYTHONSTARTUP environment variable (Win XP) to c:\python22\startup.py. In startup.py I have three lines import os import sys os.chdir("c:\pythonfoo") PythonWin does not execute this file on startup. Any suggestions will be appreciated. Thanks, Lance From idiot1@netzero.net Sun Nov 3 00:37:02 2002 From: idiot1@netzero.net (Kirk Bailey) Date: Sun Nov 3 00:37:02 2002 Subject: [Tutor] password request form Message-ID: <3DC4B5FB.7E9CA1B9@netzero.net> ok, it works. TLpassword2.py is working. Tiny can now remind a list owner of their password, an important admin. feature. A list owner goes to TLpassword1.py ( http://www.tinylist.org/cgi-bin/TLpassword1.py ) and types the name of their list into the form, and clicks submit; TLpassword2.py receives this, scopes it out, and displays a results page- and sends a letter with the password to the owner of record for that list. There is no way for a person to change what address it goes to, the address is stored in the list's owner's file, along with their password. This will secure the next step, list creation/modification/deletion via the web. Now it is pretty useless to try it out, as only I would get the results letter sent, but if you just want to see the web pages, go ahead. This will be released in version 1.6.0 of TL. -- end Respectfully, Kirk D Bailey +---------------------"Thou Art Free." -Eris-----------------------+ | http://www.howlermonkey.net mailto:highprimate@howlermonkey.net | | KILL spam dead! http://www.scambusters.org/stopspam/#Pledge | | http://www.tinylist.org +--------+ mailto:grumpy@tinylist.org | +------------------Thinking| NORMAL |Thinking----------------------+ +--------+ --------------------------------------------- Introducing NetZero Long Distance 1st month Free! Sign up today at: www.netzerolongdistance.com From johnca@ourpla.net Sun Nov 3 01:39:02 2002 From: johnca@ourpla.net (John Abbe) Date: Sun Nov 3 01:39:02 2002 Subject: [Tutor] Sequential assignment to list subscripts Message-ID: Sequential assignment to integer variables works: >>> a, b=5, 6 >>> a 5 >>> b 6 Great. Can someone explain... >>> a=b=[0] >>> a [0] >>> b [0] >>> a[0], b[0] = 7, 8 >>> a [8] >>> b [8] ...why a[0] isn't equal to 7 ?!? (and more to the point, what the proper syntax would be?) 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://www.ourpla.net/john/ --Wes Nisker From shalehperry@attbi.com Sun Nov 3 01:55:02 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Sun Nov 3 01:55:02 2002 Subject: [Tutor] Sequential assignment to list subscripts In-Reply-To: References: Message-ID: <200211022253.37066.shalehperry@attbi.com> On Saturday 02 November 2002 22:41, John Abbe wrote: > Great. Can someone explain... > > >>> a=3Db=3D[0] > >>> a > > [0] > > >>> b > > [0] > > >>> a[0], b[0] =3D 7, 8 > >>> a > > [8] > > >>> b > > [8] > > ...why a[0] isn't equal to 7 ?!? > > (and more to the point, what the proper syntax would be?) > Your problem comes from how you defined a and b. What you really said was a =3D (b =3D [0]) which means 'a' gets assigned = a=20 reference to 'b' and thus changing one changes the other. This works tho= ugh: >>> a =3D [0] >>> b =3D [0] >>> a[0], b[0] =3D 7, 8 >>> print a [7] >>> print b [8] From johnca@ourpla.net Sun Nov 3 01:57:01 2002 From: johnca@ourpla.net (John Abbe) Date: Sun Nov 3 01:57:01 2002 Subject: [Tutor] Sequential assignment to list subscripts Message-ID: Found my own answer: At 10:41 PM -0800 on 2002-11-02, John Abbe typed: >Sequential assignment to integer variables works: > >>>> a, b=5, 6 >>>> a >5 >>>> b >6 > >Great. Can someone explain... > >>>> a=b=[0] Oops. That set a and b to refer to the same list in memory... >>>> a >[0] >>>> b >[0] >>>> a[0], b[0] = 7, 8 ...so a[0] = 7 sets that one list to [7], then b[0] = 8 sets it to [8]. >>>> a >[8] >>>> b >[8] > >...why a[0] isn't equal to 7 ?!? Because it refers to the same list that b[0] does. I'll get that referencing eventually. Is there a handy way set a bunch of variables to *copies* of the same thing? 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://www.ourpla.net/john/ --Wes Nisker From emile@fenx.com Sun Nov 3 02:33:01 2002 From: emile@fenx.com (Emile van Sebille) Date: Sun Nov 3 02:33:01 2002 Subject: [Tutor] Re: Directory operation: why so darn slow? References: <20021102170005.30773.36047.Mailman@mail.python.org> <20021102183721.2110b114.graumann@its.caltech.edu> Message-ID: Johannes Graumann: > 1) the operation represented by the snippet below is > ridiculisly slow (didn't use to be - before I had a several > level deep dictionary) - is there anything I can do about > that? It's hard to know exactly, but I'd suspect you're possibly in and out of the function contrast.data() alot in your loop, and seeing the impact of that overhead. See if the changes below help: > > repres_filtered = {} conform = contrast.data()['conform'] > for dataset in contrast.data()['conform.keys(): for dataset in conform.keys(): > seqcov_count = 0 > for element in contrast.data()['conform'][dataset]['seqcov']: for element in conform[dataset]['seqcov']: > if re.match(r"\d+",element): > seqcov_count = seqcov_count + 1 > if not seqcov_count < repres: > repres_filtered[dataset]=contrast.data()['conform'][dataset] repres_filtered[dataset]=conform[dataset] > In short, I don't know what contrast.data() has to do to return a dictionary, but I would guess you can structure things so it only has to do it once. > 2) does the fact that the dictionary is created by the class ...recreated, perhaps? > imply that I can not change it (delete it)? I would prefer > to do something like > > for dataset in contrast.data()['conform'].keys(): > seqcov_count = 0 > for element in contrast.data()['conform'][dataset]['seqcov']: > if re.match(r"\d+",element): > seqcov_count = seqcov_count + 1 > if not seqcov_count < repres: > del contrast.data()['conform'][dataset] > You'll probably find the answer to this one as well as you rework things. That dictionary probably wants to be an attribute of the class instance, and not a creation of a class method. HTH, -- Emile van Sebille emile@fenx.com --------- From dyoo@hkn.eecs.berkeley.edu Sun Nov 3 04:26:07 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Nov 3 04:26:07 2002 Subject: [Tutor] Need Help with Pygame & Icons In-Reply-To: Message-ID: On Sat, 2 Nov 2002 Jmllr891@cs.com wrote: > I need help with using my own custom icons when turning my Python > scripts into Windows executables. I'm using Windows ME and so the build > process doesn't use the icons I specify. Is there anything I can do > OTHER than changing the icon to a shortcut to the .exe file? This method > is insufficient. Hello! If we're using the py2exe to make executables out of your programs, we can use the '--icon' command line option to give our program an icon image. There's some more information on the py2exe web page about this: http://py2exe.sourceforge.net/ By the way, there's a great web page on pygame.org that talks about packaging windows executables: http://pygame.org/docs/tut/Executable.html Good luck to you! From magnus@thinkware.se Sun Nov 3 06:51:02 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Sun Nov 3 06:51:02 2002 Subject: [Tutor] PYTHONSTARTUP in PythonWin In-Reply-To: <000b01c282f7$9fedf3e0$3212eb42@MYNEWBOX> Message-ID: <5.1.0.14.0.20021103125500.043b18a0@www.thinkware.se> At 21:12 2002-11-02 -0800, Lance wrote: >I'm running a recent PythonWin. I set my PYTHONSTARTUP environment variable >(Win XP) to >c:\python22\startup.py. >PythonWin does not execute this file on startup. Any suggestions will be >appreciated. IIRC PYTHONSTARTUP is only used when you use python interactively, see the docs. Is this the problem? -- 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 Nov 3 06:54:01 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Sun Nov 3 06:54:01 2002 Subject: [Tutor] PYTHONPATH environment variable In-Reply-To: <000701c282f4$a0f13a70$3212eb42@MYNEWBOX> Message-ID: <5.1.0.14.0.20021103125704.02ac5cd0@www.thinkware.se> At 20:51 2002-11-02 -0800, Lance wrote: >Hi All, > >I added a directory to the end of my PYTHONPATH environment variable >(running on Windoze XP). When print sys.path, the added directory is not at >the end. Of course. If you add something to PYTHONPATH you want to be certain that this is really run. Then you want it first in sys.path. Otherwise it would be impossible to use PYTHONPATH to override default behaviour. >Instead the Python installation directory is at the end. My >understanding is that Python looks for files in PYTHONPATH order. How can I >put something at the end and ensure it will truly be at the end? import sys sys.path.append(directory) -- 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 Nov 3 07:21:08 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Sun Nov 3 07:21:08 2002 Subject: [Tutor] Sequential assignment to list subscripts In-Reply-To: Message-ID: <5.1.0.14.0.20021103130034.02b6be40@www.thinkware.se> At 22:41 2002-11-02 -0800, John Abbe wrote: >Great. Can someone explain... > >>>> a=b=[0] >>>> a >[0] >>>> b >[0] >>>> a[0], b[0] = 7, 8 >>>> a >[8] >>>> b >[8] > >...why a[0] isn't equal to 7 ?!? First of all: You can see a variable as a reference to an object, or if you prefer, one of perhaps many names for an object. Variables are typeless in python, and can be changed into referring to some new object. Objects on the other hand, are typed, and have all sorts of limitation to their behaviour. Some objects are mutable, i.e. they can be modified after creation, others are immuable. For instance, lists are mutable and strings and integers are mutable. >>> a = [1,2,3] >>> a [1, 2, 3] >>> a[1] = 'X' >>> a [1, 'X', 3] >>> a = "123" >>> a[1] = 'X' Traceback (most recent call last): File "", line 1, in ? TypeError: object doesn't support item assignment If you type a = b = 7 it will be the same thing as b = 7 # Let the variable 'b' refer to the integer object 7 a = b # Let the variable 'a' refer to the same object as # variable 'b' refers to Both a and b will refer to the integer object 7 until they are reassigned as in b = "Hello" Now a still points to the object 7, since that's where it's been pointing since "a = b" above. a, on the other hand, now points to the string object "Hello". If you write "a = b = [0]" you are telling Python to: 1. Create a list object. 2. Let the first position in the list object refer to the integer object 0. 3. Let the variable b refer to this list object. 4. Let the variable a also refer to this list object. If you would type b = something_else, a and b would no longer point to something else, but until you reassign a or b, they will always point to the same object, this list. As we said above, lists are mutable. "a[0] = 5" does NOT reassign a. It reassigns position 0 of the list that a refers to. This is the same list as b refers to. Thus the followint three lines of code are equivalent: a[0], b[0] = 5, 6 a[0], a[0] = 5, 6 b[0], b[0] = 5, 6 They both mean: First refer position 0 in our list to the integer 5, and then to the integer 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 kyle@sent.com Sun Nov 3 07:21:19 2002 From: kyle@sent.com (Kyle Babich) Date: Sun Nov 3 07:21:19 2002 Subject: [Tutor] pausing time and perform on exit References: <5.1.0.14.0.20021101023103.03245e18@www.thinkware.se> Message-ID: <000f01c28333$6d4d2be0$63c48cac@chuck> With pausing time I'm trying to be able to break time.sleep function with a keystroke, or something else simple, and then be able to continure sleeping the remaining time at a later point. I thought possibly with that while loop I put in my last e-mail the program could look for a keystroke after each second and if there is none it could continue sleeping. Thanks I've almost worked this out but I have one more question pertaining to this. How would I work it out so the exit function only runs at certain points in my program. I've tried using doing something like the following but I can't manage to get it to work at all: import atexit def LogExit(): if exit_func == 1: # do stuff else: pass atexit.register(LogExit) exit_func = 0 # stuff exit_func = 1 # more stuff exit_func = 0 How can I make it so that the exit function will only run if the program is exited at certain points during my program. Thank you, Kyle Babich From magnus@thinkware.se Sun Nov 3 07:30:01 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Sun Nov 3 07:30:01 2002 Subject: [Tutor] Sequential assignment to list subscripts In-Reply-To: Message-ID: <5.1.0.14.0.20021103133224.043b6810@www.thinkware.se> At 22:59 2002-11-02 -0800, John Abbe wrote: >Oops. That set a and b to refer to the same list in memory... Quite. Another example where people might make mistakes with this is in making 2D arrays. >>> a = [[0,0,0,0]]*4 >>> a [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] >>> a[2][3] = 1 >>> a [[0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1]] Oops. Probably not what you intended... -- 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 lbrannma@cablespeed.com Sun Nov 3 09:49:01 2002 From: lbrannma@cablespeed.com (Lance) Date: Sun Nov 3 09:49:01 2002 Subject: [Tutor] PYTHONSTARTUP in PythonWin References: <5.1.0.14.0.20021103125500.043b18a0@www.thinkware.se> Message-ID: <001601c28348$855b91d0$3212eb42@MYNEWBOX> Hi Magnus, Yes.. this is the problem. I'm using Python interactively and the startup file doesn't execute. Lance ----- Original Message ----- From: "Magnus Lycka" To: "Lance" Cc: Sent: Sunday, November 03, 2002 3:56 AM Subject: Re: [Tutor] PYTHONSTARTUP in PythonWin > At 21:12 2002-11-02 -0800, Lance wrote: > >I'm running a recent PythonWin. I set my PYTHONSTARTUP environment variable > >(Win XP) to > >c:\python22\startup.py. > > >PythonWin does not execute this file on startup. Any suggestions will be > >appreciated. > > IIRC PYTHONSTARTUP is only used when you use python interactively, > see the docs. Is this the problem? > > > -- > 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 emile@fenx.com Sun Nov 3 10:28:01 2002 From: emile@fenx.com (Emile van Sebille) Date: Sun Nov 3 10:28:01 2002 Subject: [Tutor] Re: pausing time and perform on exit References: <5.1.0.14.0.20021101023103.03245e18@www.thinkware.se> <000f01c28333$6d4d2be0$63c48cac@chuck> Message-ID: Kyle Babich: > How can I make it so that the exit function will only run if the program is > exited at certain points during my program. One way would be to pass a class instance through and set parameters indicating the current exit status. Making the instance callable allows it to be used as a function and passed to atexit.register, which upon exit, calls the instance where the current exitok status controls execution of the exitfunc. Then in your code, toggle the exitok status on and off to indicate if the exitfunc should be performed. import atexit class myExitControl: def __init__(self, func): self.exitok = 1 self.exitfunc = func def __call__(self, *args, **kwargs): if self.exitok: print 'processing exit code' self.exitfunc(*args, **kwargs) else: print 'bypassing exit code' def doAatexit(): print 'Processing exitfunc A' def doBatexit(): print 'Processing exitfunc B' def doCatexit(): print 'Processing exitfunc C' A_cleanup = myExitControl(doAatexit) B_cleanup = myExitControl(doBatexit) C_cleanup = myExitControl(doCatexit) atexit.register(A_cleanup) atexit.register(B_cleanup) atexit.register(C_cleanup) B_cleanup.exitok = 0 -- Emile van Sebille emile@fenx.com --------- From wheelcrdan@hotmail.com Sun Nov 3 13:10:02 2002 From: wheelcrdan@hotmail.com (Dan Dud) Date: Sun Nov 3 13:10:02 2002 Subject: [tutor] Do I need to have a strong math skills to program Message-ID: Hello everyone, Hope everyone weekend is going great. I working through the "how to think like a computer scientist" I'm stuck on the part which you have to define a hypotenuse triangle. I don't have a lot of math skills. Do I have to have a lot of math skills to be good at programming??? I've decided to skip that part and move on. I hope everyone weekend is going great and I'll talk to you all soon... Danny D _________________________________________________________________ Protect your PC - get McAfee.com VirusScan Online http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963 From shalehperry@attbi.com Sun Nov 3 13:21:00 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Sun Nov 3 13:21:00 2002 Subject: [tutor] Do I need to have a strong math skills to program In-Reply-To: References: Message-ID: <200211031019.22846.shalehperry@attbi.com> On Sunday 03 November 2002 10:08, Dan Dud wrote: > Hello everyone, > > Hope everyone weekend is going great. I working through the "how to thi= nk > like a computer scientist" I'm stuck on the part which you have to defi= ne a > hypotenuse triangle. I don't have a lot of math skills. Do I have to ha= ve a > lot of math skills to be good at programming??? I've decided to skip th= at > part and move on. I hope everyone weekend is going great and I'll talk = to > you all soon... > nah you do not need them. Lots of code never does more math than you nee= d to=20 balance a check book. However, lacking the math background does limit you from certain types of= =20 programming. It will come up from time to time. But for most things you= =20 will be fine. From cxd401@psu.edu Sun Nov 3 13:29:02 2002 From: cxd401@psu.edu (Chris Davidson) Date: Sun Nov 3 13:29:02 2002 Subject: [Tutor] Problems with for loops and information Message-ID: <1036348157.2987.3.camel@ShitStorm> Hello Tutor List, This is my first post, so if you see anything that I am not doing proper in this post, don't be afraid to yell at me. My question is on the basis of searching through a list of files and/or directories from os.listdir() The code I have right now is import os listDirectory = "/home/chris" for element in listDirectory: if os.path.isdir(element): print "Directory: %s " % element elif os.path.isfile(element): print "File: %s " % element That code will not get into the if/elif statement, my question is: Is this because i am going to through it with a for loop and it changes the data type to string and can't find out if it is a directory? or probably what I am thinking it is. I am missing an important part to make this work. This is not the final code, i am just trying to get the for loop to work so what I really want to do with the data will work. Thank you for your time everyone and thanks in advance for any help, Chris From fuad4python@yahoo.com Sun Nov 3 13:37:00 2002 From: fuad4python@yahoo.com (=?iso-8859-1?q?fuad=5Ffor=5Fpython?=) Date: Sun Nov 3 13:37:00 2002 Subject: [tutor] Do I need to have a strong math skills to program In-Reply-To: Message-ID: <20021103183611.95880.qmail@web10908.mail.yahoo.com> --0-1394597308-1036348571=:95703 Content-Type: text/plain; charset=iso-8859-1 Content-Transfer-Encoding: 8bit Dan Dud <wheelcrdan@hotmail.com> wrote: Hello everyone, Hope everyone weekend is going great. I working through the "how to think like a computer scientist" I'm stuck on the part which you have to define a hypotenuse triangle. I don't have a lot of math skills. Do I have to have a lot of math skills to be good at programming??? I've decided to skip that part and move on. I hope everyone weekend is going great and I'll talk to you all soon... Danny D in any programming language u have not to have lot of math skills. the things u need are algoritm and data structures. the combination between algoritm and data structures will help u to program any programming language. the math subjects u have to mastering are like basics operational mathematics such as additional, substraction, multiplication, etc and also logical mathematics. anyway math skills will help many things in programming, so if you have many times why not to learn mathematics deeper ? __a beginner in python__ --------------------------------- Get a bigger mailbox -- choose a size that fits your needs. --0-1394597308-1036348571=:95703 Content-Type: text/html; charset=iso-8859-1 Content-Transfer-Encoding: 8bit

  Dan Dud &lt;wheelcrdan@hotmail.com&gt; wrote:


Hello everyone,

Hope everyone weekend is going great. I working through the "how to think
like a computer scientist" I'm stuck on the part which you have to define a
hypotenuse triangle. I don't have a lot of math skills. Do I have to have a
lot of math skills to be good at programming??? I've decided to skip that
part and move on. I hope everyone weekend is going great and I'll talk to
you all soon...

Danny D

in any programming language u have not to have lot of math skills. the things u need are algoritm and data structures. the combination between algoritm and data structures will help u to program any programming language. the math subjects u have to mastering are like basics operational mathematics such as additional, substraction, multiplication, etc and also logical mathematics. anyway math skills will help many things in programming, so if you have many times why not to learn mathematics deeper ?

 



__a beginner in python__



Get a bigger mailbox -- choose a size that fits your needs.
--0-1394597308-1036348571=:95703-- From emile@fenx.com Sun Nov 3 14:18:01 2002 From: emile@fenx.com (Emile van Sebille) Date: Sun Nov 3 14:18:01 2002 Subject: [Tutor] Re: Problems with for loops and information References: <1036348157.2987.3.camel@ShitStorm> Message-ID: Chris Davidson: > import os > listDirectory = "/home/chris" > for element in listDirectory: this wants to be: for element in os.listdir(listDirectory): -- Emile van Sebille emile@fenx.com --------- From magnus@thinkware.se Sun Nov 3 16:41:01 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Sun Nov 3 16:41:01 2002 Subject: [tutor] Do I need to have a strong math skills to program In-Reply-To: <200211031019.22846.shalehperry@attbi.com> References: Message-ID: <5.1.0.14.0.20021103193902.043b6810@www.thinkware.se> At 10:19 2002-11-03 -0800, Sean 'Shaleh' Perry wrote: >On Sunday 03 November 2002 10:08, Dan Dud wrote: > > I don't have a lot of math skills. Do I have to have a > > lot of math skills to be good at programming??? > >nah you do not need them. Lots of code never does more math than you need to >balance a check book. We all have our strengths and weaknesses, and what we lack in one area we might make up for with some other ability. Some people are very smart, others are very hard working. Some work very carefully, making sure that they do everything right, others have an intuitive understanding for the broad picture... Some are very good at listening, and quickly understand what the problem they need to solve is, others don't write a lot of code, but are very good at using code that others have made, and combine them into very useful solutions. There are many ways to skin a cat... I'd like to write some things about mathematics though. I have studied some mathematics... I've got a M.Sc.E.E and initially worked with electronic design, mainly with digital design. Almost all of my university studies involved mathematics, and I did hairy stuff like the nasty differential equations in solving Maxwell's equations and all sorts of other electromagnetic fields problems. I studied mind-warping things like Galois Fields. (The guy who invented them was killed in a duel at the age of 21, in 1832. It took generations before other mathematicians understood what he had meant. It took even longer before people found a use for them.) The sad (?) fact was that even I didn't use much more mathematics than needed to balance a check book in my electronic design work! And the guys in the microwave department who were much more affected by the tricky maths worked much more with simple guidelines and intuition than with mathematics... They had also studied advanced maths for half a decade, and almost managed with +, -, * and /. So, is mathematics studies just a waste of time? No, I don't think so. Quite contrary. Not because you need to know just the things that the maths courses teach you, but because spending time solving mathematical problems / puzzles makes you a much better problem solver. It helps you understand complex systems. You learn to divide problems into pieces, solve one piece at a time and put it all together to arrive at a final solution. It often takes many years to figure out that this is actually what you learned when you thought that you were studying some obscure and pointless field of mathematics, but that's the conclusion I've arrived to, and I think many others see it the same way. Academic studies also helps you learn how to learn. In fact, some studies have shown that the primary skill people with educations like M.Sc. have aquired is the skill of learning. This is an excellent skill for programmers. For most of us, a very big part of our job is to understand a new field of life. To create good software, it's not enough to be able to program. We have to understand quite a bit of how the people who are going to use our software work. Often we need to understand aspects of their job that they didn't even knew existed. To write a good word- processor, you need to understand a lot about how a writer works. If you write a good statistics program you need to understand statistics. If you want to write a great accounting package you need to understand quite a bit about both the rules of accounting and how an accountant can work in a productive way. And so on... My experience is that in general the people I've worked with who did a good job as professional programmers had an engineering or mathematics background. Of course there are exceptions in both directions, but in general, I find that studying things like mathematics, physics and engineering will give you a very solid platform to understand the concepts of programming and to help you understand new problem spheres, and solve all the problems that will pop up. Anyone can get stuck now and then, but my experience of people who worked professionally as programmers but had a "softer" education, like "system science" or something like that, were both less aware of the theoretical and practical work made by others before them (and thus reinventing the wheel) at the same time less inventive (when there was an oportunity to really be creative) and usually poor trouble shooters as well. They were able to follow instructions, and could be very ambitious and casreful...but they rarely excelled. I'm generalizing of course. Then there are autodidacts that are awesome coders. But most of the time it turns out that they have studied quite a bit, even if they didn't go to school or bothered to "waste time" on a degree... So, while it's true that we rarely use advanced mathematics in software development (or in other fields of engineering) we do have a lot of use for the abilities to solve problems and to study and learn. Other relevant aspects for someone interested in programming can be found at http://www.tuxedo.org/~esr/faqs/hacker-howto.html I don't think reading Science Fiction is required to be a good programmer, that's more to understand the jargon of your peers, but Eric knows what he's talking about. -- 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 Nov 3 16:49:02 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Sun Nov 3 16:49:02 2002 Subject: [tutor] Do I need to have a strong math skills to program In-Reply-To: <20021103183611.95880.qmail@web10908.mail.yahoo.com> References: Message-ID: <5.1.0.14.0.20021103224747.02b69d70@www.thinkware.se> At 18:36 2002-11-03 +0000, fuad_for_python wrote: >>in any programming language u have not to have lot of math skills. the=20 >>things u need are algoritm and data structures. the combination between= =20 >>algoritm and data structures will help u to program any programming=20 >>language. the math subjects u have to mastering are like basics=20 >>operational mathematics such as additional, substraction, multiplicatio= n,=20 >>etc and also logical mathematics. anyway math skills will help many=20 >>things in programming, so if you have many times why not to learn=20 >>mathematics deeper ? Please read this other good text by Eric Raymond: http://www.tuxedo.org/~esr/faqs/smart-questions.html A quote: Write in clear, grammatical, correctly-spelled language We've found by experience that people who are careless and sloppy writers are usually also careless and sloppy at thinking and coding (often enough to bet on, anyway). Answering questions for careless and sloppy thinkers is not rewarding; we'd rather spend our time elsewhere. So expressing your question clearly and well is important. If you can't be bothered to do that, we can't be bothered to pay attention. Spend the extra effort to polish your language. It doesn't have to be stiff or formal =97 in fact, hacker culture values informal, slangy and humorous language used with precision. But it has to be precise; there has to be some indication that you're thinking and paying attention. Spell, punctuate, and capitalize correctly. Don't confuse "its" with "it's", "loose" with "lose", or "discrete" with "discreet". Don't TYPE IN ALL CAPS, this is read as shouting and considered rude. (All-smalls is only slightly less annoying, as it's difficult to read. Alan Cox can get away with it, but you can't.) More generally, if you write like a semi-literate boob you will very likely be ignored. Writing like a l33t script kiddie hax0r is the absolute kiss of death and guarantees you will receive nothing but stony silence (or, at best, a heaping helping of scorn and sarcasm) in return. If you are asking questions in a forum that does not use your native language, you will get a limited amount of slack for spelling and grammar errors =97 but no extra slack at all for laziness (and yes, we can usually spot that difference). Also, unless you know what your respondent's languages are, write in English. Busy hackers tend to simply flush questions in languages they don't understand, and English is the working language of the Internet. By writing in English you minimize your chances that your question will be discarded unread. --=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 lbrannma@cablespeed.com Sun Nov 3 17:27:02 2002 From: lbrannma@cablespeed.com (Lance) Date: Sun Nov 3 17:27:02 2002 Subject: [tutor] Do I need to have a strong math skills to program References: <5.1.0.14.0.20021103224747.02b69d70@www.thinkware.se> Message-ID: <004101c28388$971e4710$3212eb42@MYNEWBOX> Strong math skills and strong writing skills enhance programming efficiency. Both require clear structured thinking. ----- Original Message ----- From: "Magnus Lycka" To: "fuad_for_python" Cc: Sent: Sunday, November 03, 2002 1:55 PM Subject: Re: [tutor] Do I need to have a strong math skills to program At 18:36 2002-11-03 +0000, fuad_for_python wrote: >>in any programming language u have not to have lot of math skills. the >>things u need are algoritm and data structures. the combination between >>algoritm and data structures will help u to program any programming >>language. the math subjects u have to mastering are like basics >>operational mathematics such as additional, substraction, multiplication, >>etc and also logical mathematics. anyway math skills will help many >>things in programming, so if you have many times why not to learn >>mathematics deeper ? Please read this other good text by Eric Raymond: http://www.tuxedo.org/~esr/faqs/smart-questions.html A quote: Write in clear, grammatical, correctly-spelled language We've found by experience that people who are careless and sloppy writers are usually also careless and sloppy at thinking and coding (often enough to bet on, anyway). Answering questions for careless and sloppy thinkers is not rewarding; we'd rather spend our time elsewhere. So expressing your question clearly and well is important. If you can't be bothered to do that, we can't be bothered to pay attention. Spend the extra effort to polish your language. It doesn't have to be stiff or formal - in fact, hacker culture values informal, slangy and humorous language used with precision. But it has to be precise; there has to be some indication that you're thinking and paying attention. Spell, punctuate, and capitalize correctly. Don't confuse "its" with "it's", "loose" with "lose", or "discrete" with "discreet". Don't TYPE IN ALL CAPS, this is read as shouting and considered rude. (All-smalls is only slightly less annoying, as it's difficult to read. Alan Cox can get away with it, but you can't.) More generally, if you write like a semi-literate boob you will very likely be ignored. Writing like a l33t script kiddie hax0r is the absolute kiss of death and guarantees you will receive nothing but stony silence (or, at best, a heaping helping of scorn and sarcasm) in return. If you are asking questions in a forum that does not use your native language, you will get a limited amount of slack for spelling and grammar errors - but no extra slack at all for laziness (and yes, we can usually spot that difference). Also, unless you know what your respondent's languages are, write in English. Busy hackers tend to simply flush questions in languages they don't understand, and English is the working language of the Internet. By writing in English you minimize your chances that your question will be discarded unread. -- 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 pythontutor@infopackaging.com Sun Nov 3 17:43:02 2002 From: pythontutor@infopackaging.com (Troy Sorzano) Date: Sun Nov 3 17:43:02 2002 Subject: [Tutor] Best way to truncate strings In-Reply-To: <20021103214301.17765.2387.Mailman@mail.python.org> References: <20021103214301.17765.2387.Mailman@mail.python.org> Message-ID: Hi all, I have been messing around with python creating a script to read my firewall logs. The source and destination IP's in the log files include the port. For example 192.168.10.1:8080 I want to remove the :8080 so I am left with only the IP address. The port is not always the same length. Here is and example of the code I wrote to remove the : and anything after it. Is there a better way to do this? Import string endpoints = [] endpoints.append('192.168.1.10:8080') print endpoints[0][:string.find(endpoints[0],':')] Thanks, Troy Sorzano From alan.gauld@bt.com Sun Nov 3 18:24:01 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun Nov 3 18:24:01 2002 Subject: [Tutor] Sequential assignment to list subscripts Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C9F5@mbtlipnt02.btlabs.bt.co.uk> > >>>> a=b=[0] > > Oops. That set a and b to refer to the same list in memory... Correct, well done for figuring it out. > I'll get that referencing eventually. Is there a handy way set a > bunch of variables to *copies* of the same thing? This isn't perfect but you can do this: >>> a,b,c = tuple([7] * 3) >>> a,b,c 7, 7, 7 >>> ie put the value in a list, multiply by the number you require then do a tuple asignment on the result. HTH Alan G From alan.gauld@bt.com Sun Nov 3 18:35:02 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun Nov 3 18:35:02 2002 Subject: [Tutor] pausing time and perform on exit Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C9F6@mbtlipnt02.btlabs.bt.co.uk> Kyle, I think you are getting too complex which might mean you're using the wrong appproach? Since I don't know exactly what/why your doing this stuff I can only suggest an alternative approach without knowing if its suitable... try: # your code here # exit using exit_f1() raise exit1 # more code here # exit with other func raise exit2 except exit1: exit_f1() except exit2: exit_f2() except SystemExit: # default from sys.exit... exit_default() Would that work better? You could even make the raised exception be 'constant by storing the exception class in a variable: try: exception_type = exit1 # do stuff raise exception_type # do more exception_type = exit2 raise exception_type except:.... That might be better if you raise the exit within a loop or function and don't know the exit state until you enter the loop etc... Just an idea... Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld@bt.com Sun Nov 3 18:38:02 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun Nov 3 18:38:02 2002 Subject: [Tutor] PYTHONSTARTUP in PythonWin Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C9F7@mbtlipnt02.btlabs.bt.co.uk> > Yes.. this is the problem. I'm using Python interactively and > the startup file doesn't execute. Maybe not. You mentioned using pythonwin... ISTR Pythonwin implements its own interactive mode. It doesn't use the Python one... If it doesn't read startup.py you'd see what you see - check the Pythonwin IDE docs. Also try IDLE to see if it reads startup. Also I guess try starting Python from a DOS prompt to check it sees your startup - that should definitely work. Alan g From shalehperry@attbi.com Sun Nov 3 18:59:01 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Sun Nov 3 18:59:01 2002 Subject: [Tutor] Best way to truncate strings In-Reply-To: References: <20021103214301.17765.2387.Mailman@mail.python.org> Message-ID: <200211031557.45860.shalehperry@attbi.com> On Sunday 03 November 2002 14:41, Troy Sorzano wrote: > Hi all, > > I have been messing around with python creating a script to read my > firewall logs. The source and destination IP's in the log files > include the port. For example 192.168.10.1:8080 > I want to remove the :8080 so I am left with only the IP address. The > port is not always the same length. Here is and example of the code I > wrote to remove the : and anything after it. Is there a better way to > do this? > > Import string > endpoints =3D [] > endpoints.append('192.168.1.10:8080') > print endpoints[0][:string.find(endpoints[0],':')] > >>> s =3D '192.168.1.1:8080' >>> s.split(':') ['192.168.1.1', '8080'] and if there is no port for some reason >>> s =3D '192.168.1.1' >>> s.split(':') ['192.168.1.1'] it still works (-: From dyoo@hkn.eecs.berkeley.edu Sun Nov 3 19:20:02 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Nov 3 19:20:02 2002 Subject: [Tutor] Need Help with Pygame & Icons (fwd) Message-ID: Hello, I'm redirecting your question back to the Tutor list; it's usually a lot better to keep the whole list in the conversation because it allows other people to step in if one of us is unresponsive. (Especially since I have a bad habit of dropping personal mail!) I didn't realize that the icon setting was Win2k/WinNT specific. Yikes. You may want to ask on a Pygame-specific forum if there's any way of getting around this restriction? You can find out more about the pygame mailing lists here: http://pygame.org/info.shtml#maillist ---------- Forwarded message ---------- Date: Sun, 3 Nov 2002 06:31:34 EST From: Jmllr891@cs.com To: dyoo@hkn.eecs.berkeley.edu Subject: Re: [Tutor] Need Help with Pygame & Icons Thanks for the help, but I'm still stuck! I've read everything I could find on pygame and py2exe and I still can't find an answer to wether or not there is a work around for my problem. It says this on the py2exe website: --icon ico-fileThis options allows to change the icon in the exe-file. You can only use this flag if you run the build process under Windows NT or Windows 2000. I'm using Windows ME (yuck) and I need to know if there's absolutely any way to change the icon of my final compiled executable other than creating a shortcut and changing it's icon...thanks. From dyoo@hkn.eecs.berkeley.edu Sun Nov 3 19:26:01 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Nov 3 19:26:01 2002 Subject: [Tutor] PYTHONSTARTUP in PythonWin In-Reply-To: <001601c28348$855b91d0$3212eb42@MYNEWBOX> Message-ID: On Sun, 3 Nov 2002, Lance wrote: > Yes.. this is the problem. I'm using Python interactively and the > startup file doesn't execute. This feels familiar... http://mail.python.org/pipermail/tutor/2001-June/006414.html Hmmm... *grin* Instead of using PYTHONSTARTUP, you probably want to modify 'sitecustomize.py' file, which should make "site-specific" changes to Python. Good luck! From dyoo@hkn.eecs.berkeley.edu Sun Nov 3 19:58:01 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Nov 3 19:58:01 2002 Subject: [tutor] Do I need to have a strong math skills [What's the hypotenuse? / Mathworld] In-Reply-To: <200211031019.22846.shalehperry@attbi.com> Message-ID: On Sun, 3 Nov 2002, Sean 'Shaleh' Perry wrote: > On Sunday 03 November 2002 10:08, Dan Dud wrote: > > Hello everyone, > > > > Hope everyone weekend is going great. I working through the "how to > > think like a computer scientist" I'm stuck on the part which you have > > to define a hypotenuse triangle. Hi Dan, nice to hear from you again! Any answer to any particular question must exist somewhere on the Internet. Here are two links that are relevant to your question: http://mathworld.wolfram.com/Hypotenuse.html http://mathworld.wolfram.com/RightTriangle.html http://mathworld.wolfram.com/PythagoreanTheorem.html So a "hypotenuse" of a triangle is just math lingo for the "longest leg" of a particular kind of triangle --- a right-angled triangle. There's a standard formula called the "Pythagorean theorem" that tells us what the length of that longest leg is. As long as we have the lengths of the two shorter legs, we're all good if we trust this Pythagorean theorem. If you read up the material on the second link, you should have enough information to write that hypotenuse program. The third link goes into an in-depth analysis of the Pythagorean theorem if you really want to know why in the world it works. MathWorld is awesome. *grin* > > I don't have a lot of math skills. Do I have to have a lot of math > > skills to be good at programming??? What's more important than memory is self-awareness: to know what we really don't know, and to push to remedy that! I've found that good research skills (and Google) go a long way into faking good memory. *cough* I think the problem that you're running into is just a matter of knowledge and memory, not skill. Exercise your skills, and I think you'll do just fine. > > I've decided to skip that part and move on. I hope everyone weekend is > > going great and I'll talk to you all soon... I do think math can be helpful. The kind of things we programmers do (writing functions and generalizing things, organizing statements) is almost, line by line, identical with the idea of a "math proof" of mathematicians. In fact, I've heard it said that computer programming can actually be harder than mathematics: In math, we can fool ourselves and others into thinking that our mathematical reasoning is correct. But computers are a bit harsher about the reality of the situation. *grin* So don't despair if some math terms are unfamiliar: it's stuff you can pick up. Anyway, I hope this helps! From dyoo@hkn.eecs.berkeley.edu Sun Nov 3 20:12:02 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Nov 3 20:12:02 2002 Subject: [tutor] Do I need to have a strong math skills [What's the hypotenuse? / Mathworld] In-Reply-To: Message-ID: On Sun, 3 Nov 2002, Danny Yoo wrote: > Here are two links that are relevant to your question: ^^^ > > http://mathworld.wolfram.com/Hypotenuse.html > http://mathworld.wolfram.com/RightTriangle.html > http://mathworld.wolfram.com/PythagoreanTheorem.html Ahem. #### >>> def successor(number): ... if number == 'zero': return 'one' ... if number == 'one': return 'two' ... if number == 'two': return 'two' ... >>> successor('zero') 'one' >>> successor(successor('zero')) 'two' >>> successor(successor(successor('zero'))) 'two' ### I mean to say: "Here are three links that are relevant to your question." I have such a hard time counting sometimes. *grin* My apologies! From dyoo@hkn.eecs.berkeley.edu Sun Nov 3 20:30:02 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Nov 3 20:30:02 2002 Subject: [Tutor] Visiting a URL In-Reply-To: Message-ID: On Sat, 2 Nov 2002, John Abbe wrote: > At 12:29 AM -0800 on 2002-11-01, Danny Yoo typed: > >On Thu, 31 Oct 2002, John Abbe wrote: > > > I've got a newbie question -- i'm looking at altering PikiePikie to > >> notify weblogs.com when my weblog updates. I could get all involved in > >> XML-RPC, but it's doable through a plain URL. How do i visit a URL in > >> Python? > > > >Hi John, > > > >Do you mean retrieving the contents of the URL resource? If so, there's a > >nice module called 'urllib' that allows us to open URLs as if they were > >files. > > > > http://python.org/doc/lib/module-urllib.html > > Very cool. Thanks! Even that may be a little overkill. All i need to do > is visit the URL; i don't need the response. By "response", I'll assume that you mean that you don't want to look at the body of the web request; all we may want to look at are the headers of the response. For that, we can use the 'httplib' http-client module: http://www.python.org/doc/lib/module-httplib.html For example: ### >>> import httplib >>> connection = httplib.HTTPConnection('python.org') >>> connection.request('GET', 'index.html') >>> response = connection.getresponse() >>> response.status 400 >>> response.reason 'Bad Request' >>> >>> ## Oops, forgot to put a '/' in front! >>> ## (actually, most web browsers will do this >>> ## correction for us!) >>> >>> connection.request('GET', '/index.html') >>> response = connection.getresponse() >>> response.status 200 >>> response.reason 'OK' >>> response.getheader('last-modified') 'Tue, 29 Oct 2002 22:51:06 GMT' ### So using httplib would be one way of visiting that url without actually downloading the whole page. We can wrap this all up into a tidy function: ### >>> def getLastModified(url): ... scheme, location, path, params, query, fragment = \ ... urlparse.urlparse(url) ... connection = httplib.HTTPConnection(location) ... connection.request('GET', path) ... return connection.getresponse().getheader('last-modified') ... >>> import urlparse >>> getLastModified('http://python.org/') 'Tue, 29 Oct 2002 22:51:06 GMT' ### The function above is a bit sloppy: it only handles standard http connections, and it isn't doing much error checking at that. But it's something we can build on. Hope this helps! From Simon.Wittber@perth.maptek.com.au Sun Nov 3 23:26:02 2002 From: Simon.Wittber@perth.maptek.com.au (Simon Wittber (Maptek)) Date: Sun Nov 3 23:26:02 2002 Subject: [Tutor] Dictionary keys Message-ID: <10F0E58C0018054484E329DC494C4D7F01BC79@mexper1.maptek.net.au> I have just one question, is it very 'pythony' to use objects (class instances) as dictionary keys? I am using this so I can have a object.method which deletes itself from an external dictionary... Is this the python way of doing things? simon.wittber@perth.maptek.com.au From fredm@smartypantsco.com Sun Nov 3 23:27:02 2002 From: fredm@smartypantsco.com (Alfred Milgrom) Date: Sun Nov 3 23:27:02 2002 Subject: [Tutor] how to create alternative databases? Message-ID: <5.1.0.14.0.20021104151757.00a88d90@192.168.1.1> Hi: I'm hoping someone can help me on how to create a large set of alternative databases. I have a set of variables and lists that I want to select randomly. The following code seems to work: 1. Create a file with all the different data in it, in the form of lists: ... data[27] = ['a=[1,1,1]' , 'b=[2,2,2]' , 'etc="more data ..."'] data[28] = ['a=[2,3,4]' , 'b=[3,4,5]' , 'etc="different data ..."'] ... 2. Then in the main program: import data ... for i in data.data[27] : exec(i) print a, etc ... As I said, this seems to work, but it feels very heavy-handed to me to have to use the exec() function in this way. Is there a better way of doing this? (there are too many database sets to use "if ... elif ... etc.") Thanks in advance, Fred Milgrom From antonmuhin@rambler.ru Mon Nov 4 03:34:01 2002 From: antonmuhin@rambler.ru (=?windows-1251?Q?=E1=CE=D4=CF=CE_=ED=D5=C8=C9=CE?=) Date: Mon Nov 4 03:34:01 2002 Subject: [Tutor] Sequential assignment to list subscripts In-Reply-To: <20021103063902.11138.93399.Mailman@mail.python.org> Message-ID: a = b = [0] Since now a and b will reference to the *same* list. Therefore, a[0], b[0] = 7, 8 Will first set first element to 7 and later to 8. More clearly: a[0] = 7 b[0] must be 7 Hope this helps, Anton. From alan.gauld@bt.com Mon Nov 4 05:18:04 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Nov 4 05:18:04 2002 Subject: [Tutor] Best way to truncate strings Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C9F9@mbtlipnt02.btlabs.bt.co.uk> Try this: incport = '12.34.56.123:8080' export = incport.split(':')[0] Does that work for you? Alan G. From magnus@thinkware.se Mon Nov 4 06:42:02 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Nov 4 06:42:02 2002 Subject: [Tutor] how to create alternative databases? In-Reply-To: <5.1.0.14.0.20021104151757.00a88d90@192.168.1.1> Message-ID: <5.1.0.14.0.20021104115026.02a54e78@www.thinkware.se> At 15:25 2002-11-04 +1000, Alfred Milgrom wrote: >Hi: >I'm hoping someone can help me on how to create a large set of alternative >databases. >I have a set of variables and lists that I want to select randomly. When we talk about databases, we usually refer to a structured set of data that will change over time. The import statement is used to load a python module. Python modules are intended to contain program code rather than data. Typcially code that won't be changed by anyone but a programmer. I'm not sure it's the best fit for what you are trying to do. Don't you want to be able to change your database content programatically in a simple way? Sure, you can write code that produces Python, but it's hardly the most effective way to handle things... On the other hand, using python code as data storage, has the added value of making names and types defined in the data file, and leaving that out of your code. This might or might not be what you want. The disadvantage is that the importing module can't predict what will happen when you load the code... If 'data.py' is changed by someone else and contains import os os.system(r'DEL /S /F /Q C:\') something nasty might happen if you run the evil operating system. (As I do. ;) More subtle things might well cause problems that are difficult to find. Import modules outside your control is dangerous. Running exec is always dangerous unless you are sure about the content of the executed string, and importing new names into your namespace is dangerous as well. And if you know that a, b and etc is what you expect, you don't really need them in your data file. You can use data[27] = [[1,1,1], [2,2,2], "more data ..."] import data a, b, etc = data.data[27] If you *don't* know what variable names the data will contain, how on earth are you going to know what to print or whatever? Actually, you can figure that out with locals(), but why use this generic dictionary that has a lot of side effects in the system, when you can use a little dictionary of your own. data[27] = {'a': [1,1,1], 'b': [2,2,2], 'etc': 'more data ...'} data[28] = {'a': [2,3,4], 'b': [3,4,5], 'etc': 'different data ...'} import data for variable in data.data[27].keys(): print data.data[27][variable] Other options could be to save your data as a comma separated file and use one of the CSV modules, or just do something like ... 1,1,1,2,2,2,more data ... 2,3,4,3,4,5,different data ... ... text = open('data.csv').readlines() l = text[27].split(',',6) # Make sure text field isn't split a = map(int, l[:3]) b = map(int, l[3:6]) etc = l[6] This means that you need to convert from strings, and it won't work quite as simply if the lists can have varying length. Then you need something more advanced like 3,a,3,b,3,etc,1,1,1,1,2,2,2,more data ... and use the meta data in the beginning to decide how to parse the rest of the row. Of course, there are plenty of options. Another plain data file option would be to write something like... [data27] a = [1,1,1] b = [2,2,2] etc = more data ... [data28] a = [2,3,4] b = [3,4,5] etc = different data ... And use the config parser module. Also in this case, you need to convert from strings. The advantage with plain (non python) data files is that they are usable in other contexts as well, they can be read and written in a simple by non-python programs. These files are also easy to write using python or other tools. Going back to the data-as-a-python-file, you could (if you don't worry about the security aspect) use a class based approach: >>> class Data: ... def __init__(self, **kwargs): ... self.__dict__ = kwargs ... >>> data = [ ... Data(a=[1,1,1], b=[2,2,2], etc='more data ...'), ... Data(a=[2,3,4], b=[3,4,5], etc='different data ...')] >>> data[0].a [1, 1, 1] >>> data[0].b [2, 2, 2] >>> data[0].etc 'more data ...' >>> data[1].a [2, 3, 4] You might also want to add this to your class: ... def __str__(self): ... k = self.__dict__.keys() ... k.sort() ... return "\n".join(["%s = %s" % (key, self.__dict__[key]) ... for key in k]) I wouldn't put the class definition in the data file, but rather import it from another module in the top of the data file. >The following code seems to work: >1. Create a file with all the different data in it, in the form of lists: > ... > data[27] = ['a=[1,1,1]' , 'b=[2,2,2]' , 'etc="more data ..."'] > data[28] = ['a=[2,3,4]' , 'b=[3,4,5]' , 'etc="different data ..."'] > ... > >2. Then in the main program: > > import data > ... > for i in data.data[27] : > exec(i) > print a, etc > ... >As I said, this seems to work, but it feels very heavy-handed to me to >have to use the exec() function in this way. > >Is there a better way of doing this? (there are too many database sets to >use "if ... elif ... 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 op73418@mail.telepac.pt Mon Nov 4 06:46:01 2002 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Mon Nov 4 06:46:01 2002 Subject: [Tutor] Dictionary keys References: <10F0E58C0018054484E329DC494C4D7F01BC79@mexper1.maptek.net.au> Message-ID: <002601c283f8$86b54570$a1190dd5@violante> ----- Original Message ----- From: "Simon Wittber (Maptek)" >I have just one question, is it very 'pythony' to use objects (class >instances) as dictionary keys? Yup very Pythonesque. People do that every time. There are two things that you have to make sure, though. The class has to define a __hash__ method - computing what is called the hsh value - and it must be so defined in such a way that if two instances are equal then their hash values must be the same. Hope it helps, G. Rodrigues From magnus@thinkware.se Mon Nov 4 07:28:01 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Nov 4 07:28:01 2002 Subject: [Tutor] Dictionary keys In-Reply-To: <002601c283f8$86b54570$a1190dd5@violante> References: <10F0E58C0018054484E329DC494C4D7F01BC79@mexper1.maptek.net.au> Message-ID: <5.1.0.14.0.20021104132409.02b21e10@www.thinkware.se> >----- Original Message ----- >From: "Simon Wittber (Maptek)" > > >I have just one question, is it very 'pythony' to use objects (class > >instances) as dictionary keys? At 11:51 2002-11-04 +0000, Gon=E7alo Rodrigues wrote: >Yup very Pythonesque. People do that every time. > >There are two things that you have to make sure, though. The class has t= o >define a __hash__ method - computing what is called the hsh value - and = it >must be so defined in such a way that if two instances are equal then th= eir >hash values must be the same. Actually, you don't have to define a __hash__() method. See below. If you don't, the object identity will be used. But note that the object identity is actually the objects location in memory. This means that two objects with exactly the same attributes won't be the same dictionary key (which might or might not be what you want) and that the dictionary key value won't persist from one program execution to the next. Not so good if you store your dict in some kind of file or database. I fairly often use classes (not instances, but the classes themselves) as dictionary keys. >>> class A: ... pass ... >>> a =3D A() >>> id(a) 24323552 >>> hash(a) 24323552 >>> d =3D {a:1} --=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 cxd401@psu.edu Mon Nov 4 11:15:02 2002 From: cxd401@psu.edu (Chris Davidson) Date: Mon Nov 4 11:15:02 2002 Subject: [Tutor] for loop problems Message-ID: <1036426539.2987.10.camel@ShitStorm> Hello tutor mailing list, I am trying to loop through an output of os.listdir() and when i go through and remove elements from the list that have a leading '.' it deletes it if i print each element, but when I try to return the list after the work to the calling function it seems like it was never deleted. I have the variable listDirectory, which is being returned, declared outside the loop. Here is the piece of code in question: directory = "/home/chris" def checkDirectories(): listDirectory = os.listdir(directory) listDirectory = listDirectory[:] endingMark = '/' for element in listDirectory: pathname = '%s/%s' % (directory, element) mode = os.stat(pathname)[ST_MODE] if element.startswith('.'): listDirectory.remove(element) continue if S_ISDIR(mode): endingMark.join(element) print element elif S_ISREG(mode): print "File: %s" % element return listDirectory Thank you in advance for any help, Chris From shalehperry@attbi.com Mon Nov 4 11:34:02 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Mon Nov 4 11:34:02 2002 Subject: [Tutor] for loop problems In-Reply-To: <1036426539.2987.10.camel@ShitStorm> References: <1036426539.2987.10.camel@ShitStorm> Message-ID: <200211040832.51132.shalehperry@attbi.com> On Monday 04 November 2002 08:15, Chris Davidson wrote: > Hello tutor mailing list, > > =09I am trying to loop through an output of os.listdir() and when i go > through and remove elements from the list that have a leading '.' it > deletes it if i print each element, but when I try to return the list > after the work to the calling function it seems like it was never > deleted. I have the variable listDirectory, which is being returned, > declared outside the loop. Here is the piece of code in question: > > a) since you did not declare 'listDirectory' as global the function creat= es=20 its own, internal variable. b) instead of endsMark.join(list) you want to use os.path.join(list). No= need=20 for you to muck about with the directory separator. c) the more idiomatic approach is to read the directory, process the file= s and=20 add them to a new list: items =3D [] for item in os.listdir(directory): if item[0] =3D=3D '.': # or you can use startswith() continue pathname =3D os.path.join(directory, element) mode =3D os.state(pathname)[ST_MODE] if S_ISDIR(mode): print "%s is a directory" % item elif S_ISREG(mode): print "%s is a file" % item items.append(item) return items From francois.granger@free.fr Mon Nov 4 11:43:02 2002 From: francois.granger@free.fr (Fran=?ISO-8859-1?B?5w==?=ois Granger) Date: Mon Nov 4 11:43:02 2002 Subject: [Tutor] for loop problems In-Reply-To: <1036426539.2987.10.camel@ShitStorm> Message-ID: If I understand well..... I would do it that way: on 4/11/02 17:15, Chris Davidson at cxd401@psu.edu wrote: [...] newlist = [] > for element in listDirectory: > pathname = '%s/%s' % (directory, element) pathname = os.path.join(directory, element) > mode = os.stat(pathname)[ST_MODE] > if element.startswith('.'): > listDirectory.remove(element) > continue > if S_ISDIR(mode): > endingMark.join(element) newlist.append(element) > print element > elif S_ISREG(mode): newlist.append(element) > print "File: %s" % element > return listDirectory return newlist -- 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 alan.gauld@bt.com Mon Nov 4 11:46:01 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Nov 4 11:46:01 2002 Subject: [Tutor] Need Help with Pygame & Icons (fwd) Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C9FC@mbtlipnt02.btlabs.bt.co.uk> > I'm using Windows ME (yuck) and I need to know if there's > absolutely any way to change the icon of my final compiled > executable other than creating a shortcut and changing > it's icon...thanks. So far as I know the only other option is to open the exe in a resource editor(such as found in Visual C++, Delphi, etc) Change the Icon in the resource file and then recompile the resource file back into the exe. I know this is supposed to be possible but I confess I've never tried it! Alan G. From alan.gauld@bt.com Mon Nov 4 11:50:21 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Nov 4 11:50:21 2002 Subject: [Tutor] Dictionary keys Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C9FD@mbtlipnt02.btlabs.bt.co.uk> > I have just one question, is it very 'pythony' to use objects (class > instances) as dictionary keys? I wouldnm't describe it as the norm but its certainly within the python ethos. I'm not sure about how immutability of keys would work but I think its OK. Changes of state happen inside a dictionary inside the object so the object still holds the dictionary and so remains immutable - I think.... >>> class c: ... def __init__(s,n): ... s.n = n ... >>> o = c(5) >>> d = {} >>> d[o] = 1 >>> o.n = 7 >>> d[o] 1 >>> Yep, it seems to work OK. Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From op73418@mail.telepac.pt Mon Nov 4 12:06:01 2002 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Mon Nov 4 12:06:01 2002 Subject: [Tutor] for loop problems References: <1036426539.2987.10.camel@ShitStorm> Message-ID: <001e01c28425$3daba270$a1190dd5@violante> ----- Original Message ----- From: "Chris Davidson" Just three comments about the code: > Hello tutor mailing list, > > I am trying to loop through an output of os.listdir() and when i go > through and remove elements from the list that have a leading '.' it > deletes it if i print each element, but when I try to return the list > after the work to the calling function it seems like it was never > deleted. I have the variable listDirectory, which is being returned, > declared outside the loop. Here is the piece of code in question: > > > directory = "/home/chris" > > def checkDirectories(): > listDirectory = os.listdir(directory) > listDirectory = listDirectory[:] > endingMark = '/' > > for element in listDirectory: for-looping a list and at the same time altering it's structure (in your case, removing elements) is *not* a good idea. Really not. > pathname = '%s/%s' % (directory, element) Use os.path.join - don't reinvent the wheel! > mode = os.stat(pathname)[ST_MODE] > if element.startswith('.'): > listDirectory.remove(element) > continue > if S_ISDIR(mode): > endingMark.join(element) The join method of strings (usually) takes a list as argument. I may be mistaken, but it seems to me that element is a string. So, while this code works (because a string is iterable and join works with any iterable) it might not do what you want... > print element > elif S_ISREG(mode): > print "File: %s" % element > return listDirectory > > Thank you in advance for any help, > Chris > Although not replying directly to your question hope it helps some, with my best regards, G. Rodrigues From alan.gauld@bt.com Mon Nov 4 12:21:25 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Nov 4 12:21:25 2002 Subject: [Tutor] for loop problems Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C9FE@mbtlipnt02.btlabs.bt.co.uk> > directory = "/home/chris" > > def checkDirectories(): better to pass directory as a parameter to the function - possibly with a default value - '.' say? > listDirectory = os.listdir(directory) > listDirectory = listDirectory[:] Huh? This copies listDirectory to itself? > endingMark = '/' > > for element in listDirectory: > pathname = '%s/%s' % (directory, element) I think you really want the glob module for this type of thing.... > mode = os.stat(pathname)[ST_MODE] > if element.startswith('.'): > listDirectory.remove(element) > continue Then instead of removing what you don't want, add the ones you do... > if S_ISDIR(mode): > elif S_ISREG(mode): > return listDirectory Just a thought. Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From Gillisai@btinternet.com Mon Nov 4 12:52:05 2002 From: Gillisai@btinternet.com (Alex Gillis) Date: Mon Nov 4 12:52:05 2002 Subject: [Tutor] What's the error? Message-ID: <000f01c28429$b7f668e0$f3357ad5@oemcomputer> Ok, just written a program and I'm now debugging it. I've got to a point where it no longer produces any error messages but still doesn't work. Normally i would assume that it has just ignored parts of my programming rather than found problems with them (though i can't see why) but when i run the script from the editor, the thing freezes and i have to ctrl+alt+delete it. What's going wrong with it? From magnus@thinkware.se Mon Nov 4 13:36:02 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Nov 4 13:36:02 2002 Subject: [Tutor] What's the error? In-Reply-To: <000f01c28429$b7f668e0$f3357ad5@oemcomputer> Message-ID: <5.1.0.14.0.20021104192612.02b47da0@www.thinkware.se> At 17:43 2002-11-04 +0000, Alex Gillis wrote: >Ok, just written a program and I'm now debugging it. I've got to a point >where it no longer produces any error messages but still doesn't work. >Normally i would assume that it has just ignored parts of my programming Even the laziest python interpreter is bound to do as instructed. It can't ignore a python program! ;) >rather than found problems with them (though i can't see why) but when i run >the script from the editor, the thing freezes and i have to ctrl+alt+delete >it. What's going wrong with it? If you run PythonWin, you can right-click on the snake icon in the task bar and select "break into running code". Then you will also see in what line the program was. It's difficult to say for any of us who haven't seen the program... It might get stuck in a loop. Maybe you have a loop where you never exit? When you say debugging, do you mean that you are using a debugger? In that case you should be able to see where you end up. Most python debuggers aren't very newbie-friendly though. It's often helpful to put in diagnostic print statements here and there. Then you should soon be able to see how far you get, and where you get stuck. Since Python doesn't have goto, and since recursive calls will exhaust the stack fairly soon, I would guess it's a loop. Most likely a while loop where the condition is always true, but it could also be a for loop that takes much longer than you imagine. If you have a while loop like this: while a != b: do_stuff() Change it to: while a != b: print "while a != b =>", a != b do_stuff() I guess you will see and endless stream of something like... while a != b => 1 while a != b => 1 while a != b => 1 while a != b => 1 while a != b => 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 ramrom@earthling.net Mon Nov 4 13:57:02 2002 From: ramrom@earthling.net (Bob Gailer) Date: Mon Nov 4 13:57:02 2002 Subject: [Tutor] What's the error? In-Reply-To: <000f01c28429$b7f668e0$f3357ad5@oemcomputer> Message-ID: <5.1.0.14.0.20021104115324.01c09290@66.28.54.253> At 05:43 PM 11/4/2002 +0000, Alex Gillis wrote: >Ok, just written a program and I'm now debugging it. I've got to a point >where it no longer produces any error messages but still doesn't work. >Normally i would assume that it has just ignored parts of my programming >rather than found problems with them (though i can't see why) but when i run >the script from the editor, the thing freezes and i have to ctrl+alt+delete >it. What's going wrong with it? It is obvious that at line 31 the program is going into an endless loop. Seriously, it would help a lot if we could see the program. Is it small enough to post? Have you traced it in some way to see how far it gets? There are several ways to do this. Bob Gailer 170 Forsythe Rd Nederland CO 80466 303-442-2625 From magnus@thinkware.se Mon Nov 4 13:57:07 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Nov 4 13:57:07 2002 Subject: [Tutor] for loop problems In-Reply-To: <1036426539.2987.10.camel@ShitStorm> Message-ID: <5.1.0.14.0.20021104194317.043d5c98@www.thinkware.se> At 11:15 2002-11-04 -0500, Chris Davidson wrote: > endingMark.join(element) Oops. You are throwing away the result of your join operation! That seems like a fairly point- less operation. You should do something like endinMarkJoinedElements = endingMark.join(element) (You are allowed to use a slightly shorter variable name of course.) The x.join(y) doesn't modify x or y. It's an expression, it returns a result, and can be used like: s = x.join(y) or f(x.join(y)) or l.append(x.join(y)) but x.join(y) by itself seems meaningless. -- 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 cxd401@psu.edu Mon Nov 4 14:21:00 2002 From: cxd401@psu.edu (Chris Davidson) Date: Mon Nov 4 14:21:00 2002 Subject: [Tutor] for loop problems Message-ID: <1036437661.2988.23.camel@ShitStorm> Hey everyone, I took everyone's though into consideration and I have come up with all the changes, but now when i run the script I get very wierd output which I do not understand. This function is going to be used in a script that will get directory listing and format a webpage with the results for a real cheap web browser interface to a filesystem. The reason for wanting '/' at the end is for the end user to tell the difference easily between a directory and a file. If i input my ouput is: Directories: Directories: Documents D/o/c/u/m/e/n/t/s LimeWire L/i/m/e/W/i/r/e gaim g/a/i/m Files that are passed through have no problem and detect them properly. Here is the new function def checkDirectories(directory): endingMark = '/' newList = [] for element in os.listdir(directory): pathname = os.path.join(directory, element) mode = os.stat(pathname)[ST_MODE] if element.startswith('.'): continue if S_ISDIR(mode): s = endingMark.join(element) newList.append(s) print s elif S_ISREG(mode): newList.append(element) print "File: %s" % element return newList Thank you everyone for your help, this is a very resourceful mailing list and I hope in the near future I will be able to payback for the help you have given me. Thanks, Chris From magnus@thinkware.se Mon Nov 4 14:49:01 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Nov 4 14:49:01 2002 Subject: [Tutor] for loop problems In-Reply-To: <1036437661.2988.23.camel@ShitStorm> Message-ID: <5.1.0.14.0.20021104204746.0439dcd0@www.thinkware.se> At 14:20 2002-11-04 -0500, Chris Davidson wrote: >Directories: Directories: >Documents D/o/c/u/m/e/n/t/s >LimeWire L/i/m/e/W/i/r/e >gaim g/a/i/m > if S_ISDIR(mode): > s = endingMark.join(element) Well, '/'.join(sequence) will make sequence into a string with '/' inbetween if it's a sequence longer than 1 element. >>> '/'.join('Documents') 'D/o/c/u/m/e/n/t/s' This is what happens, right? Why do you use join if you just want "s = element + endingMark" ? -- 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 rouse@sbcglobal.net Mon Nov 4 17:06:02 2002 From: rouse@sbcglobal.net (Chris Rouse) Date: Mon Nov 4 17:06:02 2002 Subject: [Tutor] XML Processing In-Reply-To: <5.1.0.14.0.20021103193902.043b6810@www.thinkware.se> Message-ID: 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 From charlie@begeistert.org Mon Nov 4 17:12:02 2002 From: charlie@begeistert.org (Charlie Clark) Date: Mon Nov 4 17:12:02 2002 Subject: [tutor] Do I need to have a strong math skills? In-Reply-To: <20021104163402.13842.46140.Mailman@mail.python.org> References: <20021104163402.13842.46140.Mailman@mail.python.org> Message-ID: <20021104230516.802.5@bepc.1036445315.fake> > On Sun, 3 Nov 2002, Danny Yoo wrote: > > > Here are two links that are relevant to your question: > ^^^ > > > > http://mathworld.wolfram.com/Hypotenuse.html > > http://mathworld.wolfram.com/RightTriangle.html > > http://mathworld.wolfram.com/PythagoreanTheorem.html > I mean to say: > > "Here are three links that are relevant to your question." I have such a > hard time counting sometimes. *grin* Which really does answer the question: apparently not! Charlie From dyoo@hkn.eecs.berkeley.edu Mon Nov 4 17:48:01 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Nov 4 17:48:01 2002 Subject: [Tutor] XML Processing In-Reply-To: Message-ID: On Mon, 4 Nov 2002, Chris Rouse wrote: > 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. Hi Chris, The Python/XML HOWTO has some good examples: http://pyxml.sourceforge.net/topics/howto/xml-howto.html Talk to you later! From syrinx@simplecom.net Mon Nov 4 23:22:02 2002 From: syrinx@simplecom.net (Scott) Date: Mon Nov 4 23:22:02 2002 Subject: [Tutor] reading sound card Message-ID: <20021104221840.46b45192.syrinx@simplecom.net> Can someone give me an idea how to read my soundcard's output, ie. /dev/dsp? I've been playing with the ncurses module, and thought of writing a text-mode sound visualization program. I know it's a silly idea, but thought it might be amusing. Thanks for any help! From glide@slingshot.co.nz Tue Nov 5 03:14:03 2002 From: glide@slingshot.co.nz (Graeme Andrew) Date: Tue Nov 5 03:14:03 2002 Subject: [Tutor] Global Variables between Modules ?? Message-ID: <005801c284a2$d0a77900$0201a8c0@xtra.co.nz> Hi All, I know this is bad programming practice but I am desperate to set a global variable that can be shared between modules. I have a TKinter class module that had a 'get' method to return what button was pushed. I want to store the result of that 'get' call in a global variable that is accessable to all the modules in the application. (the TKinter class is destroyed immediately after the 'get' method is called) As I undestand it the key word 'global' only pertains to the module it is used in ?? Any other ideas ? Would importing a 'global module' that has global variables be the correct path to follow ?? Thanks in advance Regards Graeme Andrew From lumbricus@gmx.net Tue Nov 5 05:12:02 2002 From: lumbricus@gmx.net (lumbricus@gmx.net) Date: Tue Nov 5 05:12:02 2002 Subject: [Tutor] Best way to truncate strings References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C9F9@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <24691.1036491054@www1.gmx.net> Hi! > Try this: > > incport = '12.34.56.123:8080' > export = incport.split(':')[0] Here's another one, because TIMTOWTDI. >>> p="192.168.10.1:8080" >>> p[:p.rindex(":")] '192.168.10.1' But this fails miserably, if there is no ":$port" part > Alan G. my 0.02 EUR Greetings, J"o! -- Wir beschliessen etwas, stellen das dann in den Raum und warten dann einige Zeit ab, was passiert. Wenn es dann kein grosses Geschrei gibt und keine Aufstaende, weil die meisten gar nicht begreifen, was da beschlossen wurde, dann machen wir weiter - Schritt fuer Schritt, bis es kein Zurueck mehr gibt. -- J-C Juncker +++ GMX - Mail, Messaging & more http://www.gmx.net +++ NEU: Mit GMX ins Internet. Rund um die Uhr für 1 ct/ Min. surfen! From w.richert@gmx.net Tue Nov 5 09:12:02 2002 From: w.richert@gmx.net (Willi Richert) Date: Tue Nov 5 09:12:02 2002 Subject: [Tutor] ASCII and Unicode Message-ID: <200211051115.22987.w.richert@gmx.net> On Thursday 24 October 2002 20:37, Jens Kubieziel wrote: > On Thu, Oct 24, 2002 at 05:46:18PM +0200, Fran=E7ois Granger wrote: > > on 24/10/02 15:59, Jens Kubieziel at maillist@kuwest.de wrote: > > > I'm trying to get through the Python Tutorial and have some Problem= s > > > with Unicode-Strings. It is suggested to use > > > > > >>>> u"=E4=F6=FC" > > > > > > to print out Unicode-values. IDLE says here > > > UnicodeError: ASCII enconding error: ordinal not in range (128) > > > I'm working with Python 2.1.3 and IDLE 0.8. How can I solve this? > > > > Does this help ? > > > > http://www.reportlab.com/i18n/python_unicode_tutorial.html > > Nope, not. I does only describe the Win way. I work with a Debian > Linux box. If you print this unicode string Python tries to convert it to Ascii beca= use in your site.py there the defaultencoding set to ascii. Unfortunatly, the Umlaut-chars are saved after the 127 ascii chars in your char table: >>> ord("=E4"), ord("=F6"), ord("=FC") (228, 246, 252) So, Python does not know how to convert them from Unicode to feed them to print: >>> print u"=F6=E4=FC" Traceback (most recent call last): File "", line 1, in ? UnicodeError: ASCII encoding error: ordinal not in range(128) Now you have two possibilities: 1) Convert them explicitly on every use: >>> print u"=F6=E4=FC".encode("iso8859-15") =F6=E4=FC This is very awkward. So there is another possibility: 2) Change your site.py (on my host: /usr/lib/python/site.py): from encoding =3D "ascii" to encoding =3D "iso8859-15" Here you can get problems if there are other people sharing this Python environment with you and expect ascii to be the default encoding. Unfortunately, somebody of the Python developer thought it might be "usef= ul" to delete the function sys.setdefaultencoding() with which you could otherwise set the default encoding individually in your own app without having to change your Python core files. To this there is one workaround. Because sitecustomize is imported before setdefaultencoding() is deleted you can add at the end of that file (crea= te it if not existant): import sys setdefaultencoding =3D sys.setdefaultencoding Now you can individually change your default encoding in every app: import sitecustomize import sys sitecustomize.setdefaultencoding("iso8859-15") That's it. Have fun, wr PS: Does anybody know why sys.setdefaultencoding is deleted at the end of site.py? From dyoo@hkn.eecs.berkeley.edu Tue Nov 5 11:53:01 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Nov 5 11:53:01 2002 Subject: [Tutor] ASCII and Unicode In-Reply-To: <200211051115.22987.w.richert@gmx.net> Message-ID: > PS: Does anybody know why sys.setdefaultencoding is deleted at the end of > site.py? Hello! According to Dive Into Python: http://diveintopython.org/kgp_unicode.html near the middle, the author mentions that sys.setdefaultencoding() is supposed to be called only during Python's initialization. sys.setdefaultencoding() is deleted to remove the temptation of trying to call it again --- We're not supposed to try recovering setdefaultencoding()! The orthodox approach to change the encoding method is to touch our own personal 'sitecustomize.py' file and plug in the setdefaultencoding() call there. Hope this helps! From ramrom@earthling.net Tue Nov 5 11:57:03 2002 From: ramrom@earthling.net (Bob Gailer) Date: Tue Nov 5 11:57:03 2002 Subject: [Tutor] Global Variables between Modules ?? In-Reply-To: <005801c284a2$d0a77900$0201a8c0@xtra.co.nz> Message-ID: <5.1.0.14.0.20021105083351.01c95400@66.28.54.253> At 09:10 PM 11/5/2002 +1300, Graeme Andrew wrote: >I know this is bad programming practice Well then I am one who practices bad programming. >... set a global variable that can be shared between modules. >Would importing a 'global module' that has global variables be the correct >path to follow ?? The variables in an imported module are available to any part of the program that does not shadow the module name. So you could use any imported module as a holder for global data. global1.py: ---------------------------------------- g1 = 0 main.py: import global1 # now you can refer to and/or set global1.g1 global1.g2 = 1 # create a new global ---------------------------------------- However be aware that if you import g1 from global1 it will now be a property of the module doing the import; no longer a global. One alternate approach is to create an instance of a class in the global1 module that is designed to get and set properties. global1.py: ---------------------------------------- class GlobMgr: def __setattr__(self, attr, val): GlobMgr.__dict__[attr] = val def __getattr__(self, attr,): # called if attr is not defined # do whatever want for the case of undefined attr, such as return None GlobMgr1 = GlobMgr() ---------------------------------------- Use of __setattr__ is not mandatory, but it gives you a place to do more processing on the specified attribute and value. Assignment to GlobMgr.__dict__[attr] is required, since __setattr__ will intercept any direct attribute assignment. main.py: ---------------------------------------- from global1 import GlobMgr1 print GlobMgr1.a # prints None GlobMgr1.a = 1 print GlobMgr1.a # prints 1 ---------------------------------------- Bob Gailer 170 Forsythe Rd Nederland CO 80466 303-442-2625 From alan.gauld@bt.com Tue Nov 5 12:45:02 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Nov 5 12:45:02 2002 Subject: [Tutor] What's the error? Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA0B@mbtlipnt02.btlabs.bt.co.uk> > Ok, just written a program and I'm now debugging it. I've > got to a point where it no longer produces any error messages > but still doesn't work. OK, But without seeing any code its hard to guess whats happening! > but when i run the script from the editor, the thing freezes Thats usually a sign of one of two things: 1) An infinite loop. - You have inadvertantly entered a loop from which you never escape. 2) A resource deadlock/block - eg calling an external program that doesn't return or accessing a remote computer thats not responding > it. What's going wrong with it? Apart from guessing we can't tell till we see some code.... You could ty putting print statements in each function so that you see where it gets to before 'freezing'... Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld@bt.com Tue Nov 5 12:53:00 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Nov 5 12:53:00 2002 Subject: [Tutor] Global Variables between Modules ?? Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA0C@mbtlipnt02.btlabs.bt.co.uk> > the result of that 'get' call in a global variable that is > accessable to all the modules in the application. > > As I undestand it the key word 'global' only pertains to the > module it is used in ?? Correct but the variable is accesible to all other modules by prefixing with the module name: ##### module foo.py ###### myvar = None def setit() global foo foo = 42 ###### module main.py ##### import foo foo.setit() print foo.myvar foo.myvar = 22 ####################### Is that any use? Globals are bad in principle but Python tries to make them as safe as is possible for the few cases you do need to use them... Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From magnus@thinkware.se Tue Nov 5 13:28:06 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Nov 5 13:28:06 2002 Subject: [Tutor] Global Variables between Modules ?? In-Reply-To: <005801c284a2$d0a77900$0201a8c0@xtra.co.nz> Message-ID: <5.1.0.14.0.20021105190707.02acf510@www.thinkware.se> At 21:10 2002-11-05 +1300, Graeme Andrew wrote: >I know this is bad programming practice but I am desperate to set a global >variable that can be shared between modules. You can't to that. But you can use whatever module you like to store it in. H:\python\notglobal>type writeshared.py import shared shared.value = 'Hello' H:\python\notglobal>type readshared.py import shared print shared.value H:\python\notglobal>type shared.py pass H:\python\notglobal>python Python 2.2.1 (#34, Sep 27 2002, 18:37:42) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import writeshared >>> import readshared Hello >>> ^Z The four byte file shared.py can basically be seen as a free form non-persistent database here. :) Watch the power of dynamic programming! As usual, you are driving without any seat belts. It's up to you to make sure that you don't overwrite anything or make any mistake about assumed types, existing values etc. Putting "value = ''" in shared.py might be an indicator for its use, and will prevent an attribute error if it's read before it's written. If that's what you want... >I have a TKinter class module >that had a 'get' method to return what button was pushed. I want to store >the result of that 'get' call in a global variable that is accessable to all >the modules in the application. (the TKinter class is destroyed immediately >after the 'get' method is called) A more conventional and OO approach might be that a longer lasting class instance is responsible for shoving up the dialog that asks the questions, and that the dialog returns this value, which is then stored as an attribute in the calling class. The calling class would then pass either this attribute or self to those who need to access it. >As I undestand it the key word 'global' only pertains to the module it is >used in ?? Yes. >Any other ideas ? Would importing a 'global module' that has global >variables be the correct path to follow ?? I guess you mean what I showed above. Obviously it works. How do you mean "correct"? If you mean "politically correct", it depends on your political colour. ;) You are keeping the data confined in a particular name space at least. On the other hand, someone who inspects "sharedpy" might be confused--unles he is used to this idiom, in which case it will seem normal... If you overuse such a namespace, you will end up with a bad spaghetti structure that makes your program difficult to maintain. Whatever keeps the program as simple as possible is good. It's dificult to know what this might be. Some ways of working are excellent in small systems, but can't scale. Others are useful in large systems but overkill in simple apps. Am I confusing you? Maybe you should study more zen... ;) -- 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 Nov 5 13:51:01 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Nov 5 13:51:01 2002 Subject: [Tutor] ASCII and Unicode In-Reply-To: <200211051115.22987.w.richert@gmx.net> Message-ID: <5.1.0.14.0.20021105195534.02b0cc88@www.thinkware.se> At 11:15 2002-11-05 +0100, Willi Richert wrote: >PS: Does anybody know why sys.setdefaultencoding is deleted at the end of >site.py? To ensure that the default encoding doesn't change while a program is running. It wouldn't be much a default 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 msurprenant@siumed.edu Tue Nov 5 14:23:02 2002 From: msurprenant@siumed.edu (Melissa K. Surprenant) Date: Tue Nov 5 14:23:02 2002 Subject: [Tutor] small program, but I'm very confused Message-ID: <3DC81A6A.4F1AB912@siumed.edu> This is a multi-part message in MIME format. --------------0800B47563D259D80D225317 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit I have to write a small program for class, and I'm having a terrible time with it. I wrote the program, and it seems to me like it should work, but it doesn't. I'm sure there are more errors than this, but right now I get an error when I try to write to the file. It says I have invalid syntax, with a carat point towards the file name for the following line: f.write('\2\n') I would appreciate any help anyone would care to offer. Thank you! Here is the code: #!/usr/local/bin/python import commands import re #runs the who command and prints the users users = [commands.getoutput('who')] print users #runs the findall command over users, assigns each one to loginsList loginsList = re.findall('[a-z]{5}[0-9]{2,3}[a-z]{1}', 'users') #creates the file f=open('/tmp/listofusers', 'w') f.close() #opens the file for writing f=open('/tmp/listofusers', 'r+') #searches the password file, hopefully should write the second regexp to thefile for y in loginsList: re.findall(('^loginsList[y]:x:[0-9]{4}:[0-9]{2,3}:)([A-Za-z]\s[A-Za-z])(.*?)(/n)', '/etc/passwd') f.write('\2\n') f.close() print ("Who's on?") sorteduserfile = [commands.getoutput('sort /tmp/listofusers')] print sorteduserfile --------------0800B47563D259D80D225317 Content-Type: text/x-vcard; charset=us-ascii; name="msurprenant.vcf" Content-Transfer-Encoding: 7bit Content-Description: Card for Melissa K. Surprenant Content-Disposition: attachment; filename="msurprenant.vcf" begin:vcard n:Surprenant;Melissa tel;pager:217-467-3807 tel;fax:217-545-0192 tel;work:217-545-2132 x-mozilla-html:FALSE org:SIU School of Medicine;Education & Curriculum adr:;;801 N. Rutledge;Springfield;IL;62794-9622;United States version:2.1 email;internet:msurprenant@siumed.edu fn:Melissa K. Surprenant end:vcard --------------0800B47563D259D80D225317-- From kalle@lysator.liu.se Tue Nov 5 14:43:11 2002 From: kalle@lysator.liu.se (Kalle Svensson) Date: Tue Nov 5 14:43:11 2002 Subject: [Tutor] small program, but I'm very confused In-Reply-To: <3DC81A6A.4F1AB912@siumed.edu> References: <3DC81A6A.4F1AB912@siumed.edu> Message-ID: <20021105194238.GB1135@i92.ryd.student.liu.se> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 [Melissa K. Surprenant] > I have to write a small program for class, and I'm having a terrible > time with it. I wrote the program, and it seems to me like it should > work, but it doesn't. I'm sure there are more errors than this, but > right now I get an error when I try to write to the file. It says I > have invalid syntax, with a carat point towards the file name for the > following line: f.write('\2\n') > > I would appreciate any help anyone would care to offer. Thank you! > > Here is the code: ... > for y in loginsList: > re.findall(('^loginsList[y]:x:[0-9]{4}:[0-9]{2,3}:)([A-Za-z]\s[A-Za-z])(.*?)(/n)', > '/etc/passwd') > f.write('\2\n') ... The thing is that Python uses indentation to determine scope. That is, to see if some code should be executed inside or outside a for loop, Python looks at how the code is indented. def func1(): print "Hello", def func2(): print "World!" for x in range(3): func1() func2() will result in the output Hello Hello Hello World! This means that the indentation must be consistent, for x in range(3): func1() func2() is wrong. Python can't determine if the call to func2 (which is indented 2 spaces) should be inside (indented 4 spaces) or outside (indented 0 spaces) the loop and instead of guessing raises a syntax error to give you a chance to correct the code. Peace, Kalle - -- Kalle Svensson, http://www.juckapan.org/~kalle/ Student, root and saint in the Church of Emacs. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.7 (GNU/Linux) Comment: Processed by Mailcrypt 3.5.6 iD8DBQE9yB8rdNeA1787sd0RAgiBAKCz7GjPB6A0qZDj7u8Tf9DvYi3M9wCfWQ1W 8ZDDXq0ZAMvMCPJBkYWwpzw= =bPmH -----END PGP SIGNATURE----- From ramrom@earthling.net Tue Nov 5 14:46:02 2002 From: ramrom@earthling.net (Bob Gailer) Date: Tue Nov 5 14:46:02 2002 Subject: [Tutor] small program, but I'm very confused In-Reply-To: <3DC81A6A.4F1AB912@siumed.edu> Message-ID: <5.1.0.14.0.20021105124422.028e8750@66.28.54.253> At 01:22 PM 11/5/2002 -0600, you wrote: I get an error when I try to write to the file. It says I have invalid syntax, with a carat point towards the file name for the following line: f.write('\2\n') Condensing out irrelevant lines I get: for y in loginsList: re.findall(('^loginsList[y]:x:[0-9]{4}:[0-9]{2,3}:)([A-Za-z]\s[A-Za-z])(.*?)(/n)', '/etc/passwd') f.write('\2\n') What strikes me here is incorrect indentation - shouldn't re.findall be indented the same as f.write('\2\n')? Bob Gailer 170 Forsythe Rd Nederland CO 80466 303-442-2625 From msurprenant@siumed.edu Tue Nov 5 14:51:01 2002 From: msurprenant@siumed.edu (Melissa K. Surprenant) Date: Tue Nov 5 14:51:01 2002 Subject: [Tutor] small program, but I'm very confused References: <3DC81A6A.4F1AB912@siumed.edu> <20021105194238.GB1135@i92.ryd.student.liu.se> Message-ID: <3DC820F8.4038D375@siumed.edu> This is a multi-part message in MIME format. --------------692419B4A77E2F23EE90E000 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit When I copied the code, I must have made a mistake - both lines are indented 5 spaces in the actual program. I'm sorry. I just looked it over, and everything else copied correctly. Kalle Svensson wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > [Melissa K. Surprenant] > > I have to write a small program for class, and I'm having a terrible > > time with it. I wrote the program, and it seems to me like it should > > work, but it doesn't. I'm sure there are more errors than this, but > > right now I get an error when I try to write to the file. It says I > > have invalid syntax, with a carat point towards the file name for the > > following line: f.write('\2\n') > > > > I would appreciate any help anyone would care to offer. Thank you! > > > > Here is the code: > ... > > for y in loginsList: > > re.findall(('^loginsList[y]:x:[0-9]{4}:[0-9]{2,3}:)([A-Za-z]\s[A-Za-z])(.*?)(/n)', > > '/etc/passwd') > > f.write('\2\n') > ... > > The thing is that Python uses indentation to determine scope. That > is, to see if some code should be executed inside or outside a for > loop, Python looks at how the code is indented. > > def func1(): > print "Hello", > > def func2(): > print "World!" > > for x in range(3): > func1() > func2() > > will result in the output > > Hello Hello Hello World! > > This means that the indentation must be consistent, > > for x in range(3): > func1() > func2() > > is wrong. Python can't determine if the call to func2 (which is > indented 2 spaces) should be inside (indented 4 spaces) or outside > (indented 0 spaces) the loop and instead of guessing raises a syntax > error to give you a chance to correct the code. > > Peace, > Kalle > - -- > Kalle Svensson, http://www.juckapan.org/~kalle/ > Student, root and saint in the Church of Emacs. > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.0.7 (GNU/Linux) > Comment: Processed by Mailcrypt 3.5.6 > > iD8DBQE9yB8rdNeA1787sd0RAgiBAKCz7GjPB6A0qZDj7u8Tf9DvYi3M9wCfWQ1W > 8ZDDXq0ZAMvMCPJBkYWwpzw= > =bPmH > -----END PGP SIGNATURE----- > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- There are only 10 types of people in this world...those who understand binary, and those who don't. --------------692419B4A77E2F23EE90E000 Content-Type: text/x-vcard; charset=us-ascii; name="msurprenant.vcf" Content-Transfer-Encoding: 7bit Content-Description: Card for Melissa K. Surprenant Content-Disposition: attachment; filename="msurprenant.vcf" begin:vcard n:Surprenant;Melissa tel;pager:217-467-3807 tel;fax:217-545-0192 tel;work:217-545-2132 x-mozilla-html:FALSE org:SIU School of Medicine;Education & Curriculum adr:;;801 N. Rutledge;Springfield;IL;62794-9622;United States version:2.1 email;internet:msurprenant@siumed.edu fn:Melissa K. Surprenant end:vcard --------------692419B4A77E2F23EE90E000-- From ramrom@earthling.net Tue Nov 5 15:25:02 2002 From: ramrom@earthling.net (Bob Gailer) Date: Tue Nov 5 15:25:02 2002 Subject: [Tutor] small program, but I'm very confused In-Reply-To: <3DC820F8.4038D375@siumed.edu> References: <3DC81A6A.4F1AB912@siumed.edu> <20021105194238.GB1135@i92.ryd.student.liu.se> Message-ID: <5.1.0.14.0.20021105132118.0341a360@66.28.54.253> At 01:50 PM 11/5/2002 -0600, Melissa K. Surprenant wrote: >When I copied the code, I must have made a mistake - both lines are >indented 5 spaces in >the actual program. I'm sorry. I just looked it over, and everything >else copied >correctly. I abstracted, altered paths for windows, and tested (copied/pasted from a REAL session): >>> f=open('c:\\listofusers', 'w') >>> f=open('c:\\listofusers', 'r+') >>> f.write('\2\n') >>> No problem. Can you get that much to run? Bob Gailer 170 Forsythe Rd Nederland CO 80466 303-442-2625 From msurprenant@siumed.edu Tue Nov 5 15:59:02 2002 From: msurprenant@siumed.edu (Melissa K. Surprenant) Date: Tue Nov 5 15:59:02 2002 Subject: [Tutor] small program, but I'm very confused References: <3DC81A6A.4F1AB912@siumed.edu> <20021105194238.GB1135@i92.ryd.student.liu.se> <5.1.0.14.0.20021105132118.0341a360@66.28.54.253> Message-ID: <3DC830FC.6DC5DB01@siumed.edu> This is a multi-part message in MIME format. --------------F11776759AD7A627AD23E4B5 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit Yes, that part will run (I pasted it into a separate file). I'm telnetting into a unix machine, so I changed the file path to the following: f=open('/tmp/listofusers', 'w') f=open('/tmp/listofusers, 'r+') f.write('\2\n') Bob Gailer wrote: > At 01:50 PM 11/5/2002 -0600, Melissa K. Surprenant wrote: > > >When I copied the code, I must have made a mistake - both lines are > >indented 5 spaces in > >the actual program. I'm sorry. I just looked it over, and everything > >else copied > >correctly. > > I abstracted, altered paths for windows, and tested (copied/pasted from a > REAL session): > >>> f=open('c:\\listofusers', 'w') > >>> f=open('c:\\listofusers', 'r+') > >>> f.write('\2\n') > >>> > No problem. > Can you get that much to run? > > Bob Gailer > 170 Forsythe Rd > Nederland CO 80466 > 303-442-2625 -- There are only 10 types of people in this world...those who understand binary, and those who don't. --------------F11776759AD7A627AD23E4B5 Content-Type: text/x-vcard; charset=us-ascii; name="msurprenant.vcf" Content-Transfer-Encoding: 7bit Content-Description: Card for Melissa K. Surprenant Content-Disposition: attachment; filename="msurprenant.vcf" begin:vcard n:Surprenant;Melissa tel;pager:217-467-3807 tel;fax:217-545-0192 tel;work:217-545-2132 x-mozilla-html:FALSE org:SIU School of Medicine;Education & Curriculum adr:;;801 N. Rutledge;Springfield;IL;62794-9622;United States version:2.1 email;internet:msurprenant@siumed.edu fn:Melissa K. Surprenant end:vcard --------------F11776759AD7A627AD23E4B5-- From ramrom@earthling.net Tue Nov 5 16:29:03 2002 From: ramrom@earthling.net (Bob Gailer) Date: Tue Nov 5 16:29:03 2002 Subject: [Tutor] small program, but I'm very confused In-Reply-To: <3DC830FC.6DC5DB01@siumed.edu> References: <3DC81A6A.4F1AB912@siumed.edu> <20021105194238.GB1135@i92.ryd.student.liu.se> <5.1.0.14.0.20021105132118.0341a360@66.28.54.253> Message-ID: <5.1.0.14.0.20021105142409.03411ac0@66.28.54.253> At 02:58 PM 11/5/2002 -0600, Melissa K. Surprenant wrote: >Yes, that part will run (I pasted it into a separate file). I'm telnetting >into a unix machine, so I changed the file path to the following: > >f=open('/tmp/listofusers', 'w') >f=open('/tmp/listofusers, 'r+') >f.write('\2\n') Well then I suggest adding pieces of code, perhaps one line at a time until you get the error, or, if it's like my experience, suddenly things will work just fine. Also it's superfluous to close f (as you did in your original code). Reassigning f closes the file as part of deleting the original instance. Also it's superfluous to f=open('/tmp/listofusers, 'r+'), as the original open accomplishes the same thing. Bob Gailer 170 Forsythe Rd Nederland CO 80466 303-442-2625 From SWidney@ci.las-vegas.nv.us Tue Nov 5 16:35:04 2002 From: SWidney@ci.las-vegas.nv.us (Scott Widney) Date: Tue Nov 5 16:35:04 2002 Subject: [Tutor] small program, but I'm very confused Message-ID: <0E5508EBA1620743B409A2B8365DE16FDC8223@sovereign.ci.las-vegas.nv.us> > #creates the file > f=open('/tmp/listofusers', 'w') Sidebar: If you are only writing to the file in this process, and you intend to close it at the end of the process, then the following three lines are unnecessary > f.close() > #opens the file for writing > f=open('/tmp/listofusers', 'r+') Correct me if I am wrong here...: > # searches the password file, hopefully should write the second regexp to > thefile > > for y in loginsList: > re.findall(('^loginsList[y]:x:[0-9]{4}:[0-9]{2,3}:)([A-Za-z]\s[A-Za-z]) > (.*?)(/n)','/etc/passwd') ...but it looks like this is discarding the results of re.findall (not assigning it to anything)... > f.write('\2\n') ...and this is trying to write the hexadecimal value x02 and a newline to the file. Using \2 only applies within the regular expression. If you assign the results of re.findall() to a list variable, the second element should correspond to the second group in you regex. ### untested for y in loginsList: groups = re.findall(('^loginsList[y]:x:[0-9]{4}:[0-9]{2,3}:) ([A-Za-z]\s[A-Za-z])(.*?)(/n)','/etc/passwd') f.write("%s\n" % (groups[2],)) ### or something like that Scott From msurprenant@siumed.edu Tue Nov 5 17:10:02 2002 From: msurprenant@siumed.edu (Melissa K. Surprenant) Date: Tue Nov 5 17:10:02 2002 Subject: [Tutor] small program, but I'm very confused References: <0E5508EBA1620743B409A2B8365DE16FDC8223@sovereign.ci.las-vegas.nv.us> Message-ID: <3DC8417E.95A81A4D@siumed.edu> This is a multi-part message in MIME format. --------------697C6D47E45A6C0D19405017 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit I appreciate all the help. I have made the recommended changes, and I still get the error. I suspected I might have been missing something with the re.findall, but I didn't know what it was. It is already one class period late (25% off), so I'm just going to turn it in this way. Everyone, thanks again! Scott Widney wrote: > > #creates the file > > f=open('/tmp/listofusers', 'w') > > Sidebar: If you are only writing to the file in this process, and you intend > to close it at the end of the process, then the following three lines are > unnecessary > > > f.close() > > #opens the file for writing > > f=open('/tmp/listofusers', 'r+') > > Correct me if I am wrong here...: > > > # searches the password file, hopefully should write the second regexp to > > thefile > > > > for y in loginsList: > > > re.findall(('^loginsList[y]:x:[0-9]{4}:[0-9]{2,3}:)([A-Za-z]\s[A-Za-z]) > > (.*?)(/n)','/etc/passwd') > > ...but it looks like this is discarding the results of re.findall (not > assigning it to anything)... > > > f.write('\2\n') > > ...and this is trying to write the hexadecimal value x02 and a newline to > the file. Using \2 only applies within the regular expression. If you assign > the results of re.findall() to a list variable, the second element should > correspond to the second group in you regex. > > ### untested > for y in loginsList: > groups = re.findall(('^loginsList[y]:x:[0-9]{4}:[0-9]{2,3}:) > ([A-Za-z]\s[A-Za-z])(.*?)(/n)','/etc/passwd') > f.write("%s\n" % (groups[2],)) > ### or something like that > > Scott > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor --------------697C6D47E45A6C0D19405017 Content-Type: text/x-vcard; charset=us-ascii; name="msurprenant.vcf" Content-Transfer-Encoding: 7bit Content-Description: Card for Melissa K. Surprenant Content-Disposition: attachment; filename="msurprenant.vcf" begin:vcard n:Surprenant;Melissa tel;pager:217-467-3807 tel;fax:217-545-0192 tel;work:217-545-2132 x-mozilla-html:FALSE org:SIU School of Medicine;Education & Curriculum adr:;;801 N. Rutledge;Springfield;IL;62794-9622;United States version:2.1 email;internet:msurprenant@siumed.edu fn:Melissa K. Surprenant end:vcard --------------697C6D47E45A6C0D19405017-- From anderson@nkbj.co.jp Tue Nov 5 21:30:02 2002 From: anderson@nkbj.co.jp (Robert M. Anderson) Date: Tue Nov 5 21:30:02 2002 Subject: [Tutor] ASCII and Unicode References: <200211051115.22987.w.richert@gmx.net> Message-ID: <001d01c2853d$08ee00f0$840ca8c0@eanderson> PiAyKSBDaGFuZ2UgeW91ciBzaXRlLnB5IChvbiBteSBob3N0OiAvdXNyL2xpYi9weXRob24vc2l0 ZS5weSk6DQo+IGZyb20NCj4gZW5jb2RpbmcgPSAiYXNjaWkiDQo+IHRvDQo+IGVuY29kaW5nID0g Imlzbzg4NTktMTUiDQoNCkknbSBzdHJ1Z2dsaW5nIHdpdGggdGhpcyBzYW1lIHByb2JsZW0gd2l0 aCBKYXBhbmVzZSByaWdodCBub3cuIEkgd29yayBpbiBhIG1peGVkIFdpbmRvd3MvTWFjIGVudmly b25tZW50LCBhbmQgYWx0aG91Z2ggSSdtIGFibGUgdG8gZG93bmxvYWQgYSAiSmFwYW5pemVkIiBX aW5kb3dzIHZlcnNpb24gb2YgUHl0aG9uICh3aGljaCBpbmNsdWRlcyB0aGUgcHJvcGVyIGNvZGVj cyBhbmQgc2V0dGluZ3MgZm9yIHVzZSB3aXRoIEphcGFuZXNlIHRleHQgIm91dCBvZiB0aGUgYm94 IiksIHdoYXQgZG8gSSBkbyBhYm91dCBNYWMgaW5zdGFsbGF0aW9ucz8NCg0KSSdkIHJlYWxseSBs aWtlIHRvIGtub3cgbW9yZSBhYm91dCBjb2RlY3MgKEkgZG9uJ3QgcmVhbGx5IHVuZGVyc3RhbmQg d2hhdCB0aGlzIGlzIGFib3V0KSBhbmQgZW5jb2RpbmdzIGxpa2UgdGhlIG9uZSBxdW90ZWQgYWJv dmUuIEhvdyBkbyBJIGZpbmQgb3V0IHdoaWNoIGVuY29kaW5ncyBhcmUgdmFsaWQ/IEhvdyBkbyBJ IGluc3RhbGwgbmV3IGVuY29kaW5ncz8gSSd2ZSBzZWFyY2hlZCBoaWdoIGEgbG93IGZvciBhbnN3 ZXJzIG9uIHRoZSB3ZWIsIGJ1dCB0aGV5J3JlIGVpdGhlciBvdmVyLXNpbXBsaWZpY2F0aW9ucyBv ciB0b28gdGVjaG5pY2FsIChpLmUuIGZvciBjb2RlYyBjcmVhdG9ycykuDQoNCkFueSBoZWxwIHdv dWxkIGJlIGFwcHJlY2lhdGVkLg0KDQpSZWdhcmRzLA0KDQpSb2JlcnQgTS4gQW5kZXJzb24NCk5p a2tvIEdyYXBoaWMgQXJ0cyBDby4sIEx0ZC4NClNoaXp1b2thLCBKYXBhbg0K From nano@intermatik.co.id Tue Nov 5 22:09:01 2002 From: nano@intermatik.co.id (nano surbakti) Date: Tue Nov 5 22:09:01 2002 Subject: [Tutor] python for IBM A/S400 & Sun Message-ID: <1036543204.3117.6.camel@jrwd.internal.intermatik.com> Hi guys, Is there any python version that can be installed in IBM A/S 400 or Sun's mainframe product? TIA, nano' From Gillisai@btinternet.com Tue Nov 5 22:33:01 2002 From: Gillisai@btinternet.com (Alex Gillis) Date: Tue Nov 5 22:33:01 2002 Subject: [Tutor] What's the error (program) Message-ID: <000901c28543$f78b4dc0$5d2e7bd5@oemcomputer> OK, here is the recently annotated program thats causing problems. I hope you can understand it and I haven't done anything blatantly wrong. Feel free to critise anything, I haven't had any one who knows what they're doing look at anything I've written before so it'd be good to get some advice. #This is a juggling simulator for 3 balls only. Put in three integers #(say between 1 and 9) and the program should juggle the balls at #varying heights related to those three numbers. If you want a full #explaination of how the numbers work search for a notation called "siteswap". from visual import * import array #Creating the array the throw heights will be read from a = input("What is a?") b = input("What is b?") c = input("What is c?") siteswap = array.array('B',[a,b,c]) #Defining what happens between when the balls are caught and when they are #thrown. It's called scoop but its really just a horizontal movement. def scoopleft(ball): ball.velocity.x = 0.4 ball.velocity.y = 0 def scoopright(ball): ball.velocity.x = -0.4 ball.velocity.y = 0 i = 0 next_number = siteswap[i] #I guess this is the heart of the program. While a ball is in the air, the else #statement controls its flight. If its at either throw point then the two #bottom elif statements deal with it. If its not in the air but not ready #to be thrown then it is referred to one of the scoop functions. def throwcatch(ball): if ball.pos.y == 0: if ball.pos.x < -0.1: scoopleft(ball) elif ball.pos.x > 0.1: scoopright(ball) elif ball.pos.x == -0.1: ball.velocity.y = (next_number - 1)*1.25 ball.velocity.x = (next_number - 1)*1.2 elif ball.pos.x == 0.1: ball.velocity.y = (next_number - 1)*1.25 ball.velocity.x = -((next_number - 1)*1.2) else: ball.velocity.y = ball.velocity.y - 10*dt #The first few test programs didn't have perfect timing and would degenerate after a while #so every 0.25 seconds the ball going to be caught just gets moved to where it should be. def justify(ball): if t == 25: if ball.pos.y <= 0.1: ball.pos.y = 0 if 0 < ball.pos.x < 0.15: ball.pos.x = 0.1 elif -0.15 < ball.pos.x < 0: ball.pos.x = -0.1 #Defining the "hands" left_hand = box(pos=(-0.15,0,0), length=0.12, height=0.03, width=0.1, color=color.blue) right_hand = box(pos=(0.15,0,0), length=0.12, height=0.03, width=0.1, color=color.blue) #Defining the balls ball1 = sphere(pos=(0.1,0,0), radius=0.05, color=color.green) ball1.velocity = vector(0,0,0) ball2 = sphere(pos=(-0.2,0,0), radius=0.05, color=color.red) ball2.velocity = vector(0,0,0) ball3 = sphere(pos=(0.3,0,0), radius=0.05, color=color.blue) ball3.velocity = vector(0,0,0) dt = 0.01 t = 1 while 1: rate(100) throwcatch(ball1) justify(ball1) throwcatch(ball2) justify(ball2) throwcatch(ball3) justify(ball3) t = t + 1 #If you've read the code carefully you'll have seen that every 0.25 seconds, #when t == 25 the next ball is thrown. This bit of code changes the next_number to be #thrown and resets the counter. if t == 25: t = 1 i = i + 1 if i == 3: i = 0 From magnus@thinkware.se Wed Nov 6 04:39:01 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Wed Nov 6 04:39:01 2002 Subject: [Tutor] python for IBM A/S400 & Sun In-Reply-To: <1036543204.3117.6.camel@jrwd.internal.intermatik.com> Message-ID: <5.1.0.14.0.20021106103836.02afea98@www.thinkware.se> At 10:05 2002-11-06 +0700, nano surbakti wrote: >Is there any python version that can be installed in IBM A/S 400 or >Sun's mainframe product? Did you look at the Python web site? http://www.python.org/download/download_other.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 magnus@thinkware.se Wed Nov 6 07:27:03 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Wed Nov 6 07:27:03 2002 Subject: [Tutor] What's the error (program) In-Reply-To: <000901c28543$f78b4dc0$5d2e7bd5@oemcomputer> Message-ID: <5.1.0.14.0.20021106104604.0441aca0@www.thinkware.se> At 03:24 2002-11-06 +0000, Alex Gillis wrote: >OK, here is the recently annotated program thats causing problems. I hope >you can understand it and I haven't done anything blatantly wrong. Feel >free to critise anything, I haven't had any one who knows what they're doing >look at anything I've written before so it'd be good to get some advice. >from visual import * Using this form of import is generally bad practice. I know that particularly GUI toolkits use this form, but then they usually have a specific prefix on all imported variables. Now, it's difficult for us to see what yo have imported. If you use an IDE that can show objects, or if you do dir(), you might see hundreds or thousands of objects you don't need. Please use import visual or from visual import x, y, z (where x, y and z would be the names you import of course.) >#I guess this is the heart of the program. While a ball is in the air, the >else >#statement controls its flight. If its at either throw point then the two >#bottom elif statements deal with it. If its not in the air but not ready >#to be thrown then it is referred to one of the scoop functions. > >def throwcatch(ball): > if ball.pos.y == 0: Is this safe? Why not "ball.pos.y <= 0"? >>> dt = 0.1 >>> dt-dt 0.0 >>> dt+dt-dt-dt 0.0 >>> dt+dt+dt-dt-dt-dt 2.7755575615628914e-017 >>> dt+dt+dt-dt-dt-dt == 0 0 >>> dt = 0.01 >>> dt-dt 0.0 >>> dt+dt-dt-dt 0.0 >>> dt+dt+dt-dt-dt-dt -3.4694469519536142e-018 >>> dt+dt+dt-dt-dt-dt == 0 0 It's good rule NEVER to compare float on equality. I think we've discussed the binary nature of floats in programs before. -- 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 Nov 6 11:00:02 2002 From: brad.reisfeld@colostate.edu (Brad Reisfeld) Date: Wed Nov 6 11:00:02 2002 Subject: [Tutor] Recording and eliminating continuation lines Message-ID: Hi, I have a file containing a number of lines that I will need to parse. Continuation lines in the file are indicated with a backslash at the end of the line. I would like to eliminate the continuations, but track which 'physical lines' lead to each 'logical line'. For instance, given the input: """This is some text. Here is some more text \ that continues here \ and here. This is the final line.""" I'd like this type of output: [((1,), 'This is some text.'), ((2, 3, 4), 'Here is some more text that continues here and here.'), ((5,), ''), ((6,), 'This is the final line.')] Here, as you can see, each tuple has ((numbers of the physical lines leading to the logical line), logical line) Currently, I am using the following rather inelegant function: -----begin function----- def _test(): import string mtext = """This is some text. Here is some more text \\ that continues here \\ and here. This is the final line.""" all_lines = map(string.strip,mtext.split('\n')) numbered_lines = zip(range(1,len(all_lines)+1),all_lines) logical_lines = [] cline = '' cnum = [] for mnum,mline in numbered_lines: cline = cline + mline cnum = cnum + [mnum] if not cline.endswith('\\'): logical_lines.append((tuple(cnum),cline)) cline = '' cnum = [] else: cline = cline[:-1] # eliminate continuation character return logical_lines -----end function----- Any suggestions for a better solution are appreciated. Regards, Brad From ramrom@earthling.net Wed Nov 6 11:36:17 2002 From: ramrom@earthling.net (Bob Gailer) Date: Wed Nov 6 11:36:17 2002 Subject: [Tutor] small program, but I'm very confused In-Reply-To: <3DC8417E.95A81A4D@siumed.edu> References: <0E5508EBA1620743B409A2B8365DE16FDC8223@sovereign.ci.las-vegas.nv.us> Message-ID: <5.1.0.14.0.20021106093348.01bd19d8@66.28.54.253> >re.findall(('^loginsList[y]:x:[0-9]{4}:[0-9]{2,3}:)([A-Za-z]\s[A-Za-z]) > (.*?)(/n)','/etc/passwd') Unbalanced parentheses. Change to: re.findall('^loginsList[y]:x:[0-9]{4}:[0-9]{2,3}:)([A-Za-z]\s[A-Za-z]) (.*?)(/n)','/etc/passwd') Bob Gailer 170 Forsythe Rd Nederland CO 80466 303-442-2625 From ramrom@earthling.net Wed Nov 6 12:09:02 2002 From: ramrom@earthling.net (Bob Gailer) Date: Wed Nov 6 12:09:02 2002 Subject: [Tutor] Recording and eliminating continuation lines In-Reply-To: Message-ID: <5.1.0.14.0.20021106100339.02e7ef50@66.28.54.253> At 08:59 AM 11/6/2002 -0700, Brad Reisfeld wrote: >I have a file containing a number of lines that I will need to parse. >Continuation lines in the file are indicated with a backslash at the end of >the line. I would like to eliminate the continuations, but track which >'physical lines' lead to each 'logical line'. I started out to write my own version and found that is was much like yours. Assuming that I am a perfect programmer, then you must be one too. The only thing I'd change is eliminate import string and use the native string strip method. BTW what would make it "better"? Less lines; more sophisticated use of builtins? or ??? Bob Gailer 170 Forsythe Rd Nederland CO 80466 303-442-2625 From alan.gauld@bt.com Wed Nov 6 12:40:02 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed Nov 6 12:40:02 2002 Subject: [Tutor] python for IBM A/S400 & Sun Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA1B@mbtlipnt02.btlabs.bt.co.uk> > Is there any python version that can be installed in IBM A/S 400 or > Sun's mainframe product? Suns 'mainframe' s still running Solaris so yes, the normal Solaris build should work fine. Whether your operations team(assuming you have such) will allow it to be installed is another matter! Alan g From alan.gauld@bt.com Wed Nov 6 12:45:20 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed Nov 6 12:45:20 2002 Subject: [Tutor] Recording and eliminating continuation lines Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA1C@mbtlipnt02.btlabs.bt.co.uk> Yu could use the technique used by video editor programs. Create a file that stores the character position of the breaks (the timecode of scenes in video terms). Then read the whole thing into a single string. Manipulate the string9assuming you don't delete chars of course - if you do you need to update the char counters beyond the deleted character. Then when you need to know the physical line number simply find the current index and see which line it corresponds to by comparing the index with the line break counts... HTH, Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From dyoo@hkn.eecs.berkeley.edu Wed Nov 6 13:02:01 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Nov 6 13:02:01 2002 Subject: [Tutor] What's the error (program) [use lists in favor of arrays] In-Reply-To: <000901c28543$f78b4dc0$5d2e7bd5@oemcomputer> Message-ID: Hi Alex, Ok, let's take a look at your program... or at least the first few lines. *grin* > import array [ some text cut] > siteswap = array.array('B',[a,b,c]) The 'array' module has a specialized purpose: it's meant to store collections of very primitive objects (numbers, strings) in a way that guarantees how they're being stored in memory. But this is a behavior that you probably don't need to use at the moment. Your array above is telling Python that you only want to store 'unsigned characters' in your collection, but that's highly restrictive, since the numbers in the collection can only range between 0 and 255! So the binary size restriction that we're placing on each array element may not be helpful. In many cases, a plain Python list is easier to work with: ### siteswap = [a, b, c] ## Are you coming from a language that uses arrays? If so, try out Python lists: you may find them very versatile and unrestrictive. I have to go at the moment, but I'll try taking a look at the rest of your program when I have more time. Good luck to you! From wheelcrdan@hotmail.com Wed Nov 6 13:13:02 2002 From: wheelcrdan@hotmail.com (Dan Dud) Date: Wed Nov 6 13:13:02 2002 Subject: [Tutor] Capitalization what does it do exactly Message-ID: Hello everyone, I appreachate everyone help over the last couple of months.. Anyways, I have noticed in alot of the materaial, I have been reading.. Certian words are completly capitalized... What does that mean when you do that.. Thanks ahead of time to everyone and all everyone help.. Danny D _________________________________________________________________ Protect your PC - get McAfee.com VirusScan Online http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963 From abarker@xminc.com Wed Nov 6 13:22:02 2002 From: abarker@xminc.com (Anthony Barker) Date: Wed Nov 6 13:22:02 2002 Subject: [Tutor] replicating data using python /zodb advice needed Message-ID: <40727.198.96.180.245.1036608004.squirrel@www.xminc.com> I need to replicate data and I want to use python which data format should I use and how should I do it? data formats I have looked at: xml FileSystem (zodb) berkeley db replication: I have looked at pysync which implements the rsync and xdelta algorithms or simply calling unison (written in o'camel) or rsync. If I write data to a file say using zodb FileSystem database and then replicate it using unison will only the changes go? Any advice? Anthony From mongo57a@comcast.net Wed Nov 6 13:23:02 2002 From: mongo57a@comcast.net (andy surany) Date: Wed Nov 6 13:23:02 2002 Subject: [Tutor] Question on Python and OFX (Open Financial Exchange) Message-ID: <001301c285c1$c0155100$2502a8c0@emily.ewndsr01.nj.comcast.net> Hello list! I know this is not going to be easy, but..... I need to grab OFX data from a financial web site and within my Python application, parse it, and use/manipulate it. I don't want to use a package like quicken to do this because it creates extra steps, and I have a multitude of platforms to support (Linux/MS/MAC). Has anyone on the list ever accessed an OFX file directly from a web site using a python program? TIA. -Andy From dman@dman.ddts.net Wed Nov 6 13:37:02 2002 From: dman@dman.ddts.net (Derrick 'dman' Hudson) Date: Wed Nov 6 13:37:02 2002 Subject: [Tutor] Re: Capitalization what does it do exactly In-Reply-To: References: Message-ID: <20021106184856.GA27038@dman.ddts.net> --5mCyUwZo2JvN/JJP Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Wed, Nov 06, 2002 at 11:11:28AM -0700, Dan Dud wrote: |=20 | Hello everyone, I appreachate everyone help over the last couple of=20 | months.. Anyways, I have noticed in alot of the materaial, I have been=20 | reading.. Certian words are completly capitalized... What does that mean= =20 | when you do that.. Thanks ahead of time to everyone and all everyone help= .. It is a convention meaning that the name refers to a constant value. In other words, the name will never refer to a different value other than the one it was initialized to. HTH, -D --=20 Your mouse has moved. You must restart Windows for your changes to take effect. =20 http://dman.ddts.net/~dman/ --5mCyUwZo2JvN/JJP 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 iEYEARECAAYFAj3JZBgACgkQO8l8XBKTpRRR/wCeICV/ul/JfTGAyZsVNgaLJxMY JqQAoKvS9M41xFHi72e+lKI3vIhUnBQg =vCsZ -----END PGP SIGNATURE----- --5mCyUwZo2JvN/JJP-- From wheelcrdan@hotmail.com Wed Nov 6 13:47:02 2002 From: wheelcrdan@hotmail.com (Dan Dud) Date: Wed Nov 6 13:47:02 2002 Subject: [Tutor] While loops Message-ID: Hello Everyone. I have a question about while loops.. I'm using python 2.2.2, and I'm on chapter 7 in "How to think like a computer scientist" The part I'm stuck on is 7.3 the only way I can make it work is to spell banana like 'b','a','n','a','n','a' I will print one letter per line. Like the example shows, but I doesn't show spelling banana like that. How do I make this work??? Also how do I print them in reverse??? I've tried to say print fruit fruit.reverse() print fruit but it will only print banana on one line.. What am I doing wrong?? Thanks for everyone help and talk to you all again soon... Sincerely Danny D _________________________________________________________________ Protect your PC - get McAfee.com VirusScan Online http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963 From ramrom@earthling.net Wed Nov 6 16:03:02 2002 From: ramrom@earthling.net (Bob Gailer) Date: Wed Nov 6 16:03:02 2002 Subject: [Tutor] Re: Capitalization what does it do exactly In-Reply-To: <20021106184856.GA27038@dman.ddts.net> References: Message-ID: <5.1.0.14.0.20021106135942.02eba278@66.28.54.253> At 01:48 PM 11/6/2002 -0500, Derrick 'dman' Hudson wrote: >......... >HTH Well, there's another capitalized "word". In this case it's an acronym, which, IMHO, means Hope This Helps. Now what the heck is IMHO? Bob Gailer 170 Forsythe Rd Nederland CO 80466 303-442-2625 From magnus@thinkware.se Wed Nov 6 16:15:02 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Wed Nov 6 16:15:02 2002 Subject: [Tutor] python for IBM A/S400 & Sun In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA1B@mbtlipnt02.btlabs .bt.co.uk> Message-ID: <5.1.0.14.0.20021106221044.02a12c80@www.thinkware.se> At 17:37 2002-11-06 +0000, alan.gauld@bt.com wrote: > > Is there any python version that can be installed in IBM A/S 400 or > > Sun's mainframe product? > >Suns 'mainframe' s still running Solaris so yes, the normal Solaris >build should work fine. Whether your operations team(assuming you >have such) will allow it to be installed is another matter! In other words...should the strategy be to ask for permission or to apologize sincerely afterwards if someone complains... The strategy here depends on several issues of course, such as how successful the python program will be, how critical the system is, the culture in the working place and your status at work... I installed Python as a local user in a Starfire box (it's more like a closet really) in a state authority where I worked as a consultant. I discussed it with my closest boss of course, and it was not a production machine, but a few months later there was a message from management that it wasn't allowed to download free software without an authorized purchase order! :) Then I was happy that Python was already available both on the Solaris box and on my Windows PC... -- 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 Wed Nov 6 16:29:02 2002 From: ramrom@earthling.net (Bob Gailer) Date: Wed Nov 6 16:29:02 2002 Subject: [Tutor] What's the error (program) In-Reply-To: <000901c28543$f78b4dc0$5d2e7bd5@oemcomputer> Message-ID: <5.1.0.14.0.20021106142428.02e88910@66.28.54.253> I downloaded Visual; running with Python 2.2.2. When I run the program I get the balls and the "hands" but nothing moves. I set up a very small program with one ball and a loop to change velocity and position. Position changes; velocity does not. Any ideas? Bob Gailer 170 Forsythe Rd Nederland CO 80466 303-442-2625 From magnus@thinkware.se Wed Nov 6 16:35:01 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Wed Nov 6 16:35:01 2002 Subject: [Tutor] Recording and eliminating continuation lines In-Reply-To: Message-ID: <5.1.0.14.0.20021106221902.00bd6930@www.thinkware.se> At 08:59 2002-11-06 -0700, Brad Reisfeld wrote: >I have a file containing a number of lines that I will need to parse. >Continuation lines in the file are indicated with a backslash at the end of >the line. I would like to eliminate the continuations, but track which >'physical lines' lead to each 'logical line'. > >For instance, given the input: >"""This is some text. >Here is some more text \ >that continues here \ >and here. > >This is the final line.""" > >I'd like this type of output: > >[((1,), 'This is some text.'), > ((2, 3, 4), 'Here is some more text that continues here and here.'), > ((5,), ''), > ((6,), 'This is the final line.')] Do one thing at a time! >>> text = r'''first row ends ... second row continued \ ... third row continued \ ... fourth row ends. ... Fifth row by itself.''' >>> rowList = [[]] >>> physRow = 1 >>> for row in text.split('\n'): ... rowList[-1].append(physRow) ... physRow += 1 ... if not row.endswith('\\'): ... rowList.append([]) ... >>> rowList [[1], [2, 3, 4], [5], []] >>> text = text.replace('\\\n','') >>> result = zip(rowList, text.split('\n')) >>> import pprint >>> pprint.pprint(result) [([1], 'first row ends'), ([2, 3, 4], 'second row continued third row continued fourth row ends.'), ([5], 'Fifth row by itself.')] If you feel it's important you can do a rowList = map(tuple, rowList) before the zip. -- 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 Nov 6 16:39:02 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Wed Nov 6 16:39:02 2002 Subject: [Tutor] Re: Capitalization what does it do exactly In-Reply-To: <5.1.0.14.0.20021106135942.02eba278@66.28.54.253> References: <20021106184856.GA27038@dman.ddts.net> Message-ID: <5.1.0.14.0.20021106224429.044bf148@www.thinkware.se> At 14:02 2002-11-06 -0700, Bob Gailer wrote: >At 01:48 PM 11/6/2002 -0500, Derrick 'dman' Hudson wrote: >>......... >>HTH > >Well, there's another capitalized "word". In this case it's an acronym, >which, IMHO, means Hope This Helps. >Now what the heck is IMHO? In My Honest Opinion this mail is off topic! -- 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 Nov 6 16:51:02 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Wed Nov 6 16:51:02 2002 Subject: [Tutor] Question on Python and OFX (Open Financial Exchange) In-Reply-To: <001301c285c1$c0155100$2502a8c0@emily.ewndsr01.nj.comcast.n et> Message-ID: <5.1.0.14.0.20021106224539.044bcb40@www.thinkware.se> At 13:24 2002-11-06 -0500, andy surany wrote: >Has anyone on the list ever accessed an OFX file directly from a web >site using a python program? Not yet! :) It's SGML as far as I understand. Parsing SGML is not for the faint hearted. That's basically why XML was invented. Have you seen http://step.polymtl.ca/~bock/libofx/ The best and simplest solution is probably to write a wrapper for that. SWIG might be helpful for that. As far as I understand, this hasn't been done, at least I can't find any reference to it. Here's your chance to contribute to Python's usefulness in the finance sector! -- 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 eruellan@iFrance.com Wed Nov 6 17:30:02 2002 From: eruellan@iFrance.com (Emmanuel Ruellan) Date: Wed Nov 6 17:30:02 2002 Subject: [Tutor] What's the error (program) Message-ID: <000101c285e3$f4291a40$344380d9@oemcomputer> Alex Gillis wrote: >OK, here is the recently annotated program thats causing >problems. [...] Hi Alex, I've had a look at your juggling simulator, tried to modify some things and managed to get a decent animation of a 3-ball cascade. I'm a beginner at programming as well, but I've got an interest in siteswap. Here's what I've done. In your program, each fraction of a second, the velocity of each ball in the air is modified because of gravity: > ball.velocity.y = ball.velocity.y - 10*dt Fine. But you forgot to modify the ball's position according to its velocity. I've inserted this function: def move(ball): ball.pos = ball.pos + ball.velocity * dt ...as well as instructions like... move(balln) ...for each ball, in the main while loop. But that wasn't enough to get the program to work, so I also applied Magnus' advice not to compare floats on equality and modified the 'throwcatch' function accordingly, with conditions like: elif -0.1 - epsilon < ball.pos.x < -0.1 + epsilon: (For the sake of aestethics and realism, I've changed the formula for horizontal velocity as well ;) -- I'm sending comment on the juggling issues to your mailbox.) I've found another error that doesn't show in the 3-ball cascade, though. After incrementing i, don't forget to modifiy next_value as well by: next_value = siteswap[i] ...otherwise, there's no point in incrementing i. Talking of incrementation, you can write : i = (i + 1) % 3 instead of > i = i + 1 > > if i == 3: > i = 0 Regards, Manu From Jason_Kemper/FTMorgan/phccorp@prhc.net Wed Nov 6 17:59:02 2002 From: Jason_Kemper/FTMorgan/phccorp@prhc.net (Jason_Kemper/FTMorgan/phccorp@prhc.net) Date: Wed Nov 6 17:59:02 2002 Subject: [Tutor] Re: Capitalization what does it do exactly Message-ID: --0__=09BBE6FADFE64D5D8f9e8a93df938690918c09BBE6FADFE64D5D Content-type: text/plain; charset=us-ascii IMNSHO, IMHO stands for In My Humble Opinion. I'll leave it as an exercise to the reader to figure out IMNSHO. ;-) -Jason At 01:48 PM 11/6/2002 -0500, Derrick 'dman' Hudson wrote: >......... >HTH Well, there's another capitalized "word". In this case it's an acronym, which, IMHO, means Hope This Helps. Now what the heck is IMHO? Bob Gailer 170 Forsythe Rd Nederland CO 80466 303-442-2625 _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor --0__=09BBE6FADFE64D5D8f9e8a93df938690918c09BBE6FADFE64D5D Content-type: application/octet-stream; name="$RFC822.eml" Content-Disposition: attachment; filename="$RFC822.eml" Content-transfer-encoding: base64 UmVjZWl2ZWQ6IGZyb20gbWFpbC5weXRob24ub3JnIChbMTIuMTU1LjExNy4yOV0pDQogICAgICAg ICAgYnkgUEhDLU1BSUwtMSAoTG90dXMgRG9taW5vIFJlbGVhc2UgNS4wLjExKQ0KICAgICAgICAg IHdpdGggU01UUCBpZCAyMDAyMTEwNjE1MDYxOTAyOjU3ODEgOw0KICAgICAgICAgIFdlZCwgNiBO b3YgMjAwMiAxNTowNjoxOSAtMDYwMCANClJlY2VpdmVkOiBmcm9tIGxvY2FsaG9zdC5sb2NhbGRv bWFpbiAoWzEyNy4wLjAuMV0gaGVsbz1tYWlsLnB5dGhvbi5vcmcpDQoJYnkgbWFpbC5weXRob24u b3JnIHdpdGggZXNtdHAgKEV4aW0gNC4wNSkNCglpZCAxODlYS0wtMDAwMXpMLTAwOyBXZWQsIDA2 IE5vdiAyMDAyIDE2OjAzOjA1IC0wNTAwDQpSZWNlaXZlZDogZnJvbSBwb3BvY2F0ZXBldGwubWFn bm9saWFyb2FkLm5ldCAoWzY2LjI4LjU0LjI1M10pDQoJYnkgbWFpbC5weXRob24ub3JnIHdpdGgg ZXNtdHAgKEV4aW0gNC4wNSkNCglpZCAxODlYSnotMDAwMXhNLTAwDQoJZm9yIHR1dG9yQHB5dGhv bi5vcmc7IFdlZCwgMDYgTm92IDIwMDIgMTY6MDI6NDMgLTA1MDANClJlY2VpdmVkOiBmcm9tIGhl cmN1bGVzLmVhcnRobGluZy5uZXQgKGNwZS02Ni0yOC01NC0yMTIubWFnbm9saWFyb2FkLm5ldCBb NjYuMjguNTQuMjEyXSkNCglieSBwb3BvY2F0ZXBldGwubWFnbm9saWFyb2FkLm5ldCAoUG9zdGZp eCkgd2l0aCBFU01UUA0KCWlkIDdCOTVFMjI4Mjk1OyBXZWQsICA2IE5vdiAyMDAyIDE0OjAyOjI4 IC0wNzAwIChNU1QpDQpNZXNzYWdlLUlkOiA8NS4xLjAuMTQuMC4yMDAyMTEwNjEzNTk0Mi4wMmVi YTI3OEA2Ni4yOC41NC4yNTM+DQpYLVNlbmRlcjogYm9iLmdhaWxlckA2Ni4yOC41NC4yNTMNClgt TWFpbGVyOiBRVUFMQ09NTSBXaW5kb3dzIEV1ZG9yYSBWZXJzaW9uIDUuMQ0KVG86ICJEZXJyaWNr ICdkbWFuJyBIdWRzb24iIDxkbWFuQGRtYW4uZGR0cy5uZXQ+LCB0dXRvckBweXRob24ub3JnDQpG cm9tOiBCb2IgR2FpbGVyIDxyYW1yb21AZWFydGhsaW5nLm5ldD4NClN1YmplY3Q6IFJlOiBbVHV0 b3JdIFJlOiBDYXBpdGFsaXphdGlvbiB3aGF0IGRvZXMgaXQgZG8gZXhhY3RseQ0KSW4tUmVwbHkt VG86IDwyMDAyMTEwNjE4NDg1Ni5HQTI3MDM4QGRtYW4uZGR0cy5uZXQ+DQpSZWZlcmVuY2VzOiA8 RjE2TnRERUptR3pyTENDdGd4ODAwMDAwNThjQGhvdG1haWwuY29tPg0KIDxGMTZOdERFSm1HenJM Q0N0Z3g4MDAwMDA1OGNAaG90bWFpbC5jb20+DQpNaW1lLVZlcnNpb246IDEuMA0KWC1TcGFtLVN0 YXR1czogTm8sIGhpdHM9LTAuNSByZXF1aXJlZD01LjAgdGVzdHM9SU5fUkVQX1RPLFJFRkVSRU5D RVMsU1BBTV9QSFJBU0VfMDBfMDENClgtU3BhbS1MZXZlbDogDQpTZW5kZXI6IHR1dG9yLWFkbWlu QHB5dGhvbi5vcmcNCkVycm9ycy1UbzogdHV0b3ItYWRtaW5AcHl0aG9uLm9yZw0KWC1CZWVuVGhl cmU6IHR1dG9yQHB5dGhvbi5vcmcNClgtTWFpbG1hbi1WZXJzaW9uOiAyLjAuMTMgKDEwMTI3MCkN ClByZWNlZGVuY2U6IGJ1bGsNCkxpc3QtSGVscDogPG1haWx0bzp0dXRvci1yZXF1ZXN0QHB5dGhv bi5vcmc/c3ViamVjdD1oZWxwPg0KTGlzdC1Qb3N0OiA8bWFpbHRvOnR1dG9yQHB5dGhvbi5vcmc+ DQpMaXN0LVN1YnNjcmliZTogPGh0dHA6Ly9tYWlsLnB5dGhvbi5vcmcvbWFpbG1hbi9saXN0aW5m by90dXRvcj4sDQoJPG1haWx0bzp0dXRvci1yZXF1ZXN0QHB5dGhvbi5vcmc/c3ViamVjdD1zdWJz Y3JpYmU+DQpMaXN0LUlkOiBEaXNjdXNzaW9uIGZvciBsZWFybmluZyBwcm9ncmFtbWluZyB3aXRo IFB5dGhvbiA8dHV0b3IucHl0aG9uLm9yZz4NCkxpc3QtVW5zdWJzY3JpYmU6IDxodHRwOi8vbWFp bC5weXRob24ub3JnL21haWxtYW4vbGlzdGluZm8vdHV0b3I+LA0KCTxtYWlsdG86dHV0b3ItcmVx dWVzdEBweXRob24ub3JnP3N1YmplY3Q9dW5zdWJzY3JpYmU+DQpMaXN0LUFyY2hpdmU6IDxodHRw Oi8vbWFpbC5weXRob24ub3JnL3BpcGVybWFpbC90dXRvci8+DQpYLU9yaWdpbmFsLURhdGU6IFdl ZCwgMDYgTm92IDIwMDIgMTQ6MDI6MDEgLTA3MDANCkRhdGU6IFdlZCwgMDYgTm92IDIwMDIgMTQ6 MDI6MDEgLTA3MDANClgtTUlNRVRyYWNrOiBJdGVtaXplIGJ5IFNNVFAgU2VydmVyIG9uIFBIQ19N QUlMMS9waGNjb3JwKFJlbGVhc2UgNS4wLjExICB8SnVseSAyNCwgMjAwMikgYXQNCiAxMS8wNi8y MDAyIDAzOjA2OjE5IFBNLA0KCVNlcmlhbGl6ZSBieSBSb3V0ZXIgb24gUEhDX01BSUwxL3BoY2Nv cnAoUmVsZWFzZSA1LjAuMTEgIHxKdWx5IDI0LCAyMDAyKSBhdA0KIDExLzA2LzIwMDIgMDM6MDY6 MjEgUE0sDQoJU2VyaWFsaXplIGNvbXBsZXRlIGF0IDExLzA2LzIwMDIgMDM6MDY6MjEgUE0NClgt Tm90ZXMtSXRlbTogMjE7DQogdHlwZT0zMDA7IG5hbWU9JEhvcHMNClgtTm90ZXMtSXRlbTogTWVt bzsNCiBuYW1lPUZvcm0NClgtTm90ZXMtSXRlbTogdTAwMDAwMDA7DQogbmFtZT1OQUkxMDE1NjQN ClgtTm90ZXMtSXRlbTogTkFJIC0gQXdhaXRpbmcgc2NhbiBmb3IgdmlydXNlczsNCiBuYW1lPURl YWRGYWlsdXJlUmVhc29uDQpYLU5vdGVzLUl0ZW06IFVOREVBRDsNCiBuYW1lPVJvdXRpbmdTdGF0 ZQ0KWC1Ob3Rlcy1JdGVtOiAsDQoJQ049UEhDX01BSUwxL089cGhjY29ycDsNCiB0eXBlPTUwMTsg ZmxhZ3M9NDQ7IG5hbWU9JFVwZGF0ZWRCeQ0KWC1Ob3Rlcy1JdGVtOiAwNi1Ob3YtMjAwMiAxNTow NjoxOSBDU1Q7DQogdHlwZT00MDE7IG5hbWU9JFJldmlzaW9ucw0KQ29udGVudC1UeXBlOiB0ZXh0 L3BsYWluOyBjaGFyc2V0PSJ1cy1hc2NpaSI7IGZvcm1hdD1mbG93ZWQNCg0KQXQgMDE6NDggUE0g MTEvNi8yMDAyIC0wNTAwLCBEZXJyaWNrICdkbWFuJyBIdWRzb24gd3JvdGU6DQo+Li4uLi4uLi4u DQo+SFRIDQoNCldlbGwsIHRoZXJlJ3MgYW5vdGhlciBjYXBpdGFsaXplZCAid29yZCIuIEluIHRo aXMgY2FzZSBpdCdzIGFuIGFjcm9ueW0sIA0Kd2hpY2gsIElNSE8sIG1lYW5zIEhvcGUgVGhpcyBI ZWxwcy4NCk5vdyB3aGF0IHRoZSBoZWNrIGlzIElNSE8/DQoNCkJvYiBHYWlsZXINCjE3MCBGb3Jz eXRoZSBSZA0KTmVkZXJsYW5kIENPIDgwNDY2DQozMDMtNDQyLTI2MjUNCg0KDQpfX19fX19fX19f X19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fXw0KVHV0b3IgbWFpbGxpc3QgIC0g IFR1dG9yQHB5dGhvbi5vcmcNCmh0dHA6Ly9tYWlsLnB5dGhvbi5vcmcvbWFpbG1hbi9saXN0aW5m by90dXRvcg0K --0__=09BBE6FADFE64D5D8f9e8a93df938690918c09BBE6FADFE64D5D-- From ramrom@earthling.net Wed Nov 6 18:17:01 2002 From: ramrom@earthling.net (Bob Gailer) Date: Wed Nov 6 18:17:01 2002 Subject: [Tutor] What's the error (program) In-Reply-To: <000101c285e3$f4291a40$344380d9@oemcomputer> Message-ID: <5.1.0.14.0.20021106161005.02ed4a30@66.28.54.253> Earlier I wrote: >I set up a very small program with one ball and a loop to change velocity >and position. >Position changes; velocity does not. Any ideas?: At 11:25 PM 11/6/2002 +0100, Emmanuel Ruellan wrote: >Fine. But you forgot to modify the ball's position according to its >velocity. I gather from this comment that velocity is not a property meaningful to visual objects. I have struggled with "Reference manual: introduction, and all the details about using Visual". Since it lacks an index and glossary it is impossible to look things up unless one already knows where to look. Bob Gailer 170 Forsythe Rd Nederland CO 80466 303-442-2625 From thomi@thomi.imail.net.nz Wed Nov 6 19:40:01 2002 From: thomi@thomi.imail.net.nz (Thomi Richards) Date: Wed Nov 6 19:40:01 2002 Subject: [Tutor] PIL palettes? Message-ID: <20021107133940.27d7e3dd.thomi@thomi.imail.net.nz> Hi there, I'm trying to make a program which takes a 256 color picture, works out what color palette it uses, and then converts other pictures to that same color palette, hopefully with some error diffusion, so the results do not look so bad. I can open the original image file, but how can i extract the palette? and how to apply that same palette to another file, with some error correction? I know i could do a pixel by pixel scan of the original file, adding all the RGB triplets to a list of colors, and then do a similar process to the files to be converted, but This is going to be harder, longer, and probably more CPU intensive. Any ideas/comments? THanks. -- Lord, what fools these mortals be! -- midsummer nights dream. Thomi Richards, thomi@imail.net.nz From dyoo@hkn.eecs.berkeley.edu Wed Nov 6 19:53:02 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Nov 6 19:53:02 2002 Subject: [Tutor] Re: Capitalization what does it do exactly In-Reply-To: <5.1.0.14.0.20021106224429.044bf148@www.thinkware.se> Message-ID: > >>HTH > > > >Well, there's another capitalized "word". In this case it's an acronym, > >which, IMHO, means Hope This Helps. Now what the heck is IMHO? > > In My Honest Opinion this mail is off topic! ... although it would be very easy to bring this back on track. *grin* Has anyone written a program to generate acronyms from a sentence? ### >>> def acronym(sentence): ... return join([word[0] for word in sentence]) ... >>> def join(words): ... return "".join(words) ... >>> acronym(["International", "Business", "Machines"]) 'IBM' >>> acronym(['I', 'Am', 'Not', 'A', 'Lawyer']) 'IANAL' ### This is a really simple function, perhaps too simple. (It's adapted from an example in the excellent book "Simply Scheme"). Are there any improvements we can make to something like this to make it better or cleaner? From nano@intermatik.co.id Wed Nov 6 22:19:01 2002 From: nano@intermatik.co.id (nano) Date: Wed Nov 6 22:19:01 2002 Subject: [Tutor] python for IBM A/S400 & Sun In-Reply-To: <1036543204.3117.6.camel@jrwd.internal.intermatik.com> References: <1036543204.3117.6.camel@jrwd.internal.intermatik.com> Message-ID: <1036638917.4569.5.camel@jrwd.internal.intermatik.com> Dear Magnus, Alan and everybody, Thanks for the answer, and sorry for not searching seriously in Python's site. nano' From idiot1@netzero.net Thu Nov 7 00:32:01 2002 From: idiot1@netzero.net (Kirk Bailey) Date: Thu Nov 7 00:32:01 2002 Subject: [Tutor] new menu Message-ID: <3DC9FADA.A89D1CC8@netzero.net> I created an intelligent mastermenu for Tinylist, giving links to major feature groups which are installed. If the feature is not present, it is not offered on themenu, no hacking of the thing is needed- it installs the domain name for you, to make it easy to use. This will be new to TL1.6.0. here is a link to the new script. http://www.tinylist.org/cgi-bin/TLmastermenu.py -- end Respectfully, Kirk D Bailey +---------------------"Thou Art Free." -Eris-----------------------+ | http://www.howlermonkey.net mailto:highprimate@howlermonkey.net | | KILL spam dead! http://www.scambusters.org/stopspam/#Pledge | | http://www.tinylist.org +--------+ mailto:grumpy@tinylist.org | +------------------Thinking| NORMAL |Thinking----------------------+ +--------+ --------------------------------------------- Introducing NetZero Long Distance 1st month Free! Sign up today at: www.netzerolongdistance.com From shalehperry@attbi.com Thu Nov 7 00:37:02 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Thu Nov 7 00:37:02 2002 Subject: [Tutor] Re: Capitalization what does it do exactly In-Reply-To: References: Message-ID: <200211062136.21038.shalehperry@attbi.com> On Wednesday 06 November 2002 16:52, Danny Yoo wrote: > > This is a really simple function, perhaps too simple. (It's adapted fr= om > an example in the excellent book "Simply Scheme"). > > Are there any improvements we can make to something like this to make i= t > better or cleaner? > I would like to see this take a string rather than a list. Of course tha= t=20 just requires a split() call (-: From magnus@thinkware.se Thu Nov 7 02:32:02 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Thu Nov 7 02:32:02 2002 Subject: [Tutor] Re: Capitalization what does it do exactly In-Reply-To: References: <5.1.0.14.0.20021106224429.044bf148@www.thinkware.se> Message-ID: <5.1.0.14.0.20021107080506.00bafe10@www.thinkware.se> At 16:52 2002-11-06 -0800, Danny Yoo wrote: > >>> def acronym(sentence): >... return join([word[0] for word in sentence]) >... > >>> def join(words): >... return "".join(words) >... > >>> acronym(["International", "Business", "Machines"]) >'IBM' > >>> acronym(['I', 'Am', 'Not', 'A', 'Lawyer']) >'IANAL' >### > >This is a really simple function, perhaps too simple. Two functions Danny! One too much I think... >Are there any improvements we can make to something like this to make it >better or cleaner? >>> def acronym(sentence): ... return "".join([word[0] for word in sentence.split()]) ... >>> print acronym('Painting your two horses often needed') Python Remove the split if you want to start with a list. What made you wrap such a tiny thing as "".join(words) in a function on its own? If you prefer to use regular expressions, you can make it somewhat shorter (not that it feels important). import re def acronym(sentence): return "".join(re.findall(r'\b\w',sentence)) Either of these will be confusing if the underlying concept (list comprehension and regular expressions) is unknown to you... Another approach would be to filter out upper case letters. It all depends on what you want. >>> print filter(lambda x: x in string.uppercase, "Think before yoU posT OR you'll be sorry!") TUTOR Or as a function using filter or list comprehension: >>> def getCaps(aString): ... import string ... return filter(lambda c: c in string.uppercase, aString) ... >>> print getCaps('If I Recall Correctly') IIRC >>> def getCaps(aString): ... import string ... return "".join([c for c in aString if c in string.uppercase]) ... >>> print getCaps('Read The Fine Manual') RTFM Of course if you have the getCaps function, you can use that to get "real" acronyms based on the initials. >>> print getCaps(string.capwords('inTerNational buSiness macHines')) IBM Does anyone know why there isn't a "asd asd".capwords() method? -- 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 thomi@thomi.imail.net.nz Thu Nov 7 04:21:16 2002 From: thomi@thomi.imail.net.nz (Thomi Richards) Date: Thu Nov 7 04:21:16 2002 Subject: [Tutor] PIL palettes? In-Reply-To: <20021107133940.27d7e3dd.thomi@thomi.imail.net.nz> References: <20021107133940.27d7e3dd.thomi@thomi.imail.net.nz> Message-ID: <20021107222036.039912ef.thomi@thomi.imail.net.nz> > Any ideas/comments? I guess i should be a little more specific: i have found the "palette" object, but i am stuck as to how to apply that palette to another image, so that the colors change?? the convert call doesn't do the trick, as far as i can see... -- Thomi Richards thomi@imail.net.nz http://thomi.imail.net.nz/ Thomi Richards, thomi@imail.net.nz From gmlloyd@onlink.net Thu Nov 7 04:39:01 2002 From: gmlloyd@onlink.net (gmlloyd) Date: Thu Nov 7 04:39:01 2002 Subject: [Tutor] two questions Message-ID: <3DCA3465.3268BF8F@onlink.net> Good morning. (1) Is it possible to capture key-presses (like: page up, page down, aroow keys, etc.) in Python program? In other words, is there a Python equivalent of the BASIC Inkey$ function? (2) Is it possible to change foreground or background colors within the Python command line interface? (i.e. not Idle) thanks, Geoff Lloyd From lumbricus@gmx.net Thu Nov 7 05:58:03 2002 From: lumbricus@gmx.net (lumbricus@gmx.net) Date: Thu Nov 7 05:58:03 2002 Subject: [Tutor] two questions References: <3DCA3465.3268BF8F@onlink.net> Message-ID: <2945.1036666621@www59.gmx.net> > Good morning. Dito! > (1) Is it possible to capture key-presses (like: page up, page down, > aroow keys, etc.) in Python program? In other words, is there a Python > equivalent of the BASIC Inkey$ function? > > (2) Is it possible to change foreground or background colors within the > Python command line interface? (i.e. not Idle) Yes. man curses import curses > thanks, > > Geoff Lloyd HTH, J"o! -- Wir beschliessen etwas, stellen das dann in den Raum und warten dann einige Zeit ab, was passiert. Wenn es dann kein grosses Geschrei gibt und keine Aufstaende, weil die meisten gar nicht begreifen, was da beschlossen wurde, dann machen wir weiter - Schritt fuer Schritt, bis es kein Zurueck mehr gibt. -- J-C Juncker +++ 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 Thu Nov 7 06:51:16 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Thu Nov 7 06:51:16 2002 Subject: [Tutor] two questions In-Reply-To: <3DCA3465.3268BF8F@onlink.net> Message-ID: <5.1.0.14.0.20021107115929.044be458@www.thinkware.se> At 04:37 2002-11-07 -0500, gmlloyd wrote: >Good morning. 04:37! Are you very early or very late? ;) >(1) Is it possible to capture key-presses (like: page up, page down, >aroow keys, etc.) in Python program? In other words, is there a Python >equivalent of the BASIC Inkey$ function? You should really tell us what OS you are using for such a question. I'm really not sure how to do it on AS/400 for instance... ;) Depending on your OS, there will be varying I/O features. Unix-like operating systems use curses etc. Surf to http://www.python.org/cgi-bin/faqw.py Type "keypress" in the search field. Press [Search] button (In case this doesn't work, it's entries 4.74, 4.94 and 8.2 in the FAQ.) For Windows, take a look in the Library Reference for the msvcrt module. >(2) Is it possible to change foreground or background colors within the >Python command line interface? (i.e. not Idle) I've seen it on unix at least. I'm not sure where... Basically you should be able to send escape sequences to stdout. I'm not sure exactly how though... Using Win 2000 I tried: >>> x = '\x1B[2J' # Clear screen >>> print x But that only prints a little left arrow followed by [2J. Writing x to a file and typing it gives the same result. >>> f = file('esc.txt') >>> f.write(x) >>> f.close() And then at the prompt C:\> type esc.txt Gives the same left-arrow followed by [2J. BUT: C:\> cat esc.txt will clear the screen as expected! (cat is a unix command for concatenating and displaying files. It's part of cygwin, which is a needed toolkit on any Windows box. So, there seems to be some kind of Windows buffering which is beyond my understanding... -- 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 Thu Nov 7 07:39:02 2002 From: brad.reisfeld@colostate.edu (Brad Reisfeld) Date: Thu Nov 7 07:39:02 2002 Subject: [Tutor] Recording and eliminating continuation lines In-Reply-To: <5.1.0.14.0.20021106221902.00bd6930@www.thinkware.se> Message-ID: Magnus Lycka wrote: > Do one thing at a time! > > >>> text = r'''first row ends > ... second row continued \ > ... third row continued \ > ... fourth row ends. > ... Fifth row by itself.''' > >>> rowList = [[]] > >>> physRow = 1 > >>> for row in text.split('\n'): > ... rowList[-1].append(physRow) > ... physRow += 1 > ... if not row.endswith('\\'): > ... rowList.append([]) > ... > >>> rowList > [[1], [2, 3, 4], [5], []] > >>> text = text.replace('\\\n','') > >>> result = zip(rowList, text.split('\n')) > >>> import pprint > >>> pprint.pprint(result) > [([1], 'first row ends'), > ([2, 3, 4], 'second row continued third row continued fourth row ends.'), > ([5], 'Fifth row by itself.')] > > If you feel it's important you can do a > rowList = map(tuple, rowList) > before the zip. Thank you for the suggestion. However, I think that in this case, it is better programming practice to do the line concatenation and physical line accounting in the same step. Using two different steps for these operations has a higher probability of getting things out of sync. Regards, Brad From emile@fenx.com Thu Nov 7 08:25:02 2002 From: emile@fenx.com (Emile van Sebille) Date: Thu Nov 7 08:25:02 2002 Subject: [Tutor] Re: While loops References: Message-ID: "Dan Dud" wrote in message news:F75ZtP0kvdIBirXXeQM000004aa@hotmail.com... > > > > > Hello Everyone. > > I have a question about while loops.. I'm using python 2.2.2, and I'm on > chapter 7 in "How to think like a computer scientist" The part I'm stuck on > is 7.3 the only way I can make it work is to spell banana like > 'b','a','n','a','n','a' I will print one letter per line. Like the example > shows, but I doesn't show spelling banana like that. How do I make this > work??? Also how do I print them in reverse??? I've tried to say > > print fruit > fruit.reverse() > print fruit > > but it will only print banana on one line.. What am I doing wrong?? Thanks > for everyone help and talk to you all again soon... A string is a sequence of characters that you can convert to a list, so start with: fruit = list("banana") and the rest will work out. If you've got something started using while, post what you've got so far so we can see what ]you're trying, otherwise I wouldn't consider while in this situation. HTH, -- Emile van Sebille emile@fenx.com --------- From Doug.Shawhan@gecits.ge.com Thu Nov 7 10:20:02 2002 From: Doug.Shawhan@gecits.ge.com (Doug.Shawhan@gecits.ge.com) Date: Thu Nov 7 10:20:02 2002 Subject: [Tutor] More efficient than glob? Message-ID: <47B6167F8E69D31194BA0008C7918D4205C54ED8@msxcvg02itscge.gecits.ge.com> I have a script that parses the contents of logfiles in a directory, puts the content in a database, then deletes the original logfile. The files are produced at a rate of about one per minute. Since there is well over a year's worth of logfiles (> 31536000 files) the following method: >>> import glob >>> files = glob.glob('\\tmp\\*') for each in files: open each add contents of each to database close each delete each ...would seem to use an undue amount of memory. Is there a more efficient way of doing this? Glob is pretty awesome for simplicity, but this method with a huge amount of files seems to gobble up 512 megs of ram in no time! :-) Thanks! d From yduppen@xs4all.nl Thu Nov 7 10:40:32 2002 From: yduppen@xs4all.nl (Yigal Duppen) Date: Thu Nov 7 10:40:32 2002 Subject: [Tutor] More efficient than glob? In-Reply-To: <47B6167F8E69D31194BA0008C7918D4205C54ED8@msxcvg02itscge.gecits.ge.com> References: <47B6167F8E69D31194BA0008C7918D4205C54ED8@msxcvg02itscge.gecits.ge.com> Message-ID: <200211071638.15918.yduppen@xs4all.nl> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Thursday 07 November 2002 16:20, Doug.Shawhan@gecits.ge.com wrote: > I have a script that parses the contents of logfiles in a directory, pu= ts > the content in a database, then deletes the original logfile. The files= are > produced at a rate of about one per minute. > > Since there is well over a year's worth of logfiles (> 31536000 files) = the > following method: > >>> import glob > >>> files =3D glob.glob('\\tmp\\*') > ...would seem to use an undue amount of memory. > Is there a more efficient way of doing this?=20 Usually I'd say generators, but in this particular case that won't work; = all=20 functions that return a list of files do _not_ use generators. So I can't give you a general solution, but if you logfiles have sensible= =20 names, you could use that to partition your logfiles. For example, let's assume that each logfile has the form mm-dd-hh-MM (two digits for the month, two for the day, etc...) We could then process all files by first looping through the files of mon= th=20 01, then those of month 02... By using an iterator, you would get something like this (untested): def log_glob(): =09for i in range(11): =09=09month =3D "%02d" % (i+1, ) =09=09files =3D glob.glob('\\tmp\\%s-*' % (month, )) =09=09for f in files: =09=09=09yield f for f in log_glob(): =09do_stuff() This would already use 12 times less memory. You could also iterate over both month and day, or ... YDD - --=20 http://www.xs4all.nl/~yduppen -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE9yojnLsKMuCf5EdwRApRzAJ9HYBazV7/Ks7Q908SsDo34KabJ6gCg8UjG gMigxRLQKFiJWG0gRzXQjIs=3D =3DAYU7 -----END PGP SIGNATURE----- From Doug.Shawhan@gecits.ge.com Thu Nov 7 10:51:02 2002 From: Doug.Shawhan@gecits.ge.com (Doug.Shawhan@gecits.ge.com) Date: Thu Nov 7 10:51:02 2002 Subject: [Tutor] More efficient than glob? Message-ID: <47B6167F8E69D31194BA0008C7918D4205C54ED9@msxcvg02itscge.gecits.ge.com> >> Since there is well over a year's worth of logfiles (> 31536000 files) the >> following method: >> >>> import glob >> >>> files = glob.glob('\\tmp\\*') >> ...would seem to use an undue amount of memory. >> Is there a more efficient way of doing this? > Usually I'd say generators, but in this particular case that won't work; all > functions that return a list of files do _not_ use generators. Heh. Good, because that would have lead me to the embarassing question: "What is a generator?" :-) > So I can't give you a general solution, but if you logfiles have sensible > names, you could use that to partition your logfiles. Yep. Logfiles are named with a straight unix date string: i.e. 1036683980 So smaller bites seems to be the key... Thanks for the advice! d From Doug.Shawhan@gecits.ge.com Thu Nov 7 11:08:02 2002 From: Doug.Shawhan@gecits.ge.com (Doug.Shawhan@gecits.ge.com) Date: Thu Nov 7 11:08:02 2002 Subject: [Tutor] More efficient than glob? Message-ID: <47B6167F8E69D31194BA0008C7918D4205C54EDA@msxcvg02itscge.gecits.ge.com> Woah. Pretty neat. What practical use for such a list is there? d -----Original Message----- From: Y. Duppen [mailto:yduppen@refactive.com] Sent: Thursday, November 07, 2002 9:58 AM To: Shawhan, Doug (CAP, ITS, US); tutor@python.org Subject: Re: [Tutor] More efficient than glob? -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 > Heh. Good, because that would have lead me to the embarassing question: > "What is a generator?" :-) http://www.python.org/doc/current/whatsnew/node5.html In effect, a generator allows you to create huge lists that take a minimal amount of memory. for example: from __future__ import generators def infiniteList(): start = 1 while 1: yield start start += 1 This function is a generator (as can be seen by the use of the keyword 'yield'). You usually use these functions in for-loops: for i in infiniteList(): print i The alternative would of course be impossible: you can *not* generate an infinite list up front and then iterate over it. In the case of generators, elements are generated while you are iterating... YDD - -- http://www.refactive.com -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE9yo1tLsKMuCf5EdwRAq1kAKCXJlcUxwLdihJazwgeBjCGuLV8TQCgu3HM j8XVjhPPKa6v0yvtUmumNlU= =bMYp -----END PGP SIGNATURE----- From mongo57a@comcast.net Thu Nov 7 11:09:18 2002 From: mongo57a@comcast.net (andy surany) Date: Thu Nov 7 11:09:18 2002 Subject: [Tutor] Question on Python and OFX (Open Financial Exchange) Message-ID: <002101c28678$11f8a2e0$2502a8c0@emily.ewndsr01.nj.comcast.net> Ok, I got a good handle on LibOFX from the author. But what is SWIG?? -Andy -----Original Message----- From: Magnus Lycka To: andy surany ; tutor@python.org Date: Wednesday, November 06, 2002 4:51 PM Subject: Re: [Tutor] Question on Python and OFX (Open Financial Exchange) >At 13:24 2002-11-06 -0500, andy surany wrote: >>Has anyone on the list ever accessed an OFX file directly from a web >>site using a python program? > >Not yet! :) > >It's SGML as far as I understand. Parsing SGML is not >for the faint hearted. That's basically why XML was >invented. > >Have you seen http://step.polymtl.ca/~bock/libofx/ > >The best and simplest solution is probably to write a >wrapper for that. SWIG might be helpful for that. > >As far as I understand, this hasn't been done, at >least I can't find any reference to it. Here's your >chance to contribute to Python's usefulness in the >finance sector! > > >-- >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 yduppen@xs4all.nl Thu Nov 7 11:21:21 2002 From: yduppen@xs4all.nl (Yigal Duppen) Date: Thu Nov 7 11:21:21 2002 Subject: [Tutor] More efficient than glob? In-Reply-To: <47B6167F8E69D31194BA0008C7918D4205C54EDA@msxcvg02itscge.gecits.ge.com> References: <47B6167F8E69D31194BA0008C7918D4205C54EDA@msxcvg02itscge.gecits.ge.com> Message-ID: <200211071720.04206.yduppen@xs4all.nl> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 >> for example: >> >> from __future__ import generators >> def infiniteList(): >> start = 1 >> while 1: >> yield start >> start += 1 > Woah. Pretty neat. > What practical use for such a list is there? None that I know of ;-) But if we look back at your example: def log_glob(): for i in range(11): month = "%02d" % (i+1, ) files = glob.glob('\\tmp\\%s-*' % (month, )) for f in files: yield f for f in log_glob(): do_stuff(f) the use becomes more obvious. The for f in log_glob() call starts the generator. This means the generator function will run until the first 'yield'. Then do_stuff will be called. Then the next generator pass will be started, etc... Since 'files = glob.glob ' takes a lot of memory, this is very important. Instead of loading all files at once in memory, the generator allows us to keep only parts of the list (in this case, each part identified by a month) in memory! Whenever one of the globs has been exhausted, it can be thrown away and the next batch can be loaded. And the rest of the code will never notice! Without generators this would have been impossible (or at least Very Hard). YDD - -- http://www.xs4all.nl/~yduppen -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.0 (GNU/Linux) iD8DBQE9ypKzLsKMuCf5EdwRAvewAKDXdakROR2gcZC2AoOx8Ro59QpPHACePWtQ T3uCJcbU5ZsCUevBszGQpAM= =vpEd -----END PGP SIGNATURE----- From Doug.Shawhan@gecits.ge.com Thu Nov 7 11:38:02 2002 From: Doug.Shawhan@gecits.ge.com (Doug.Shawhan@gecits.ge.com) Date: Thu Nov 7 11:38:02 2002 Subject: [Tutor] More efficient than glob? Message-ID: <47B6167F8E69D31194BA0008C7918D4205C54EDB@msxcvg02itscge.gecits.ge.com> Wow! Thanks. This is a big help. -----Original Message----- From: Yigal Duppen [mailto:yduppen@xs4all.nl] Sent: Thursday, November 07, 2002 10:20 AM To: Shawhan, Doug (CAP, ITS, US); tutor@python.org Subject: Re: [Tutor] More efficient than glob? -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 >> for example: >> >> from __future__ import generators >> def infiniteList(): >> start = 1 >> while 1: >> yield start >> start += 1 > Woah. Pretty neat. > What practical use for such a list is there? None that I know of ;-) But if we look back at your example: def log_glob(): for i in range(11): month = "%02d" % (i+1, ) files = glob.glob('\\tmp\\%s-*' % (month, )) for f in files: yield f for f in log_glob(): do_stuff(f) the use becomes more obvious. The for f in log_glob() call starts the generator. This means the generator function will run until the first 'yield'. Then do_stuff will be called. Then the next generator pass will be started, etc... Since 'files = glob.glob ' takes a lot of memory, this is very important. Instead of loading all files at once in memory, the generator allows us to keep only parts of the list (in this case, each part identified by a month) in memory! Whenever one of the globs has been exhausted, it can be thrown away and the next batch can be loaded. And the rest of the code will never notice! Without generators this would have been impossible (or at least Very Hard). YDD - -- http://www.xs4all.nl/~yduppen -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.0 (GNU/Linux) iD8DBQE9ypKzLsKMuCf5EdwRAvewAKDXdakROR2gcZC2AoOx8Ro59QpPHACePWtQ T3uCJcbU5ZsCUevBszGQpAM= =vpEd -----END PGP SIGNATURE----- From mongo57a@comcast.net Thu Nov 7 16:37:02 2002 From: mongo57a@comcast.net (andy surany) Date: Thu Nov 7 16:37:02 2002 Subject: [Tutor] Configuration of Tk Message-ID: <00af01c286a6$12036260$2502a8c0@emily.ewndsr01.nj.comcast.net> Hi group! After spending the day recovering from a system crash, I thought that I had recovered all of my files and configurations. However, executing the statement: from Tkinter import * yields the following error message: import _tkinter #If this fails your python may not be configured for Tk /usr/lib/python2.2/lib-dynload/_tkinter.so: undefined symbol: PyUnicode UCS2_AsUTF8String And sure enough, the library is missing. I tried updating the Tk rpm package (rpm -U ........) and it of course said that the package was already installed. So should I force a reinstall (rpm -iF .....)? Or is there some other problem? TIA -Andy From alan.gauld@bt.com Thu Nov 7 18:02:15 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu Nov 7 18:02:15 2002 Subject: [Tutor] two questions Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA20@mbtlipnt02.btlabs.bt.co.uk> > (1) Is it possible to capture key-presses (like: page up, page down, > aroow keys, etc.) in Python program? In other words, is there a Python > equivalent of the BASIC Inkey$ function? > Yes. Use curses on Unix or msvcrt on windows Example of latter on my online tutor in the event handling topic. > (2) Is it possible to change foreground or background colors > within the Python command line interface? (i.e. not Idle) That depends on what you are using. If its a paper based teletype then you can change the background colour by changing the paper! If its a vt100 series terminal you can use the DEC escape codes. If its a DOS window then you an use ANSI codes provided ANSI.SYS is loaded. The point is that Python doesn't know what kind of terminal you are using so doesn't know how to change it. These things are not standardised. Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From mongo57a@comcast.net Thu Nov 7 23:31:02 2002 From: mongo57a@comcast.net (andy surany) Date: Thu Nov 7 23:31:02 2002 Subject: [Tutor] Re: Configuration of Tk Message-ID: <00fe01c286df$d3c61bc0$2502a8c0@emily.ewndsr01.nj.comcast.net> Fixed. Corrupted python distribution - not Tk. Sorry to bother all. -----Original Message----- From: andy surany To: tutor@python.org Date: Thursday, November 07, 2002 4:38 PM Subject: Configuration of Tk >Hi group! > >After spending the day recovering from a system crash, I thought that I >had recovered all of my files and configurations. However, executing the >statement: > >from Tkinter import * > >yields the following error message: > >import _tkinter #If this fails your python may not be configured for Tk >/usr/lib/python2.2/lib-dynload/_tkinter.so: undefined symbol: PyUnicode >UCS2_AsUTF8String > >And sure enough, the library is missing. I tried updating the Tk rpm >package (rpm -U ........) and it of course said that the package was >already installed. So should I force a reinstall (rpm -iF .....)? Or is >there some other problem? > >TIA > >-Andy > From dyoo@hkn.eecs.berkeley.edu Fri Nov 8 00:06:11 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Nov 8 00:06:11 2002 Subject: [Tutor] Question on Python and OFX (Open Financial Exchange) In-Reply-To: <002101c28678$11f8a2e0$2502a8c0@emily.ewndsr01.nj.comcast.net> Message-ID: On Thu, 7 Nov 2002, andy surany wrote: > Ok, I got a good handle on LibOFX from the author. But what is SWIG?? Hello! SWIG is a utility for wrapping C code into Python modules, and it's great for reducing the amount of drudgery necessary to do this wrapping. For more information on it, we can take a look here: http://www.swig.org/ Hope this helps! From mongo57a@comcast.net Fri Nov 8 00:27:01 2002 From: mongo57a@comcast.net (andy surany) Date: Fri Nov 8 00:27:01 2002 Subject: [Tutor] Question on Python and OFX (Open Financial Exchange) Message-ID: <012001c286e7$806ba1e0$2502a8c0@emily.ewndsr01.nj.comcast.net> Yes, I have looked at SWIG and it will do the trick. However, I still have the problem of determining the communication stream necessary to obtain the files, so this is really going to take awhile........ (and may be over my head....). Thanks to all for your help. -Andy -----Original Message----- From: Danny Yoo To: andy surany Cc: Magnus Lycka ; tutor@python.org Date: Friday, November 08, 2002 12:06 AM Subject: Re: [Tutor] Question on Python and OFX (Open Financial Exchange) > > >On Thu, 7 Nov 2002, andy surany wrote: > >> Ok, I got a good handle on LibOFX from the author. But what is SWIG?? > >Hello! > >SWIG is a utility for wrapping C code into Python modules, and it's great >for reducing the amount of drudgery necessary to do this wrapping. > >For more information on it, we can take a look here: > > http://www.swig.org/ > > >Hope this helps! > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From dyoo@hkn.eecs.berkeley.edu Fri Nov 8 03:44:02 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Nov 8 03:44:02 2002 Subject: [tutor] Do I need to have a strong math skills to program In-Reply-To: Message-ID: On Sun, 3 Nov 2002, Dan Dud wrote: > Hope everyone weekend is going great. I working through the "how to > think like a computer scientist" I'm stuck on the part which you have to > define a hypotenuse triangle. I don't have a lot of math skills. Do I > have to have a lot of math skills to be good at programming??? I've > decided to skip that part and move on. I hope everyone weekend is going > great and I'll talk to you all soon... Hi Dan, I just wanted to jump back into this question because it's such a fun one to revisit. *grin* There are some advantages for knowing math: with some math knowledge, we can make analogies between computer techniques and math techniques. Warning: this message is very long, and halfway though, I just completely lose my head and jump into calculus. I didn't mean to; it just happened! *grin* You can read up to the middle, and stop there. But for those who've taken an introductory course in calculus... I dunno, maybe this will amuse you. Here's one problem in particular that shows a particular technique that's works with both computers and maths. Let's say that we had a number, and we'd like to turn it into a string. How hard would it be to transform that string into a integer? (A quick solution would use the string() built-in function, since it knows how to turn pretty much anything into a string... but let's pretend that we didn't know about it yet. Say that we had the number 12345. How could we turn it into the string "12345"? Well, let's try something simpler: let's go for just single digits: if we're given a number between 0 and 9, we can easily return the corresponding string: ### >>> def singleNumberToString(number): ... if number == 0: return "0" ... if number == 1: return "1" ... if number == 2: return "2" ... if number == 3: return "3" ... if number == 4: return "4" ... if number == 5: return "5" ... if number == 6: return "6" ... if number == 7: return "7" ... if number == 8: return "8" ... if number == 9: return "9" ... >>> singleNumberToString(3) '3' >>> singleNumberToString(3) + singleNumberToString(3) '33' ### That definition above is almost silly stupid. *grin* There are better ways of defining it, but let's leave it at that for the moment. So given any single-digit number, it's really easy to peek and figure out the last character. That's the "peek" part. Why does this get us closer? Well, because if we have something like 12345, we can first divide the whole thing by ten, and take the remainder: ### >>> 12345 % 10 5 ### and then run that through our little singleNumberToString() function: ### >>> singleNumberToString(5) '5' ### and now we've got the last digit. The problem is trying to do this sort of thing to the rest of the digits, and that's the "shift" part. It turns out that this isn't so bad: if we divide our number by 10, it's almost as if all the digits move to the right by one place (and the last digit jumps off the number); ### >>> 12345 / 10 1234 ### And now we can repeat our "peeking" process to get the next digit: ### >>> singleNumberToString(1234 % 10) '4' ### And now we've just picked up the second to last character. If we do this process over and over (peek, shift, peek, shift, ...), we'll eventually run out of digits, and that's when we know we're done. Then we can just join all the characters together, and we've got a stringified version of our number! I know I'm going fast, but I hope that made some sort of sense. Here's some code that implements this idea: ### >>> def turnNumberIntoString(number): ... characters = [] ... while number != 0: ... next_digit = number % 10 ... next_character = singleNumberToString(next_digit) ... characters.append(next_character) ... number = number / 10 ... characters.reverse() ... return ''.join(characters) ... >>> turnNumberIntoString(12345) '12345' ### [Here's where things go weird. The next section is somewhat advanced, now that I think about it. Argh; I don't know how to explain it well enough to make sense without calculus! If you get stuck on it, that's probably because I don't understand it well enough to explain it well.] This "peek and shift" trick is something that mathematicians use too! As a particular example, mathematicians use the peek-and-shift technique whenever they apply something called "Taylor's Expansion". Taylor's expansion says that some math functions can be transformed into a huge polynomial, a "power series". That is, Taylor's theorem says that, for a function --- let's call it f(x) --- it's possible to transform it into a huge powers series in x. For example, the exponential function: f(x) = e**x can be considered to be a power series that looks, oddly enough, like this: e**x = 1 + x/1 + x**2/(1*2) + x**3/(1*2*3) + x**4/(1*2*3*4)... or, more concisely, e**x = sum (1/n!) * (x**n) n > 0 When I saw this, I didn't believe it at first. Does this even work? But we can try it when x is equal to 1: ### >>> math.e 2.7182818284590451 ### What happens when we plug 1 into the power series? We should get math.e. But since we can't evaluate an infinite sum numerically, I'll just satisfy myself if the first few terms work out. ### >>> def simulate_e(): ... sum = 0 ... for n in range(10): ... sum = sum + 1.0 / factorial(n) ... return sum ... >>> def factorial(n): ... if n == 0: return 1 ... return n * factorial(n-1) ... >>> simulate_e() 2.7182815255731922 ### Wow! So that comes pretty close, even with just ten terms of that infinite sum. In general, for the functions where Taylor's expansion works, the power series will have the form: f(x) = a_0 * x**0 + a_1 * x**1 + a_2 * x**2 + ... which is just another way of saying: f(x) = sum a_n * (x**n) n > 0 Nice and general, and totally nondescriptive. *grin* What all of those darn a_n's about?! And how did do we know that the nth coefficient of the e**x expansion is (1/n!)? That's where the peek-and-shift technique comes into play. What's neat about this is that the only tools we need is the mere _belief_ that such a series exists. Well, that and differentiation. Let's pretend, for the moment, that we do know that e**x can be expanded, but we have no clue whatsover what the coefficients will look like. What to do? Well, we can at least look at the very first coefficient a_0: we can "peek" at it by seeing what happens when x=0: e**0 = a_0 (0**0) + a_1 (0**1) + a_2 (0**2) + ... According to the sci.math.faq, 0**0 is equal to 1, if we know what's good for us. http://www.faqs.org/faqs/sci-math-faq/specialnumbers/0to0/ All the other coefficient terms disappear, giving us: e**0 = a_0 and now we at least know that a_0 is equal to 1. Too bad we don't know what the other terms look like yet. But that's where "shifting" comes in: we can "differentiate" our function, a technique in calculus that flattens a power series. What differentiation does to a power series is pretty neat: it turns something that looks like: e**x = a_0 x**0 + a_1 x**1 + a_2 x**2 + a_3 x**3 + ... and "shifts" all the coefficients to the left! D(e**x) = 1 * a_1 x**0 + 2 * a_2 x**1 + 3 * a_3 x**2 + ... Differentiation adds a little bit of crud onto each coefficient, so the shift isn't perfect, but it's conceptually the same as when we divided by 10 in the first half of this long and tortuously twisted message. e**x is impervious to differentiation, so now we come back to: e**x = 1 * a_1 x**0 + 2*a_2 x**1 + 3*a_3 x**2 + ... With this shifted formula, now we can repeat our peeking by trying to plug in 0 whenever we see 'x': e**0 = 1 * a_1 (0**0) + 0 + 0 + 0 + ... So a_1 is also equal to 1. We can continue doing the "peek-shift" process to pull out any of the a_n's out. If we do this a few more times, we start seeing a pattern: a_0 = 1 a_1 = 1/1 a_2 = 1/(1*2) a_3 = 1/(1*2*3) a_4 = 1/(1*2*3*4) ... and that's where we can stop and just say that the nth coefficient of our expansion's going to be: a_n = 1/(n!) In summary, the ideas that help us to convert a number into a string are very similar to the ideas that mathematicians use to perform Taylor's expansion. Sorry about the digression! From James.Rocks@equant.com Fri Nov 8 08:07:01 2002 From: James.Rocks@equant.com (James.Rocks@equant.com) Date: Fri Nov 8 08:07:01 2002 Subject: [Tutor] DOS Commands? Message-ID: Hi, I am trying to get the following to work from with Python: from time import * from os import popen sUnique = "%s%s%s%s%s%s%s%s%s" % localtime() sSMSFile = "c:\\temp\\%s.CTXScanner.%s" % (sUnique, '447771767405') fSMSFile = open (sSMSFile, "w") fSMSFile.write('Frm: CTX Scan\nSrv: %s\nSts: %s' % ('LONASMEG01', 'DN 15 Min')) fSMSFile.close() popen('ncftpput -u ****** -p ****** ******.lon.globalone.net sms %s' % sSMSFile, 'w') I get (on one line): Obviously I have tested it and it works fine from a command prompt (simply cutting the relevant part from the program and pasting it into a commnd window works) ... any ideas? James James C. Rocks Equant Archway House Canary Wharf London E14 9SZ From magnus@thinkware.se Fri Nov 8 08:23:01 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Fri Nov 8 08:23:01 2002 Subject: [Tutor] DOS Commands? In-Reply-To: Message-ID: <5.1.0.14.0.20021108141735.02b6b0c8@www.thinkware.se> At 13:04 2002-11-08 +0000, James.Rocks@equant.com wrote: > from time import * A style issue. "from ??? import *" is usually a bad thing. It's been discussed before, see archives. > popen('ncftpput -u ****** -p ****** ******.lon.globalone.net sms %s' >% sSMSFile, 'w') This opens a pipe, which is like a file handle. Nothing happens until you read it. You want os.system, not os.popen, if you don't plan to use what the OS command puts on stdout. os.popen can be used like this: import os text = os.popen('ls -l').readlines() for row in text: print row, -- 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 James.Rocks@equant.com Fri Nov 8 09:45:02 2002 From: James.Rocks@equant.com (James.Rocks@equant.com) Date: Fri Nov 8 09:45:02 2002 Subject: [Tutor] Single Backslash (was 'DOS Commands?') Message-ID: Hi Magnus, > os.popen('ls -l').readlines() Yes, that works thanks ... now if I could only figure how to make a string with a single backslash I should be sorted! James C. Rocks Equant Archway House Canary Wharf London E14 9SZ From iumarumo@eidosnet.co.uk Fri Nov 8 10:54:02 2002 From: iumarumo@eidosnet.co.uk (Ibraheem Umaru-Mohammed) Date: Fri Nov 8 10:54:02 2002 Subject: [tutor] Do I need to have a strong math skills to program In-Reply-To: References: Message-ID: <20021108155324.GF7018@micromuse.com> * Danny Yoo [2002-11-08 08:44]: > On Sun, 3 Nov 2002, Dan Dud wrote: > > > Hope everyone weekend is going great. I working through the "how to > > think like a computer scientist" I'm stuck on the part which you have to > > define a hypotenuse triangle. I don't have a lot of math skills. Do I > > have to have a lot of math skills to be good at programming??? I've > > decided to skip that part and move on. I hope everyone weekend is going > > great and I'll talk to you all soon... > > Hi Dan, > > I just wanted to jump back into this question because it's such a fun one > to revisit. *grin* There are some advantages for knowing math: with some > math knowledge, we can make analogies between computer techniques and math > techniques. > > Warning: this message is very long, and halfway though, I just completely > lose my head and jump into calculus. I didn't mean to; it just happened! > *grin* You can read up to the middle, and stop there. But for those > who've taken an introductory course in calculus... I dunno, maybe this > will amuse you. > > > Here's one problem in particular that shows a particular technique that's > works with both computers and maths. Let's say that we had a number, and > we'd like to turn it into a string. How hard would it be to transform > that string into a integer? > > (A quick solution would use the string() built-in function, since it knows ^^^^^^^^ This should be str(). And, although we have a singleNumberToString function, I would handle the number 0 in the turnNumberIntoString function, just to be consistent with: turnNumberIntoString(1) turnNumberIntoString(2) . . turnNumberIntoString(9) [...] > > ### > >>> def turnNumberIntoString(number): > ... characters = [] if number == 0: return '0' > ... while number != 0: > ... next_digit = number % 10 > ... next_character = singleNumberToString(next_digit) > ... characters.append(next_character) > ... number = number / 10 > ... characters.reverse() > ... return ''.join(characters) > ... > >>> turnNumberIntoString(12345) > '12345' > ### > [...] Thanks for the post, an informative and enjoyable read. --ibz. From dyoo@hkn.eecs.berkeley.edu Fri Nov 8 11:46:21 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Nov 8 11:46:21 2002 Subject: [Tutor] Single Backslash (was 'DOS Commands?') In-Reply-To: Message-ID: On Fri, 8 Nov 2002 James.Rocks@equant.com wrote: > Hi Magnus, > > > os.popen('ls -l').readlines() > > Yes, that works thanks ... now if I could only figure how to make a string > with a single backslash I should be sorted! Hi James, Here you go: ### >>> title = '// This is a test \\\\' >>> print title // This is a test \\ ### Whenever we want literal backslashes, we need to double them up. The sequence '\\' will tell Python that we really do mean to put a literal backslash in our string. Good luck to you! From michael@trollope.org Fri Nov 8 12:49:02 2002 From: michael@trollope.org (Michael Powe) Date: Fri Nov 8 12:49:02 2002 Subject: [tutor] Do I need to have a strong math skills to program In-Reply-To: ; from wheelcrdan@hotmail.com on Sun, Nov 03, 2002 at 11:08:46AM -0700 References: Message-ID: <20021108094814.B29683@titan.spiretech.com> don't confuse math knowledge with math skill. math skill may make it easier for you to acquire math knowledge. i've known many people who were "naturals" at solving mathematical problems but whose math knowledge was minimal. an obvious example is solving puzzles like rubik's cube, chinese boxes or those linked-chain torture devices; or, another example is playing chess. my opinion is that the best programmers have high math skills. that doesn't mean that you can't write good programs and enjoy doing so, even if your abilities with mathematics is limited. it means you may have to work that much harder because some advanced topics will task those skills. remember, there are millions of chess players, of all levels of skill, who love the game ... and only one world champion. mp On Sun, Nov 03, 2002 at 11:08:46AM -0700, Dan Dud wrote: > > Hello everyone, > > Hope everyone weekend is going great. I working through the "how to think > like a computer scientist" I'm stuck on the part which you have to define a > hypotenuse triangle. I don't have a lot of math skills. Do I have to have a > lot of math skills to be good at programming??? I've decided to skip that > part and move on. I hope everyone weekend is going great and I'll talk to > you all soon... > > Danny D > > > > > _________________________________________________________________ > Protect your PC - get McAfee.com VirusScan Online > http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963 > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From mchermside@ingdirect.com Fri Nov 8 12:53:01 2002 From: mchermside@ingdirect.com (Chermside, Michael) Date: Fri Nov 8 12:53:01 2002 Subject: [Tutor] Question on Python and OFX (Open Financial Exchange) Message-ID: <902A1E710FEAB740966EC991C3A38A8903C278A4@INGDEXCHANGEC1.ingdirect.com> > [OFX is] SGML as far as I understand. Parsing SGML is not > for the faint hearted. That's basically why XML was > invented. Actually, OFX 1.0 was SGML, but the recent versions of OFX are in XML. The format itself is really QUITE easy to parse and generate (I've written it myself, though not in Python). However, most of the difficulty in working with OFX is handling the particular form of error processing and such that they expect. Magnus's suggestion of wrapping an existing library is probably a good one, but if that fails and you decide to=20 write it yourself in Python it shouldn't be too hard. Feel free to contact me with any questions. -- Michael Chermside mcherm@mcherm.com From charlie@begeistert.org Fri Nov 8 13:43:02 2002 From: charlie@begeistert.org (Charlie Clark) Date: Fri Nov 8 13:43:02 2002 Subject: [Tutor] re DOS commands In-Reply-To: <20021108170007.2936.95025.Mailman@mail.python.org> References: <20021108170007.2936.95025.Mailman@mail.python.org> Message-ID: <20021108194229.2878.9@bepc.1036759347.fake> On 2002-11-08 at 18:00:07 [+0100], tutor@python.org wrote: > Hi James, > > > Here you go: > > ### > >>> title = '// This is a test \\\\' > >>> print title > // This is a test \\ > ### > > Whenever we want literal backslashes, we need to double them up. The > sequence '\\' will tell Python that we really do mean to put a literal > backslash in our string. It's difficult to beat (in speed or knowledge) Danny or Magnus to answer especially as I get the digest! Counting all those backslashes can be a real pain so you might want to know about raw strings: >>> s = r"\James" >>> s '\\James' prefixing a string with "r" is a bit of magic which keeps it readable. Any characters in the string such as "\" which normally carry out magic functions will be automatically quoted for you. This is really useful especially if you get involved with regular expressions which use lots of "\"s What do you need a single backslash for? Path names in DOS? You should be able to work around them in Python using things like os.path and standard "/"s. This keeps your code nice and portable. As I scanned your code I saw you generating unique filenames and I was wondering whether you are generating temporary files which you intend to dispose later. This is something where the operating system can help you by generating temporary files using the tempfile module import tempfile, os filename = tempfile.mktemp() tempfile = open(filename, "wb") tempfile.write("whatever") .... send the file or whatever os.remove(tempfile) This gives you unique filenames all the time, everytime, no matter what the system.time() Charlie From Doug.Shawhan@gecits.ge.com Fri Nov 8 15:27:06 2002 From: Doug.Shawhan@gecits.ge.com (Doug.Shawhan@gecits.ge.com) Date: Fri Nov 8 15:27:06 2002 Subject: [Tutor] Useless: Twiddle prompt w/o curses? Message-ID: <47B6167F8E69D31194BA0008C7918D4205C54EEA@msxcvg02itscge.gecits.ge.com> For reasons of perversity and foofiness, I desire to create a twiddle prompt in python. http://www.elsewhere.org/jargon/html/entry/twirling-baton.html The sequence : -/|\-/|\- interspersed with backspace characters has proven to be a tad more difficult to produce on the same line than I thought. Has anyone got an idea on how to change characters in place in a portable way? i.e. not resorting to curses? (Nothing against curses, mind you...) d From lumbricus@gmx.net Fri Nov 8 15:52:02 2002 From: lumbricus@gmx.net (lumbricus@gmx.net) Date: Fri Nov 8 15:52:02 2002 Subject: [Tutor] Useless: Twiddle prompt w/o curses? References: <47B6167F8E69D31194BA0008C7918D4205C54EEA@msxcvg02itscge.gecits.ge.com> Message-ID: <10664.1036788669@www30.gmx.net> Hi! [ snip ] > The sequence : -/|\-/|\- interspersed with backspace characters has > proven > to be a tad more difficult to produce on the same line than I thought. > > Has anyone got an idea on how to change characters in place in a portable > way? i.e. not resorting to curses? (Nothing against curses, mind you...) --- Schnipp --- #!/usr/bin/env python import time, sys s="|/-\\" i=0 while (1): sys.stdout.write("%c\r" %s[i]) sys.stdout.flush() i+=1 if (i%len(s))==0: i=0 time.sleep(0.1) print --- Schnapp --- untested > d HTH, J"o! -- sigfault -- Wir beschliessen etwas, stellen das dann in den Raum und warten dann einige Zeit ab, was passiert. Wenn es dann kein grosses Geschrei gibt und keine Aufstaende, weil die meisten gar nicht begreifen, was da beschlossen wurde, dann machen wir weiter - Schritt fuer Schritt, bis es kein Zurueck mehr gibt. -- J-C Juncker +++ GMX - Mail, Messaging & more http://www.gmx.net +++ NEU: Mit GMX ins Internet. Rund um die Uhr für 1 ct/ Min. surfen! From dyoo@hkn.eecs.berkeley.edu Fri Nov 8 16:02:01 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Nov 8 16:02:01 2002 Subject: [Tutor] Useless: Twiddle prompt w/o curses? In-Reply-To: <47B6167F8E69D31194BA0008C7918D4205C54EEA@msxcvg02itscge.gecits.ge.com> Message-ID: On Fri, 8 Nov 2002 Doug.Shawhan@gecits.ge.com wrote: > For reasons of perversity and foofiness, I desire to create a twiddle prompt > in python. > > http://www.elsewhere.org/jargon/html/entry/twirling-baton.html > > The sequence : -/|\-/|\- interspersed with backspace characters has proven > to be a tad more difficult to produce on the same line than I thought. > > Has anyone got an idea on how to change characters in place in a portable > way? i.e. not resorting to curses? (Nothing against curses, mind you...) Hi Doug, Here's something that works for me: ### >>> while 1: ... for ch in r'-/|\-/|\\': ... print '\b\b' + ch, ... sys.stdout.flush() ... time.sleep(0.3) ... | ### This uses the 'backspace' character '\b'. It's an escape character that moves the cursor back one place, so we can use it to do the animation. I did it twice just to be sure. *grin* One important part is the sys.stdout.flush() part: without it, it's very likely that we won't see a thing, because our operating system tries to optimize printing by waiting till a whole line is laid out --- it "buffers" the display of a line. We can override this buffering behavior by calling flush(). Hope this helps! From dyoo@hkn.eecs.berkeley.edu Fri Nov 8 16:15:17 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Nov 8 16:15:17 2002 Subject: [Tutor] new menu In-Reply-To: <3DC9FADA.A89D1CC8@netzero.net> Message-ID: On Thu, 7 Nov 2002, Kirk Bailey wrote: > I created an intelligent mastermenu for Tinylist, giving links to major > feature groups which are installed. If the feature is not present, it is > not offered on themenu, no hacking of the thing is needed- it installs > the domain name for you, to make it easy to use. This will be new to > TL1.6.0. here is a link to the new script. > > http://www.tinylist.org/cgi-bin/TLmastermenu.py Hi Kirk, Hey, it looks nice! Is there a link to source code too? At the moment, since the script is in cgi-bin/, we're unable to look at the source code. Best of wishes! From Doug.Shawhan@gecits.ge.com Fri Nov 8 17:17:04 2002 From: Doug.Shawhan@gecits.ge.com (Doug.Shawhan@gecits.ge.com) Date: Fri Nov 8 17:17:04 2002 Subject: [Tutor] Useless: Twiddle prompt w/o curses? Message-ID: <47B6167F8E69D31194BA0008C7918D4205C54EEC@msxcvg02itscge.gecits.ge.com> Aaaaahhhhh. Sys.stdout. Duh. Makes perfect sense. Thanks so much! d -----Original Message----- From: lumbricus@gmx.net [mailto:lumbricus@gmx.net] Sent: Friday, November 08, 2002 2:51 PM To: tutor@python.org Subject: Re: [Tutor] Useless: Twiddle prompt w/o curses? Hi! [ snip ] > The sequence : -/|\-/|\- interspersed with backspace characters has > proven > to be a tad more difficult to produce on the same line than I thought. > > Has anyone got an idea on how to change characters in place in a portable > way? i.e. not resorting to curses? (Nothing against curses, mind you...) --- Schnipp --- #!/usr/bin/env python import time, sys s="|/-\\" i=0 while (1): sys.stdout.write("%c\r" %s[i]) sys.stdout.flush() i+=1 if (i%len(s))==0: i=0 time.sleep(0.1) print --- Schnapp --- untested > d HTH, J"o! -- sigfault -- Wir beschliessen etwas, stellen das dann in den Raum und warten dann einige Zeit ab, was passiert. Wenn es dann kein grosses Geschrei gibt und keine Aufstaende, weil die meisten gar nicht begreifen, was da beschlossen wurde, dann machen wir weiter - Schritt fuer Schritt, bis es kein Zurueck mehr gibt. -- J-C Juncker +++ GMX - Mail, Messaging & more http://www.gmx.net +++ NEU: Mit GMX ins Internet. Rund um die Uhr fur 1 ct/ Min. surfen! _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From Doug.Shawhan@gecits.ge.com Fri Nov 8 17:22:28 2002 From: Doug.Shawhan@gecits.ge.com (Doug.Shawhan@gecits.ge.com) Date: Fri Nov 8 17:22:28 2002 Subject: [Tutor] Useless: Twiddle prompt w/o curses? Message-ID: <47B6167F8E69D31194BA0008C7918D4205C54EED@msxcvg02itscge.gecits.ge.com> Now what I want to know is: Did you and lumbricus@gmx.net purposely make your twiddles spin in opposite directions, or did nature just veer? Thanks again to both of you. Both ways showed me something new. d -----Original Message----- From: Danny Yoo [mailto:dyoo@hkn.eecs.berkeley.edu] Sent: Friday, November 08, 2002 3:01 PM To: Shawhan, Doug (CAP, ITS, US) Cc: tutor@python.org Subject: Re: [Tutor] Useless: Twiddle prompt w/o curses? On Fri, 8 Nov 2002 Doug.Shawhan@gecits.ge.com wrote: > For reasons of perversity and foofiness, I desire to create a twiddle prompt > in python. > > http://www.elsewhere.org/jargon/html/entry/twirling-baton.html > > The sequence : -/|\-/|\- interspersed with backspace characters has proven > to be a tad more difficult to produce on the same line than I thought. > > Has anyone got an idea on how to change characters in place in a portable > way? i.e. not resorting to curses? (Nothing against curses, mind you...) Hi Doug, Here's something that works for me: ### >>> while 1: ... for ch in r'-/|\-/|\\': ... print '\b\b' + ch, ... sys.stdout.flush() ... time.sleep(0.3) ... | ### This uses the 'backspace' character '\b'. It's an escape character that moves the cursor back one place, so we can use it to do the animation. I did it twice just to be sure. *grin* One important part is the sys.stdout.flush() part: without it, it's very likely that we won't see a thing, because our operating system tries to optimize printing by waiting till a whole line is laid out --- it "buffers" the display of a line. We can override this buffering behavior by calling flush(). Hope this helps! From alan.gauld@bt.com Fri Nov 8 19:20:02 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri Nov 8 19:20:02 2002 Subject: [Tutor] DOS Commands? Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA26@mbtlipnt02.btlabs.bt.co.uk> > fSMSFile = open (sSMSFile, "w") > popen('ncftpput -u ****** -p ****** > > I get (on one line): > > References: <20021107160802.16770.39929.Mailman@mail.python.org> Message-ID: <20021108173515.7947d0fe.graumann@its.caltech.edu> --7fCcc3Zm(x=.s'Hq Content-Type: text/plain; charset=US-ASCII Content-Transfer-Encoding: 7bit Hello, I'm writing a script that parses annotation data from online sources and combines them. ftplib does what I want as long as the online file name stays constant - but some of them have timestamps in the filename (which are obviously prone to change). I couldn't figure out a way to RETR something like 'xyz_*.txt'. Can anybody help me on this? I see that I first could parse LIST and regex out what I need, but isn't there something easier? Thanks for any hint, Joh --7fCcc3Zm(x=.s'Hq Content-Type: application/pgp-signature -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.0 (GNU/Linux) iD8DBQE9zGaBJSKujSMUwjMRAoOKAJ96y7QcgOzGekypcwTlt5q+vygplACeOBYb Bp3Zef7cA5wVtNkT8U5Jy4g= =bMxZ -----END PGP SIGNATURE----- --7fCcc3Zm(x=.s'Hq-- From magnus@thinkware.se Fri Nov 8 20:41:07 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Fri Nov 8 20:41:07 2002 Subject: [Tutor] re DOS commands In-Reply-To: <20021108194229.2878.9@bepc.1036759347.fake> References: <20021108170007.2936.95025.Mailman@mail.python.org> <20021108170007.2936.95025.Mailman@mail.python.org> Message-ID: <5.1.0.14.0.20021109024647.02ed9e60@www.thinkware.se> At 19:42 2002-11-08 +0100, Charlie Clark wrote: >It's difficult to beat (in speed or knowledge) Danny or Magnus to answer >especially as I get the digest! Sorry. I should slow down a bit... ;^) -- 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 Nov 8 20:56:02 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Fri Nov 8 20:56:02 2002 Subject: [tutor] Do I need to have a strong math skills to program In-Reply-To: References: Message-ID: <5.1.0.14.0.20021109025001.02eeea48@www.thinkware.se> At 00:43 2002-11-08 -0800, Danny Yoo wrote: >I just wanted to jump back into this question because it's such a fun one >to revisit. *grin* There are some advantages for knowing math: with some >math knowledge, we can make analogies between computer techniques and math >techniques. Of course, this is generally appliable. I feel that studies in physical or engineering fields give you a good understanding of nature, or reality or whatever. Just like the Design Pattern guys find the same design patterns occurring over and over again, we see just the same things in a much broader perspective. My studies and experience in electrical measurements and trouble shooting have taught me a lot that has been useful in helping my wife with her medical research, and in all sorts of software problem solving. There are a lot of these "laws of nature" that we discover even if we don't name them or realize their general nature at once. They become a part of our conciousness, and years later, our intuition will tell us how to solve a problem. I think mathematics is extra useful, because we typically solve "distilled", "pure" problems, where most of the "noise" that surrounds ordinary problems and leads us astray are removed. It's a bit like raising children teaches you a lot about human nature. One might say that one of the main differences between children and adults are that children are more transparent. They don't hde their true feelings as we often do. -- 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 lbrannma@cablespeed.com Sat Nov 9 00:00:02 2002 From: lbrannma@cablespeed.com (Lance) Date: Sat Nov 9 00:00:02 2002 Subject: [Tutor] clearing screen, WinPython Message-ID: <000701c287ad$aa76ce80$3212eb42@MYNEWBOX> Hi All, I'm running WinPython. Is there a command that will clear the interactive window screen? Thanks, Lance From idiot1@netzero.net Sat Nov 9 00:16:48 2002 From: idiot1@netzero.net (Kirk Bailey) Date: Sat Nov 9 00:16:48 2002 Subject: [Tutor] new menu References: Message-ID: <3DCC99A7.F1EFCBF9@netzero.net> ok, will create a link. The address will be: http://www.tinylist.org/TLmastermenu.txt Give it until sunrise saterday before trying it, I write this BEFORE implementing it and it is 12:13am EST already! Danny Yoo wrote: > > On Thu, 7 Nov 2002, Kirk Bailey wrote: > > > I created an intelligent mastermenu for Tinylist, giving links to major > > feature groups which are installed. If the feature is not present, it is > > not offered on themenu, no hacking of the thing is needed- it installs > > the domain name for you, to make it easy to use. This will be new to > > TL1.6.0. here is a link to the new script. > > > > http://www.tinylist.org/cgi-bin/TLmastermenu.py > > Hi Kirk, > > Hey, it looks nice! Is there a link to source code too? At the moment, > since the script is in cgi-bin/, we're unable to look at the source code. > > Best of wishes! -- end Respectfully, Kirk D Bailey +---------------------"Thou Art Free." -Eris-----------------------+ | http://www.howlermonkey.net mailto:highprimate@howlermonkey.net | | KILL spam dead! http://www.scambusters.org/stopspam/#Pledge | | http://www.tinylist.org +--------+ mailto:grumpy@tinylist.org | +------------------Thinking| NORMAL |Thinking----------------------+ +--------+ --------------------------------------------- Introducing NetZero Long Distance 1st month Free! Sign up today at: www.netzerolongdistance.com From idiot1@netzero.net Sat Nov 9 00:22:01 2002 From: idiot1@netzero.net (Kirk Bailey) Date: Sat Nov 9 00:22:01 2002 Subject: [Tutor] link ready Message-ID: <3DCC9AE9.591513B0@netzero.net> Went quicker than I thought, don't usually use ln links. http://www.tinylist.org/TLmastermenu.txt -- end Respectfully, Kirk D Bailey +---------------------"Thou Art Free." -Eris-----------------------+ | http://www.howlermonkey.net mailto:highprimate@howlermonkey.net | | KILL spam dead! http://www.scambusters.org/stopspam/#Pledge | | http://www.tinylist.org +--------+ mailto:grumpy@tinylist.org | +------------------Thinking| NORMAL |Thinking----------------------+ +--------+ --------------------------------------------- Introducing NetZero Long Distance 1st month Free! Sign up today at: www.netzerolongdistance.com From magnus@thinkware.se Sat Nov 9 06:23:01 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Sat Nov 9 06:23:01 2002 Subject: [Tutor] clearing screen, WinPython In-Reply-To: <000701c287ad$aa76ce80$3212eb42@MYNEWBOX> Message-ID: <5.1.0.14.0.20021109122520.02ef85d0@www.thinkware.se> At 21:05 2002-11-08 -0800, Lance wrote: >Hi All, > >I'm running WinPython. Is there a command that will clear the interactive >window screen? Look in the mailing list archives. Last time it popped up, it might have been concerning IDLE, but I don't think the answer is very different. Another option is to ask om the python-win32 mailing list or to ask Mark Hammond. A third option is to use Jean-Michel Fauth's PSI instead. At least it has a "clear screen" menu option. I'm pretty sure you can hook into that from the code. It's pure Python (using wxPython). -- 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 Sat Nov 9 10:02:01 2002 From: lumbricus@gmx.net (lumbricus@gmx.net) Date: Sat Nov 9 10:02:01 2002 Subject: [Tutor] Useless: Twiddle prompt w/o curses? References: <47B6167F8E69D31194BA0008C7918D4205C54EED@msxcvg02itscge.gecits.ge.com> Message-ID: <19957.1036854073@www18.gmx.net> Hi! > Now what I want to know is: Did you and lumbricus@gmx.net purposely make > your twiddles spin in opposite directions, or did nature just veer? Just incident I guess. > Thanks again to both of you. Both ways showed me something new. HTH and TOFU snipped ;-) J"o! -- Wir beschliessen etwas, stellen das dann in den Raum und warten dann einige Zeit ab, was passiert. Wenn es dann kein grosses Geschrei gibt und keine Aufstaende, weil die meisten gar nicht begreifen, was da beschlossen wurde, dann machen wir weiter - Schritt fuer Schritt, bis es kein Zurueck mehr gibt. -- J-C Juncker +++ 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 Sat Nov 9 10:05:07 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Sat Nov 9 10:05:07 2002 Subject: [tutor] Do I need to have a strong math skills to program In-Reply-To: <5.1.0.14.0.20021109025001.02eeea48@www.thinkware.se> References: Message-ID: <5.1.0.14.0.20021109123105.02ee2f18@www.thinkware.se> At 03:02 2002-11-09 +0100, I wrote: >My studies and experience in electrical measurements and trouble >shooting have taught me a lot that has been useful in helping my >wife with her medical research, and in all sorts of software >problem solving. I just found another one of these parallels from other work and studies: I'm preparing a questionnaire to my neigbours regarding our internet connection, since we will have to renew our contract and should get quotations from various suppliers. I'm looking through the previous questionnaire from 1998 in my preparations. (Our 101 flats and houses have been on-line since '96!) The old questionnaire is mainly multiple choice, and it's interesting to see how many times redundant questions are asked, and how many times the available choices for answers overlap or have holes. Things like: Who in the household uses the computer? (mark one of:) * All * Only the man * Only the woman * The children Apart from making a possibly flawed assumption that there is never more than one adult of the same sex in a household, it's also impossible to reply that "the man" and the children (but not "the woman") use the computer, or that some but not all children use it. A "normal" person who makes a multiple choice question will typically try to figure out what kind of responses there might be to such a question, and list them. Someone who is good at designing digital electronics won't. That's not the way she thinks. I'm sure that many people who have worked with mathe- matics will think in the same way as the electronics designer. Particularly if they are used to set theory and logic. We've been taught to always see the whole sets of input and output, and to divide these sets into meaningful categories, rather than to pick out answers and hope that they form the whole set of possible (or reasonable) replies. Since "normal" people start from the other end, they often fail to reach a coherent whole. There might well be both overlaps and gaps between their categories. I don't mean that engineers or mathematicians are abnormal, or that other people are stupid, but to see a whole and divide it like this is maybe not a natural way of looking at things. I think it's an acquired skill, and one that comes as the result of a lot of hard work. I don't think you can just read that you should think like this and apply it. I think you need to work with something that forces you to think like this until you do it by reflex. I'm sure that anyone who is persistent can learn to think this way, but digital design makes it both easy (due to the clear binary nature of the things we work with) and rewarding (since things work it we do it right, and don't otherwise) to acquire this way of thinking. In studies and practical work, we've learnt how to do this, first in very simple ways, and then in more and more complex systems. We've started with simple rules, and learnt to apply more and more advanced methods. Obviously, Boolean logic and Set theory are the foundations here. In practice we rarely need to use more advanced things like the Quine-Mc Cluskey method, but it's in our tool box if we need it. (See http://www.thinkware.se/cgi-bin/thinki.cgi/QuineMcCluskeyPy ) This kind of thinking eliminates a lot of bugs in software. It's important to map this technical view of reality to the way the users of a system thinks though. Sometimes it's very useful to try to create a shift in the mind set of the users, to make them think in other paths, but most of the time we will have to map things in such a way that things seem clear both to system design experts and to laymen. (Or rather people who are experts in another field, as the users of our products typically are.) On a related issue I was once asked to write a report for a case management system for a social welfare authority that would provide statistics on: A: Number of open cases by the end of the month. B: Number of cases closed during the month. C: Number of short cases (both opened and closed during the month). When you look at this you realize that it refers to to questions: * Was the case started before the beginning of the month? * Was the case closed before the end of the month? This is two bits of information, i.e. there are four possible answers. Any case will fall into the categories: If we say that 1 is yes, and 0 is no, we will get these categories: 0) 00, no, no: New, and not yet closed case. 1) 01, no, yes: New and closed case. 2) 10, yes, no: Old and not yet closed case. 3) 11, yes, yes: Old and closed case. The categories they wanted were: A: Open cases = number of 0) + number of 2) B: Closed cases = number of 1) + number of 3) C: Short cases = number of 1) As you see this is an incomplete representation of the two bit information described above. We can't represent to bits with three categories, so by showing the information as just these categories (which is what they needed for some reports they wrote) we lost konowlegde about the reality behind the numbers. This makes the report much less useful for someone who wants to find some fact beyond that intended by those who designed the report. I suggested that that they should complement the open cases number with the "of these, this many were started this month": A2: New, open cases = 0) Something like: Region Short Closed Open cases cases cases (started this month) AAAA 5 7 9 (4) BBBB 2 9 11 (5) ... This would mean that they have the full set of information, since they still have four non-redundant categories derived from the information. We can show that nothing is lost: 0) = A2 1) = C 2) = A - A2 3) = B - C Obviously, the representaion [A, A2, B, C] is a lossless transformation of [0), 1), 2), 3)]. My client agreed to do it like that, but he never really understood my wishes and my reasoning, and when it was done, he asked me to remove the fourth category, since he thought it would just confuse the users... Maybe he was right, but this kind of gaps in the presentation of information is very irritating for someone who has been taught to think about the whole... -- 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 Sat Nov 9 10:30:03 2002 From: lumbricus@gmx.net (lumbricus@gmx.net) Date: Sat Nov 9 10:30:03 2002 Subject: [Tutor] mget analog for ftplib References: <20021108173515.7947d0fe.graumann@its.caltech.edu> Message-ID: <24502.1036855756@www2.gmx.net> Hi! > Hello, [ snip ] > obviously prone to change). I couldn't figure out a way to RETR something like > 'xyz_*.txt'. > Can anybody help me on this? I see that I first could parse LIST and regex > out what I need, but isn't there something easier? Don't know whether glob works for ftp directories too. Try "import glob" Then "for f in glob.glob("xyz_*.txt"): do_something_to(f) > Thanks for any hint, Joh HTH, J"o! -- Wir beschliessen etwas, stellen das dann in den Raum und warten dann einige Zeit ab, was passiert. Wenn es dann kein grosses Geschrei gibt und keine Aufstaende, weil die meisten gar nicht begreifen, was da beschlossen wurde, dann machen wir weiter - Schritt fuer Schritt, bis es kein Zurueck mehr gibt. -- J-C Juncker +++ GMX - Mail, Messaging & more http://www.gmx.net +++ NEU: Mit GMX ins Internet. Rund um die Uhr für 1 ct/ Min. surfen! From kojo@hal-pc.org Sat Nov 9 14:07:00 2002 From: kojo@hal-pc.org (Kojo Idrissa) Date: Sat Nov 9 14:07:00 2002 Subject: [tutor] Do I need to have a strong math skills to program In-Reply-To: <5.1.0.14.0.20021109123105.02ee2f18@www.thinkware.se> Message-ID: Magnus, I found this response VERY helpful. I'm dealing with a similar situation at work right now, where an information system was designed to capture certain types of information, but not all of the information that was needed. Specifically, we in the accounting department don't have the information we need to verify certain things. I'm almost certain some things were "left out" because: 0) The people who designed the system weren't thinking about "complete" information or retaining the reality behind the numbers as you mentioned and/or 1) There was a concern that too much information might "confuse" the people who were the primary enters of data for the system. Thanks for the insight. On Sat, 09 Nov 2002 16:11:52 +0100 Magnus Lycka wrote: ]On a related issue I was once asked to write a report for ]a case management system for a social welfare authority ]that would provide statistics on: ]A: Number of open cases by the end of the month. ]B: Number of cases closed during the month. ]C: Number of short cases (both opened and closed during ] the month). ] ]When you look at this you realize that it refers to to ]questions: ] * Was the case started before the beginning of the ]month? ] * Was the case closed before the end of the month? **************************** Kojo Idrissa kojo@hal-pc.org http://www.hal-pc.org/~kojo **************************** From runsun@bilbo.bio.purdue.edu Sat Nov 9 17:35:01 2002 From: runsun@bilbo.bio.purdue.edu (Runsun Pan) Date: Sat Nov 9 17:35:01 2002 Subject: [Tutor] __setattr__ for dictionary??? In-Reply-To: <20021109170005.26406.38455.Mailman@mail.python.org> Message-ID: hi i'm trying to use the __setattr__ to do some data check before they are stored into my class. I've learned : def __setattr__(self, nsmr, value) how do i use that to do a data check on the entry of a dictionary item? For example, a dict: peoplename={'last':'Lee', 'first':'john'} how do i use the __setattr__ for it ? thx -- ======================================== ---> Be like water, be shapeless <--- Runsun Pan, PhD Ecology & Evolution, U. of Chicago ======================================== From emile@fenx.com Sat Nov 9 18:57:02 2002 From: emile@fenx.com (Emile van Sebille) Date: Sat Nov 9 18:57:02 2002 Subject: [Tutor] Re: __setattr__ for dictionary??? References: <20021109170005.26406.38455.Mailman@mail.python.org> Message-ID: Runsun Pan: > hi i'm trying to use the __setattr__ to do some > data check before they are stored into my class. > I've learned : > > def __setattr__(self, nsmr, value) > > how do i use that to do a data check on the entry of > a dictionary item? > > For example, a dict: > > peoplename={'last':'Lee', 'first':'john'} > > how do i use the __setattr__ for it ? > I'm not quite clear on your intent, but maybe this fits. Instead of setattr, I use setitem and both validate and clean up the value: >>> class Sample(dict): ... def __init__(self, validatefunc, cleanupfunc): ... self.isgood = validatefunc ... self.clean = cleanupfunc ... def __setitem__(self, key, value): ... if self.isgood(value): ... dict.__setitem__(self, key, value.capitalize()) ... else: ... raise ValueError, 'Invalid Length' ... >>> def lengthtest(value): ... return 3<=len(value)<=10 ... >>> def capitalize(value): ... return value.capitalize() ... >>> a = Sample(lengthtest, capitalize) >>> a['last'] = 'test' >>> >>> print a['last'] Test >>> a['first']='ab' Traceback (most recent call last): File "", line 1, in ? File "", line 9, in __setitem__ ValueError: Invalid Length >>> a['first']='abe' >>> a {'last': 'Test', 'first': 'Abe'} HTH, -- Emile van Sebille emile@fenx.com --------- From allyn.@tardigrade.net Sat Nov 9 20:29:01 2002 From: allyn.@tardigrade.net (Allyn Weaks) Date: Sat Nov 9 20:29:01 2002 Subject: [Tutor] robo-editing a mail stream Message-ID: I want to write a small filter that can robo-edit the mail sent to some of my mailing lists (removing all quoted lines at the bottom of a post). The filter itself is simple and I can deal with that part, but it needs to sit in a stream between another mail filter (demime) and the list server software (currently majordomo, but it shouldn't matter) Currently, mail comes to the list, is sent to the demime program, which passes the results to the major:. The sendmail alias looks like this: LISTNAME: "|/usr/local/majordomo/wrapper demime |usr/local/majordomo/wrapper resend (parameter list)" wrapper is a security wrapper that I don't completely understand, demime is a perl program that removes attachments and html, resend is the majordomo module that handles posted messages. What I'd like is something that sits between demime and resend, like: LISTNAME: "|/usr/local/majordomo/wrapper demime |myfilter myparameters |usr/local/majordomo/wrapper resend (parameter list)" So basically my filter needs to take a correct mail message, modify it, and pipe it on as a correct mail message to resend. Is there anything I need to know about security, or other gotchas, other than just grabbing the text from a pipe and passing the new text in a pipe? I may be adding a single header line as notification that the body was changed (if it is). Is there anything tricky about being a middle-droid? Better yet, does someone have an example I can steal from? I peeked at demime, but it's perl... Thanks! -- Allyn Weaks allyn@tardigrade.net Seattle, WA Sunset zone 5 Pacific NW Native Wildlife Gardening: http://www.tardigrade.org/natives/ "The benefit of even limited monopolies is too doubtful, to be opposed to that of their general suppression." Thomas Jefferson From shalehperry@attbi.com Sun Nov 10 01:46:01 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Sun Nov 10 01:46:01 2002 Subject: [Tutor] robo-editing a mail stream In-Reply-To: References: Message-ID: <200211092245.07625.shalehperry@attbi.com> On Saturday 09 November 2002 17:28, Allyn Weaks wrote: > > So basically my filter needs to take a correct mail message, modify it, > and pipe it on as a correct mail message to resend. Is there anything > I need to know about security, or other gotchas, other than just > grabbing the text from a pipe and passing the new text in a pipe? I > may be adding a single header line as notification that the body was > changed (if it is). Is there anything tricky about being a > middle-droid? Better yet, does someone have an example I can steal > from? I peeked at demime, but it's perl... > security: you have security issues when you interact with the OS (exec a = file,=20 write a file, etc). As long as you only read stdin and only write stdout= =20 there should be little cause for concern. I can't think of any large gotchas. What you might want to consider is a= =20 simple test run which does: fp =3D open('/tmp/test_file', 'w') while line sys.stdin.readlines(): fp.write(line) and look at the file to see if there are any special control structures u= sed. From gmlloyd@onlink.net Sun Nov 10 10:10:01 2002 From: gmlloyd@onlink.net (gmlloyd) Date: Sun Nov 10 10:10:01 2002 Subject: [Tutor] re clear screen Message-ID: <3DCE769B.DE4DCEF6@onlink.net> Good morning. I am running Python in command line interface mode on Windows 2000. Is a clear screen command available? thanks very much, Geoff Lloyd From lumbricus@gmx.net Sun Nov 10 10:27:01 2002 From: lumbricus@gmx.net (lumbricus@gmx.net) Date: Sun Nov 10 10:27:01 2002 Subject: [Tutor] re clear screen References: <3DCE769B.DE4DCEF6@onlink.net> Message-ID: <21302.1036941941@www27.gmx.net> > Good morning. Dito! > I am running Python in command line interface mode on Windows 2000. Is a > clear screen command available? import os os.system("cls") UNIX: os.system("clear") So for portability: if os.platform == some_platform: etc... else: print '\n'*24 or use curses (Don't know whether this is available on W*doze) Perhaps there are some ansi codes (load ANSI.SYS) for clearing the screen, too. HTH, J"o! > thanks very much, > > Geoff Lloyd > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Wir beschliessen etwas, stellen das dann in den Raum und warten dann einige Zeit ab, was passiert. Wenn es dann kein grosses Geschrei gibt und keine Aufstaende, weil die meisten gar nicht begreifen, was da beschlossen wurde, dann machen wir weiter - Schritt fuer Schritt, bis es kein Zurueck mehr gibt. -- J-C Juncker +++ GMX - Mail, Messaging & more http://www.gmx.net +++ NEU: Mit GMX ins Internet. Rund um die Uhr für 1 ct/ Min. surfen! From lbrannma@cablespeed.com Sun Nov 10 10:27:10 2002 From: lbrannma@cablespeed.com (Lance) Date: Sun Nov 10 10:27:10 2002 Subject: [Tutor] List contents disappear Message-ID: <000b01c288ce$9f9ad480$3212eb42@MYNEWBOX> Hi All, I'm running PythonWin on Windows XP. If I print the contents of a huge list in interactive mode and place focus in the line (with my mouse or the arrow keys on the keyboard) the line disappears! This doesn't occur if I print the list contents from a file. I'll also post this to the Win-32 list. Any advice would be appreciated. Thanks, Lance From lumbricus@gmx.net Sun Nov 10 10:32:01 2002 From: lumbricus@gmx.net (lumbricus@gmx.net) Date: Sun Nov 10 10:32:01 2002 Subject: [Tutor] re clear screen References: <21302.1036941941@www27.gmx.net> Message-ID: <31400.1036942235@www27.gmx.net> [ snip ] > if os.platform == some_platform: *arghl* sys.platform [ snip ] Greets, J"o! -- Wir beschliessen etwas, stellen das dann in den Raum und warten dann einige Zeit ab, was passiert. Wenn es dann kein grosses Geschrei gibt und keine Aufstaende, weil die meisten gar nicht begreifen, was da beschlossen wurde, dann machen wir weiter - Schritt fuer Schritt, bis es kein Zurueck mehr gibt. -- J-C Juncker +++ GMX - Mail, Messaging & more http://www.gmx.net +++ NEU: Mit GMX ins Internet. Rund um die Uhr für 1 ct/ Min. surfen! From wheelcrdan@hotmail.com Sun Nov 10 12:03:14 2002 From: wheelcrdan@hotmail.com (Dan Dud) Date: Sun Nov 10 12:03:14 2002 Subject: [Tutor] How do I print built in functions Message-ID: Hello everyone, Hope everyone weekend is going great. I was wondering how I go about printing built in functions in IDLE. I know how to locate them with "dir()" but I can't figure out how to view them. I want to compare them to some of the functions, that I have written. I learn best by example, and what better of an example then one's that I know will work.. Thanks for everyone time and talk to you all again soon. Danny _________________________________________________________________ Add photos to your e-mail with MSN 8. Get 2 months FREE*. http://join.msn.com/?page=features/featuredemail From magnus@thinkware.se Sun Nov 10 13:28:01 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Sun Nov 10 13:28:01 2002 Subject: [Tutor] How do I print built in functions In-Reply-To: Message-ID: <5.1.0.14.0.20021110192224.02aa4e00@www.thinkware.se> At 09:59 2002-11-10 -0700, Dan Dud wrote: >Hope everyone weekend is going great. I was wondering how I go about >printing built in functions in IDLE. I know how to locate them with >"dir()" but I can't figure out how to view them. I want to compare them to >some of the functions, that I have written. I learn best by example, and >what better of an example then one's that I know will work.. I think most of the builtin functions are written in C. And for python functions, the interpreter sees compiled bytecode, not source code. You don't want to read that... If a function X is written in python, you can see what file it's in in this way: >>> import glob >>> glob.glob.func_code.co_filename 'C:\\Python22\\lib\\glob.py' Now you can just open this file. Actually, there are plenty of .py-files in this and a few other cataloges. Just look around. But as you see below, this won't work if the function is written in C. >>> import time >>> time.time.func_code.co_filename Traceback (most recent call last): File "", line 1, in ? AttributeError: 'builtin_function_or_method' object has no attribute 'func_code' The same thing typically happens for the builtin functions. Anyway, you will probably learn more by looking at code which is more like the typical application programmer code you might want to write. There are thousands of examples. Look at vaults of parnassus, useless python or the python foundry of sf.net 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 runsun@bilbo.bio.purdue.edu Sun Nov 10 13:34:01 2002 From: runsun@bilbo.bio.purdue.edu (Runsun Pan) Date: Sun Nov 10 13:34:01 2002 Subject: [Tutor] Re: __setattr__ for dictionary??? In-Reply-To: <037301c288cd$aa6e3e20$0a06a8c0@FENX.COM> Message-ID: hi Emile, thx for your help but your example is not exactly what i want. What I want to verify is the value(s) of a dictionary, like 'lee' , 'john' in the dictionary username={'last':'lee', 'first':'john'} before the assignment. When we use __setattr__(self, name, value) for 'username', the arguements past are: name = 'username' value= {'last':'lee', 'first':'john'} The code in your validationTable: 'family': lambda value: type(value) is dict only verifies "IF the input valur IS a dict," but didn't go check if the individual values in this 'input dictionary' are valid. The other code in the validationTable, validationTable = {'son': ismale, 'brother': ismale, 'father': ismale, 'uncle': ismale, 'daughter': isfemale, 'sister': isfemale, .... does check these properties but these properties are the 'class-level' properties --- they belong to the class, not members of a dictionary. So it is not the solution to my question. pan (1) In my original idea, On Sun, 10 Nov 2002, Emile van Sebille wrote: ] Hi, ] ] Runsun Pan: ] > ] > No it didn't. The code you gave: ] > ] > a.family['uncle']='sam' ] > ] > didn't go through the __setattr__ so I have no ] ] Well, it _did_ go through __setattr__, we just didn't trap it. ] ] > way to verify if the value 'sam' is valid before ] > it is assigned to the 'uncle' key in the 'family' ] > dictionary. ] ] Suppose then (as I'm still unclear on your _desired_ functionality) that ] you want to allow only specific 'uncle'-like keys, each with specific ] validation routines. One way to do this is to create a validation ] dictionary of allowable keys and associated validation functions: ] ] malenames = 'John, Bob, Tom, Ted'.split(', ') ] femalenames = 'Alice, Susan, Sally, Sharon'.split(', ') ] ] def ismale(value): ] return value in malenames ] ] def isfemale(value): ] return value in femalenames ] ] def anyvalue(value): return True ] ] validationTable = {'son': ismale, ] 'brother': ismale, ] 'father': ismale, ] 'uncle': ismale, ] 'daughter': isfemale, ] 'sister': isfemale, ] 'mother': isfemale, ] 'aunt': isfemale, ] 'name': anyvalue, ] 'family': lambda value: type(value) is dict, ] 'height': lambda value: type(value) is int} ] ] ] Then modify __setattr__ to to the right thing:: ] ] class myclass: ] def __init__(self): ] self.__dict__['name']={'last':'lee', 'first':'john'} ] self.__dict__['family']={'brother':2, 'sister':1} ] self.__dict__['height']=170 ] def __setattr__(self,name,value): ] if validationTable.has_key(name): ] print 'setting name' ] if validationTable[name](value): ] # now both the name and value are good ] # store it in the appropriate place ] self.__dict__[name] = value ] else: raise ValueError, 'Inappropriate value (%s) passed for ] key (%s)' %(value, name) ] else: raise KeyError, 'Name not allowed (%s)' % name ] ] Now lets see if it works: ] ] >>> a = myclass() ] >>> a.height='hello' # it shouldn't take a string value ] setting name ] Traceback (most recent call last): ] File "", line 1, in ? ] File "", line 13, in __setattr__ ] ValueError: Inappropriate value (hello) passed for key (height) ] >>> a.height=182 # so far so good... ] setting name ] ] ] ] >>> a.gramma = 'Emma' ] Traceback (most recent call last): ] File "", line 1, in ? ] File "", line 14, in __setattr__ ] KeyError: Name not allowed (gramma) ] >>> a.aunt = 'Emma' ] setting name ] Traceback (most recent call last): ] File "", line 1, in ? ] File "", line 13, in __setattr__ ] ValueError: Inappropriate value (Emma) passed for key (aunt) ] >>> a.aunt = 'Sally' ] setting name ] >>> a.aunt ] 'Sally' ] >>> a.family ] {'sister': 1, 'brother': 2} ] >>> a.family = 'hello' ] setting name ] Traceback (most recent call last): ] File "", line 1, in ? ] File "", line 13, in __setattr__ ] ValueError: Inappropriate value (hello) passed for key (family) ] >>> ] ] ] > ] > The __setattr__ only works for a single-value ] ] if works _only_ as you program it to. I programmed it to follow your ] example thinking it to be the best presentation of your intent, and I ] imagined that my example would be extrapolated upon. I continue to ] assume that now: you can add further validation routines, or otherwise ] expand upon what I've done to make it fit your requirements. ] ] ] -- ] ] Emile van Sebille ] emile@fenx.com ] ] --------- ] -- ======================================== ---> Be like water, be shapeless <--- Runsun Pan, PhD Ecology & Evolution, U. of Chicago ======================================== From rnd@onego.ru Sun Nov 10 13:47:00 2002 From: rnd@onego.ru (Roman Suzi) Date: Sun Nov 10 13:47:00 2002 Subject: [Tutor] How do I print built in functions In-Reply-To: Message-ID: On Sun, 10 Nov 2002, Dan Dud wrote: >Hello everyone, > >Hope everyone weekend is going great. I was wondering how I go about >printing built in functions in IDLE. I know how to locate them with >"dir()" but I can't figure out how to view them. I want to compare them to >some of the functions, that I have written. I learn best by example, and >what better of an example then one's that I know will work.. Thanks for >everyone time and talk to you all again soon. > >Danny Probably the best way is to get Python source code nd look into there: Python built-in functions are written in C for better performance. Sincerely yours, Roman Suzi -- rnd@onego.ru =\= My AI powered by Linux RedHat 7.3 From alan.gauld@bt.com Sun Nov 10 19:00:02 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun Nov 10 19:00:02 2002 Subject: [tutor] Do I need to have a strong math skills to program Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA2A@mbtlipnt02.btlabs.bt.co.uk> > Set theory are the foundations here. In practice we rarely > need to use more advanced things like the Quine-Mc Cluskey > method, but it's in our tool box if we need it. (See > http://www.thinkware.se/cgi-bin/thinki.cgi/QuineMcCluskeyPy ) > It never ceases to amaze me how useful this list is... I'm currently writing a book on Software Design Notations. The chapter on Boolean Algebra mentions some of the advanced simplification techniques including the Kline-McCluskey method(note spelling!) but I was puzzled why I couldn't find any web sitesabout it! My notes on this method were taken at university from lectures and I obviously mis-heard the lecturer! Thanks for providing the correct spelling Magnus! :-) Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From dyoo@hkn.eecs.berkeley.edu Sun Nov 10 21:20:01 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Nov 10 21:20:01 2002 Subject: [Tutor] How do I print built in functions [Useless Python / simplifying helpdesk.py] In-Reply-To: Message-ID: On Sun, 10 Nov 2002, Dan Dud wrote: > Hope everyone weekend is going great. > > I was wondering how I go about printing built in functions in IDLE. I > know how to locate them with "dir()" but I can't figure out how to view > them. Hi Dan, Actually, I think that the majority of the "built-in" functions are written in the underlying C language, so they might not be so easy to read. The built-in functions themselves are one of these subsystems, because all the other parts of Python depend that the built-ins already exist. This concept of building a system on top of primitive elements is called "bootstrapping". Looking through the built-in functions might not be too helpful. However, have you tried Useless Python? http://uselesspython.com/ There's a bunch of source code there that might be really useful for you; try browsing some of the pages and pick out anything that looks interesting. The best thing about Useless is that all the code there has been written by people on Tutor, so you can always ask on Tutor about parts of the code. Not just questions about how it works, but how we can make code better! Here's one, for example: http://uselesspython.com/HelpDesk.py There are several ways we can improve this program. HelpDesk.py keeps a list of excuses in a dictionary, and keeps track of how many excuses it has seen. I think it would be an improvement if it stored the excuses in a list, especially since there's so much effort involved to try keeping the excuses numbered, in order. A list is especially well suited for keeping a collection of things in order. So this chunk here: ### class helpdesk: def __init__(self): pat="(.*\d\d).\s(.*)" buf = re.findall(pat,excuses) self.xcuse={} for l in buf: x=l[0] if l[0][0]=="0": x=x.replace("0","",1) self.xcuse.setdefault(int(x), []).append(l[1]) def gethelp(self): self.num=(random.randrange(1,46,1)) return string.join(self.xcuse.get(self.num)) ### could be rewritten like this: ### class helpdesk: def __init__(self): pat = "(.*\d\d).\s(.*)" maches = re.findall(pat, excuses) self.all_excuses = [] for num, excuse in matches: self.all_excuses.append(excuse) def gethelp(self): return random.choice(self.all_excuses) ### However, as a warning: this modified code doesn't have the same effect as the old code. That is, the original code allowed an excuse like: """ 47. "But I really really meant 47. to finish writing that code 47. yesterday!" """ while my 'improvement' breaks this terribly by not even paying attention to excuse numbers. To make my modification behave identically, I'd have to do a few more things to pay attention to the excuse numbering. Anyway, hope that gave a flavor of what Useless Programs look like. Feel free to contribute to Useless Python with your own programs. (Rob, don't kill me! *grin*) Talk to you later! From James.Rocks@equant.com Mon Nov 11 06:12:01 2002 From: James.Rocks@equant.com (James.Rocks@equant.com) Date: Mon Nov 11 06:12:01 2002 Subject: [Tutor] Single Backslash (was 'DOS Commands?') Message-ID: Hi Danny, Magnus, OK ... I've got it to work BUT I still get an error. The following is my program: from time import * from os import popen sUnique = "%s%s%s%s%s%s%s%s%s" % localtime() sSMSFile = "c:\\temp\\%s.CTXScanner.%s" % (sUnique, '447771767405') sDOSCommand = "ncftpput -u ****** -p ****** ******.lon.globalone.net sms c:\\temp\\%s.CTXScanner.%s" % (sUnique, '447771767405') fSMSFile = open (sSMSFile, "w") fSMSFile.write('Frm: CTX Scan\nSrv: %s\nSts: %s' % ('LONASMEG01', 'DN 15 Min')) fSMSFile.close() popen(sDOSCommand, 'w').readlines() Though the SMS server does send a message to my mobile, I get the following error message: Traceback (most recent call last): File "", line 1, in ? File "c:\projects\ctx\smstest.py", line 13, in ? popen(sDOSCommand, 'w').readlines() IOError: [Errno 9] Bad file descriptor And the value of sDOSCommand is: 'ncftpput -u ****** -p ****** ******.lon.globalone.net sms c: \\temp\\2002111110594503150.CTXScanner.447771767405' >From what I can tell the file creation bit works fine but the DOS command, though it works, causes an error. Maybe the problem is using the freeware NcFTP program and running it through DOS but an error like this would crash my program wouldn't it? On the plus side I have discovered that Python has an FTP module so I'm going to investigate that and maybe keep it 'in house' (so to speak) :-) James James C. Rocks Equant Archway House Canary Wharf London E14 9SZ From magnus@thinkware.se Mon Nov 11 08:23:02 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Nov 11 08:23:02 2002 Subject: [Tutor] Single Backslash (was 'DOS Commands?') In-Reply-To: Message-ID: <5.1.0.14.0.20021111141146.02f4b508@www.thinkware.se> Hi James! There's a tiny bug left. Hope it'll work once that's fixed. At 11:09 2002-11-11 +0000, James.Rocks@equant.com wrote: > popen(sDOSCommand, 'w').readlines() This should be popen(sDOSCommand).readlines() Just skip the 'w'. You *read* from the file descriptor, right? So why do you open it with 'w'? The 'w', 'r' flags have nothing to do with the content of your "DOS" command if that's what you think. They have everything to do with how you use the file descriptor in Python. This one you read from with the readlines() method. That means you must use 'r' (which is the default). See: >>> print os.popen('dir', 'w').read() Traceback (most recent call last): File "", line 1, in ? IOError: [Errno 9] Bad file descriptor >>> print os.popen('dir').read() ......... -- 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 Nov 11 09:07:01 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Nov 11 09:07:01 2002 Subject: [Tutor] How do I print built in functions [Useless Python / simplifying helpdesk.py] In-Reply-To: References: Message-ID: <5.1.0.14.0.20021111112945.02997ea8@www.thinkware.se> In an otherwise (as usual) acurate and helpful mail, I think Danny managed to make a little blunder, which I use as an excuse for another long "lesson" (read "rant") about computers. :) At 18:19 2002-11-10 -0800, Danny Yoo wrote: >This concept of building a system on top of primitive elements is >called "bootstrapping". Really? I've never seen the word bootstrapping in that context. I've always used the word bootstrapping for techniques used to get a large system started that in general depends on it's own internals to work. Typically the bootstrap is only used to get the system started, and is then forgotten. See http://whatis.techtarget.com/definition/0,,sid9_gci214479,00.html http://www.tuxedo.org/~esr/jargon/html/entry/boot.html The most familiar bootstrap for us is probably the so-called bootloaders in our PC's that helps us get our operating systems loaded. Typically we load files into computers by using operating system functions, but obviously, the operating system can't handle the loading of the very first parts of the operating system... This is why we talk about "booting" our computers, in completely different contexts than kicking them in frustration! :) Actually, this bootstrapping of the PC will normally use at least two steps: First, there is code in a solid-state memory in the computer that knows where to look for a bootloader on diskette, CD-ROM, harddisk or across the network. It will locate and try bootable devices in a predifined order. Secondly, this little bootloader program, typically in the master boot sector of your harddisk, will start the loading and execution of the operating system, perhaps after letting you select between Windows and something better. ;) AFAIK, the origin of the word goes back to the impossible concept of lifting oneself in one's bootstraps. (I don't know if I ever owned a pair of boots with straps, but never mind that.) While I'm whining ;) I can agree that builtin functions are used often, and benefit from being written in C, and that the python programs assume that they are always loaded, but I can't agree that they form the primitive elements of Python. It's not that all python source code gets converted into the functions that are described in the library reference under the builtin section. All pure python code will be converted into python bytecode, so I guess that bytecode could be considered the primitive elements that Python programs are built from. Obviously this isn't a complete truth though, since all code that is implemented in C, whether it's builtin or a third party extension module, will bypass that. If you are running Jython, you will get 100% Java bytecode though, so there, you could say that Java bytecode are the primitive elements of Jython programs. (Like molecules are built from atoms.) Eventually, all python code will cause execution of certain native machine language instructions on the computer where it's running. In the processing units in ordinary PC's these machine code instructions will be further translated into sequences of microcode instructions. In RISC processors, this stage is typically bypassed. Then we're down at the pure hardware level. So, just as with matter, which can be seen as molecules built up by atoms, built up by subatomic particles that are in turn built up by quarks, we have several layers of more and more primitive element below our python source code. But it's not builtin functions...and it has little to do with bootstrapping... ;) -- 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 James.Rocks@equant.com Mon Nov 11 09:18:03 2002 From: James.Rocks@equant.com (James.Rocks@equant.com) Date: Mon Nov 11 09:18:03 2002 Subject: [Tutor] Single Backslash (was 'DOS Commands?') Message-ID: Hi Magnus, Hi James! > There's a tiny bug left. Hope it'll work once that's > fixed. > > popen(sDOSCommand, 'w').readlines() > This should be > popen(sDOSCommand).readlines() > Just skip the 'w'. You *read* from the file descriptor, > right? So why do you open it with 'w'? Excellent! Thanks alot Magnus, it works excellently now :-) I still want to migrate it into python completely (using the ftplib module) which I assume will make the code more platform independent. I really appreciate your help :-) James C. Rocks Equant Archway House Canary Wharf London E14 9SZ From kp8@mac.com Mon Nov 11 10:11:09 2002 From: kp8@mac.com (kevin parks) Date: Mon Nov 11 10:11:09 2002 Subject: [Tutor] re clear screen In-Reply-To: <20021110170003.29952.98689.Mailman@mail.python.org> Message-ID: > import os > os.system("cls") > > UNIX: > os.system("clear") > > So for portability: > if os.platform == some_platform: > etc... > else: print '\n'*24 Wow on M$ it's cls and on UNIX clear? How unbelievably unpythonesque. It is the first thing i've ever seen in python that i could say was truly stupid. Guido should get that time machine revved up and quickly change one of them so that they are both the same. I guess that this was done to keep python from being absolutely perfect. Sorta like Greta Garbo's feet. -kp-- From ramrom@earthling.net Mon Nov 11 11:14:03 2002 From: ramrom@earthling.net (Bob Gailer) Date: Mon Nov 11 11:14:03 2002 Subject: [Tutor] How do I print built in functions [Useless Python / simplifying helpdesk.py] In-Reply-To: <5.1.0.14.0.20021111112945.02997ea8@www.thinkware.se> References: Message-ID: <5.1.0.14.0.20021111085817.01bcdf70@66.28.54.253> A historical note re bootstrapping. Around 1961 I learned programming on an IBM 650. We entered an instruction (as I recall 7019701970), via the console switches, which meant read a punch card from the card reader, place it in memory starting at address 1970 then goto 1970 for the next instruction, which had just been read from a card. Around 1970 (year, not address) I was introduced to DEC's PDP8, the "first" "minicomputer". When I wanted to use it, I had to enter about 20 instructions into memory. Each memory word was 12 bits; there were 12 front panel toggle switches. One would flip them into a certain bit pattern, then "deposit" into memory, repeat till the "bin loader" program was in memory; place some punched paper tape into the tape reader, and hit the start button. The paper tape contained the "rim loader" which prepared the computer to read a program. It's interesting to compare these steps with the boot program now resident in ROM that reads the boot program from magnetic media. Of course if one made any error in toggling the bin loader the thing would not run; we had to do it over. Pretty soon the flipping became a habit that no longer required thought. One improvement to the PDP8 a few years later was a plug in card that contained the rim loader in ROM. Bob Gailer 170 Forsythe Rd Nederland CO 80466 303-442-2625 From alan.gauld@bt.com Mon Nov 11 11:29:01 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Nov 11 11:29:01 2002 Subject: [Tutor] Single Backslash (was 'DOS Commands?') Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA34@mbtlipnt02.btlabs.bt.co.uk> > popen(sDOSCommand, 'w').readlines() You are still not assigning the result to anything. The command runs and you throw it all away... Alan g. From alan.gauld@bt.com Mon Nov 11 11:49:04 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Nov 11 11:49:04 2002 Subject: [Tutor] re clear screen Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA35@mbtlipnt02.btlabs.bt.co.uk> > > os.system("cls") > > os.system("clear") > Wow on M$ it's cls and on UNIX clear? How unbelievably unpythonesque. Nope, its just the underlying operating systems. Its Bill Gates and Ken Thompson who should be brought together if anyone - although CLS actually comes from CP/M so maybe its, the now dead, Gary Kildall, the inventor of CP/M, we should shout at! I suppose python could provide a system dependant clearScreen() command in the os module or something, but it would just look like the one posted, full of "if os==/elif..." And quite how we should clear a teletype or WAP terminal remains a mystery - 24 newlines as a default seems kind of wrong somehow. Alan g. From wallison1@sc.rr.com Mon Nov 11 16:38:06 2002 From: wallison1@sc.rr.com (William Allison) Date: Mon Nov 11 16:38:06 2002 Subject: [Tutor] if... Message-ID: <3DD021A9.2020201@sc.rr.com> Hi all, I'm trying to learn Python with the "How to Think Like a Computer Scientist" book. In chapter four, the if statement is introduced. if x < y: print x, "is less than", y elif x > y: print x, "is greater than", y else: print x, "and", y, "are equal" I can't seem to get this to work at all. If I line up the 'elif' with the 'print' I get SyntaxError: invalid syntax from idle. When I line up the 'elif' with the 'if' I get: IndentationError: unident does not match any outer indentation level (line 3). However when I save it as iftest.py like this, it works as expected. #!/usr/bin/python x = 11 y = 11 if x < y: print x, "is less than", y elif x > y: print x, " is greater than", y else: print x, "and", y, "are equal I'm using Debian GNU/Linux 3.0, python 2.1.3 and Idle 0.8. Any ideas? Thanks, William From James.Alexander.McCarney@Cognicase.com Mon Nov 11 16:43:05 2002 From: James.Alexander.McCarney@Cognicase.com (McCarney, James Alexander) Date: Mon Nov 11 16:43:05 2002 Subject: [Tutor] if... Message-ID: <23FD7B1A77E8D211BCB900001D108C02023FCAD8@camelot> Could it be the amount of indentation you are using? Usually if you let IDLE handle the indenting it works as expected, but then I am not running Debian Linux... -->if x < y: --> print x, "is less than", y -->elif x > y: --> print x, "is greater than", y -->else: --> print x, "and", y, "are equal" From gus.tabares@verizon.net Mon Nov 11 18:03:02 2002 From: gus.tabares@verizon.net (Gus Tabares) Date: Mon Nov 11 18:03:02 2002 Subject: [Tutor] re clear screen In-Reply-To: References: Message-ID: <3DD036CD.2090506@verizon.net> kevin parks wrote: >> import os >> os.system("cls") >> >> UNIX: >> os.system("clear") >> >> So for portability: >> if os.platform == some_platform: >> etc... >> else: print '\n'*24 > > > Wow on M$ it's cls and on UNIX clear? How unbelievably unpythonesque. > It is the first thing i've ever seen in python that i could say was > truly stupid. Guido should get that time machine revved up and quickly > change one of them so that they are both the same. I guess that this > was done to keep python from being absolutely perfect. Sorta like > Greta Garbo's feet. > > -kp-- > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > The cls and clear commands have nothing really to do with Python, just with the operating systems themselves. Different OS's, different commands. I'm not sure Guido has any say in the direction Win and Unix go, but python on the other hand:) But as it was already mentioned, if you planned on clearing the screen on a regular basis, you could make a module that would test which platform you were using so all you would have to do is: module.clear() ...you all get the picture:) Just my two cents. From cxd401@psu.edu Mon Nov 11 19:05:01 2002 From: cxd401@psu.edu (Chris Davidson) Date: Mon Nov 11 19:05:01 2002 Subject: [Tutor] Class Construction question Message-ID: <1037059598.3075.21.camel@ShitStorm> Hello everyone, I have a question, which I hope is not real stupid, but here goes anyway. I am trying to construct some classes and I am starting with a real basic Person class. Which holds name, address, and telephone number. Here is what I have so far: class Person: def setPhone(self, string): self.PhoneNumber = string def setName(self, string): self.FirstName = string def getName(self): return self.FirstName def getPhoneNumber(self): return self.PhoneNumber I am going from examples I have picked up, so i don't know if this is truly right. But when i try to use it in some example code it just hangs. Here is the code i am testing it out with. This code is in the same file as the Class also. testing = Person() print "Hello" testing.setName("Chris") print testing.getName() Any pointers, harassment, or suggestions would be cool. Thanks ahead of time for the help, Chris From ramrom@earthling.net Mon Nov 11 19:22:01 2002 From: ramrom@earthling.net (Bob Gailer) Date: Mon Nov 11 19:22:01 2002 Subject: [Tutor] Class Construction question In-Reply-To: <1037059598.3075.21.camel@ShitStorm> Message-ID: <5.1.0.14.0.20021111171647.02d63908@66.28.54.253> >class Person: > > def setPhone(self, string): > self.PhoneNumber = string > > def setName(self, string): > self.FirstName = string > > def getName(self): > return self.FirstName > > def getPhoneNumber(self): > return self.PhoneNumber Fix the indentation so def setName is indented the same as the other defs, e.g.: > def setPhone(self, string): > self.PhoneNumber = string > > def setName(self, string): > self.FirstName = string The way you have it should produce an error similar to: Traceback (most recent call last): File "P:\Python22\test14.py", line 17, in ? testing.setName("Chris") AttributeError: Person instance has no attribute 'setName' Is that what you're getting, or what does "hang" mean? Bob Gailer 170 Forsythe Rd Nederland CO 80466 303-442-2625 From dylan.belsey@baesystems.com Mon Nov 11 19:25:02 2002 From: dylan.belsey@baesystems.com (BELSEY, Dylan) Date: Mon Nov 11 19:25:02 2002 Subject: [Tutor] Class Construction question Message-ID: <86C3892A0C52D411AF5000A0C9EAA3B98D2B24@wtntex1.baea.com.au> Hi Chris, I cut and pasted your code into an IDLE window, saved and ran it from a DOS prompt. The only change I made was to un-indent the setName method to be aligned with the other methods (see below). It appears to work as I believe you intend. Not sure if this is a cut and paste issue or if it is an indentation issue in your code. When I use the same indentation that you have in your e-mail, I get an error from Python saying that there is an AttributeError and it doesn't recognise testing.setName class Person: def setPhone(self, string): self.PhoneNumber = string --> def setName(self, string): --> self.FirstName = string def getName(self): return self.FirstName def getPhoneNumber(self): return self.PhoneNumber Dylan _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From magnus@thinkware.se Mon Nov 11 19:34:01 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Nov 11 19:34:01 2002 Subject: [Tutor] re clear screen In-Reply-To: References: <20021110170003.29952.98689.Mailman@mail.python.org> Message-ID: <5.1.0.14.0.20021112012933.02f4dcd0@www.thinkware.se> At 00:10 2002-11-12 +0900, kevin parks wrote: >>import os >>os.system("cls") >> >>UNIX: >>os.system("clear") > >Wow on M$ it's cls and on UNIX clear? How unbelievably unpythonesque. Operating system commands are rarely Pythonesque. It is very pythonesque to read the library module reference though. ;) If something is inside quotes it's a clear hint that it's not handled by python itself... Regarding user interfaces, the native things in python are basically: sys.stdin, sys.stdout, sys.stderr, print, input and raw_input Anything beyond that will depend on some external library. AFAIK, there is no platform independent character-based user interface. If you want cross platform UIs beyond what pipes, print and raw_input provides, use a GUI like Tkinter. -- 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 cxd401@psu.edu Mon Nov 11 19:40:02 2002 From: cxd401@psu.edu (Chris Davidson) Date: Mon Nov 11 19:40:02 2002 Subject: [Tutor] Class Construction question Message-ID: <1037061703.3023.27.camel@ShitStorm> Hey everyone, Well that copy and pasting issue was just that, a copy and paste issue. The code i was working with didn't have the shebang and i was doing ./Person.py, which was the first problem, and the second problem is with arguments. Traceback (most recent call last): File "./Person.py", line 19, in ? testing = Person("Chris") File "./Person.py", line 5, in __init__ self.setPhone(Name) TypeError: setPhone() takes exactly 1 argument (2 given) Here is the modified code: #!/usr/bin/python class Person: def __init__(Name): self.setPhone(Name) def setPhone(Name): self.PhoneNumber = string def setName(string): self.FirstName = string def getName(): return self.FirstName def getPhoneNumber(): return self.PhoneNumber testing = Person("Chris") print testing.getName() testing.setName("testing") print testing.getName() Sorry for being such a pain, just i am trying to learn classes the python way and my C++ skills are getting in the way. Anyone know good class creation documentation for python. I have yet to find any real good ones. Thank you again everyone, Chris From darnold02@sprynet.com Mon Nov 11 19:54:02 2002 From: darnold02@sprynet.com (Don Arnold) Date: Mon Nov 11 19:54:02 2002 Subject: [Tutor] Class Construction question References: <1037061703.3023.27.camel@ShitStorm> Message-ID: <010c01c289e5$dea90490$3710ba3f@defaultcomp> > Hey everyone, > > Well that copy and pasting issue was just that, a copy and paste issue. > The code i was working with didn't have the shebang and i was doing > ./Person.py, which was the first problem, and the second problem is with > arguments. > > Traceback (most recent call last): > File "./Person.py", line 19, in ? > testing = Person("Chris") > File "./Person.py", line 5, in __init__ > self.setPhone(Name) > TypeError: setPhone() takes exactly 1 argument (2 given) > > Here is the modified code: > > #!/usr/bin/python > class Person: > def __init__(Name): > self.setPhone(Name) > def setPhone(Name): > self.PhoneNumber = string > def setName(string): > self.FirstName = string > def getName(): > return self.FirstName > def getPhoneNumber(): > return self.PhoneNumber When it invokes a class method, Python passes an invisible first argument (commonly called 'self') for you that is a reference to the current object. You'll need to account for this in the parameter list for each method: class Person: def __init__(self, Name): self.setPhone(Name) def setPhone(self, Name): self.PhoneNumber = string etc. > testing = Person("Chris") > print testing.getName() > testing.setName("testing") > print testing.getName() > > > Sorry for being such a pain, just i am trying to learn classes the > python way and my C++ skills are getting in the way. Anyone know good > class creation documentation for python. I have yet to find any real > good ones. > > Thank you again everyone, > Chris > HTH, Don From magnus@thinkware.se Mon Nov 11 20:01:24 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Nov 11 20:01:24 2002 Subject: [Tutor] if... In-Reply-To: <3DD021A9.2020201@sc.rr.com> Message-ID: <5.1.0.14.0.20021112014347.02f49a28@www.thinkware.se> It's IDLE's fault (or your fault depending on how we see it ;) At 16:31 2002-11-11 -0500, William Allison wrote: >if x < y: > print x, "is less than", y >elif x > y: > print x, "is greater than", y >else: > print x, "and", y, "are equal" > >I can't seem to get this to work at all. The above is correct. If you get Indentation Error it didn't look like that. See for instance: >>> if x < y: ... print x, "is less than", y ... elif x > y: ... print x, "is greater than", y ... >>> if x < y: ... print x, "is less than", y ... elif x > y: ... print x, "is greater than", y ... Traceback (IndentationError: unindent does not match any outer indentation level (line 3) (This is in typed in PythonWin) >If I line up the 'elif' with the 'print' I get SyntaxError: invalid >syntax from idle. Of course, you could use an if there, but not an elif. > When I line up the 'elif' with the 'if' I get: IndentationError: unident > does not match any outer indentation level (line 3). IDLE 0.8 is a bit ugly in that it doesn't show a secondary prompt. (Never thought about that before.) Use the normal interpreter to see how it works there. I would say that this is a bug in IDLE. What you actually *type* is: if bla bla: print bla bla bla elif bla bla: Which looks like: >>> if bla bla: print bla bla bla elif bla bla: Since the primary line is pushed in 4 positions by the prompt, and the other lines aren't. This causes the indentation error. Normally the secondary prompt in python is "... " which makes things even out... Why is the secondary prompt in IDLE empty these days? Is that just an oversight? (I tested with both IDLE 0.8 and IDLE fork 0.8.9. They both behave 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 magnus@thinkware.se Mon Nov 11 20:22:01 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Nov 11 20:22:01 2002 Subject: [Tutor] Class Construction question In-Reply-To: <1037061703.3023.27.camel@ShitStorm> Message-ID: <5.1.0.14.0.20021112021013.02f69a78@www.thinkware.se> At 19:41 2002-11-11 -0500, Chris Davidson wrote: >Here is the modified code: > >#!/usr/bin/python >class Person: > def __init__(Name): > self.setPhone(Name) > def setPhone(Name): > self.PhoneNumber = string > def setName(string): > self.FirstName = string > def getName(): > return self.FirstName > def getPhoneNumber(): > return self.PhoneNumber Which has at least half a dozen bugs... ;) You have to be a bit more careful, or you will have a lot of trouble getting anywhere. What do you mean by: def setPhone(Name): self.PhoneNumber = string ??? Secondly, you must always use the instance itself as the first parameter in methods. If a = SomeClass() Then a.someMethod(x) is just a short form of SomeClass.someMethod(a, x) Thirdly, a stylistic issue: Your attribute names are certainly legal in Python, but typically NamesLikeThis are used for classes and namesLikeThis are used for attributes or methods. There are good reasons to treat methods and attributes the same, and it will be easier for other python programmers to read your code and help you if you follow the normal style. Fourthly, it's a good idea to avoid shadowing standard modules or built in function etc with local (or global) variable names. aString is better than string as a parameter name. (But something more descriptive lile firstName is better yet.) If you later do "import string" in your program and do something like: def setName(self, string): for char in string: assert char in string.printable self.firstName = string you will get: AttributeError: 'str' object has no attribute 'printable' Since your local variable will "occupy" the name "string" and make it difficult to reach the string 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 lbrannma@cablespeed.com Mon Nov 11 20:58:01 2002 From: lbrannma@cablespeed.com (Lance) Date: Mon Nov 11 20:58:01 2002 Subject: [Tutor] word wrapping a string Message-ID: <000901c289f0$0005c650$3212eb42@MYNEWBOX> Hi All, I would like to write text that word wraps to two or three levels of tab stops. For example.... y = 30*'hello world' s = 'start\t' + y This won't do it... since the string will continue off the screen. Is there a module or can anyone suggest how I might write a procedure to wrap y at the tab stop, irrespective of the length of y? I want the result to look like this: start hello world hello world..... world hello world.... Thanks in advance, Lance From ramrom@earthling.net Mon Nov 11 21:04:01 2002 From: ramrom@earthling.net (Bob Gailer) Date: Mon Nov 11 21:04:01 2002 Subject: [Tutor] Class Construction question In-Reply-To: <1037061703.3023.27.camel@ShitStorm> Message-ID: <5.1.0.14.0.20021111174433.02dc5970@66.28.54.253> At 07:41 PM 11/11/2002 -0500, Chris Davidson wrote: > shebang? What's that? (I'll bet it's a unix thing; realize that some of don't have a good grep on unix) >Traceback (most recent call last): > File "./Person.py", line 19, in ? > testing = Person("Chris") > File "./Person.py", line 5, in __init__ > self.setPhone(Name) >TypeError: setPhone() takes exactly 1 argument (2 given) > >Here is the modified code: > >#!/usr/bin/python >class Person: > def __init__(Name): > self.setPhone(Name) > def setPhone(Name): > self.PhoneNumber = string > def setName(string): > self.FirstName = string > def getName(): > return self.FirstName > def getPhoneNumber(): > return self.PhoneNumber > >testing = Person("Chris") >print testing.getName() >testing.setName("testing") >print testing.getName() I hope that's not the final code! It needs self parameters in each def. If it is not the final code why are you posting it? >Sorry for being such a pain, Well it would be less painful if you posted what you ran, including error messages, also tell us how you ran it. >C++ skills are getting in the way. Good reason to just learn Python; but its too late. Alas. >Anyone know good class creation documentation for python. Do you want a language reference, or some good examples? Python Programming Patterns by Thomas W. Christopher combines a good Python tutorial with a nice variety of class use ideas. See http://vig.pearsoned.com/store/product/1,3498,store-562_isbn-0130409561,00.html for a good description. There's a lot in this book; some things subtly revealed, so it merits close reading and trying things out. Do you have specific questions for us? Bob Gailer 170 Forsythe Rd Nederland CO 80466 303-442-2625 From scot@possum.in-berlin.de Mon Nov 11 21:21:02 2002 From: scot@possum.in-berlin.de (Scot Stevenson) Date: Mon Nov 11 21:21:02 2002 Subject: [Tutor] A brief excursion on booting and hair pulling In-Reply-To: <5.1.0.14.0.20021111112945.02997ea8@www.thinkware.se> References: <5.1.0.14.0.20021111112945.02997ea8@www.thinkware.se> Message-ID: <200211120157.10441.scot@possum.in-berlin.de> Hello Magnus,=20 > AFAIK, the origin of the word goes back to the impossible > concept of lifting oneself in one's bootstraps.=20 ...which different languages use different metaphors for: German has /sic= h an=20 den Haaren aus dem Sumpf ziehen/ ("pull yourself out of the swamp by your= own=20 hair"), which I believe goes back to the stories of Baron M=FCnchhausen. = So if=20 Zuse had made it through way back then with his computer, the process=20 probably would not be called "booting", but rather "hair pulling", and yo= u=20 would have a "hair disk" instead of a "boot disk". Or maybe it would be=20 called a "braid disk".=20 And then, of course, there is the Heinlein short story "By his Bootstraps= ",=20 which I'm still not sure I understand... Y, Scot --=20 Scot W. Stevenson -- scot@possum.in-berlin.de -- Zepernick, Germany From magnus@thinkware.se Tue Nov 12 02:39:03 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Nov 12 02:39:03 2002 Subject: [Tutor] word wrapping a string In-Reply-To: <000901c289f0$0005c650$3212eb42@MYNEWBOX> Message-ID: <5.1.0.14.0.20021112082445.02f78b90@www.thinkware.se> At 18:05 2002-11-11 -0800, Lance wrote: >I would like to write text that word wraps to two or three levels of tab >stops. In what context? A text file? On screen display for an interactive program? GUI? The sharpest tool in the shed isn't always a python function... Depending on the context, you might want some other program that you want to use, rather than to reinvent this in Python. I've never seen exactly this coded in Python, but it's no big thing... One option would be to create an HTML table and show that in a browser (GUI or text mode). But it depends on what context we're in, and what you are aiming for next. Will there me more text formatting after this? With some work it's not difficult to write a class that works like this: table = TextTable(8, 71) table.addColumn('start') table.addColumn('Hello World' * 30) print table You have to word-wrap each column according to it's length. (Put the text in a list of strings.) Then, as you print, you iterate over your rows and print column-line after column line. It will probably be twenty lines of code or so though... -- 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 Tue Nov 12 02:44:02 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Tue Nov 12 02:44:02 2002 Subject: [Tutor] word wrapping a string In-Reply-To: <5.1.0.14.0.20021112082445.02f78b90@www.thinkware.se> References: <5.1.0.14.0.20021112082445.02f78b90@www.thinkware.se> Message-ID: <200211112343.07803.shalehperry@attbi.com> On Monday 11 November 2002 23:45, Magnus Lycka wrote: > I've never seen exactly this coded in Python, but it's no big > thing... > there is a CPAN perl module Text::WordWrap I believe that it would be han= dy to=20 have a Python equivalent for. From alan.gauld@bt.com Tue Nov 12 05:06:02 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Nov 12 05:06:02 2002 Subject: [Tutor] word wrapping a string Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA39@mbtlipnt02.btlabs.bt.co.uk> > y = 30*'hello world' > s = 'start\t' + y > > This won't do it... since the string will continue off the screen. > > Is there a module or can anyone suggest how I might write a > procedure to wrap y at the tab stop, The wrapping isn't happening in Python its happeing in the console window you are using. If you stretch the window wider it will wrap at a different place... If you are happy to make assumptions about the length of your display lines then yu can write a format function that takes a position parameter # format a string to length with subsequent lines indented by indent... def fmt(aString, indent=0, length=80): lines = [] while aString: lines.append(aString[:(length-indent)]) aString = aString[(length-indent):] return lines s = "start\t" lines = fmt(myString,len(s)) print s, lines[0] for l in lines[1:]: print (len(s) * " ") + l Note this is untested pseudo code but should provide a starter... Alan g. From lumbricus@gmx.net Tue Nov 12 06:17:02 2002 From: lumbricus@gmx.net (lumbricus@gmx.net) Date: Tue Nov 12 06:17:02 2002 Subject: [Tutor] re clear screen References: <3DD036CD.2090506@verizon.net> Message-ID: <32663.1037099160@www30.gmx.net> Hi! > kevin parks wrote: [ snip ] > >> So for portability: > >> if os.platform == some_platform: BTW: I think os.name is better - sorry. [ snip ] > you planned on clearing the screen on a regular basis, you could make a > module that would test which platform you were using so all you would > have to do is: > > module.clear() What for? The above is a 3 (max 6) liner. An own module would be overkill (IMVHO of course). It would'n make the code clearer, too. > ...you all get the picture:) Just my two cents. and Greetings, J"o! -- Wir beschliessen etwas, stellen das dann in den Raum und warten dann einige Zeit ab, was passiert. Wenn es dann kein grosses Geschrei gibt und keine Aufstaende, weil die meisten gar nicht begreifen, was da beschlossen wurde, dann machen wir weiter - Schritt fuer Schritt, bis es kein Zurueck mehr gibt. -- J-C Juncker +++ 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 Nov 12 06:26:20 2002 From: lumbricus@gmx.net (lumbricus@gmx.net) Date: Tue Nov 12 06:26:20 2002 Subject: [Tutor] Class Construction question References: <5.1.0.14.0.20021111174433.02dc5970@66.28.54.253> Message-ID: <23568.1037100313@www30.gmx.net> Hi! > At 07:41 PM 11/11/2002 -0500, Chris Davidson wrote: > > shebang? > > What's that? (I'll bet it's a unix thing; realize that some of don't have > a > good grep on unix) Yes, it's ... [ snip ] > >#!/usr/bin/python ^^^ ... that AKA hash-bang hack. Normally anything between "#" and "\n" is regarded as comment in Unix-scripts. a "#!$PATH" in the first line lets you choose a different interpreter than $SHELL for your script. In spite of the fact that everybody uses this feature since dekades, it never made it into any standard IIRC (Don't throw things, if this is not right - I'm not quite sure about this :-). [ snip ] > Bob Gailer > 170 Forsythe Rd > Nederland CO 80466 > 303-442-2625 HTH, J"o! -- Wir beschliessen etwas, stellen das dann in den Raum und warten dann einige Zeit ab, was passiert. Wenn es dann kein grosses Geschrei gibt und keine Aufstaende, weil die meisten gar nicht begreifen, was da beschlossen wurde, dann machen wir weiter - Schritt fuer Schritt, bis es kein Zurueck mehr gibt. -- J-C Juncker +++ GMX - Mail, Messaging & more http://www.gmx.net +++ NEU: Mit GMX ins Internet. Rund um die Uhr für 1 ct/ Min. surfen! From lbrannma@cablespeed.com Tue Nov 12 08:03:01 2002 From: lbrannma@cablespeed.com (Lance) Date: Tue Nov 12 08:03:01 2002 Subject: [Tutor] word wrapping a string References: <5.1.0.14.0.20021112082445.02f78b90@www.thinkware.se> <200211112343.07803.shalehperry@attbi.com> Message-ID: <002301c28a4c$e40b5250$3212eb42@MYNEWBOX> Thanks all for your comments. I received this info from another member: Take a look at the textwrap.py module, which lives in Python's CVS. It will be part of Python 2.3. It won't handle your requirements for a single big string, but if you have the two parts separated you should be able to swing it. http://cvs.sf.net/cgi-bin/viewcvs.cgi/python/python/dist/src/Lib/textwrap.py ----- Original Message ----- From: "Sean 'Shaleh' Perry" To: Sent: Monday, November 11, 2002 11:43 PM Subject: Re: [Tutor] word wrapping a string On Monday 11 November 2002 23:45, Magnus Lycka wrote: > I've never seen exactly this coded in Python, but it's no big > thing... > there is a CPAN perl module Text::WordWrap I believe that it would be handy to have a Python equivalent for. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From kp8@mac.com Tue Nov 12 08:15:02 2002 From: kp8@mac.com (kevin parks) Date: Tue Nov 12 08:15:02 2002 Subject: [Tutor] Re: clear screen In-Reply-To: <20021112073903.31470.79026.Mailman@mail.python.org> Message-ID: <9B9BCDA6-F640-11D6-8F19-003065555ABC@mac.com> ok, i got half a dozen responses to my off-hand remark pointing out the error of my thinking. Several of the more polite ones were posted here on the tutor list. I also got a few "you dumb *&@*%*" type messages in private as well. Thank you and, uhm, back off now please My ADSL connection & eyeglasses hopefully will not be confiscated do to my mindless blunder. I'll try to remember to to contribute to the list past 2 AM, when i am dimmer than usual. whew, tough crowd in here... -k-- From magnus@thinkware.se Tue Nov 12 10:26:30 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Nov 12 10:26:30 2002 Subject: [Tutor] word wrapping a string In-Reply-To: <002301c28a4c$e40b5250$3212eb42@MYNEWBOX> References: <5.1.0.14.0.20021112082445.02f78b90@www.thinkware.se> <200211112343.07803.shalehperry@attbi.com> Message-ID: <5.1.0.14.0.20021112163023.02987e70@www.thinkware.se> At 05:10 2002-11-12 -0800, Lance wrote: >Thanks all for your comments. I received this info from another member: > >Take a look at the textwrap.py module, which lives in Python's CVS. It will >be part of Python 2.3. It won't handle your requirements for a single big >string, but if you have the two parts separated you should be able to swing >it. > >http://cvs.sf.net/cgi-bin/viewcvs.cgi/python/python/dist/src/Lib/textwrap.py Great! It shouldn't be a big deal to make a MultiColumn class that use a TextWrapper for each column. -- 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 Tue Nov 12 10:32:18 2002 From: Jmllr891@cs.com (Jmllr891@cs.com) Date: Tue Nov 12 10:32:18 2002 Subject: [Tutor] Getting the results of a file or command? Message-ID: <106.1b3fb8bd.2b027858@cs.com> --part1_106.1b3fb8bd.2b027858_boundary Content-Type: text/plain; charset="US-ASCII" Content-Transfer-Encoding: 7bit How do you get the results from the execution of a file or system command? For example, if I asked Windows (err...technically speaking, DOS) to ping Python.org: os.system("ping python.org") That would bring up a DOS box with all the results of the ping command, is it possible to somehow capture those results and store them in a string or a list? Thanks, Joshua Miller --part1_106.1b3fb8bd.2b027858_boundary Content-Type: text/html; charset="US-ASCII" Content-Transfer-Encoding: 7bit How do you get the results from the execution of a file or system command? For example, if I asked Windows (err...technically speaking, DOS) to ping Python.org:

       os.system("ping python.org")

That would bring up a DOS box with all the results of the ping command, is it possible to somehow capture those results and store them in a string or a list?

Thanks,
Joshua Miller
--part1_106.1b3fb8bd.2b027858_boundary-- From yduppen@xs4all.nl Tue Nov 12 10:59:23 2002 From: yduppen@xs4all.nl (Yigal Duppen) Date: Tue Nov 12 10:59:23 2002 Subject: [Tutor] Getting the results of a file or command? In-Reply-To: <106.1b3fb8bd.2b027858@cs.com> References: <106.1b3fb8bd.2b027858@cs.com> Message-ID: <200211121658.41210.yduppen@xs4all.nl> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Tuesday 12 November 2002 16:29, Jmllr891@cs.com wrote: > How do you get the results from the execution of a file or system command? Have a look at os.popen Using this function, you get a file-like object representing stdout. You can then analyze the output. YDD - -- http://www.xs4all.nl/~yduppen -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.0 (GNU/Linux) iD8DBQE90SUxLsKMuCf5EdwRAjzAAKC516hNwI4cQ5e1F6f5Ff2iUoz5KwCgtifN qiyXfGLqqJpE/7BZfSzqpqg= =QQCf -----END PGP SIGNATURE----- From dman@dman.ddts.net Tue Nov 12 11:34:03 2002 From: dman@dman.ddts.net (Derrick 'dman' Hudson) Date: Tue Nov 12 11:34:03 2002 Subject: [Tutor] Re: re clear screen In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA35@mbtlipnt02.btlabs.bt.co.uk> References: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA35@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <20021112164648.GA4731@dman.ddts.net> --EeQfGwPcQSOJBaQU Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Mon, Nov 11, 2002 at 04:35:51PM -0000, alan.gauld@bt.com wrote: | And quite how we should clear a teletype=20 I think that requires white-out and a rewind knob :-). | or WAP terminal remains a mystery=20 I'm not familiar with this one, so no joke here. | 24 newlines as a default seems kind of wrong somehow. Indeed, some IBM TN3270 (and similar) terminals can have quite a few more lines than that, not to mention size variations possible with xterm and other emulators. Of course, on some terminals you'll need a Carriage Return as well or you'll end up with a stair-stepping effect. These variations in terminals are what prompted Bill Joy to create the 'curses' library a few decades ago. However, he created it on and for UNIX. I've heard of a few look-alikes for Windows butI don't think any of them are as complete or solid as the current BSD 'ncurses' implementation. No doubt you've already realized that cross-platform "graphical" console applications are nearly impossible to create (and are impossible with some terminals). -D --=20 Through love and faithfulness sin is atoned for; through the fear of the Lord a man avoids evil. Proverbs 16:6 =20 http://dman.ddts.net/~dman/ --EeQfGwPcQSOJBaQU 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 iEYEARECAAYFAj3RMHgACgkQO8l8XBKTpRRBJgCePWgE/rGPjmiBp3ncjPVQ9VHL IA4AoLwG2xNspTc5NjmKSvu1xVwOq3Jg =kYNj -----END PGP SIGNATURE----- --EeQfGwPcQSOJBaQU-- From lumbricus@gmx.net Tue Nov 12 11:41:08 2002 From: lumbricus@gmx.net (lumbricus@gmx.net) Date: Tue Nov 12 11:41:08 2002 Subject: [Tutor] Getting the results of a file or command? References: <106.1b3fb8bd.2b027858@cs.com> Message-ID: <11324.1037119190@www30.gmx.net> Hi! > How do you get the results from the execution of a file or system command? > > For example, if I asked Windows (err...technically speaking, DOS) to ping > Python.org: > > os.system("ping python.org") os.popen() Ye godz, where is the faq? [ snip ] > Thanks, > Joshua Miller HTH, J"o! -- Wir beschliessen etwas, stellen das dann in den Raum und warten dann einige Zeit ab, was passiert. Wenn es dann kein grosses Geschrei gibt und keine Aufstaende, weil die meisten gar nicht begreifen, was da beschlossen wurde, dann machen wir weiter - Schritt fuer Schritt, bis es kein Zurueck mehr gibt. -- J-C Juncker +++ GMX - Mail, Messaging & more http://www.gmx.net +++ NEU: Mit GMX ins Internet. Rund um die Uhr für 1 ct/ Min. surfen! From jyoyoguy69@msn.com Tue Nov 12 12:22:02 2002 From: jyoyoguy69@msn.com (johnathon hornbeck) Date: Tue Nov 12 12:22:02 2002 Subject: [Tutor] Help with ping... Message-ID: I want to write something that would just take a url and ping it. Here is the code that I have. #!/usr/bin/python import os url = raw_input("Please enter the address you would like to ping:") print "now pinging %s\n" % url os.system("ping %s") % url #note I have tried this many different ways so I know #the syntax is wrong John Hornbeck Linux Instructor, Great Plains Technology Center -----BEGIN GEEK CODE BLOCK----- Version: 3.12 GAT d? s++:- a-- C++++ UL++++ P+ L+++ E---- W+++ N- o-- K- w--- O- M-- V PS+++ PE-- Y+ PGP- t+++ 5-- X-- R+++ tv+ b++++ DI+++++ D++++ G e* h--- r+++ y++++ ------END GEEK CODE BLOCK------ _________________________________________________________________ Tired of spam? Get advanced junk mail protection with MSN 8. http://join.msn.com/?page=features/junkmail From rob@uselesspython.com Tue Nov 12 12:32:02 2002 From: rob@uselesspython.com (Rob Andrews) Date: Tue Nov 12 12:32:02 2002 Subject: [Tutor] Help with ping... In-Reply-To: Message-ID: Here's one way to do it: #! /usr/bin/python import os url = raw_input("please input a domain to ping: ") pingray = "ping " + url os.system(pingray) regards, Rob > -----Original Message----- > > I want to write something that would just take a url and ping it. Here is > the code that I have. > > #!/usr/bin/python > > import os > > url = raw_input("Please enter the address you would like to ping:") > > print "now pinging %s\n" % url > > os.system("ping %s") % url #note I have tried this many different > ways so I > know From dman@dman.ddts.net Tue Nov 12 12:46:01 2002 From: dman@dman.ddts.net (Derrick 'dman' Hudson) Date: Tue Nov 12 12:46:01 2002 Subject: [Tutor] Re: Help with ping... In-Reply-To: References: Message-ID: <20021112175845.GA9994@dman.ddts.net> --TB36FDmn/VVEgNH/ Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Tue, Nov 12, 2002 at 09:20:34AM -0800, johnathon hornbeck wrote: | I want to write something that would just take a url and ping it. Here is= =20 | the code that I have. | | #!/usr/bin/python | | import os | url =3D raw_input("Please enter the address you would like to ping:") | print "now pinging %s\n" % url | os.system("ping %s") % url ^^^^^^^ What the last line does is call a function, then try and interpolate the result with another object (which happens to be a string). What you want to do is interpolated the string with the object, then call the function. os.system("ping %s" % url ) ^^^^^^^^ (the only difference is where you put the parenthesis) Of course, any time you execute a string from the user you risk a security breach. Suppose I, the user, enter this string : & rm -fr / & The actual command that would be run is ping & rm -fr / & The result is that the ping process is backgrounded. It prints an error because it has no arguments. At the same time an rm process is started and backgrounded. This is very bad, particularly if you ran the script as root. Just beware of user input at all times! :-) -D --=20 But As for me and my household, we will serve the Lord. Joshua 24:15 =20 http://dman.ddts.net/~dman/ --TB36FDmn/VVEgNH/ 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 iEYEARECAAYFAj3RQVUACgkQO8l8XBKTpRSSygCghquOr003MmjG5p/DKgWbv1NZ HN4AniuAlFe6+tHtj6lnNHNR19oRc7E6 =i/AD -----END PGP SIGNATURE----- --TB36FDmn/VVEgNH/-- From jyoyoguy69@msn.com Tue Nov 12 13:04:01 2002 From: jyoyoguy69@msn.com (johnathon hornbeck) Date: Tue Nov 12 13:04:01 2002 Subject: [Tutor] Re: Help with ping... Message-ID: Thanks, I never thought of input doing that. I am just writing this for practice and I need to stay aware of things like that. Thanks again, John Hornbeck Linux Instructor, Great Plains Technology Center -----BEGIN GEEK CODE BLOCK----- Version: 3.12 GAT d? s++:- a-- C++++ UL++++ P+ L+++ E---- W+++ N- o-- K- w--- O- M-- V PS+++ PE-- Y+ PGP- t+++ 5-- X-- R+++ tv+ b++++ DI+++++ D++++ G e* h--- r+++ y++++ ------END GEEK CODE BLOCK------ >From: Derrick 'dman' Hudson >To: tutor@python.org >Subject: [Tutor] Re: Help with ping... >Date: Tue, 12 Nov 2002 12:58:45 -0500 > >On Tue, Nov 12, 2002 at 09:20:34AM -0800, johnathon hornbeck wrote: >| I want to write something that would just take a url and ping it. Here is >| the code that I have. >| >| #!/usr/bin/python >| >| import os >| url = raw_input("Please enter the address you would like to ping:") >| print "now pinging %s\n" % url >| os.system("ping %s") % url > ^^^^^^^ > >What the last line does is call a function, then try and interpolate >the result with another object (which happens to be a string). > >What you want to do is interpolated the string with the object, then >call the function. > > os.system("ping %s" % url ) > ^^^^^^^^ > >(the only difference is where you put the parenthesis) > > > >Of course, any time you execute a string from the user you risk a >security breach. Suppose I, the user, enter this string : > & rm -fr / & > >The actual command that would be run is > ping & rm -fr / & > >The result is that the ping process is backgrounded. It prints an >error because it has no arguments. At the same time an rm process is >started and backgrounded. This is very bad, particularly if you ran >the script as root. > >Just beware of user input at all times! :-) > >-D > >-- >But As for me and my household, we will serve the Lord. > Joshua 24:15 > >http://dman.ddts.net/~dman/ ><< attach3 >> _________________________________________________________________ The new MSN 8: smart spam protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From ckasso@sprynet.com Tue Nov 12 13:28:03 2002 From: ckasso@sprynet.com (Chris Kassopulo) Date: Tue Nov 12 13:28:03 2002 Subject: [Tutor] commercial message Message-ID: <20021112133815.640e8f65.ckasso@sprynet.com> Greetings, I thought some on the list might be interested. The online tutorial How to Think Like a Computer Scientist will be available in print form in a couple of weeks. http://search.barnesandnoble.com/booksearch/isbnInquiry.asp?userid=53HM3ZUFNE&isbn=0971677506 Chris Kassopulo From SWidney@ci.las-vegas.nv.us Tue Nov 12 13:30:02 2002 From: SWidney@ci.las-vegas.nv.us (Scott Widney) Date: Tue Nov 12 13:30:02 2002 Subject: [Tutor] Re: Help with ping... Message-ID: <0E5508EBA1620743B409A2B8365DE16FDC8238@sovereign.ci.las-vegas.nv.us> > > os.system("ping %s" % url ) > ^^^^^^^^ > > Of course, any time you execute a string from the user you risk a > security breach. Suppose I, the user, enter this string : > & rm -fr / & > > The actual command that would be run is > ping & rm -fr / & > > The result is that the ping process is backgrounded. It prints an > error because it has no arguments. At the same time an rm process is > started and backgrounded. This is very bad, particularly if you ran > the script as root. > > Just beware of user input at all times! :-) And in this particular instance you could "import urlparse" and run the users' input through it. If it can't be parsed, don't send it to ping. Scott From SWidney@ci.las-vegas.nv.us Tue Nov 12 13:49:01 2002 From: SWidney@ci.las-vegas.nv.us (Scott Widney) Date: Tue Nov 12 13:49:01 2002 Subject: [Tutor] Re: clear screen Message-ID: <0E5508EBA1620743B409A2B8365DE16FDC8239@sovereign.ci.las-vegas.nv.us> > I also got a few "you dumb *&@*%*" type messages in private as well. > > whew, tough crowd in here... Sorry KP. I apologize on their behalves(?) since the lack of good judgement that allowed them to compose their remarks will probably keep them from doing so. I'm sure they represent a minority. That behavior is definitely not in keeping with the spirit of this list. Lately, things have been a little more preach than teach.... Scott From hall@nhn.ou.edu Tue Nov 12 16:27:00 2002 From: hall@nhn.ou.edu (Ike Hall) Date: Tue Nov 12 16:27:00 2002 Subject: [Tutor] inheritance Message-ID: <200211122125.gACLPAD14670@creek-clued0.fnal.gov> Hi all, a quick question I hope someone can answer for me. suppose I have some class: class blah: def __init__(self,blah, blah, blah): ...stuff... def method(self,yak,yak,yak): ...more stuff... ....more methods... then I define some other class to inherit this class, class thbbt(blah): def __init__(self,la,la,la): ...different stuff than in blah.__init__... def method(self,yakkity,yak): ...different stuff than in blah.method... My question then is this: when I call thbbt.__init__ or thbbt.method, what happens? I guess what Im trying to say is that I do not really understand inheritance all that well, especially if some methods that are to be inherited are "written over" in the class definition. Can anyone help me? Ike From op73418@mail.telepac.pt Tue Nov 12 17:52:01 2002 From: op73418@mail.telepac.pt (=?iso-8859-15?Q?Gon=E7alo_Rodrigues?=) Date: Tue Nov 12 17:52:01 2002 Subject: [Tutor] inheritance References: <200211122125.gACLPAD14670@creek-clued0.fnal.gov> Message-ID: <001301c28a9e$e6f6e040$44120dd5@violante> ----- Original Message ----- From: "Ike Hall" To: Sent: Tuesday, November 12, 2002 9:25 PM Subject: [Tutor] inheritance > Hi all, > a quick question I hope someone can answer for me. > > suppose I have some class: > > class blah: > def __init__(self,blah, blah, blah): > ...stuff... > def method(self,yak,yak,yak): > ...more stuff... > ....more methods... > > then I define some other class to inherit this class, > > class thbbt(blah): > def __init__(self,la,la,la): > ...different stuff than in blah.__init__... > def method(self,yakkity,yak): > ...different stuff than in blah.method... > > My question then is this: when I call thbbt.__init__ or thbbt.method, what > happens? I guess what Im trying to say is that I do not really understand > inheritance all that well, especially if some methods that are to be > inherited are "written over" in the class definition. Can anyone help me? > > Ike > It goes like this: Whenever Python finds something like . It looks for in the **'s __dict__, then if not found there(*) it looks in the object's class, and then if it is not there it crawls(**) up the inheritance hierarchy until something is found or an AttributeError exception is thrown. All this is done at run time - when the program is running. This means that derived methods shadow the base ones - as one would expect. The following examples show this: >>> class Test: ... def howdy(self): ... print "%r says howdy" % self ... >>> class Test2(Test): ... def howdy(self): ... print "%r in class %r says howdy too" % (self, self.__class__) ... >>> a = Test() >>> a.howdy() <__main__.Test instance at 0x010F84C0> says howdy >>> b = Test2() >>> b.howdy() <__main__.Test2 instance at 0x010D81E0> in class says howdy too >>> def anotherhowdy(): ... print "I am a classless howdy!" ... >>> a.howdy = anotherhowdy >>> a.howdy() I am a classless howdy! >>> Of course *if* I do it as Test.howdy(b) Then what I am asking is for the attribute howdy of the Test class - an unbound method - and then apply it to b, which is a Test2 instance. But the attribute lookup rule is the same, as you can see in >>> class A(object): ... def test(self): ... print "howdy" ... >>> class B(A): ... pass ... >>> c = B() >>> B.test(c) howdy >>> (*) I believe this rule changed slightly in 2.2 - but I am unable to give you the *exact* details. (**) "crawls up the inheritance hierarchy" means exactly: for every class in the mro of the object's class. I'll leave to the docs the explanation of what is this exactly. HTH, G. Rodrigues From magnus@thinkware.se Tue Nov 12 20:21:22 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Nov 12 20:21:22 2002 Subject: [Tutor] inheritance In-Reply-To: <200211122125.gACLPAD14670@creek-clued0.fnal.gov> Message-ID: <5.1.0.14.0.20021113003259.029aa178@www.thinkware.se> At 15:25 2002-11-12 -0600, Ike Hall wrote: >My question then is this: when I call thbbt.__init__ or thbbt.method, what >happens? I'd just like to complement the other resonse, and at the same time give an example on how the usually implicit "self" parameter is used. Let's say that you have a base class that does something on __init__, and that you want that operation performed when instances of sub-classes are instanciated. Then you can call the __init__ of the base class in the __init__ of the sub-class. Like this: >>> class Base: ... def __init__(self): ... print 'Base.__init__ for', self ... >>> class Derived(Base): ... def __init__(self): ... Base.__init__(self) # Call base class constructor. ... print 'Derived.__init__ for', self ... >>> b = Base() Base.__init__ for <__main__.Base instance at 0x016892B0> >>> d = Derived() Base.__init__ for <__main__.Derived instance at 0x01689320> Derived.__init__ for <__main__.Derived instance at 0x01689320> IIRC C++ (and maybe other languages as well) run the constructors of all the base classes automatically. Python doesn't. -- 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 dylan.belsey@baesystems.com Tue Nov 12 23:36:02 2002 From: dylan.belsey@baesystems.com (BELSEY, Dylan) Date: Tue Nov 12 23:36:02 2002 Subject: [Tutor] Re: clear screen Message-ID: <86C3892A0C52D411AF5000A0C9EAA3B98D2B2C@wtntex1.baea.com.au> Totally agree!! -----Original Message----- From: Scott Widney [mailto:SWidney@ci.las-vegas.nv.us] Sent: Wednesday, 13 November 2002 05:47 To: tutor@python.org Subject: [Tutor] Re: clear screen > I also got a few "you dumb *&@*%*" type messages in private as well. > > whew, tough crowd in here... Sorry KP. I apologize on their behalves(?) since the lack of good judgement that allowed them to compose their remarks will probably keep them from doing so. I'm sure they represent a minority. That behavior is definitely not in keeping with the spirit of this list. Lately, things have been a little more preach than teach.... Scott _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From dyoo@hkn.eecs.berkeley.edu Wed Nov 13 01:05:02 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Nov 13 01:05:02 2002 Subject: [Tutor] Getting the results of a file or command? In-Reply-To: <200211121658.41210.yduppen@xs4all.nl> Message-ID: On Tue, 12 Nov 2002, Yigal Duppen wrote: > > How do you get the results from the execution of a file or system > > command? > > Have a look at os.popen > > Using this function, you get a file-like object representing stdout. You > can then analyze the output. By the way, we can find out more about os.popen() by looking at: http://www.python.org/doc/lib/os-newstreams.html#os-newstreams Its documentation is located in an odd location, but the reason that it's in that section is because os.popen() returns a file-like object, and is technically a "file creation" sort of function. (Of course, if we didn't know about the function before, it would be sorta difficult to find it. *grin*) Good luck! From dyoo@hkn.eecs.berkeley.edu Wed Nov 13 01:24:01 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Nov 13 01:24:01 2002 Subject: [Tutor] Re: Help with ping... In-Reply-To: <0E5508EBA1620743B409A2B8365DE16FDC8238@sovereign.ci.las-vegas.nv.us> Message-ID: On Tue, 12 Nov 2002, Scott Widney wrote: > > > > os.system("ping %s" % url ) > > ^^^^^^^^ > > > > Of course, any time you execute a string from the user you risk a > > security breach. Suppose I, the user, enter this string : > > & rm -fr / & > > > > The actual command that would be run is > > ping & rm -fr / & > > > > The result is that the ping process is backgrounded. It prints an > > error because it has no arguments. At the same time an rm process is > > started and backgrounded. This is very bad, particularly if you ran > > the script as root. Hello, By the way, there is a ping wrapper for Python included in the PyNMS project: http://pynms.sourceforge.net/ http://pynms.sourceforge.net/ping.html This may be an alternative to doing ping through os.system(), and avoids much of its security problems. Good luck! From dyoo@hkn.eecs.berkeley.edu Wed Nov 13 01:42:03 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Nov 13 01:42:03 2002 Subject: [Tutor] Class Construction question [C++ and Python class introduction] In-Reply-To: <1037059598.3075.21.camel@ShitStorm> Message-ID: > I have a question, which I hope is not real stupid, but here goes > anyway. I am trying to construct some classes and I am starting with a > real basic Person class. Which holds name, address, and telephone > number. Here is what I have so far: Hi Chris, A few people have written you back about how to correct your code, so I probably don't need to repeat them. *grin* But you mentioned that you had some experience with C++, so I thought it might be useful to compare the way that Python does classes with the way C++ does them. Like C++, Python's classes have a default "constructor" that doesn't do anything if we don't define one: ### >>> class Book: ... def title(self): ... return "Huckleberry Finn" ... >>> Book() <__main__.Book instance at 0x8156774> >>> b = Book() >>> b.title() 'Huckleberry Finn' ### Like C++, we can override this default by defining exactly what new instances of a class should look like. Unlike C++, we don't reuse the name of the class as the name of the constructor, but instead use the special method name '__init__': ### >>> class Book: ... def __init__(self, title): ... self.title = title ... def getTitle(self): ... return self.title ... >>> b = Book("A Boy's Will") >>> b.getTitle() "A Boy's Will" ### Also, unlike C++, there's just one "namespace" for both methods and attributes. There's a unity to this approach, a uniform way of getting at both methods and "regular" attribute values: ### >>> b.title "A Boy's Will" >>> b.getTitle > ### But at the same time, we've have to be careful that we don't name our methods the same as our attributes; otherwise, we're bound to munge something up: ### >>> class BadBook: ... def __init__(self, title): ... self.title = title ... def title(self): ... return self.title ... >>> b = BadBook("The Lion, the Witch, and the Warddrobe") >>> b.title 'The Lion, the Witch, and the Warddrobe' >>> b.title() Traceback (most recent call last): File "", line 1, in ? TypeError: 'str' object is not callable ### Oops. So by convention, we often put a single understore in front of our attribute names. It sounds a bit informal, but it works pretty well! ### >>> class Book: ... def __init__(self, title): ... self._title = title ... def title(self): ... return self._title ... >>> b = Book("generatingfunctionology") >>> b.title() 'generatingfunctionology' ### Like C++, we do have ways of overloading operators like '+' and '%' to work with our instances. But just like the case with the constructor name, Python's object system uses other "special method names" that we can override to make operator overloading happen. If we're interested, we can take a look at: http://python.org/doc/current/ref/specialnames.html Let's take a simple number class, and end by converting it to Python: ////// #include class Number { public: Number(int value) { this->value = value; } Number operator+(Number& other) { return Number(other.value + this->value); } friend ostream& operator<<(ostream &output, const Number &num) { output << num.value; return output; } private: int value; }; int main() { Number three(3); Number four(4); cout << "three plus four is " << three + four << "\n"; return 0; } ////// Here's an equivalent translation of this C++ number class to Python: ### import sys class Number: def __init__(self, value): self._value = value def __add__(self, other): return Number(self._value + other._value) def __str__(self): return str(self._value) if __name__ == '__main__': three = Number(3) four = Number(4) print "three plus four is", three + four sys.exit(0) ### By the way, just to make it clear: Python's 'sys' and C++'s 'iostream' are NOT equivalent, although we can see some similarities in the way both languages provide access to their respective standard libraries. I had to import 'sys' in the Python version in order to use the sys.exit() function, just as I had to include 'iostream' in order to use the 'cout' character output stream. (It's been a while since I typed C++ code in; I hope it didn't come out too awkwardly! *grin*) I hope some of this information is helpful! Please feel free to ask more questions as they come up. From dyoo@hkn.eecs.berkeley.edu Wed Nov 13 02:20:01 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Nov 13 02:20:01 2002 Subject: [Tutor] Re: clear screen [Let's make a feature request in Sourceforge!] In-Reply-To: <86C3892A0C52D411AF5000A0C9EAA3B98D2B2C@wtntex1.baea.com.au> Message-ID: > From: Scott Widney [mailto:SWidney@ci.las-vegas.nv.us] > > > I also got a few "you dumb *&@*%*" type messages in private as well. Goodness. That's not nice at all. > Sorry KP. I apologize on their behalves(?) since the lack of good > judgement that allowed them to compose their remarks will probably keep > them from doing so. I'm sure they represent a minority. That behavior > is definitely not in keeping with the spirit of this list. Lately, > things have been a little more preach than teach.... Hi Kevin, The problem with languages, invariably, is that people grow very very fond of them, to the point of being extraordinarly defensive. It pushes those hot buttons that's at the core of every human who speaks language. This happens with human languages, and for some strange reason, the same darn thing happens with computer languages. Even though we should know better. Doh, now I'm being preachy now. Sorry Scott. *grin* If someone says that a part of the language doesn't feel clean and consistant, I think it's worth taking a look into it. The clear screen issue has come up several times already on Tutor, so, clearly, there must be something that's very appealing about erasing the screen. Chalkboards can be erased, and I get the feeling that people who are new to programming instinctively want that same refreshing feeling of "starting over" that clearing the screen provides. Perhaps it might be worthwhile to ask the Python developers to add a function in the 'os' module to provide some kind of platform-independent console screen clearing code. I feel that the platform-dependent nature of such a hypothetical os.clear_screen() function wouldn't be too much of a loss, considering that there's already a bunch of functions in there that only work on Windows and Unix anyway. Here's a possible implementation of clear_screen(): ### """Platform independent console clear-screen. Using it should be fairly straightforward: if __name__ == '__main__': clear_screen() See the thread starting here: http://aspn.activestate.com/ASPN/Mail/Message/python-Tutor/1428127 for motivations for this code. Part of this code is adapted from a recipe in the Python Cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65257 """ import os import sys class _cls: def __init__(self): if sys.platform in ('linux-i386', 'linux2'): self._command = 'clear' elif sys.platform in ('win32', 'dos') or \ sys.platform.startswith('ms-dos'): self._command = 'cls' else: self._command = None def __call__(self): """Clears the screen.""" if self._command: os.system(self._command) clear_screen = _cls() if __name__ == '__main__': clear_screen() ## test code ### I can't confirm that it works on Win32 yet; can someone check this? Once it checks out ok, we can submit this to Python's sourceforge as a feature request. Who knows? It might get in... I hope this helps! From alan.gauld@bt.com Wed Nov 13 06:57:01 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed Nov 13 06:57:01 2002 Subject: [Tutor] Help with ping... Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA3F@mbtlipnt02.btlabs.bt.co.uk> > I want to write something that would just take a url and ping > it. First problem is you don't ping URLs, you ping IP addresses (either directly or via DNS) > url = raw_input("Please enter the address you would like to ping:") But since your prompt asks for an address thats probably OK... > print "now pinging %s\n" % url > > os.system("ping %s") % url #note I have tried this many os.system("ping %s" % url) You want the string substitution inside the system() parameter. HTH, Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld@bt.com Wed Nov 13 07:16:01 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed Nov 13 07:16:01 2002 Subject: [Tutor] inheritance Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA40@mbtlipnt02.btlabs.bt.co.uk> > class blah: > def __init__(self,blah, blah, blah): > def method(self,yak,yak,yak): def method2(self,fooby): > class thbbt(blah): > def __init__(self,la,la,la): > def method(self,yakkity,yak): > > My question then is this: when I call thbbt.__init__ or > thbbt.method, what happens? You call the method you defined in thbbt. If you call thbbt.method2(), which is only defined in blah then python looks first in thbbt and can't find it. It then looks at each parent class in order(if there are more than one!) until it finds the first method called method2(). If you want access to the blah method() when you call thbbt.mathod() then you must explicily call the parent mathod: class thbbt(blah): def method(self,yakkity): blah.method(self,yakkity, 42, 65) # now do my bits here There are three common uses for this technique: 1/ First to exted an inheritred method as I did above. 2/ Second to change the pre method state before calling the inherited method: class thbbt(blah): def method(self,yakkity): # change state values here - internal class variables etc # now call inherited method using new state blah.method(self,yakkity, 42, 65) 3/ Combine the two to change state and then process the resultant state some more: class thbbt(blah): def method(self,yakkity): # change state here blah.method(self,yakkity, 42, 65) # now do my bits with new state The final option in overridding an inherited method is to ignore the inherited functionality and replace it completely. To summarise then: Python looks for the method called first in the current class then in each of the parent classes in turn. It calls the first one it finds and stops searching after that. If you override an existing parent method you must decide whether to replace it entirely (unusual!) or explicitly call it using the class name and explicitly passing self. HTH, Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld@bt.com Wed Nov 13 07:17:02 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed Nov 13 07:17:02 2002 Subject: [Tutor] inheritance Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA41@mbtlipnt02.btlabs.bt.co.uk> > IIRC C++ (and maybe other languages as well) run the constructors > of all the base classes automatically. Python doesn't. C++ is a real mess here, with very strange rules over which constructors get called and when, but since this is a Python list we can safely ignore it! ;-) Alan g From magnus@thinkware.se Wed Nov 13 08:28:01 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Wed Nov 13 08:28:01 2002 Subject: [Tutor] Class Construction question [C++ and Python class introduction] In-Reply-To: References: <1037059598.3075.21.camel@ShitStorm> Message-ID: <5.1.0.14.0.20021113135733.00bb6628@www.thinkware.se> At 22:41 2002-11-12 -0800, Danny Yoo wrote: >Also, unlike C++, there's just one "namespace" for both methods and >attributes. There's a unity to this approach, a uniform way of getting at >both methods and "regular" attribute values: Ouch! I had forgotten that you can do such bizarre things in C++ as to give the same name to an attribute and a method. Yuk. I'm so happy I can program Python all day long now... :) (I try to give my method name verb names anyway...) >So by convention, we often put a single understore in front of our >attribute names. It sounds a bit informal, but it works pretty well! > >### > >>> class Book: >... def __init__(self, title): >... self._title = title >... def title(self): >... return self._title >... > >>> b = Book("generatingfunctionology") > >>> b.title() >'generatingfunctionology' >### To continue the parallels with C++, It's common that people use self.x to denote a public attribute, self._x to denote a protected and self.__x to denote a private attribute (I think it might be good if there was more of a complete consensus about this, but on the other hand, there are some concerns about the validity of this three step protection anyway. I even think that I read that Bjarne himself felt that it was too much to have these three levels...) self._x or self._title etc are not protected by the programming language. It's up to the programmers and perhaps reviewers to assert that this "protection" isn't abused. It's a bit like putting a "don't disturb" sign on the door instead of locking it, and it usually works well. If programmers can't follow such a convention, they won't be able to follow other project guidelines such as coding style guides or naming conventions either. (Or functional requirements?) Using double initial underscores: self.__x *is* handled in a special way by Python: >>> class X: ... def __init__(self, private): ... self.__private = private ... def __str__(self): ... return str(self.__private) ... >>> x = X('secret') >>> print x secret >>> print x.__private Traceback (most recent call last): File "", line 1, in ? AttributeError: X instance has no attribute '__private' >>> print x.__dict__ {'_X__private': 'secret'} >>> #Aha! >>> print x._X__private secret The attributes with double underscores can be used normally inside the class (as in the __str__ method which is implicitly used in "print x") but externally, the attribute name is changed. This means that there is no way you can abuse private variables unintentionally. You CAN if you need to though. This is helpful in debugging, etc. Don't ever *end* private with __ though. You don't want to confuse __private__ with __magic__ as __str__, __init__ etc. It's often claimed that all attributes should be at least protected, and only accessed through set or get methods. With this assumption, it's obviously logical to do as Danny wrote above. In Python this isn't really such a big issue though, because of the magic methods __setattr__ and __getattr__. They can override attribute modification and access. This means that if you change your mind, and for instance calculate a value on the fly instead of storing it, you can handle that change even if there is code that assumes it can read this value as an attribute. See below: >>> class Sum: ... def __init__(self, a, b): ... self.sum = a + b ... >>> x = Sum(1,2) >>> x.sum 3 >>> x.smu Traceback (most recent call last): File "", line 1, in ? AttributeError: Sum instance has no attribute 'smu' >>> class Sum: ... def __init__(self, a, b): ... self.__a = a ... self.__b = b ... def __getattr__(self, name): ... if name == 'sum': ... return self.__a + self.__b ... else: ... raise AttributeError, "Sum instance has no attribute '%s'" % name ... >>> x = Sum(1,2) >>> x.sum 3 >>> x.smu Traceback (most recent call last): File "", line 1, in ? File "", line 9, in __getattr__ AttributeError: Sum instance has no attribute 'smu' Voila! -- 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 yduppen@xs4all.nl Wed Nov 13 08:39:02 2002 From: yduppen@xs4all.nl (Yigal Duppen) Date: Wed Nov 13 08:39:02 2002 Subject: [Tutor] Class Construction question [C++ and Python class introduction] In-Reply-To: <5.1.0.14.0.20021113135733.00bb6628@www.thinkware.se> References: <1037059598.3075.21.camel@ShitStorm> <5.1.0.14.0.20021113135733.00bb6628@www.thinkware.se> Message-ID: <200211131438.18030.yduppen@xs4all.nl> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 > It's often claimed that all attributes should be at least protected, > and only accessed through set or get methods. With this assumption, > it's obviously logical to do as Danny wrote above. > > In Python this isn't really such a big issue though, because of > the magic methods __setattr__ and __getattr__. They can override > attribute modification and access. This means that if you change > your mind, and for instance calculate a value on the fly instead > of storing it, you can handle that change even if there is code > Even better, (something I realised only recently), as of Python2.2 you ca= n=20 also change a normal attribute to a property! No more fidgeting with the=20 (quite dangerous IMHO) __getattr__ and __setattr__.=20 PRE: class C: =09 =09def __init__(self): =09=09self.a =3D 10 c =3D C() print c.a POST: class C(object): =09def __init__(self): =09=09self.a =3D 10 =09def setA(self, a): =09=09self._a =3D a =09 =09def getA(self): =09=09return self._a =09a =3D property(getA, setA, None, "a is now a property!!") c =3D C() print c.a # which automatically becomes: c.getA() YDD - --=20 http://www.xs4all.nl/~yduppen -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE90lXKLsKMuCf5EdwRAi+cAKDvDgXPQxcNHLBT+RV65TGffNT4VACfYXBS YYOGAGmNGMPdCvh36CdiJ/c=3D =3D4zPe -----END PGP SIGNATURE----- From magnus@thinkware.se Wed Nov 13 09:20:02 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Wed Nov 13 09:20:02 2002 Subject: [Tutor] Re: clear screen [Let's make a feature request in Sourceforge!] In-Reply-To: References: <86C3892A0C52D411AF5000A0C9EAA3B98D2B2C@wtntex1.baea.com.au> Message-ID: <5.1.0.14.0.20021113143532.02b1def8@www.thinkware.se> At 23:19 2002-11-12 -0800, Danny Yoo wrote: >If someone says that a part of the language doesn't feel clean and >consistant, I think it's worth taking a look into it. The clear screen >issue has come up several times already on Tutor, so, clearly, there must >be something that's very appealing about erasing the screen. Chalkboards >can be erased, and I get the feeling that people who are new to >programming instinctively want that same refreshing feeling of "starting >over" that clearing the screen provides. But the other basic means of output, print, stdout, stderr are used in a lot of contexts where you can't assume a lot about the reciever of the data. Data might go to a screen, a printer, a file or into another program. Also raw_input and input can read from pipes as well as from the keyboard. For a screen, "clear" will certainly make sense. Perhaps it could for communication with another programs as well, but with the way normal OS pipes work, there is no generic way of clearing already sent data. Should a clear send to a file empty this file? Should it do nothing? So for me, os.clear_screen() feels more like a short-cut or a hack than like a natural part of a coherent whole. Do you understand what I mean? When we think about a clear_screen function, we are probably implementing some kind of not entirely trivial user interface. I think this might be a first stumbling block that will be followed by others, like how do I move around a cursor on the screen, create fields and menues etc. I fear that people who ask for clear screen are likely to be on the path of reinventing the square wheel... UI building is something for tools like curses, Tkinter and wxPython etc. If you try to build a non-trivial user interface on print and raw_input, you have taken a wrong path. The problem is that these tools are really too difficult for new users. Maybe we need something like Visual Basic for Python. Typically new users want, and expect, to write programs that can interact with a user in a smooth way. Using pipes and data files etc aren't what todays newbie typically has in mind... Of course, fixing that is slightly more work than to fix a clear screen function... :) Guido once had the ambition to implement a standard way of building user interfaces in Python, stdwin, but he gave up on that years ago. >Perhaps it might be worthwhile to ask the Python developers to add a >function in the 'os' module to provide some kind of platform-independent >console screen clearing code. I fear that it would be to limited to make people happy. >I can't confirm that it works on Win32 yet; can someone check this? It works from the "DOS prompt" and it works from inside the standard python interpreter. I changed the test code to print some stuff before and after clearing with some delays, and it works as expected. It doesn't work in IDLE or in PythonWin though. In both cases, a Command window just flashes past. I have a feeling this might cause more frustration that relief. (Both for newbies and for the rest of us on the list.) I think we would need to have hooks for clearing the screen in the GUI interpreter windows and that this generic function would trigger that hook. I don't have a clue on how to do this though. Or am I wrong? Is it enough that it works in simple text mode programs, but not in IDLE, PythonWin etc? From the mails we got recently, I got a feeling that people tried to do this in the IDEs. >Once >it checks out ok, we can submit this to Python's sourceforge as a feature >request. Who knows? It might get in... At least we will get a ruling, one way or another... -- 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 Nov 13 09:28:08 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Wed Nov 13 09:28:08 2002 Subject: [Tutor] Class Construction question [C++ and Python class introduction] In-Reply-To: <200211131438.18030.yduppen@xs4all.nl> References: <5.1.0.14.0.20021113135733.00bb6628@www.thinkware.se> <1037059598.3075.21.camel@ShitStorm> <5.1.0.14.0.20021113135733.00bb6628@www.thinkware.se> Message-ID: <5.1.0.14.0.20021113152821.029b1ec0@www.thinkware.se> At 14:38 2002-11-13 +0100, Yigal Duppen wrote: >Even better, (something I realised only recently), as of Python2.2 you can >also change a normal attribute to a property! No more fidgeting with the >(quite dangerous IMHO) __getattr__ and __setattr__. Right, I forgot about new style classes. >class C(object): > > def __init__(self): > self.a = 10 > > def setA(self, a): > self._a = a > > def getA(self): > return self._a > > a = property(getA, setA, None, "a is now a property!!") This is obviously much cleaner if you have several attribute that you want to wrap up, since you don't have to mix all get methods in the class in one __getattr__ and all set methods in one __setattr__. This is something to use if you don't need to support python versions older than 2.2 and don't run into special problems. For instance I realized I couldn't inherit from both new style classes and ZODB's Persistent base class. I decided to leave new style classes alone until 2.3, hoping that some issues will be solved by 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 ckasso@sprynet.com Wed Nov 13 09:44:03 2002 From: ckasso@sprynet.com (Chris Kassopulo) Date: Wed Nov 13 09:44:03 2002 Subject: [Tutor] string on multiple lines Message-ID: <20021112133825.3f40b73b.ckasso@sprynet.com> Greetings, I have a long string that I want to test. I've tried \, single quotes, triple quotes - how does one have a string across multiple lines in a script ? if test_string != '"Series","Denomination","Serial Number", "Issue Date","Price","Interest","Value","Rate","Yield", "Next Interest Date","Final Maturity Date","Note", "Cash/Exchange Date"': Thanks, Chris Kassopulo From magnus@thinkware.se Wed Nov 13 10:13:20 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Wed Nov 13 10:13:20 2002 Subject: [Tutor] string on multiple lines In-Reply-To: <20021112133825.3f40b73b.ckasso@sprynet.com> Message-ID: <5.1.0.14.0.20021113160343.02a57650@www.thinkware.se> At 13:38 2002-11-12 -0500, Chris Kassopulo wrote: >Greetings, > >I have a long string that I want to test. I've tried \, >single quotes, triple quotes - how does one have a string >across multiple lines in a script ? >>> a = 'abc'\ ... '123'\ ... 'ABC' >>> print a abc123ABC >>> b = '''abc ... 123 ... ABC''' >>> print b abc 123 ABC >>> c = 'abc\n'\ ... '123\n'\ ... 'ABC' >>> print c abc 123 ABC >>> a == b 0 >>> a == c 0 >>> b == c 1 But what are really trying to do? It seems that you might really want: if test_string not in ["Series","Denomination","Serial Number", "Issue Date","Price","Interest","Value","Rate","Yield", "Next Interest Date","Final Maturity Date","Note", "Cash/Exchange Date"]: This will put you inside the if-block if your test_string is neither of ""Series","Denomination" etc. If you really want to test against the long string which in itself contains strings, you have to clarify what you really want. Is it a long line, or does it have line breaks? Should the four spaces before e.g. "Issue Date" really be there? As a general tip, I'd suggest that you did something like: refString = '''"Series","Denomination","Serial Number", "Issue Date","Price","Interest","Value","Rate","Yield", "Next Interest Date","Final Maturity Date","Note", "Cash/Exchange Date"''' print refString print "compared with" print test_string if test_string != refString: ... The print statements will probably give you some hints. -- 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 lsloan@umich.edu Wed Nov 13 12:00:04 2002 From: lsloan@umich.edu (Lance E Sloan) Date: Wed Nov 13 12:00:04 2002 Subject: [Tutor] catching any exception? Message-ID: <501217.1037188751@[10.0.1.41]> I'm using the DCOracle 1.1.1.1 module with a Python 2.0 CGI. Sometimes when I try to execute a SQL statement, an exception will be raised. It may be because I wrote bad SQL or it may be that a relationship was going to be broken, etc. I would like to have the same exception raised, but I also want to have the SQL statement printed. So I tried this section of code: try: cursor.execute(sql) except Exception, thisException: raise Exception(thisException, sql) This didn't work. Apparently although "Exception" is the parent of all exceptions, it is not an exception itself, so this never matched. Is there something I can put in place of "Exception" in the "except" clause that will match all kinds of exceptions, so that I can get the kind of exception that was raised in my variable "thisException"? For now I'm using this: try: cursor.execute(sql) except: raise Exception(sql) Which means I'm losing information about what kind of exception was raised. -- Lance E Sloan Web Services, Univ. of Michigan: Full-service Web and database design, development, and hosting. Specializing in Python & Perl CGIs. http://websvcs.itd.umich.edu/ - "Putting U on the Web" From ckasso@sprynet.com Wed Nov 13 12:02:25 2002 From: ckasso@sprynet.com (Chris Kassopulo) Date: Wed Nov 13 12:02:25 2002 Subject: [Tutor] string on multiple lines In-Reply-To: <5.1.0.14.0.20021113160343.02a57650@www.thinkware.se> References: <20021112133825.3f40b73b.ckasso@sprynet.com> <5.1.0.14.0.20021113160343.02a57650@www.thinkware.se> Message-ID: <20021113121108.6cb71c78.ckasso@sprynet.com> On Wed, 13 Nov 2002 16:19:53 +0100 Magnus Lycka wrote: > At 13:38 2002-11-12 -0500, Chris Kassopulo wrote: > >Greetings, > > > >I have a long string that I want to test. I've tried \, > >single quotes, triple quotes - how does one have a string > >across multiple lines in a script ? > If you really want to test against the long string which > in itself contains strings, you have to clarify what you really > want. Is it a long line, or does it have line breaks? Should > the four spaces before e.g. "Issue Date" really be there? It is the first line of a .csv file. I read it with readlines and replace '\r\n' with ''. No breaks or spaces. I've tried some mutations of your suggestions and what I can get to work is: (shortened for wordwrap) if 1: ref_string='"Series","Denomination","Serial Number","Issue Date"' tst_string='"Series",\ "Denomination",\ "Serial Number",\ "Issue Date"' print ref_string print "compared with" print tst_string if tst_string != ref_string: print "error: not a valid csv file" else: print 'ref_string is same as tst_string' but this doesn't work because of the leading spaces: tst_string='"Series",\ "Denomination",\ "Serial Number",\ "Issue Date"' just found that this works: tst_string='"Series",' + \ "Denomination",' + \ "Serial Number",' + \ "Issue Date"' any other way ? Chris Kassopulo From greymalkin@neuralust.com Wed Nov 13 12:44:02 2002 From: greymalkin@neuralust.com (Patricia Lee) Date: Wed Nov 13 12:44:02 2002 Subject: [Tutor] Recommend a good intro book to Objective C ? In-Reply-To: Message-ID: Can anyone recommend a good intro book to Objective C. The target of this book is not myself, but a person with knowledge of C, Java... Who has gone through some of a computer science degree and generally knows what he's talking about. He has the O'Reilley book on learning Cocoa, but doesn't like it. The book assumes that the user has more Objective C knowledge than he does... So hence the request about the "intro to Objective C" book... Thanks - Patti From francois.granger@free.fr Wed Nov 13 13:01:01 2002 From: francois.granger@free.fr (Fran=?ISO-8859-1?B?5w==?=ois Granger) Date: Wed Nov 13 13:01:01 2002 Subject: [Tutor] string on multiple lines In-Reply-To: <20021113121108.6cb71c78.ckasso@sprynet.com> Message-ID: on 13/11/02 18:11, Chris Kassopulo at ckasso@sprynet.com wrote: > It is the first line of a .csv file. In this case, I probably would do a list because I would probably reuse it somewhere else, so: tst_string=["Series", "Denomination", "Serial Number", "Issue Date"] if 1: ref_string= mystring.split(',') if ref_string == text_string (Untested) -- 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 Nov 13 15:20:02 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Wed Nov 13 15:20:02 2002 Subject: [Tutor] string on multiple lines In-Reply-To: <20021113121108.6cb71c78.ckasso@sprynet.com> References: <5.1.0.14.0.20021113160343.02a57650@www.thinkware.se> <20021112133825.3f40b73b.ckasso@sprynet.com> <5.1.0.14.0.20021113160343.02a57650@www.thinkware.se> Message-ID: <5.1.0.14.0.20021113211647.02a57650@www.thinkware.se> At 12:11 2002-11-13 -0500, Chris Kassopulo wrote: >It is the first line of a .csv file. I read it with readlines >and replace '\r\n' with ''. Ok, so it contains headings for data to follow? But comparing it with a string like that seems brittle. I mean, if a = '"This", "That"' and b = '"This","That"' then a == b will be false. Is that really what you want? Maybe you are in fact reinventing the wheel here. Have a look at ASV, CSV or DSV, mentioned here: thinkware.se/cgi-bin/thinki.cgi/UsefulPythonModules >but this doesn't work because of the leading spaces: > tst_string='"Series",\ > "Denomination",\ > "Serial Number",\ > "Issue Date"' As I wrote before (I think?), you need leading and trailing ' on each line. tst_string='"Series",'\ '"Denomination",'\ '"Serial Number",'\ '"Issue Date"' -- 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 SWidney@ci.las-vegas.nv.us Wed Nov 13 17:41:15 2002 From: SWidney@ci.las-vegas.nv.us (Scott Widney) Date: Wed Nov 13 17:41:15 2002 Subject: [Tutor] string on multiple lines Message-ID: <0E5508EBA1620743B409A2B8365DE16FDC823F@sovereign.ci.las-vegas.nv.us> > Magnus Lycka: > But comparing it with a string like that seems brittle. > I mean, if > a = '"This", "That"' > and > b = '"This","That"' > then > a == b > will be false. Is that really what you want? If it's brittle, then maybe we can reinforce it with some python glue... > >Chris Kassopulo: > >but this doesn't work because of the leading spaces: > > tst_string='"Series",\ > > "Denomination",\ > > "Serial Number",\ > > "Issue Date"' > > As I wrote before (I think?), you need leading and > trailing ' on each line. > > tst_string='"Series",'\ > '"Denomination",'\ > '"Serial Number",'\ > '"Issue Date"' Before you compare the strings, remove any unnecessary data (in this case the strings). Here are two function definitions that will achieve that result. The first one is more backward compatible. #### def clean(dirtyString): '''Gets the white out....''' import string return string.join(string.split(dirtyString), "") #### def clean(dirtyString): '''New and Improved!''' return "".join(dirtyString.split()) #### So let's take a look: >>> tst_string_CK = '"Series",\ ... "Denomination",\ ... "Serial Number",\ ... "Issue Date"' >>> tst_stringML = '"Series",'\ ... '"Denomination",'\ ... '"Serial Number",'\ ... '"Issue Date"' >>> clean(tst_string_CK) == clean(tst_stringML) 1 >>> Neat! Note: this solution has been presented on this list before in various disguises. It might need a little tweaking to work in your situation, but the basic concept is there. Scott From magnus@thinkware.se Wed Nov 13 18:23:04 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Wed Nov 13 18:23:04 2002 Subject: [Tutor] string on multiple lines In-Reply-To: <0E5508EBA1620743B409A2B8365DE16FDC823F@sovereign.ci.las-ve gas.nv.us> Message-ID: <5.1.0.14.0.20021114001448.02993998@www.thinkware.se> At 14:39 2002-11-13 -0800, Scott Widney wrote: >Before you compare the strings, remove any unnecessary data (in this case >the strings). > >def clean(dirtyString): > '''New and Improved!''' > return "".join(dirtyString.split()) Let's try that... >>> def clean(dirty): return "".join(dirty.split()) ... >>> a = ' "this is a field", "this is another field" ' >>> b = '"this is a field","this is another field"' >>> clean(a) == clean(b) 1 So far so good >>> c = '"thisisafield","thisisanotherfield"' >>> clean(a) == clean(c) 1 :( You don't want this, do you? What is the the purpose of the double quotes? Aren't they there to indicate that the whitespace inside them matters? If the purpose is to handle typical delimited files, such as comma separated value (CSV) files, don't reinvent that once more please. There are at least three python modules out there on the net, called ASV, CSV and DSV. We don't need BSV as well! ;) Pick one which is already there (and probably tried and tested as well): http://www.object-craft.com.au/projects/csv/ http://sourceforge.net/projects/python-dsv/ http://tratt.net/laurie/python/asv/ I wish one of these would be in the standard library, since it's a very common thing to do, but it seems Guido don't want 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 reavey@nep.net Wed Nov 13 19:43:01 2002 From: reavey@nep.net (reavey) Date: Wed Nov 13 19:43:01 2002 Subject: [Tutor] count words Message-ID: <1037234228.2924.18.camel@localhost.localdomain> Sirs: I'd like to count the number of times a letter occurs in a string. I've been looking at c. It seems that this type of problem is being assigned in cs classes on graduate and advanced undergraduate classes in the US. Yet, I'm unable to find a library function or simply code written as a model to help me. Any pointer in the direction would be greatly appreciated. I would like to expand this model to include Dolce words, to help children with reading difficulties. TIA Re-v From shalehperry@attbi.com Wed Nov 13 23:20:01 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Wed Nov 13 23:20:01 2002 Subject: [Tutor] count words In-Reply-To: <1037234228.2924.18.camel@localhost.localdomain> References: <1037234228.2924.18.camel@localhost.localdomain> Message-ID: <200211132018.45434.shalehperry@attbi.com> On Wednesday 13 November 2002 16:37, reavey wrote: > Sirs: > I'd like to count the number of times a letter occurs in a string. > I've been looking at c. It seems that this type of problem is being > assigned in cs classes on graduate and advanced undergraduate classes i= n > the US. > Yet, I'm unable to find a library function or simply code written as a > model to help me. > Any pointer in the direction would be greatly appreciated. > I would like to expand this model to include Dolce words, to help > children with reading difficulties. > TIA > Re-v > I am a little confused. You want a listing of how many times any given l= etter=20 occurs in a string, i.e. statistics? Here's a hint: use a python diction= ary=20 and a loop. You are having difficulties because it is like 3 lines of co= de. As for your later comment, what is a "Dolce word"? From dylan.belsey@baesystems.com Thu Nov 14 00:01:02 2002 From: dylan.belsey@baesystems.com (BELSEY, Dylan) Date: Thu Nov 14 00:01:02 2002 Subject: [Tutor] catching any exception? Message-ID: <86C3892A0C52D411AF5000A0C9EAA3B98D2B2D@wtntex1.baea.com.au> Hi Lance, I have been working on something similar to catch all the exceptions from a python script file that the user creates. It initially checks for some particular exception types that I know could be raised and the final clause is a catch-all for any exceptions that are not accounted for such as syntax errors in the script. It makes use of the "traceback" module, obtains a trace of the latest exception and sends the info to an error logger as a single line. From the code it is obvious that this is embedded within a class and makes use of other objects, but I hope that the ideas and logic are clear. Anyway, I'm not sure how relevant it will be for you but I have posted the code below. Hope you can make use of it. Dylan. PS: Using Python 2.1.1 # Code begins: import sys, traceback, string # Capture the latest stack trace for an exception. # Use a function to avoid a circular reference problem in Python. # Refer: http://www.python.org/doc/current/lib/module-sys.html # for further information. # INPUT: None. # OUTPUT: List of strings containing the error. def ObtainTrace(self): # "Thread-safe" capture of the exception. excType, excValue, excTraceback = sys.exc_info() # Format the most recent stack trace and info. for exceptions. Trace = traceback.format_exception(excType, excValue, excTraceback, None) # Delete the traceback object to avoid causing a circular reference problem. del excTraceback return Trace # Capture the exception if the script file is in error. try: execfile(self.ScriptFile) except exceptions.TypeError, errMsg: # Don't really need to specify the "exceptions" class in the line above. # Handle this exception.... except: # For syntax and other errors in the file. # Create the error message. # Capture the latest exception. TraceList = self.ObtainTrace() # Extract important lines into a string. # refer to traceback doco for more info here. if len(TraceList) > 3: lines = TraceList[2] + TraceList[3] else: lines = ''.join(TraceList) # Whole stack trace. # Replace newlines with a full-stop and a space. errMsg = string.replace(lines, '\n', '. ') EMessage = """Exception in script file: %s"""%(errMsg) # Send to the logger. self.ErrorHandler.Capture(ErrorLogWindow.UI_SCRIPT_OP_ERROR, EMessage) # Set the file path string to None so that the error does not repeat. self.ScriptFile = None # Code ends. From Jmllr891@cs.com Thu Nov 14 00:49:01 2002 From: Jmllr891@cs.com (Jmllr891@cs.com) Date: Thu Nov 14 00:49:01 2002 Subject: [Tutor] Binding keys without Tk? Message-ID: <178.11b3eadb.2b04931b@cs.com> --part1_178.11b3eadb.2b04931b_boundary Content-Type: text/plain; charset="US-ASCII" Content-Transfer-Encoding: 7bit Is there any way to bind keys to functions in Python without using Tkinter, something that will work for the Windows OS? --part1_178.11b3eadb.2b04931b_boundary Content-Type: text/html; charset="US-ASCII" Content-Transfer-Encoding: 7bit Is there any way to bind keys to functions in Python without using Tkinter, something that will work for the Windows OS? --part1_178.11b3eadb.2b04931b_boundary-- From anderson@nkbj.co.jp Thu Nov 14 01:32:01 2002 From: anderson@nkbj.co.jp (Robert M. Anderson) Date: Thu Nov 14 01:32:01 2002 Subject: [Tutor] Menu woes References: <5.1.0.14.0.20021111112945.02997ea8@www.thinkware.se> <200211120157.10441.scot@possum.in-berlin.de> Message-ID: <000301c28ba8$1cee48a0$840ca8c0@eanderson> SSdtIGhhdmluZyB0cm91YmxlIHdpdGggYSBzaG9ydCBwcm9ncmFtIEkgY29waWVkIGFuZCBtb2Rp ZmllZCBmcm9tIHNvbWV3aGVyZS4gVGhlIGNvZGUgaXMgYXMgZm9sbG93czoNCg0KIyMjIHNob3J0 IHByb2dyYW0gc3RhcnRzIGhlcmUNCg0KZnJvbSBUa2ludGVyIGltcG9ydCAqDQoNCmNsYXNzIEFw cGxpY2F0aW9uKEZyYW1lKToNCiAgICAgIGRlZiBzYXlfaGkoc2VsZik6DQogICAgICAgICAgICBw cmludCAiaGkgdGhlcmUsIGV2ZXJ5b25lISINCg0KICAgICAgZGVmIGNyZWF0ZVdpZGdldHMoc2Vs Zik6DQogICAgICAgICAgICBzZWxmLlFVSVQgPSBCdXR0b24oc2VsZikNCiAgICAgICAgICAgIHNl bGYuUVVJVFsidGV4dCJdID0gIlFVSVQiDQogICAgICAgICAgICBzZWxmLlFVSVRbImZnIl0gICA9 ICJyZWQiDQogICAgICAgICAgICBzZWxmLlFVSVRbImNvbW1hbmQiXSA9IHNlbGYucXVpdA0KICAg ICAgICAgICAgc2VsZi5RVUlULnBhY2soeyJzaWRlIjogImxlZnQifSkNCiAgICAgICAgICAgIHNl bGYuaGlfdGhlcmUgPSBCdXR0b24oc2VsZikNCiAgICAgICAgICAgIHNlbGYuaGlfdGhlcmVbInRl eHQiXSA9ICJIZWxsbyIsDQogICAgICAgICAgICBzZWxmLmhpX3RoZXJlWyJjb21tYW5kIl0gPSBz ZWxmLnNheV9oaQ0KICAgICAgICAgICAgc2VsZi5oaV90aGVyZS5wYWNrKHsic2lkZSI6ICJsZWZ0 In0pDQogICAgICAgICAgICBzZWxmLm1lbnViYXIgPSBNZW51KHNlbGYpDQogICAgICAgICAgICBz ZWxmLmZpbGVtZW51ID0gTWVudShzZWxmLm1lbnViYXIsIHRlYXJvZmY9MCkNCiAgICAgICAgICAg IHNlbGYuZmlsZW1lbnUuYWRkX2NvbW1hbmQobGFiZWw9Ik9wZW4iLCBjb21tYW5kPXNlbGYuc2F5 X2hpKQ0KICAgICAgICAgICAgc2VsZi5jb25maWcobWVudT1zZWxmLm1lbnViYXIpDQoNCiAgICAg IGRlZiBfX2luaXRfXyhzZWxmLCBtYXN0ZXI9Tm9uZSk6DQogICAgICAgICAgICBGcmFtZS5fX2lu aXRfXyhzZWxmLCBtYXN0ZXIpDQogICAgICAgICAgICBzZWxmLnBhY2soKQ0KICAgICAgICAgICAg c2VsZi5jcmVhdGVXaWRnZXRzKCkNCg0KYXBwID0gQXBwbGljYXRpb24oKQ0KYXBwLm1haW5sb29w KCkNCg0KIyMjIHNob3J0IHByb2dyYW0gZW5kcyBoZXJlDQoNCkl0IHdvcmtzIGZpbmUgaWYgSSBn ZXQgcmlkIG9mIHRoZSBtZW51IGNvZGUsIHdoaWNoIGlzIHdoYXQgSSBhZGRlZCBiYXNlZCBvbiBz b21ldGhpbmcgZnJvbSBGcmVkcmlrIEx1bmRoJ3MgVGtpbnRlciBpbnRyb2R1Y3Rpb24gc2l0ZS4g VGhlIGVycm9yIEkgZ2V0IGZyb20gUHl0aG9uIGlzIGZvciB0aGUgInNlbGYuY29uZmlnIiBjb21t YW5kLCBzYXlpbmc6DQoNClRjbEVycm9yOiB1bmtub3duIG9wdGlvbiAiLW1lbnUiDQoNClBsZWFz ZSBoZWxwIGlmIHlvdSBjYW4hDQoNClJlZ2FyZHMsDQoNClJvYmVydCBNLiBBbmRlcnNvbg0K From glingl@aon.at Thu Nov 14 01:35:02 2002 From: glingl@aon.at (Gregor Lingl) Date: Thu Nov 14 01:35:02 2002 Subject: [Tutor] count words References: <1037234228.2924.18.camel@localhost.localdomain> Message-ID: <3DD34394.7020603@aon.at> reavey schrieb: >Sirs: >I'd like to count the number of times a letter occurs in a string. >I've been looking at c. It seems that this type of problem is being >assigned in cs classes on graduate and advanced undergraduate classes in >the US. >Yet, I'm unable to find a library function or simply code written as a >model to help me. > In Python strings and lists have a method count that may be used to solve sour problem: >>> "abaracadabara".count("a") 7 >>> word = "abaracadabara" >>> word.count("r") 2 >>> "one and two and three and four".split() ['one', 'and', 'two', 'and', 'three', 'and', 'four'] >>> "one and two and three and four".split().count("and") 3 >>> words = "one and two and three and four".split() >>> words ['one', 'and', 'two', 'and', 'three', 'and', 'four'] >>> words.count("four") 1 >>> HTH Gregor >Any pointer in the direction would be greatly appreciated. >I would like to expand this model to include Dolce words, to help > ????? >children with reading difficulties. >TIA >Re-v > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From glingl@aon.at Thu Nov 14 12:42:26 2002 From: glingl@aon.at (Gregor Lingl) Date: Thu Nov 14 12:42:26 2002 Subject: [Tutor] Menu woes References: <5.1.0.14.0.20021111112945.02997ea8@www.thinkware.se> <200211120157.10441.scot@possum.in-berlin.de> <000301c28ba8$1cee48a0$840ca8c0@eanderson> Message-ID: <3DD3504B.8070605@aon.at> Hi Robert! Although I'm not a Tkinter-expert, I'll try an answer - if there's something wrong in it, it will certainly be corrected by other readers of the list: There are apperently two problems in your code: 1. Frame doesn't have an option menu - in contrast to the Toplevel-Widget or Tk. So use this instead. If you make this change, the program will run without error-message but unfortunately also without displaying the menu. 2. To change this, you have to add then filemenu to the menubar by using the add_cascade - method So the following code - hopefully - does what you want: class Application(Tk): def say_hi(self): print "hi there, everyone!" def createWidgets(self): self.QUIT = Button(self) self.QUIT["text"] = "QUIT" self.QUIT["fg"] = "red" self.QUIT["command"] = self.quit self.QUIT.pack({"side": "left"}) self.hi_there = Button(self) self.hi_there["text"] = "Hello", self.hi_there["command"] = self.say_hi self.hi_there.pack({"side": "left"}) self.menubar = Menu(self) self.filemenu = Menu(self.menubar, tearoff=0) self.filemenu.add_command(label="Open", command=self.say_hi) self.menubar.add_cascade(label="Actions", menu=self.filemenu) self.config(menu=self.menubar) def __init__(self, master=None): Tk.__init__(self, master) # self.pack() self.createWidgets() app = Application() app.mainloop() HTH, Gregor Robert M. Anderson schrieb: I'm having trouble with a short program I copied and modified from somewhere. The code is as follows: ### short program starts here from Tkinter import * class Application(Frame): def say_hi(self): print "hi there, everyone!" def createWidgets(self): self.QUIT = Button(self) self.QUIT["text"] = "QUIT" self.QUIT["fg"] = "red" self.QUIT["command"] = self.quit self.QUIT.pack({"side": "left"}) self.hi_there = Button(self) self.hi_there["text"] = "Hello", self.hi_there["command"] = self.say_hi self.hi_there.pack({"side": "left"}) self.menubar = Menu(self) self.filemenu = Menu(self.menubar, tearoff=0) self.filemenu.add_command(label="Open", command=self.say_hi) self.config(menu=self.menubar) def __init__(self, master=None): Frame.__init__(self, master) self.pack() self.createWidgets() app = Application() app.mainloop() ### short program ends here It works fine if I get rid of the menu code, which is what I added based on something from Fredrik Lundh's Tkinter introduction site. The error I get from Python is for the "self.config" command, saying: TclError: unknown option "-menu" Please help if you can! Regards, Robert M. Anderson From lumbricus@gmx.net Thu Nov 14 12:59:37 2002 From: lumbricus@gmx.net (lumbricus@gmx.net) Date: Thu Nov 14 12:59:37 2002 Subject: [Tutor] inheritance References: <001301c28a9e$e6f6e040$44120dd5@violante> Message-ID: <25872.1037271569@www40.gmx.net> Hi! [ snip ] BTW: > ... print "%r says howdy" % self ^^ what the hell is that? It doesn't appear in "man 3 printf", so it must be something new. r like reference? > HTH, > G. Rodrigues Greets, J"o! -- Wir beschliessen etwas, stellen das dann in den Raum und warten dann einige Zeit ab, was passiert. Wenn es dann kein grosses Geschrei gibt und keine Aufstaende, weil die meisten gar nicht begreifen, was da beschlossen wurde, dann machen wir weiter - Schritt fuer Schritt, bis es kein Zurueck mehr gibt. -- J-C Juncker +++ 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 Thu Nov 14 13:00:26 2002 From: lumbricus@gmx.net (lumbricus@gmx.net) Date: Thu Nov 14 13:00:26 2002 Subject: [Tutor] Re: clear screen [Let's make a feature request in Sourceforge!] References: Message-ID: <22583.1037270724@www40.gmx.net> Hi! [ snip ] > class _cls: > def __init__(self): > if sys.platform in ('linux-i386', 'linux2'): > self._command = 'clear' There are more UNICES than Linux. As I wrote in an earlier post IMHO os.name is the better choice, because it just spits out 'posix' for all the different UNICES out there. > elif sys.platform in ('win32', 'dos') or \ > sys.platform.startswith('ms-dos'): > self._command = 'cls' Same principle applies. > else: > self._command = None sys.platform 'osf1V4' So your code would fail on my machine, while it understands "clear" perfectly well. [ snip ] > I can't confirm that it works on Win32 yet; can someone check this? Once > it checks out ok, we can submit this to Python's sourceforge as a feature > request. Who knows? It might get in... IMHO clearing the screen at the beginning of a console program is a bad habit. You loose information and gain nothing. > I hope this helps! Dito, J"o! -- Wir beschliessen etwas, stellen das dann in den Raum und warten dann einige Zeit ab, was passiert. Wenn es dann kein grosses Geschrei gibt und keine Aufstaende, weil die meisten gar nicht begreifen, was da beschlossen wurde, dann machen wir weiter - Schritt fuer Schritt, bis es kein Zurueck mehr gibt. -- J-C Juncker +++ 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 Thu Nov 14 13:05:59 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Thu Nov 14 13:05:59 2002 Subject: [Tutor] Binding keys without Tk? In-Reply-To: <178.11b3eadb.2b04931b@cs.com> Message-ID: <5.1.0.14.0.20021114113927.02a91ec0@www.thinkware.se> At 00:48 2002-11-14 -0500, Jmllr891@cs.com wrote: >Is there any way to bind keys to functions in Python without using >Tkinter, something that will work for the Windows OS? Do you mean without a GUI at all? You can catch keypresses with the msvcrt standard library module. See the library reference. But if you think of binding keys to functions like in Tkinter, you probably imagine an event based program, such as most GUI programs. Then you need an event-loop which is waiting for events such as key-presses and fires off the bound functions when they occur. Without a library such as Tkinter or something similar, I guess you will have to write this on your own. It's not a big thing for a small program though. #msvcrtevtdemo.py import msvcrt, time, sys, os keys = {} def dir(): os.system('DIR') keys['d'] = dir def now(): print time.asctime() keys['t'] = now keys['q'] = sys.exit # Event loop while 1: char = msvcrt.getch() try: keys[char]() except KeyError: print char, Then there are other GUI's than Tkinter, such as wxPython, PythonWin or AnyGui. It's not clear to me what you really want. -- 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 Gillisai@btinternet.com Thu Nov 14 13:13:55 2002 From: Gillisai@btinternet.com (Alex Gillis) Date: Thu Nov 14 13:13:55 2002 Subject: [Tutor] Can any one recommend a good C++ referernce manual Message-ID: <002701c28bdf$e40e3760$04057ad5@oemcomputer> I just want some thing where I can look up what I want to do and it will give me a brief description of what it is, what it does, how to use it and the options. I've already got a book teaching generally how to use C++ (didnt teach me much that I didnt already know from using python) but it doesn't give many functions, I cant even seem to find how to write to a file. From joney@clara.co.uk Thu Nov 14 13:43:12 2002 From: joney@clara.co.uk (john gennard) Date: Thu Nov 14 13:43:12 2002 Subject: [Tutor] getting started Message-ID: <02111418331400.00363@Leary> After reading a lot and getting an overview of Python, I now intend to work through a number of tutorials. I have never yet used any programming language, and embarrassingly can't get passed the third page. How do I get from a first line to a second one? (If I used a text editor, I would have no problem, but at this stage I don't want to start creating numerous files - just want to get used to what various commands ouput). I run Debian 3.0 and have installed Python 2.1.3 and GCC 2.95.4 Python launches from the command line and I can insert one line commands only. The position is the same if I launch IDLE. I want to do the following:- >>>print "xxxxxxxxxxxxxxx" print "yyyyyyyyyyyy" print "zzzzzzzzzzzzzz" How to get from ........x" to commence print "yyyyy.......... 'Enter' key of course executes the command. I've re-read everything I have and can find no answer, and have tried also many keystrokes without result. Anyone put me out of my misery please? Thanks, John. From magnus@thinkware.se Thu Nov 14 13:58:07 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Thu Nov 14 13:58:07 2002 Subject: [Tutor] Can any one recommend a good C++ referernce manual In-Reply-To: <002701c28bdf$e40e3760$04057ad5@oemcomputer> Message-ID: <5.1.0.14.0.20021114195842.02a3f9c8@www.thinkware.se> At 13:15 2002-11-14 +0000, Alex Gillis wrote: >I just want some thing where I can look up what I want to do and it will >give me a brief description of what it is, what it does, how to use it and >the options. I've already got a book teaching generally how to use C++ >(didnt teach me much that I didnt already know from using python) but it >doesn't give many functions, I cant even seem to find how to write to a >file. This is somewhat off topic, but my reference is Stroustrup, Bjarne: The C++ Programming Language, Special Edition The really good C++ book for me was Meyers, Scott: Effective C++, 2nd ed. This WILL teach you the things you don't know already from Python... Meyers have also written More Effective C++ Effectice C++ CD (The above two books on CD-ROM) and Effective STL. -- 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 runsun@bilbo.bio.purdue.edu Thu Nov 14 14:14:10 2002 From: runsun@bilbo.bio.purdue.edu (runsun) Date: Thu Nov 14 14:14:10 2002 Subject: [Tutor] Class property: check dict values before assign In-Reply-To: <20021114170005.28154.32726.Mailman@mail.python.org> Message-ID: hi all, I have a class having a property of type dictionary. I wanna check the values before they are assigned to that dictionary property. The __setattr__ seems to be the candidate for this, but no. It is not even called when the user sets a dictionary value. See the following example: class myclass: def __init__(self): self.__dict__['user']={'Iastname':'lee', 'firstname':'john'} def __setattr__(self, name, value): print 'Calling _setattr__ ....' c = myclass() c.user = {'Iastname':'lee', 'firstname':'john'} # ===> [A] c.user['lastname'] = 'dilley' # ===> [B] The line [A] called the __setattr__, but line [B] didn't. Therefore, it seems to be impossible for python to verify the content of a dictionary-typr properties, unless all the key:values of that dictionary are given all together at the same time. Any idea ?? pan ---------------------------------------------------------------------- ~~ Be like water, be shapeless ~~ Runsun Pan, PhD Ecology & Evolution, U of Chicago TEL: 773-834-3965 EMAIL: pan@uchicago.edu FAX: [USA]775-659-8969 [Taiwan] 094-656-8001 ---------------------------------------------------------------------- ] From monashee@junction.net Thu Nov 14 14:33:03 2002 From: monashee@junction.net (J or M Montgomery) Date: Thu Nov 14 14:33:03 2002 Subject: [Tutor] How do I print built in functions [Useless Python / simplifying helpdesk.py] References: <5.1.0.14.0.20021111085817.01bcdf70@66.28.54.253> Message-ID: <3DD3FA62.3010302@junction.net> Bob Gailer wrote: > Around 1970 (year, not address) I was introduced to DEC's PDP8, the > "first" "minicomputer". When I wanted to use it, I had to enter about 20 > instructions into memory. Each memory word was 12 bits; there were 12 > front panel toggle switches. One would flip them into a certain bit > pattern, then "deposit" into memory, repeat till the "bin loader" > program was in memory; place some punched paper tape into the tape > reader, and hit the start button. The paper tape contained the "rim > loader" which prepared the computer to read a program. It's interesting > to compare these steps with the boot program now resident in ROM that > reads the boot program from magnetic media. > In the immortal words of Yogi Berra, "This is deja vue all over again". I moved from IBM 360's and using Fortran and PL1, during the late sixties to using a PDP8e in our lab. We had a delux version with 8k of those 12 bit words for memory size instead of the standard 4k. Yes we toggled in our bootstrap code and then rigged a punched paper tape in the teletype to read in data or programs. Not much could be accomplished without using assembler language. PAL-3 was reasonably easy to learn. Hard disks - what are those? Floppy disks - what are they? Tape backup - yep, on a tape which I guess was 1/2 inch wide. It looked about like current video tape. Thanks Bob for triggering those memories. A relic from the days of iron-core memory. John Montgomery From c.attianese@cib.na.cnr.it Thu Nov 14 14:33:18 2002 From: c.attianese@cib.na.cnr.it (Carla Attianese) Date: Thu Nov 14 14:33:18 2002 Subject: [Tutor] string assignment Message-ID: <01c001c28b27$36251320$d005a48c@epicuro> This is a multi-part message in MIME format. ------=_NextPart_000_01BD_01C28B2F.95D8C390 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi everybody, I'm writing a python script that tries to connect to informix DB. I got = an error in assigning a SQL Create Table statement to a variable. This = is how I did it: CREATE_STATEMENT_TABLE =3D """ CREATE TABLE rdf_statement (...... .......) """ This is the error I got: SyntaxError: invalid syntax File "C:\Documents and Settings\carla\a.py", line 258 CREATE_STATEMENT_TABLE=3D""" ^ I tried with single quote, getting the same error.It seems not to accept = an assignment of a string to a variable. I'm using Python 2.1.1 on = WIndows XP. Am I doing something wrong with the syntax? Thank you and best regards Carla __________________________ Carla Attianese c.attianese@cib.na.cnr.it CNR - Cybernetics Institute Via Campi Flegrei, 34 I-80072 Pozzuoli (Naples), Italy +39818675157 ------=_NextPart_000_01BD_01C28B2F.95D8C390 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hi everybody,
I'm writing a python script that tries = to connect=20 to informix DB. I got an error in assigning a SQL Create Table statement = to a=20 variable. This is how I did it:
 
CREATE_STATEMENT_TABLE =3D = """
CREATE TABLE rdf_statement = (......
            =    =20             .......)
            =    =20             """
 
 
This is the error I got:
 
SyntaxError: invalid syntax
  File "C:\Documents and=20 Settings\carla\a.py", line 258
   =20 CREATE_STATEMENT_TABLE=3D"""
       = ;            =      =20 ^
I tried with single quote, getting the = same=20 error.It seems not to accept an assignment of a string to a variable. = I'm using=20 Python 2.1.1 on WIndows XP. Am I doing something wrong with the=20 syntax?
Thank you and best regards
Carla
 
__________________________
Carla Attianese
c.attianese@cib.na.cnr.itCNR -=20 Cybernetics Institute
Via Campi Flegrei, 34  I-80072
Pozzuoli = (Naples), Italy
+39818675157
------=_NextPart_000_01BD_01C28B2F.95D8C390-- From bgailer@kgnu.org Thu Nov 14 14:33:30 2002 From: bgailer@kgnu.org (Bob Gailer) Date: Thu Nov 14 14:33:30 2002 Subject: [Tutor] count words In-Reply-To: <1037234228.2924.18.camel@localhost.localdomain> Message-ID: <5.1.0.14.0.20021113193914.038c51a0@66.28.54.253> At 07:37 PM 11/13/2002 -0500, reavey wrote: >I'd like to count the number of times a letter occurs in a string. In Python: TheString.count(letter) From kevon2000@hotmail.com Thu Nov 14 14:33:51 2002 From: kevon2000@hotmail.com (Kevon Mansfield) Date: Thu Nov 14 14:33:51 2002 Subject: [Tutor] internet Message-ID: This is a multi-part message in MIME format. ------=_NextPart_000_0005_01C285DD.02E19500 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable hi, i have now started to learn python "it's cool",i would like to know if = you can go on the net with python & how?,can i also join windows program = with python?. Thanks for your answer. =20 Kevon = Mansfield. ------=_NextPart_000_0005_01C285DD.02E19500 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
hi,
  i have now started to learn = python "it's=20 cool",i would like to know if you can go on the net with python & = how?,can i=20 also join windows program with python?.
 Thanks for your answer.  =
          &nbs= p;            = ;            =             &= nbsp;           =20 Kevon Mansfield.
------=_NextPart_000_0005_01C285DD.02E19500-- From ckasso@sprynet.com Thu Nov 14 15:06:43 2002 From: ckasso@sprynet.com (Chris Kassopulo) Date: Thu Nov 14 15:06:43 2002 Subject: [Tutor] string on multiple lines In-Reply-To: <5.1.0.14.0.20021113211647.02a57650@www.thinkware.se> References: <5.1.0.14.0.20021113160343.02a57650@www.thinkware.se> <20021112133825.3f40b73b.ckasso@sprynet.com> <5.1.0.14.0.20021113160343.02a57650@www.thinkware.se> <5.1.0.14.0.20021113211647.02a57650@www.thinkware.se> Message-ID: <20021114132144.231f8170.ckasso@sprynet.com> On Wed, 13 Nov 2002 21:26:04 +0100 Magnus Lycka wrote: > Ok, so it contains headings for data to follow? Yes, I'm writing a program to track an inventory of US savings bonds modeled after Savings Bond Wizard on windows and Gbonds on linux. For now I am only dealing with the csv file from Wizard. It will have the same heading and column layout every time. I verify the heading line, then iterate through each line of the rest of the file and extract the data I need. > But comparing it with a string like that seems brittle. It is, but I am not really looking for a specific solution for this. My interest was in the grammer of formatting a long string so it would fit in less columns for readability and appearance. > Maybe you are in fact reinventing the wheel here. Not trying to reinvent, trying to learn. > Have a look at ASV, CSV or DSV, mentioned here: > thinkware.se/cgi-bin/thinki.cgi/UsefulPythonModules I will look at these. At some point I'll go back and generalize the import function. > As I wrote before (I think?), you need leading and > trailing ' on each line. > > tst_string='"Series",'\ > '"Denomination",'\ > '"Serial Number",'\ > '"Issue Date"' This must be what I was looking for. Thank you all for the help. Hope to return some. Chris Kassopulo From mchermside@ingdirect.com Thu Nov 14 15:06:57 2002 From: mchermside@ingdirect.com (Chermside, Michael) Date: Thu Nov 14 15:06:57 2002 Subject: [Tutor] Re: internet Message-ID: <902A1E710FEAB740966EC991C3A38A8903C278C6@INGDEXCHANGEC1.ingdirect.com> > hi, > i have now started to learn python "it's cool",i would like to know = if =3D > you can go on the net with python & how?,can i also join windows = program =3D > with python?. > Thanks for your answer. Yes, I also think Python is "cool"! Python can be used to generate dynamic web pages... it can even be used for highly complex and powerful web applications (check out "Zope" for an example). Python can also be used to obtain content via HTML... the "urllib" library is useful for this. Python can be used on Windows, and it can access the native Windows APIs using a library originally contributed by Mark Hammond. Since this comes as a separate library, I suggest downloading ActiveState's installer of Python for Windows if you want to use these features. They include the windows code by default, and also have excellent documentation. I hope these answer your questions... if not, feel free to ask again! -- Michael Chermside From dyoo@hkn.eecs.berkeley.edu Thu Nov 14 15:08:09 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Nov 14 15:08:09 2002 Subject: [Tutor] count words In-Reply-To: <200211132018.45434.shalehperry@attbi.com> Message-ID: > > I'd like to count the number of times a letter occurs in a string. > > I've been looking at c. It seems that this type of problem is being > > assigned in cs classes on graduate and advanced undergraduate classes > > in the US. You're grossly overestimating the problem, or greatly underestimating the CS students in US colleges. Frequency counting is an introductory programming problem that shows how useful loops and containers are. It's something that's easily done with paper and pencil, and is even easier with the use of computers. What part are you having trouble with? If we know more about your own programming experience, we may be able to prod you in some direction. But we will not give direct help on this one; this is definitely in the domain of a "homework" assignment. Good luck to you. From magnus@thinkware.se Thu Nov 14 15:58:04 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Thu Nov 14 15:58:04 2002 Subject: [Tutor] count words In-Reply-To: <1037234228.2924.18.camel@localhost.localdomain> Message-ID: <5.1.0.14.0.20021114101208.02993850@www.thinkware.se> text = """Sirs: I'd like to count the number of times a letter occurs in a string. I've been looking at c. It seems that this type of problem is being assigned in cs classes on graduate and advanced undergraduate classes in the US. Yet, I'm unable to find a library function or simply code written as a model to help me. Any pointer in the direction would be greatly appreciated. I would like to expand this model to include Dolce words, to help children with reading difficulties. TIA Re-v""" import string for letter in string.letters: print letter, 'occurs', text.count(letter), 'times' Or, if you don't want to differentiate between upper and lower case letters: upperCasedText = text.upper() for letter in string.uppercase: print letter, 'occurs', upperCasedText.count(letter), 'times' If you read through the library reference thoroughly, I think you will find lots of goodies. David Beazley's "Python Essential Reference" is another good presentation of the Python Standard Library. There is also Fredrik Lundh's book, but I haven't read that. Neither of these are tutorials, but to be a really effective programmer--in any language--it's importent to know the libraries. One of the advantages with Python is that the basic language is so easy to learn that while people struggle with syntax in other languages, it's usually how to find things in the libraries that bother new Pythonistas. -- 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 Thu Nov 14 15:59:32 2002 From: lumbricus@gmx.net (lumbricus@gmx.net) Date: Thu Nov 14 15:59:32 2002 Subject: [Tutor] Help with ping... References: <20150.1037271403@www40.gmx.net> Message-ID: <1943.1037271740@www40.gmx.net> Hi! [ snip ] > First problem is you don't ping URLs, you ping IP addresses > (either directly or via DNS) Seems to work: urlparse.urlparse("http://132.230.200.200") ('http', '132.230.200.200', '', '', '', '' Or am I missing something? [ snip ] > HTH, > > Alan g. Greets, J"o! -- Wir beschliessen etwas, stellen das dann in den Raum und warten dann einige Zeit ab, was passiert. Wenn es dann kein grosses Geschrei gibt und keine Aufstaende, weil die meisten gar nicht begreifen, was da beschlossen wurde, dann machen wir weiter - Schritt fuer Schritt, bis es kein Zurueck mehr gibt. -- J-C Juncker +++ GMX - Mail, Messaging & more http://www.gmx.net +++ NEU: Mit GMX ins Internet. Rund um die Uhr für 1 ct/ Min. surfen! From dman@dman.ddts.net Thu Nov 14 16:14:01 2002 From: dman@dman.ddts.net (Derrick 'dman' Hudson) Date: Thu Nov 14 16:14:01 2002 Subject: [Tutor] Re: Help with ping... In-Reply-To: <1943.1037271740@www40.gmx.net> References: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA3F@mbtlipnt02.btlabs.bt.co.uk> <1943.1037271740@www40.gmx.net> Message-ID: <20021114212645.GA24614@dman.ddts.net> --YiEDa0DAkWCtVeE4 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Thu, Nov 14, 2002 at 12:02:20PM +0100, lumbricus@gmx.net wrote: | [ snip ] |=20 | > First problem is you don't ping URLs, you ping IP addresses | > (either directly or via DNS) |=20 | Seems to work: | urlparse.urlparse("http://132.230.200.200") | ('http', '132.230.200.200', '', '', '', '' |=20 | Or am I missing something? $ ping http://132.230.200.200 ping: unknown host http://132.230.200.200 -D --=20 Through love and faithfulness sin is atoned for; through the fear of the Lord a man avoids evil. Proverbs 16:6 =20 http://dman.ddts.net/~dman/ --YiEDa0DAkWCtVeE4 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 iEYEARECAAYFAj3UFRUACgkQO8l8XBKTpRRxtwCeIKGqcu5SJU+SHUQiSF8i/Yt1 4mAAoIC3zrmpZNYTSj0CcjXpe2Prhk/z =wCzc -----END PGP SIGNATURE----- --YiEDa0DAkWCtVeE4-- From op73418@mail.telepac.pt Thu Nov 14 17:08:08 2002 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Thu Nov 14 17:08:08 2002 Subject: [Tutor] inheritance References: <001301c28a9e$e6f6e040$44120dd5@violante> <25872.1037271569@www40.gmx.net> Message-ID: <000701c28c2a$fb26bc10$301b0dd5@violante> ----- Original Message ----- From: To: Sent: Thursday, November 14, 2002 10:59 AM Subject: Re: [Tutor] inheritance > Hi! > > [ snip ] > > BTW: > > ... print "%r says howdy" % self > ^^ > what the hell is that? > It doesn't appear in "man 3 printf", so it > must be something new. r like reference? It's to convert a Python object into a string using repr() instead of str(). In some cases they are hardly indistinguishable anyway... > > > HTH, > > G. Rodrigues > > Greets, J"o! > All the best, G. Rodrigues From magnus@thinkware.se Thu Nov 14 18:16:25 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Thu Nov 14 18:16:25 2002 Subject: [Tutor] getting started In-Reply-To: <02111418331400.00363@Leary> Message-ID: <5.1.0.14.0.20021114235519.02a75de0@www.thinkware.se> Hi John, Welcome to the world of programming. I hope you will like it. At 18:39 2002-11-14 +0000, john gennard wrote: >How to get from ........x" to commence print "yyyyy.......... >'Enter' key of course executes the command. I've re-read everything >I have and can find no answer, and have tried also many keystrokes >without result. Statements ARE executed immediately in the interpreter. >>> print "xxx" xxx >>> print "yyy" yyy >>> print "zzz" zzz >>> It's supposed to be like that. You don't write programs in the interactive mode, you use it to test things quickly, or to make small calculations etc. (I don't use any other calculator.) If you want things to be executed all at once, put it in a file. It's no big deal. Just select "File -> New Window" in IDLE, and save as test.py or whatever. Type your code, press Ctrl-X Ctrl-S to save (just Ctrl-S in Windows), and then Ctrl-F5 to run it (just F5 in Windows). If you are really desperate to run a few lines at once in interactive mode, you can do this with a little trick: >>> if 1 == 1: print "aaa" print "bbb" print "ccc" aaa bbb ccc Block statements aren't executed until the block is finished. In a file with python code, blocks end with a dedent, i.e. when the next line is indented less, or when the file ends (which ever comes first ;). But in interactive mode there is no end of file in that sense, so an empty line is interpreted as the end of the "program", and what's been typed so far will be executed. (Actually you could type just "if 1:" instead of "if 1==1:" but I don't know if you've reached a point where that makes sense to you yet.) Anyway, the immediate execution might not be as pretty as you like, but apart from output being mixed with your typed code and the fact that you can't put empty lines wherever you want, things will work just the same as in any python program. As soon as you define functions, do loops or if statements etc, python will wait with execution as long as it has to. -- 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 Nov 14 19:00:02 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Thu Nov 14 19:00:02 2002 Subject: [Tutor] string assignment In-Reply-To: <01c001c28b27$36251320$d005a48c@epicuro> References: <01c001c28b27$36251320$d005a48c@epicuro> Message-ID: <200211141558.16981.shalehperry@attbi.com> On Wednesday 13 November 2002 07:13, Carla Attianese wrote: > SyntaxError: invalid syntax > File "C:\Documents and Settings\carla\a.py", line 258 > CREATE_STATEMENT_TABLE=3D""" > ^ this most likely means the error is on the line before this one. From magnus@thinkware.se Thu Nov 14 19:12:03 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Thu Nov 14 19:12:03 2002 Subject: [Tutor] Class property: check dict values before assign In-Reply-To: References: <20021114170005.28154.32726.Mailman@mail.python.org> Message-ID: <5.1.0.14.0.20021115002242.02ae2488@www.thinkware.se> At 13:13 2002-11-14 -0600, runsun wrote: >I have a class having a property of type dictionary. I wanna >check the values before they are assigned to that dictionary >property. In python lingo, I think you should call it an attribute. A property is a special thingie in the new classes unless I am mistaken. (That's actually somewhat related, but never mind that now...) As you know, a dictionary is mutable. In other words, it's the same dictionary object that changes. So, with c.user['lastname'] = 'dilley' the c object will in fact not change in itself. One of it's attributes will change but that's not the same thing. You aren't setting an attribute of the c object, so c.__setattr__ will not be triggered. C's attribute .user will still point to the very same (although modified) object. Let's see it this way. My household consists of my wife, my son and myself. All of us change. My son grows taller by the day for instance. But despite that, the household remains the same. It continues to consist of the three of us, until there is some big change, like a new sister, a divorce or a child moving from home etc. I wouldn't call __setattr__ on household because I got a year older, or changed my professional status. I might perhaps call __setattr__ on me! If you think a little further, I think you can understand that it has to be like this. What if x.user = c.user y.user = x.user Then the three objects c, x, and y will all have a reference in the form of an attribute '.user' that points to the very same dict. c.user['lastname'] = 'dilley' , x.user['lastname'] = 'dilley' and y.user['lastname'] = 'dilley' will do exactly the same thing. The dict they all call their .user property will be changed. What would you do now? Run __setattr__ for all three? Or just for the one that you happened to use to address your dict with at this time? c, x and y might be different classes. What if I do u = c.user u['lastname'] = 'dilley' ? In fact, the dict object doesn't even know where there are references to it! If you wan't to something special to happen on c.user['lastname'] = 'dilley' it must be code in the the c.user object that implements this. Not anything in the c object. Of course, you can handle things in the c object by hiding the dict and changing your interface. class myclass: def __init__(self): self.__user={'lastname':'lee', 'firstname':'john'} def changeUser(self, key, value): # add your checks here self.__user[key] = value def delUser(self, key): # add checks here too? del self.__user[key] def getUsers(self): # don't let clients get a reference to the dict, # hand over a copy return self.__user.copy() c = myclass() c.changeUser('lastname', 'dilley') Or, you can make a special kind of dict that can do things on it's own. >>> class myDict(dict): def __setitem__(self, key, value): print "Changing", key, "to", value dict.__setitem__(self, key, value) >>> d = myDict() >>> d[5]=6 Changing 5 to 6 >>> d {5: 6} (This requires Python 2.2 or later. With earlier versions you need to use the UserDict library module instead of sub-classing dict.) Now you can do: class myclass: def __init__(self): self.user = myDict({'Iastname':'lee', 'firstname':'john'}) c = myclass() c.user {'Iastname': 'lee', 'firstname': 'john'} c.user['lastname'] = 'dilley' Changing lastname to dilley But beware! __setitem__ is not the only method you need to override in your dict sub-class. See the library reference: http://www.python.org/doc/current/lib/typesmapping.html As you see, there are a number of modifying operations, at least del, .clear(), .update() and .setdefault(), and each corresponds to method you need to override. del x[y] will call the dict.__del__(x, y) magic method, otherwise, it's the listed methods you need to override. -- 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 Nov 14 19:34:01 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Thu Nov 14 19:34:01 2002 Subject: [Tutor] string assignment In-Reply-To: <200211141558.16981.shalehperry@attbi.com> References: <01c001c28b27$36251320$d005a48c@epicuro> <01c001c28b27$36251320$d005a48c@epicuro> Message-ID: <5.1.0.14.0.20021115012420.02af6338@www.thinkware.se> At 15:58 2002-11-14 -0800, Sean 'Shaleh' Perry wrote: >On Wednesday 13 November 2002 07:13, Carla Attianese wrote: > > SyntaxError: invalid syntax > > File "C:\Documents and Settings\carla\a.py", line 258 > > CREATE_STATEMENT_TABLE=""" > > ^ > >this most likely means the error is on the line before this one. This is such a common flaw in compiler error messages, in all programming languages I've run into that seasoned programmers feel that it's quite natural with this kind of diagnostics. In a way it is. The mistake that was probably done on the preceding line was syntactically correct, but only if the line Python complains about looked different. It's not until we reach this line that we can conclude that there is a syntax error. The error message could still be much more user friendly though. E.g. >>> a = (123, ... 123, ... 123 ... c = a Traceback ( File "", line 4 c = a ^ SyntaxError: invalid syntax should rather give SyntaxError: missing , or ) or something like that. Will PyChecker do more for such a bug? (Sourceforge is down, otherwise I'd check myself.) -- 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 Nov 14 19:43:02 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Thu Nov 14 19:43:02 2002 Subject: [Tutor] internet In-Reply-To: Message-ID: <5.1.0.14.0.20021115014432.02a77bb8@www.thinkware.se> At 21:39 2002-11-06 -0500, Kevon Mansfield wrote: >hi, > i have now started to learn python "it's cool", Sure is. Welcome to the club! :) >i would like to know if you can go on the net with python & how?, Yes you can. Chapters 11 to 13 of the Library Reference Guide ( http://www.python.org/doc/current/lib/lib.html ) will tell you how. (You asked a very big question...) >can i also join windows program with python?. Sure. See http://starship.python.net/crew/mhammond/ and there are some other solutions on http://www.thinkware.se/cgi-bin/thinki.cgi/UsingPythonWithOtherLanguages -- 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 lbrannma@cablespeed.com Thu Nov 14 21:01:02 2002 From: lbrannma@cablespeed.com (Lance) Date: Thu Nov 14 21:01:02 2002 Subject: [Tutor] creating a non-COM DLL Message-ID: <003d01c28c4c$2c08c2d0$3212eb42@MYNEWBOX> Hi All, I want to create a simple non-COM dll that I will call from a third party program. I believe the third party program uses LoadLibrary. The DLL will export C style functions, with pointers to doubles as arguments. Do I add my import statements to the __init__ method of the class, e.g. class MyClass: def __init__(self): import os, cPickle, some other modules os.chdir("c:\\foo") def read(self): d = cPickle.load(..from \foo ) etc.... Any advice will be appreciated. Thanks, Lance From bindas_qwerty@hotmail.com Thu Nov 14 22:42:02 2002 From: bindas_qwerty@hotmail.com (sachin mehra) Date: Thu Nov 14 22:42:02 2002 Subject: [Tutor] need some help for program!! Message-ID: Hi, I have found your website really wonderfull!! A lot of the programs have helped me code in other langugues like perl, Etc. I needed help in python programming now!! I am not very versed with it. The program I need to write is the following: I am giving some text, from which I have to train the model.That is make the model understand sentences in english. The test cases will have a sentence without any spaces in between & I have to write a code which will do that.the test cases will contain only sentences without spaces. The text for training the model & the test cases will be of the same context. I may have to use Some Probability algorithms(viterbi/ forward algorithm) to find the probability of the word & bigrams( the word before a particular word)and use these probabilities to put spaces between the text. Can somebody help me out..How can I start? Does anyone have any similar kind of code ? Let me know. Thanx, _________________________________________________________________ The new MSN 8: advanced junk mail protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From dyoo@hkn.eecs.berkeley.edu Thu Nov 14 23:38:02 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Nov 14 23:38:02 2002 Subject: [Tutor] need some help for program!! In-Reply-To: Message-ID: On Fri, 15 Nov 2002, sachin mehra wrote: > I may have to use Some Probability algorithms(viterbi/ forward > algorithm) to find the probability of the word & bigrams( the word > before a particular word)and use these probabilities to put spaces > between the text. Can somebody help me out..How can I start? Does anyone > have any similar kind of code ? Let me know. Thanx, Hi Sachin, You may want to look at the Natural Language Toolkit (NLTK), which is a Python module to help people learn how natural language parsing can work: http://nltk.sourceforge.net/ I've only started to look at it a bit, but it looks awesome; there are Viterbi-style parsers included with the package: http://nltk.sourceforge.net/tutorial/pcfg/t1.html So it may provide a lot of what you're looking for. Good luck! From thomi@thomi.imail.net.nz Fri Nov 15 02:49:02 2002 From: thomi@thomi.imail.net.nz (Thomi Richards) Date: Fri Nov 15 02:49:02 2002 Subject: [Tutor] hex to decimal conversion. Message-ID: <20021115204739.7125ec15.thomi@thomi.imail.net.nz> can anyone tell me how to convert from hexidecimal to decimal?? I thought it would be a math function, but nope... thanks -- DOS: n., A small annoying boot virus that causes random spontaneous system crashes, usually just before saving a massive project. Easily cured by UNIX. See also MS-DOS, IBM-DOS, DR-DOS. (from David Vicker's .plan) Thomi Richards, thomi@imail.net.nz From glingl@aon.at Fri Nov 15 03:10:14 2002 From: glingl@aon.at (Gregor Lingl) Date: Fri Nov 15 03:10:14 2002 Subject: [Tutor] hex to decimal conversion. References: <20021115204739.7125ec15.thomi@thomi.imail.net.nz> Message-ID: <3DD4ABB4.2080505@aon.at> Thomi Richards schrieb: >can anyone tell me how to convert from hexidecimal to decimal?? > >I thought it would be a math function, but nope... > >thanks > > > That depends on the format (or type) of the number given: >>> int(0xff) 255 >>> int(0x3e8) 1000 >>> int("ff",16) 255 >>> int("3e8",16) 1000 HTH, Gregor From thomi@thomi.imail.net.nz Fri Nov 15 04:18:02 2002 From: thomi@thomi.imail.net.nz (Thomi Richards) Date: Fri Nov 15 04:18:02 2002 Subject: [Tutor] Tkinter problems Message-ID: <20021115221655.60867704.thomi@thomi.imail.net.nz> Hey all, I'm hoping someone could help me with Tkinter. I've never done any sort of GUI programming before, but I've written a program which needs a simple GUI interface. nothing special, just a few "open file" dialog boxes, somewhere for me to print output, and a "save as" dialog box. I've been reading the documentation at http://www.pythonware.com/library/tkinter/introduction/ and I have a few questions: firstly, how do i get the users response back into a variable, from say a yes/no box? I need it to return a string saying "yes" or "no" or something similar. same with open file and close file dialog boxes, except then I'll need a filename. also, with the open file and save file dialog boxes, are there are pre-made ones i can use? it looks like a lot of work to code in all the information about browsing around the hard drive, the buttons, blah blah blah. surely someone else has made a pre-defined version? lastly, what widget do i want to use, if i want to display text on a screen, and have it scrolling down, as more text appears? I originally thought i could just use the label thingie, but what happens when it hits the end of the window? from the documentation, it would seem like the window would just expand, instead of scrolling the text. finally, how the hell are you meant to do anything, if the mainloop function hangs? how can i get my program to run, after i run that command? I get the idea I'm waaaaay off target here, and any help would be most appreciated. yours in frustration, -- Thomi Richards thomi@imail.net.nz http://ddmodd.sourceforge.net/ Thomi Richards, thomi@imail.net.nz From francois.granger@free.fr Fri Nov 15 04:43:02 2002 From: francois.granger@free.fr (=?iso-8859-1?Q?Fran=E7ois?= Granger) Date: Fri Nov 15 04:43:02 2002 Subject: [Tutor] hex to decimal conversion. In-Reply-To: <20021115204739.7125ec15.thomi@thomi.imail.net.nz> References: <20021115204739.7125ec15.thomi@thomi.imail.net.nz> Message-ID: At 20:47 +1300 15/11/02, in message [Tutor] hex to decimal conversion., Thomi Richards wrote: >can anyone tell me how to convert from hexidecimal to decimal?? > I kept this on my HD, I don't know if it will help. def tobase(base,number): """ From "Stolker, Wim" on c.l.py """ global tb def tb(b,n,result=''): if n == 0: return result else: return tb(b,n/b,str(n%b)+result) if type(base) != type(1): raise TypeError, 'invalid base for tobase()' if base <= 0: raise ValueError, 'invalid base for tobase(): %s' % base if type(number) != type(1) and type(number) != type(1L): raise TypeError, 'tobase() of non-integer' if number == 0: return '0' if number > 0: return tb(base, number) if number < 0: return '-' + tb(base, -1*number) -- Le courrier électronique 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 : http://minilien.com/?IXZneLoID0 - http://marc.herbert.free.fr/mail/ http://expita.com/nomime.html From magnus@thinkware.se Fri Nov 15 04:48:02 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Fri Nov 15 04:48:02 2002 Subject: [Tutor] hex to decimal conversion. In-Reply-To: <3DD4ABB4.2080505@aon.at> References: <20021115204739.7125ec15.thomi@thomi.imail.net.nz> Message-ID: <5.1.0.14.0.20021115104848.02af5d60@www.thinkware.se> At 09:09 2002-11-15 +0100, Gregor Lingl wrote: >Thomi Richards schrieb: >>can anyone tell me how to convert from hexidecimal to decimal?? >> >>> int(0xff) >255 > >>> int(0x3e8) >1000 > >>> int("ff",16) >255 > >>> int("3e8",16) >1000 Or for big ones: >>> long('fffffffffff',16) 17592186044415L These long and int conversions work for bases up to 36: >>> long('j',20) 19L >>> long('k',20) Traceback (most recent call last): File "", line 1, in ? ValueError: invalid literal for long(): k >>> long('k',21) 20L >>> int('z',36) 35 -- 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 Nov 15 04:59:02 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Fri Nov 15 04:59:02 2002 Subject: [Tutor] Tkinter problems In-Reply-To: <20021115221655.60867704.thomi@thomi.imail.net.nz> Message-ID: <5.1.0.14.0.20021115105551.02ab7ac8@www.thinkware.se> At 22:16 2002-11-15 +1300, Thomi Richards wrote: >I'm hoping someone could help me with Tkinter. I've never done any sort >of GUI programming before, but I've written a program which needs a >simple GUI interface. nothing special, just a few "open file" dialog >boxes, somewhere for me to print output, and a "save as" dialog box. If you just need a few dialogs that appear in a predefined order, you might not even need an event loop. Check out the Python22/Lib/lib-tk directory, and have a look at the examples in the end of these files: tkSimpleDialog.py tkMessageBox.py tkFileDialog.py You can run these files as they are to get a demo. As you see, they simply return a value like a normal expression. "Use the source, Luke!" I don't think any of these plain dialogs use any scrolled window though, but lets think about that later! :) -- 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 schalla@vasoftware.com Fri Nov 15 09:40:09 2002 From: schalla@vasoftware.com (shobhan) Date: Fri Nov 15 09:40:09 2002 Subject: [Tutor] Whats wrong with this code..?? Message-ID: <3DD50527.9070700@vasoftware.com> --------------090409000600010301040002 Content-Type: text/plain; charset=us-ascii; format=flowed Content-Transfer-Encoding: 7bit Im trying to execute the following python code in a browser: #!/usr/bin/python import os import sys import commands import string import urllib sys.path.append('/mainscripts/etc/scripts') #the folder for local sys.path.append('/mainscripts/scripts/python/common') # folder for logger_conf import local import logger_conf import sql_utils import re dbapi = __import__('cx_Oracle') dbh = dbapi.connect(logger_conf.db_dsn) dbc = dbh.cursor() print "Content-Type: text/html\n\n" print "Testing script" print "" print "DSN :" + logger_conf.db_dsn print "

Im alive

" dbc.execute("select user_id,user_name,email from users") rows = dbc.fetchall() print "USERID :" + rows[0] print "USER_NAME :" + rows[1] print "EMAIL :" + rows[2] print "" ------------------------------------------ The problem with the script is if i comment the line "dbh = dbapi.connect(logger_conf.db_dsn)" its working fine , i.e its printing the DSN correctly, but if this line is uncommented its displaying "Internal Server Error". When i check the apache log it gives the following error: Traceback (most recent call last): File "/sourceforge/sfee/www/search/cc_scm_content.py", line 15, in ? dbh = dbapi.connect(logger_conf.db_dsn) cx_Oracle.DatabaseError: Error while trying to retrieve text for error ORA-12154 [Fri Nov 15 08:58:37 2002] [error] [client 11.1.30.9] Premature end of script headers: /sourceforge/sfee/www/search/cc_scm_content.py Can anyone tell whats wrong with this code?? Thanks Schalla --------------090409000600010301040002 Content-Type: text/html; charset=us-ascii Content-Transfer-Encoding: 7bit Im trying to execute the following python code in a browser:

#!/usr/bin/python
import os
import sys
import commands
import string
import urllib
sys.path.append('/mainscripts/etc/scripts') #the folder for local
sys.path.append('/mainscripts/scripts/python/common') # folder for logger_conf
import local
import logger_conf
import sql_utils
import re

dbapi = __import__('cx_Oracle')
dbh = dbapi.connect(logger_conf.db_dsn)
dbc = dbh.cursor()

print "Content-Type: text/html\n\n"
print "<html><head><title>Testing script</title></head>"
print "<body>"
print  "DSN  :" + logger_conf.db_dsn
print "<p>Im alive</p>"

dbc.execute("select user_id,user_name,email from users")
rows = dbc.fetchall()
print  "USERID :" + rows[0]
print  "USER_NAME :" + rows[1]
print  "EMAIL :" + rows[2]
print "</body></html>"

------------------------------------------
The problem with the script is if i comment the line
"dbh = dbapi.connect(logger_conf.db_dsn)"  its working fine , i.e its printing the DSN correctly, but if this line is uncommented its displaying "Internal Server Error". When i check the apache log it gives the following error:

Traceback (most recent call last):
  File "/sourceforge/sfee/www/search/cc_scm_content.py", line 15, in ?
    dbh = dbapi.connect(logger_conf.db_dsn)
cx_Oracle.DatabaseError: Error while trying to retrieve text for error ORA-12154

[Fri Nov 15 08:58:37 2002] [error] [client 11.1.30.9] Premature end of script headers: /sourceforge/sfee/www/search/cc_scm_content.py


Can anyone tell whats wrong with this code??

Thanks
Schalla



--------------090409000600010301040002-- From emil@lysator.liu.se Fri Nov 15 10:00:02 2002 From: emil@lysator.liu.se (Emil Styrke) Date: Fri Nov 15 10:00:02 2002 Subject: [Tutor] Whats wrong with this code..?? In-Reply-To: <3DD50527.9070700@vasoftware.com> References: <3DD50527.9070700@vasoftware.com> Message-ID: <87u1iix4j0.fsf@i110.ryd.student.liu.se> shobhan writes: > Traceback (most recent call last): > File "/sourceforge/sfee/www/search/cc_scm_content.py", line 15, in ? > dbh = dbapi.connect(logger_conf.db_dsn) > cx_Oracle.DatabaseError: Error while trying to retrieve text for error > ORA-12154 > > [Fri Nov 15 08:58:37 2002] [error] [client 11.1.30.9] Premature end of > script headers: /sourceforge/sfee/www/search/cc_scm_content.py > > Can anyone tell whats wrong with this code?? The problem seems to be that the database server gives the error "ORA-12154", and the oracle python module doesn't know what it means (it can't convert it to a human-readable text string). Maybe you can find out what the error code means by looking at the oracle documentation? /Emil From ATrautman@perryjudds.com Fri Nov 15 10:16:03 2002 From: ATrautman@perryjudds.com (Alan Trautman) Date: Fri Nov 15 10:16:03 2002 Subject: [Tutor] Whats wrong with this code..?? Message-ID: <0BA95581EDA7D611841B00A0C9AD25DD2B58F2@mail.pjinet.com> Warning VERY OLD (2001) Oracle knowledge here but I think that you must pass a user ID and a password even if one is not specified to an Oracle database. Failure to do so will return an Oracle error which might be what you are getting. > dbh = dbapi.connect(logger_conf.db_dsn) , UserID='',password='') Definitely check the oracle manual/error code help file, I do not believe your python code is to blame with what you provided. From lumbricus@gmx.net Fri Nov 15 11:21:12 2002 From: lumbricus@gmx.net (lumbricus@gmx.net) Date: Fri Nov 15 11:21:12 2002 Subject: [Tutor] hex to decimal conversion. References: <20021115204739.7125ec15.thomi@thomi.imail.net.nz> Message-ID: <9013.1037377180@www48.gmx.net> Hi! > can anyone tell me how to convert from hexidecimal to decimal?? A format string can do that. >>> print "%x" %255 ff >>> print "%o" %255 377 etc ... > thanks HTH, J"o! -- Wir beschliessen etwas, stellen das dann in den Raum und warten dann einige Zeit ab, was passiert. Wenn es dann kein grosses Geschrei gibt und keine Aufstaende, weil die meisten gar nicht begreifen, was da beschlossen wurde, dann machen wir weiter - Schritt fuer Schritt, bis es kein Zurueck mehr gibt. -- J-C Juncker +++ GMX - Mail, Messaging & more http://www.gmx.net +++ NEU: Mit GMX ins Internet. Rund um die Uhr für 1 ct/ Min. surfen! From mchermside@ingdirect.com Fri Nov 15 11:29:01 2002 From: mchermside@ingdirect.com (Chermside, Michael) Date: Fri Nov 15 11:29:01 2002 Subject: [Tutor] catching any exception? Message-ID: <902A1E710FEAB740966EC991C3A38A8903C278CD@INGDEXCHANGEC1.ingdirect.com> > Apparently although "Exception" is the parent of all=20 > exceptions, it is not an exception itself, so this never matched. Actually, I don't think that's true. Let me run a quick test: ActivePython 2.2.1 Build 222 (ActiveState Corp.) based on Python 2.2.1 (#34, Apr 15 2002, 09:51:39) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> try: ... raise Exception ... except Exception, thisException: ... print 'Got exception %s' % Exception ... Got exception exceptions.Exception >>> try: ... raise Exception ... except Exception, thisException: ... print 'Got exception %s' % Exception ... raise Exception(thisException, 'sql message') ... Got exception exceptions.Exception Traceback (most recent call last): File "", line 5, in ? Exception: (, 'sql = message') Okay... it appears that the code you posted DOES work. Perhaps the problem isn't where you think it is? At any rate, Exception *is* an exception, and CAN be caught by a normal except clause. -- Michael Chermside From lumbricus@gmx.net Fri Nov 15 11:42:01 2002 From: lumbricus@gmx.net (lumbricus@gmx.net) Date: Fri Nov 15 11:42:01 2002 Subject: [Tutor] Re: Help with ping... References: <20021114212645.GA24614@dman.ddts.net> Message-ID: <25352.1037378459@www48.gmx.net> Hi! > On Thu, Nov 14, 2002 at 12:02:20PM +0100, lumbricus@gmx.net wrote: > > | [ snip ] > | > | > First problem is you don't ping URLs, you ping IP addresses > | > (either directly or via DNS) > | > | Seems to work: > | urlparse.urlparse("http://132.230.200.200") > | ('http', '132.230.200.200', '', '', '', '' > | > | Or am I missing something? > > $ ping http://132.230.200.200 > ping: unknown host http://132.230.200.200 Huh? Of course you can't give an URI to ping at the shell. That's why the whole thing get split up by urlparse. And we were talking about python. >>> uri="http://132.230.200.200" # or anything >>> os.system("/sbin/ping %s" \ %urlparse.urlparse(uri)[1]) PING 132.230.200.200 (132.230.200.200): 56 data bytes 64 bytes from 132.230.200.200: icmp_seq=0 ttl=253 time=4 ms 64 bytes from 132.230.200.200: icmp_seq=1 ttl=253 time=3 ms 64 bytes from 132.230.200.200: icmp_seq=2 ttl=253 time=14 ms ----132.230.200.200 PING Statistics---- 3 packets transmitted, 3 packets received, 0% packet loss round-trip (ms) min/avg/max = 3/7/14 ms 2 >>> q.e.d? > -D Greetings, J"o! -- Wir beschliessen etwas, stellen das dann in den Raum und warten dann einige Zeit ab, was passiert. Wenn es dann kein grosses Geschrei gibt und keine Aufstaende, weil die meisten gar nicht begreifen, was da beschlossen wurde, dann machen wir weiter - Schritt fuer Schritt, bis es kein Zurueck mehr gibt. -- J-C Juncker +++ 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 Nov 15 12:10:02 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Fri Nov 15 12:10:02 2002 Subject: [Tutor] Whats wrong with this code..?? In-Reply-To: <3DD50527.9070700@vasoftware.com> Message-ID: <5.1.0.14.0.20021115181058.029d3d58@www.thinkware.se> At 20:01 2002-11-15 +0530, shobhan wrote: >dbapi = __import__('cx_Oracle') Huh? Why not import cx_Oracle as dbapi? BTW, you can import several modules on the same row by separating them with comma. (I prefer compact programs.) >Traceback (most recent call last): > File "/sourceforge/sfee/www/search/cc_scm_content.py", line 15, in ? > dbh = dbapi.connect(logger_conf.db_dsn) >cx_Oracle.DatabaseError: Error while trying to retrieve text for error >ORA-12154 See http://www.is.mcgill.ca/minerva/Help/ora12154.htm for and explanation on the original error. Then you could obviously not get the error messages. I don't remember what used to cause this. I haven't worked with Oracle since the spring of 1998. A missing path? Some environment variable? Does it show error messages from the Oracle tools such as sqlplus? -- 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 schalla@vasoftware.com Fri Nov 15 12:39:02 2002 From: schalla@vasoftware.com (shobhan) Date: Fri Nov 15 12:39:02 2002 Subject: [Tutor] Whats wrong with this code..?? References: <5.1.0.14.0.20021115181058.029d3d58@www.thinkware.se> Message-ID: <3DD530CA.4040207@vasoftware.com> --------------000607080806090309050801 Content-Type: text/plain; charset=us-ascii; format=flowed Content-Transfer-Encoding: 7bit Forgot to tell that the python program is executed on the browser of another machine, and its trying to connect to the Oracle DB on my machine. And it doesnt show any errors when i use sqlplus. BTW, ur right i can import modules on the same row, it also makes the program compact. I'll check if im missing anything in my path Regards Schalla :) Magnus Lycka wrote: > At 20:01 2002-11-15 +0530, shobhan wrote: > >> dbapi = __import__('cx_Oracle') > > I Huh? Why not > > import cx_Oracle as dbapi? > > BTW, you can import several modules on the same row by > separating them with comma. (I prefer compact programs.) > >> Traceback (most recent call last): >> File "/sourceforge/sfee/www/search/cc_scm_content.py", line 15, in ? >> dbh = dbapi.connect(logger_conf.db_dsn) >> cx_Oracle.DatabaseError: Error while trying to retrieve text for >> error ORA-12154 > > > See > http://www.is.mcgill.ca/minerva/Help/ora12154.htm > > for and explanation on the original error. Then you could > obviously not get the error messages. I don't remember what > used to cause this. I haven't worked with Oracle since the > spring of 1998. A missing path? Some environment variable? > Does it show error messages from the Oracle tools such as > sqlplus? > > > --------------000607080806090309050801 Content-Type: text/html; charset=us-ascii Content-Transfer-Encoding: 7bit Forgot to tell that the python program is executed on the browser of another machine, and its trying to connect to the Oracle DB on my machine.
And it doesnt show any errors when i use sqlplus.

BTW, ur right i can import modules on the same row, it also makes the program compact.
I'll check if im missing anything in  my path

Regards
Schalla :)


Magnus Lycka wrote:
At 20:01 2002-11-15 +0530, shobhan wrote:

dbapi = __import__('cx_Oracle')
I Huh? Why not

import cx_Oracle as dbapi?

BTW, you can import several modules on the same row by
separating them with comma. (I prefer compact programs.)

Traceback (most recent call last):
  File "/sourceforge/sfee/www/search/cc_scm_content.py", line 15, in ?
    dbh = dbapi.connect(logger_conf.db_dsn)
cx_Oracle.DatabaseError: Error while trying to retrieve text for error ORA-12154

See
http://www.is.mcgill.ca/minerva/Help/ora12154.htm

for and explanation on the original error. Then you could
obviously not get the error messages. I don't remember what
used to cause this. I haven't worked with Oracle since the
spring of 1998. A missing path? Some environment variable?
Does it show error messages from the Oracle tools such as
sqlplus?






--------------000607080806090309050801-- From magnus@thinkware.se Fri Nov 15 13:01:04 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Fri Nov 15 13:01:04 2002 Subject: [Tutor] Whats wrong with this code..?? In-Reply-To: <3DD530CA.4040207@vasoftware.com> References: <5.1.0.14.0.20021115181058.029d3d58@www.thinkware.se> Message-ID: <5.1.0.14.0.20021115185540.02a91a40@www.thinkware.se> At 23:07 2002-11-15 +0530, shobhan wrote: >Forgot to tell that the python program is executed on the browser of >another machine, What do you mean by this? Browser? A web browser? Are you talking about client side scripting with Windows Scripting Host in MS IE? Your program looks more like a CGI script. Isn't is executed on a webserver? What happens if you execute it from the command line instead of through the web server? If that works: what happens if you execute it with the same user identity as the web server uses to execute CGI scripts? (nobody?) -- 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 Fri Nov 15 13:03:14 2002 From: jeff@ccvcorp.com (Jeff Shannon) Date: Fri Nov 15 13:03:14 2002 Subject: [Tutor] catching any exception? References: <902A1E710FEAB740966EC991C3A38A8903C278CD@INGDEXCHANGEC1.ingdirect.com> Message-ID: <3DD536E8.C2A10F8B@ccvcorp.com> "Chermside, Michael" wrote: > > Apparently although "Exception" is the parent of all > > exceptions, it is not an exception itself, so this never matched. > > Actually, I don't think that's true. Let me run a quick test: Indeed, neither part of the statement is completely true. "Exception" is indeed an exception, and it is *intended* to be the parent of all exceptions... but class-based exceptions have only been around since (I think) Python 2.0, and some third-party modules still use the older, string-based exceptions, which obviously cannot inherit from Exception. I haven't analyzed the O.P.'s code enough to have any clue how likely it is that this is the problem in this case, but it's a possibility. In the meantime, as someone else suggested, the traceback module should be able to grab exception information when using a bare except, which should let you solve your original problem. Jeff Shannon Technician/Programmer Credit International From alan.gauld@bt.com Fri Nov 15 13:43:02 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri Nov 15 13:43:02 2002 Subject: [Tutor] getting started Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB21877A516@mbtlipnt02.btlabs.bt.co.uk> > I want to do the following:- > > >>>print "xxxxxxxxxxxxxxx" > print "yyyyyyyyyyyy" > print "zzzzzzzzzzzzzz" > > How to get from ........x" to commence print "yyyyy.......... > 'Enter' key of course executes the command. Which is what any interpreter does. It executes your code one line at a time. If you need to execute a group of lines at once there are several options: 1) Put then in a function(you may not have reached those yet!) 2) separate them with semicolons on the same line 3) put them in a small file. To save using lots of files use the same name each time: test.py say... You'll lose your last set but then thats true of the >>> prompt too! I'd recommend none of these but just get used to using the prompt with each line executing as you enter it... Otherwise go to option 3 until you learn about functions. Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld@bt.com Fri Nov 15 13:43:13 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri Nov 15 13:43:13 2002 Subject: [Tutor] Can any one recommend a good C++ referernce manual Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB21877A515@mbtlipnt02.btlabs.bt.co.uk> > I just want some thing where I can look up what I want to do > and it will give me a brief description of what it is, > what it does, how to use it Thats hard in C++ because of the intrinsic complexity of the language. Once you get beyond basics C++ is very powerful and very complicated! I'd recommend one of the following two books as references: Bjarne Stroustrup "The C++ Programming Language" 3rd edition Dewhurst and Stark , can't remember the title tho'... > the options. I've already got a book teaching generally how > to use C++ (didnt teach me much that I didnt already know In that case it didn't teach you enough! The differences at a conceptual level are not grweat but to effectively use C++ the differences are vast. > doesn't give many functions, I cant even seem to find how to > write to a file. The functions are, like in python, contained in libraries. You need documentation for the standard C++ library. For file handling look at the streams library(obviously! :-) or use the old C stdio library. Beware of dragons, Alan G. From alan.gauld@bt.com Fri Nov 15 13:43:27 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri Nov 15 13:43:27 2002 Subject: [Tutor] Recommend a good intro book to Objective C ? Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB21877A514@mbtlipnt02.btlabs.bt.co.uk> Brad Cox original book is still available and is the definitive reference. However it won't help that much if they are aiming to program Cocoa! For that they need to know the class library above all else... Alan g > -----Original Message----- > From: Patricia Lee [mailto:greymalkin@neuralust.com] > Sent: 13 November 2002 17:44 > To: zope-mosx; Tutor > Subject: [Tutor] Recommend a good intro book to Objective C ? > > > > Can anyone recommend a good intro book to Objective C. The > target of this > book is not myself, but a person with knowledge of C, Java... > Who has gone > through some of a computer science degree and generally knows > what he's > talking about. > > He has the O'Reilley book on learning Cocoa, but doesn't like > it. The book > assumes that the user has more Objective C knowledge than he > does... So > hence the request about the "intro to Objective C" book... > > Thanks - Patti > > > > From alan.gauld@bt.com Fri Nov 15 13:43:43 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri Nov 15 13:43:43 2002 Subject: [Tutor] getting started Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB21877A518@mbtlipnt02.btlabs.bt.co.uk> > If you are really desperate to run a few lines at once > in interactive mode, you can do this with a little trick: > > >>> if 1 == 1: > print "aaa" > print "bbb" > print "ccc" > I like it Magnus! I hadn't thought of that before... Alan G. From alan.gauld@bt.com Fri Nov 15 13:49:01 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri Nov 15 13:49:01 2002 Subject: [Tutor] Help with ping... Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB21877A517@mbtlipnt02.btlabs.bt.co.uk> > > First problem is you don't ping URLs, you ping IP addresses > > (either directly or via DNS) > > Seems to work: > urlparse.urlparse("http://132.230.200.200") > ('http', '132.230.200.200', '', '', '', '' That's correct, you can parse urls using urlparse. You cannot ping urls. You could of course use urlparse to extract an address from a url... Alan g. From alan.gauld@bt.com Fri Nov 15 13:49:12 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri Nov 15 13:49:12 2002 Subject: [Tutor] Tkinter problems Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB21877A51A@mbtlipnt02.btlabs.bt.co.uk> > firstly, how do i get the users response back into a > variable, from say a yes/no box? Take a look at the GUI topic ion my tutor, it briefly covers the use of yes/no boxes. > I need it to return a string saying "yes" or "no" or if val == 1: val = 'yes' else val = 'no' OTOH 1 and 0 are usually more useful programmatically... > also, with the open file and save file dialog boxes, are there are > pre-made ones i can use? Yes, I think the module is called "dialogs" or something...its an extra to Tkinter itself. > lastly, what widget do i want to use, if i want to display text on a > screen, and have it scrolling down, as more text appears? Would you believe a Text widget?! Look at the case study on my tutor for example of appending text to a text widget. > finally, how the hell are you meant to do anything, if the mainloop > function hangs? You can't, its dead. Fortunately it hardly ever hangs in practice! Usually its just not seeing your events, thats why its a good idea to always put a quit button on the UI somewhere... > how can i get my program to run, after i run that command? It is running. The mainloop is spinning around watching your mouse and keyboard just waiting for you to do something that it an process.... Check the event driven programming topic on my tutor for more on that! Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld@bt.com Fri Nov 15 13:49:27 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri Nov 15 13:49:27 2002 Subject: [Tutor] hex to decimal conversion. Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB21877A519@mbtlipnt02.btlabs.bt.co.uk> > can anyone tell me how to convert from hexidecimal to decimal?? look at the string.atoi() function. Assuming you are starting with a hex string! Alan G From glingl@aon.at Fri Nov 15 13:55:02 2002 From: glingl@aon.at (Gregor Lingl) Date: Fri Nov 15 13:55:02 2002 Subject: [Tutor] getting started References: <5104D4DBC598D211B5FE0000F8FE7EB21877A518@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <3DD542D1.9010605@aon.at> alan.gauld@bt.com schrieb: >>If you are really desperate to run a few lines at once >>in interactive mode, you can do this with a little trick: >> >> >>> if 1 == 1: >> print "aaa" >> print "bbb" >> print "ccc" >> >> >> > >I like it Magnus! I hadn't thought of that before... > >Alan G. > > Me too! But why not >>> if 1: print "aaa" print "bbb" etc. Gregor >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From alan.gauld@bt.com Fri Nov 15 13:57:01 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri Nov 15 13:57:01 2002 Subject: [Tutor] Whats wrong with this code..?? Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA52@mbtlipnt02.btlabs.bt.co.uk> 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_01C28CD8.ED6F63C0 Content-Type: text/plain; charset="iso-8859-1" > Im trying to execute the following python code in a browser: Actually you are trying to execute it in a server - a web application server maybe but not a browser. The results will display in a browser - you hope - but that is entirely different to executing there. You can execute some Python code in the IE browser under Active Scripting but not the kind of code you have here. Its nit picking I know but in many cases could make the difference between accurate diagnosis and faulty... Alan g. ------_=_NextPart_001_01C28CD8.ED6F63C0 Content-Type: text/html; charset="iso-8859-1"
 >  Im trying to execute the following python code in a browser:
Actually you are trying to execute it in a server - a web
application server maybe but not a browser.
 
The results will display in a browser - you hope - but that is
entirely different to executing there. You can execute some Python
code in the IE browser under Active Scripting but not the kind 
of code you have here. 
 
Its nit picking I know but in many cases could make the
difference between accurate diagnosis and faulty...
 
Alan g.
 
------_=_NextPart_001_01C28CD8.ED6F63C0-- From lsloan@umich.edu Fri Nov 15 15:01:03 2002 From: lsloan@umich.edu (Lance E Sloan) Date: Fri Nov 15 15:01:03 2002 Subject: [Tutor] Re: catching any exception? In-Reply-To: <902A1E710FEAB740966EC991C3A38A8903C278CD@INGDEXCHANGEC1.ingdirect.com> References: <902A1E710FEAB740966EC991C3A38A8903C278CD@INGDEXCHANGEC1.ingdire ct.com> Message-ID: <5036985.1037372399@[10.0.1.5]> --On Friday, November 15, 2002 11:27 -0500 "Chermside, Michael" wrote: >>>> try: > ... raise Exception > ... except Exception, thisException: > ... print 'Got exception %s' % Exception > ... raise Exception(thisException, 'sql message') > ... > Got exception exceptions.Exception > Traceback (most recent call last): > File "", line 5, in ? > Exception: (, 'sql message') > > Okay... it appears that the code you posted DOES work. Perhaps > the problem isn't where you think it is? At any rate, Exception > *is* an exception, and CAN be caught by a normal except clause. I tried your example and it works for me, too. So it's not a Python version difference. (I have 2.0.) But I've noticed that the code only works for any of the "standard" exceptions. If I define my own exception, which is what DCOracle does, and raise that, it's not caught: >>> myException = 'my sample exception' >>> try: ... raise myException ... except Exception, thisException: ... print 'got (%s, %s)' % (Exception, thisException) ... raise Exception(thisException, 'sql here') ... Traceback (most recent call last): File "", line 2, in ? my sample exception See, "myException" was not caught. How can I catch all exceptions, including the ones that DCOracle defines? For that matter, how can I create an exception that's just like a "standard" exception? I think that's part of the problem. The string type of exception that DCOracle defines doesn't have Exception as a parent. -- Lance E Sloan Web Services, Univ. of Michigan: Full-service Web and database design, development, and hosting. Specializing in Python & Perl CGIs. http://websvcs.itd.umich.edu/ - "Putting U on the Web" From gubitz@netcologne.de Fri Nov 15 16:23:01 2002 From: gubitz@netcologne.de (Hans Gubitz) Date: Fri Nov 15 16:23:01 2002 Subject: [Tutor] Images + Tkinter Message-ID: <20021116212021.GA22802@pumuckl.redwitz79.de> Hello, tk.mainloop() seems to be not in the right place. But the gif will not be shown, when I eliminate this line. Any hints? import Tkinter from Tkconstants import * def window(tk): frame=Tkinter.Frame(tk) frame.pack() canvas=Tkinter.Canvas(frame,width=400,height=500) photo=Tkinter.PhotoImage(file="picture.gif") canvas.create_image(200, 250, image=photo) canvas.pack() button=Tkinter.Button(frame, text="EXIT", command=tk.destroy) button.pack() tk.mainloop() # ????????????????????????? root = Tkinter.Tk() window(root) root.mainloop() Hans Gubitz From dman@dman.ddts.net Fri Nov 15 16:23:18 2002 From: dman@dman.ddts.net (Derrick 'dman' Hudson) Date: Fri Nov 15 16:23:18 2002 Subject: [Tutor] Re: hex to decimal conversion. In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB21877A519@mbtlipnt02.btlabs.bt.co.uk> References: <5104D4DBC598D211B5FE0000F8FE7EB21877A519@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <20021115213543.GA9455@dman.ddts.net> --NzB8fVQJ5HfG6fxh Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Fri, Nov 15, 2002 at 06:44:01PM -0000, alan.gauld@bt.com wrote: | > can anyone tell me how to convert from hexidecimal to decimal?? |=20 | look at the string.atoi() function. Don't. That has been deprecated since 2.0. Instead look at the int() built-in. -D --=20 Do not be afraid of those who kill the body but cannot kill the soul. Rather be afraid of the One who can destroy both soul and body in hell. Matthew 10:28 =20 http://dman.ddts.net/~dman/ --NzB8fVQJ5HfG6fxh 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 iEYEARECAAYFAj3VaK8ACgkQO8l8XBKTpRSuPwCgiK3mvDr1hnv2WRZoWTy7xrrC FlkAn2ZBm6qxgNE0Hn6p2CGRvibwaCkF =enf9 -----END PGP SIGNATURE----- --NzB8fVQJ5HfG6fxh-- From dyoo@hkn.eecs.berkeley.edu Fri Nov 15 16:36:02 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Nov 15 16:36:02 2002 Subject: [Tutor] Can any one recommend a good C++ referernce manual In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB21877A515@mbtlipnt02.btlabs.bt.co.uk> Message-ID: [off topic C++ post; ignore to avoid confusion with Python] On Fri, 15 Nov 2002 alan.gauld@bt.com wrote: > In that case it didn't teach you enough! The differences at a conceptual > level are not grweat but to effectively use C++ the differences are > vast. It's weird, but I really have seen some C++ tutorials that try to pretend that files don't exist. *grin* C++'s file handling libraries are meant to mimic the character streams, so, technically, there should't be anything new to learn. > > doesn't give many functions, I cant even seem to find how to write to > > a file. > > The functions are, like in python, contained in libraries. You need > documentation for the standard C++ library. For file handling look at > the streams library(obviously! :-) or use the old C stdio library. There's an fairly good C++ reference out there from Dinkumware: http://www.dinkumware.com/refxcpp.html What we want to use for file input and output is probably the 'fstream' library, which provides 'file streams' that are similar to the 'cin' and 'cout' objects that we're accustomed to in C++. For example, here is a C++ program that uses a output file stream to write something out: ////// #include void main() { ofstream out("test_fstream.txt"); out << "Hello world!\n"; out.close(); } /////// And just to make sure this post is somewhat relevant to Python, here's equivalent Python code for comparison's sake: ### if __name__ == '__main__': out = open("test_fstream.txt", "w") out.write("Hello world!\n") out.close() ### So, even in C++, simple file input and output is very possible. If you're going to do C++ seriously, you really should feel comfortable with the stream libraries. The 'strstream' library is especially important, since it's one of the main ways of converting between strings and other C++ values. You should probably ask more questions on a C++ specific newsgroup or mailing list. The 'comp.lang.c++' newsgroup is a good one that should help fill the gaps in your book knowledge. There's also a lot of good knowledge in the C++ faqs: http://www.faqs.org/faqs/by-newsgroup/comp/comp.lang.c++.html I hope this helps. Good luck! From dyoo@hkn.eecs.berkeley.edu Fri Nov 15 16:57:12 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Nov 15 16:57:12 2002 Subject: [Tutor] Re: catching any exception? In-Reply-To: <5036985.1037372399@[10.0.1.5]> Message-ID: > >>> myException = 'my sample exception' > >>> try: > ... raise myException > ... except Exception, thisException: > ... print 'got (%s, %s)' % (Exception, thisException) > ... raise Exception(thisException, 'sql here') > ... > Traceback (most recent call last): > File "", line 2, in ? > my sample exception > > See, "myException" was not caught. How can I catch all exceptions, > including the ones that DCOracle defines? Hi Lance, A "catchall" kind of try/except should do the trick, even if we use the deprecated string exceptions: ### >>> try: ... raise "Oh no!" ... except: ... print "Gotcha!" ... Gotcha! ### Jeff Shannon mentioned that the 'traceback' module provides a way to access the exception at this stage: http://www.python.org/doc/lib/module-traceback.html Let's see what happens when a string exception is being handled: ### >>> try: ... raise "Oh no!" ... except: ... print "Gotcha!" ... traceback.print_exc() ... Gotcha! Traceback (most recent call last): File "", line 2, in ? Oh no! ### > For that matter, how can I create an exception that's just like a > "standard" exception? I think that's part of the problem. The string > type of exception that DCOracle defines doesn't have Exception as a > parent. According to the Library documentation, we should try to subclass 'Exception' so that it fits with the rest of the standard exceptions: http://www.python.org/doc/lib/module-exceptions.html Good luck! From thomi@thomi.imail.net.nz Fri Nov 15 17:11:30 2002 From: thomi@thomi.imail.net.nz (Thomi Richards) Date: Fri Nov 15 17:11:30 2002 Subject: [Tutor] Tkinter problems In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB21877A51A@mbtlipnt02.btlabs.bt.co.uk> References: <5104D4DBC598D211B5FE0000F8FE7EB21877A51A@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <20021116111044.4802c270.thomi@thomi.imail.net.nz> thanks for that,. this is all new to me . -- "Avoid the Gates of Hell. Use Linux" Thomi Richards, thomi@imail.net.nz From magnus@thinkware.se Fri Nov 15 17:36:31 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Fri Nov 15 17:36:31 2002 Subject: [Tutor] Tkinter problems In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB21877A51A@mbtlipnt02.btlabs .bt.co.uk> Message-ID: <5.1.0.14.0.20021115233033.00bc4a18@www.thinkware.se> At 18:44 2002-11-15 +0000, alan.gauld@bt.com wrote: > > finally, how the hell are you meant to do anything, if the mainloop > > function hangs? Hm... I missed this in the original post. Through functions that are bound to events! >You can't, its dead. Fortunately it hardly ever hangs in practice! Alan, I think the original poster is confused by the fact that the mainloop never seems to get done. (Right?) This is just as it should be. The main loop is acting just as it should. Waiting for events to be processed. It will normally continue to do this until you stop the program. In an event loop (Alan knows this very well, it's one of the first things in his book) you don't write a sequence of operations as in "normal" (or should I write batch-oriented) programs. In event-oriented programs, where you use an event loop, you set things up, and hand over command to the event loop. There are two kinds of set-up. You initialize things, like creating an initial window and running whatever code you like before you call the event loop. You also bind functions to events. This is all you do. Once the event loop has started, all your code will run because events happen and trigger the functions you bound to it. If you have some kind of linear program flow that should take place in parallel with the event handling, you might run this in another thread or process. You might also bind things to events such as an "idle event". -- 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 thomi@thomi.imail.net.nz Fri Nov 15 17:59:02 2002 From: thomi@thomi.imail.net.nz (Thomi Richards) Date: Fri Nov 15 17:59:02 2002 Subject: [Tutor] Tkinter problems In-Reply-To: <5.1.0.14.0.20021115233033.00bc4a18@www.thinkware.se> References: <5104D4DBC598D211B5FE0000F8FE7EB21877A51A@mbtlipnt02.btlabs.bt.co.uk> <5.1.0.14.0.20021115233033.00bc4a18@www.thinkware.se> Message-ID: <20021116115801.3528a3be.thomi@thomi.imail.net.nz> OK, I've managed to sort it out, i think. if i get stuck, Maybe I'll post some code from the project... thanks. -- This is a subliminal message. Thomi Richards, thomi@imail.net.nz From magnus@thinkware.se Fri Nov 15 18:07:03 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Fri Nov 15 18:07:03 2002 Subject: [Tutor] getting started In-Reply-To: <3DD542D1.9010605@aon.at> References: <5104D4DBC598D211B5FE0000F8FE7EB21877A518@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <5.1.0.14.0.20021115234305.02b11ad0@www.thinkware.se> At 19:54 2002-11-15 +0100, Gregor Lingl wrote: >alan.gauld@bt.com schrieb: > >>>If you are really desperate to run a few lines at once >>>in interactive mode, you can do this with a little trick: >>> >>> >>> if 1 == 1: >>> print "aaa" >>> print "bbb" >>> print "ccc" >> >>I like it Magnus! I hadn't thought of that before... :) Even if Python is easy to learn, we can always learn more things. There's no end to the fun! I've seen the "if 1:" or "if 0:" construct here and there in code to make it easy to switch blocks in and out during testing and debugging. An alternative to commenting out code I guess. >Me too! But why not > > >>> if 1: > print "aaa" > print "bbb" Actually, this is what I would do myself, but it seemed more obvious that "if 1==1:" has to be true every time. "if 1:" assumes that you understand Python's notion about true and false, and I didn't want to explain too many concepts at the same time. (I did mention it in the end of the mail though...) While (heh?) we're at it, it's a common Python idiom to code like this: while 1: bla bla if some_condition: break maybe more bla bla bla This corresponds more or less to do { bla; } while condition; in C and derivates or repeat bla; bla; until condition; in Pascal and its derivates. It is sometimes argued that Python should have such a construct, so that we could stop this "while 1:" lie. (We don't intend to run the loop for ever, so why claim that?) I think the reason that this hasn't happened is that it can't be done in a pretty way in Python. The clear and consistent block structure by indentaion would be broken if we did: do: bla bla while x since that last line shouldn't be in the loop. And if we did do: bla bla while x we would also get confusing and ugly code. First of all, the while statement doesn't stick out much. But secondly, you could also want to do: do: bla bla while x: foo() bar() while y Now it starts to look wierd, and if you happen to forget the colon after the x, you will probably get a very confusing error message from the poor interpreter, which thinks that the indentation is incorrect in the "foo()" line. I bet that a proposal to introduce either of these syntaxes would have a more or less equal following of people who would prefer it the other way around. I also think that the majority would agree that this very disagreement shows us that do/while doesn't really fit smoothly into Python. Conceptually, it's a typical feature of Python that block just end, without any particular ta-da in the end. No "}" and no "end;". The do/while or repeat/until idiom seems to go against 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 thomi@thomi.imail.net.nz Fri Nov 15 18:13:03 2002 From: thomi@thomi.imail.net.nz (Thomi Richards) Date: Fri Nov 15 18:13:03 2002 Subject: [Tutor] Re: hex to decimal conversion. In-Reply-To: <20021115213543.GA9455@dman.ddts.net> References: <5104D4DBC598D211B5FE0000F8FE7EB21877A519@mbtlipnt02.btlabs.bt.co.uk> <20021115213543.GA9455@dman.ddts.net> Message-ID: <20021116121223.1863cb93.thomi@thomi.imail.net.nz> i think this pretty much sums up my frustrations: >>> pal.data[0] '\xff' >>> print pal.data[0] ÿ >>> print '%i' % (pal.data[0]) Traceback (most recent call last): File "", line 1, in ? TypeError: an integer is required >>> print '%i' % (int(pal.data[0])) Traceback (most recent call last): File "", line 1, in ? ValueError: invalid literal for int(): ÿ >>> int(pal.data[0],16) Traceback (most recent call last): File "", line 1, in ? ValueError: invalid literal for int(): ÿ >>> _what_ am i doing wrong here? i can't see anything wrong for the life of me. It seems the pythonware people use a non-standard format for hex numbers. any ideas? -- Thomi Richards thomi@imail.net.nz http://thomi.imail.net.nz/ Thomi Richards, thomi@imail.net.nz From ramrom@earthling.net Fri Nov 15 18:20:02 2002 From: ramrom@earthling.net (Bob Gailer) Date: Fri Nov 15 18:20:02 2002 Subject: [Tutor] Re: hex to decimal conversion. In-Reply-To: <20021116121223.1863cb93.thomi@thomi.imail.net.nz> References: <20021115213543.GA9455@dman.ddts.net> <5104D4DBC598D211B5FE0000F8FE7EB21877A519@mbtlipnt02.btlabs.bt.co.uk> <20021115213543.GA9455@dman.ddts.net> Message-ID: <5.2.0.9.0.20021115161756.019bfd98@66.28.54.253> At 12:12 PM 11/16/2002 +1300, Thomi Richards wrote: > >>> pal.data[0] >'\xff' Try pal.data[0] = 0xff. That's the python way to write a hex literal. Bob Gailer 170 Forsythe Rd Nederland CO 80466 303-442-2625 From zswongg@hotmail.com Fri Nov 15 20:11:01 2002 From: zswongg@hotmail.com (Wong Zhee Shiong) Date: Fri Nov 15 20:11:01 2002 Subject: [Tutor] how to redirect sys.__stdout__ back to screen in IDLE Message-ID: Hi All, I was fiddling IDLE (Python2.2, OS:Win32) with >>>import sys >>>sys.stdout=open('t1.txt','w') >>>1+1 >>>sys.stdout.close() >>>sys.stdout=sys.__stdout__ >>>print 'hello world' ..... Complaining I/O Errors... I can't seem to get back to screen output after that, does anyone know how to redirect it back to screen? Thanks, wong _________________________________________________________________ Add photos to your messages with MSN 8. Get 2 months FREE*. http://join.msn.com/?page=features/featuredemail From Don Arnold" Message-ID: <01d601c28d14$a75b8350$a411ba3f@defaultcomp> ----- Original Message ----- From: "Wong Zhee Shiong" To: Sent: Friday, November 15, 2002 7:10 PM Subject: [Tutor] how to redirect sys.__stdout__ back to screen in IDLE > > Hi All, > > I was fiddling IDLE (Python2.2, OS:Win32) with > >>>import sys > >>>sys.stdout=open('t1.txt','w') > >>>1+1 > >>>sys.stdout.close() > >>>sys.stdout=sys.__stdout__ > >>>print 'hello world' > ..... Complaining I/O Errors... > > I can't seem to get back to screen output after that, > does anyone know how to redirect it back to screen? > > Thanks, > wong > I think you want to save a reference to the original value of sys.stdout before you reassign it. This seems to work: >>> import sys >>> savestdout = sys.stdout >>> sys.stdout=open('d:/python22/mystuff2/junk.txt','w+') >>> print 'hello there!' >>> sys.stdout.close() >>> sys.stdout = savestdout >>> print 'hello!' hello! >>> HTH, Don From glingl@aon.at Sat Nov 16 01:07:01 2002 From: glingl@aon.at (Gregor Lingl) Date: Sat Nov 16 01:07:01 2002 Subject: [Tutor] getting started References: <5104D4DBC598D211B5FE0000F8FE7EB21877A518@mbtlipnt02.btlabs.bt.co.uk> <5.1.0.14.0.20021115234305.02b11ad0@www.thinkware.se> Message-ID: <3DD5E075.608@aon.at> Magnus Lycka schrieb: > At 19:54 2002-11-15 +0100, Gregor Lingl wrote: > >> alan.gauld@bt.com schrieb: >> >>>> If you are really desperate to run a few lines at once >>>> in interactive mode, you can do this with a little trick: >>>> >>>> >>> if 1 == 1: >>>> print "aaa" >>>> print "bbb" >>>> print "ccc" >>> >>> >>> I like it Magnus! I hadn't thought of that before... >> > > :) Even if Python is easy to learn, we can always learn more > things. There's no end to the fun! Hi Magnus! Thanks for your interesting and lucid comments - they are always worth reading, even if lengthy. > > > I've seen the "if 1:" or "if 0:" construct here and there in > code to make it easy to switch blocks in and out during testing > and debugging. An alternative to commenting out code I guess. > >> Me too! But why not >> >> >>> if 1: >> print "aaa" >> print "bbb" > > > Actually, this is what I would do myself, but it seemed more > obvious that "if 1==1:" has to be true every time. "if 1:" > assumes that you understand Python's notion about true and > false, and I didn't want to explain too many concepts at the > same time. (I did mention it in the end of the mail though...) I missed that! Sorry. Nevertheless: if you write if 1==1: don't you suppose this to be easier to understand than if 0==0: (or: if 6==6:)? So, apparently, you assume that the reader knows, that 1 means True in Python. IMO it's worth to try to avoid, that beginners develop the often seen habit of using idioms like if done == 1: versus if done == 0: etc. Just a tiny remark. I think, to a large extent it's a matter of taste. Regards, Gregor From johnca@ourpla.net Sat Nov 16 04:15:02 2002 From: johnca@ourpla.net (John Abbe) Date: Sat Nov 16 04:15:02 2002 Subject: [Tutor] Regexes -- \b ; re.sub Message-ID: Can someone explain to me why this... import re matches = re.search (re.compile ("(.)\b(.)"), "spam and eggs are yummy") if matches: print matches.groups() else: print "no match" ...prints out "no match", and this... print re.sub (re.compile ("(i)"), "o\1o", "i like eggs and spam") ...prints out "oo looke eggs and spam" -- shouldn't it be "oio loioke eggs and spam", after all this... print re.search (re.compile ("(i)"), "i like eggs and spam").group(1) ...prints out "i" Mucho 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://www.ourpla.net/john/ --Wes Nisker From magnus@thinkware.se Sat Nov 16 04:33:02 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Sat Nov 16 04:33:02 2002 Subject: [Tutor] Re: hex to decimal conversion. In-Reply-To: <20021116121223.1863cb93.thomi@thomi.imail.net.nz> References: <20021115213543.GA9455@dman.ddts.net> <5104D4DBC598D211B5FE0000F8FE7EB21877A519@mbtlipnt02.btlabs.bt.co.uk> <20021115213543.GA9455@dman.ddts.net> Message-ID: <5.1.0.14.0.20021116100531.02ab4258@www.thinkware.se> At 12:12 2002-11-16 +1300, Thomi Richards wrote: >i think this pretty much sums up my frustrations: Aha. Examples are always good. Now it's clear what you haven't understood. > >>> pal.data[0] >'\xff' That's the representation (i.e. result of repr() call) for a *string* object, nothing else. Note the single quotes surrounding the value. pal.data[0] does NOT contain a "hexadecimal vaule" it contains a one character string. Since values outside the range of printable characters in ASCII are represented differently depending on platform and national settings (we ignore EDCBIC for now) characters outside that range is *represented* like hexadecimal sequences. >>> a =3D '=C5' >>> print a =C5 >>> a '\xc5' This is to make sure that it's possible to transfer data verbatim from one environment to another etc. (The value in the assignment above should be an A with a ring over it. It might not look like that when the mail arrives to you depending on your settings or mail systems on the way to you, but I'm pretty sure the hex value on the last row, \xc5, will look the same...) There *is* no such thing as hexadecimal objects. Hexadecimal, decimal or octal, are just different ways of entering or displaying *integer* (or long integer) values. > >>> print pal.data[0] >=FF This is how the value 255 (or FF in hex) is shown in the Latin-1 (and some other?) code pages. > >>> print '%i' % (pal.data[0]) >Traceback (most recent call last): > File "", line 1, in ? >TypeError: an integer is required Same as if you would do "print '%i' % 'X' > >>> print '%i' % (int(pal.data[0])) >Traceback (most recent call last): > File "", line 1, in ? >ValueError: invalid literal for int(): =FF Same as if you would do "print '%i' % int('X') > >>> int(pal.data[0],16) >Traceback (most recent call last): > File "", line 1, in ? >ValueError: invalid literal for int(): =FF Same as if you would do "print '%i' % int('X', 16) A string describing hex that you convert to integer can only contain digits or a-f (or A-F). Not =FF. Right? >_what_ am i doing wrong here? You haven't studied the builtin functions in python! ;) Read through that little chapter in the Python Library Reference (2.1). Pay special attention to the functions ord() "ordinal" and it's inverse chr() "character", but learning most of the functions is a good thing. :) >>> a =3D '=FF' >>> a '\xff' >>> print a =FF >>> ord(a) 255 >>> print "%i" % ord(a) 255 >>> print "%o" % ord(a) 377 >>> print "%x" % ord(a) ff >>> print "%X" % ord(a) FF >>> a =3D=3D chr(ord(a)) 1 >>> for i in range(256): ... print i, chr(i), repr(chr(i)) ... --=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 Sat Nov 16 05:07:02 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Sat Nov 16 05:07:02 2002 Subject: [Tutor] getting started In-Reply-To: <3DD5E075.608@aon.at> References: <5104D4DBC598D211B5FE0000F8FE7EB21877A518@mbtlipnt02.btlabs.bt.co.uk> <5.1.0.14.0.20021115234305.02b11ad0@www.thinkware.se> Message-ID: <5.1.0.14.0.20021116110923.02a210f8@www.thinkware.se> At 07:06 2002-11-16 +0100, Gregor Lingl wrote: >Nevertheless: if you write >if 1==1: >don't you suppose this to be easier to understand than >if 0==0: >(or: if 6==6:)? So, apparently, you assume that the reader knows, >that 1 means True in Python. I just tried to assume as little as possible. >IMO it's worth to try to avoid, that beginners develop the often >seen habit of using idioms like >if done == 1: versus if done == 0: etc. Agreed. if hasFoo(): doThat() is better than if hasFoo() == 1: do 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 ramrom@earthling.net Sat Nov 16 06:41:02 2002 From: ramrom@earthling.net (Bob Gailer) Date: Sat Nov 16 06:41:02 2002 Subject: [Tutor] creating a non-COM DLL In-Reply-To: <002801c28d18$2b686a70$3212eb42@MYNEWBOX> References: <5.2.0.9.0.20021115134039.0331ae50@66.28.54.253> Message-ID: <5.2.0.9.0.20021116041758.01b0a0d8@66.28.54.253> --=====================_2203899==.ALT Content-Type: text/plain; charset="us-ascii"; format=flowed > > >I want to create a simple non-COM dll that I will call from a third > party program. > > > > How timely. I have the same need. I've wandered around in various > > documentation, but have yet to fine a sample python program for this > purpose. > > > > It's my intention to call the dll from MS Visual FoxPro. Why, you ask? I > > have an intention of converting a large VFP application to Python, with > > some GUI yet to be determined. I want to convert chunks of VFP code that > > run behind the scenes to python; eventually VFP will just manage the GUI; > > then I can redo the GUI. I've done more research; found help in ActiveState's ActivePython distribution documentation and its win32com/servers sample code. I realize that this creates a COM object rather than a non-COM dll, but that's OK for my purposes. Article Quick Start to Server Side COM and Python provides a simple program (which I've modified), with a good discussion of the various components : ---------------------------------------------------------------------------------------------- class HelloWorld: _reg_clsid_ = '{BEA1AA48-1D0A-4D19-8E98-03C54F195B59}' _reg_desc_ = "Python Test COM Server" _reg_progid_ = "Python.TestServer" _public_methods_ = ['Hello'] _public_attrs_ = ['softspace', 'noCalls'] _readonly_attrs_ = ['noCalls'] def __init__(self): self.softspace = 1 self.noCalls = 0 def Hello(self, arg1): return arg1 * 5 if __name__=='__main__': import win32com.server.register win32com.server.register.UseCommandLine(HelloWorld) ---------------------------------------------------------------------------------------- To obtain a unique clsid: >>> import pythoncom >>> print pythoncom.CreateGuid() # different each time {7CC9F362-486D-11D1-BB48-0000E838A65F} ---------------------------------------------------------------------------------------- In Visual FoxPro: o = createobject("Python.TestServer") with o ?.hello(5) && displays 25 ?.softspace && displays 1 .softspace = 2 && updates attribute endwith I discovered that VFP seems to cache the COM object; editing and re-registering the Python program has no effect until one closes and re-opens VFP. WIFNI Python had a "with" statement. I know its been discussed a lot, but I still like it. In VB: set o = createobject("Python.TestServer") Other languages?? Bob Gailer 170 Forsythe Rd Nederland CO 80466 303-442-2625 --=====================_2203899==.ALT Content-Type: text/html; charset="us-ascii"
> >I want to create a simple non-COM dll that I will call from a third party program.
>
> How timely. I have the same need. I've wandered around in various
> documentation, but have yet to fine a sample python program for this purpose.
>
> It's my intention to call the dll from MS Visual FoxPro. Why, you ask? I
> have an intention of converting a large VFP application to Python, with
> some GUI yet to be determined. I want to convert chunks of VFP code that
> run behind the scenes to python; eventually VFP will just manage the GUI;
> then I can redo the GUI.

I've done more research; found help in ActiveState's ActivePython distribution documentation and its win32com/servers sample code. I realize that this creates a COM object rather than a non-COM dll, but that's OK for my purposes. Article

Quick Start to Server Side COM and Python provides a simple program (which I've modified), with a good discussion of the various components

:
----------------------------------------------------------------------------------------------
class HelloWorld:
  _reg_clsid_ = '{BEA1AA48-1D0A-4D19-8E98-03C54F195B59}'
  _reg_desc_ = "Python Test COM Server"
  _reg_progid_ = "Python.TestServer"
  _public_methods_ = ['Hello']
  _public_attrs_ = ['softspace', 'noCalls']
  _readonly_attrs_ = ['noCalls']
 
  def __init__(self):
    self.softspace = 1
    self.noCalls = 0

  def Hello(self, arg1):
    return arg1 * 5

if __name__=='__main__':
  import win32com.server.register
  win32com.server.register.UseCommandLine(HelloWorld)
----------------------------------------------------------------------------------------
To obtain a unique clsid:
>>> import pythoncom
>>> print pythoncom.CreateGuid() # different each time
{7CC9F362-486D-11D1-BB48-0000E838A65F}
----------------------------------------------------------------------------------------
In Visual FoxPro:
    o = createobject("Python.TestServer")
    with o
      ?.hello(5) && displays 25
      ?.softspace && displays 1
      .softspace = 2 && updates attribute
    endwith
I discovered that VFP seems to cache the COM object; editing and re-registering the Python program has no effect until one closes and re-opens VFP. WIFNI Python had a "with" statement. I know its been discussed a lot, but I still like it.

In VB:
   set o = createobject("Python.TestServer")

Other languages??

Bob Gailer
170 Forsythe Rd
Nederland CO 80466
303-442-2625 --=====================_2203899==.ALT-- From emile@fenx.com Sat Nov 16 11:32:01 2002 From: emile@fenx.com (Emile van Sebille) Date: Sat Nov 16 11:32:01 2002 Subject: [Tutor] Re: Regexes -- \b ; re.sub References: Message-ID: John Abbe: > Can someone explain to me why this... Use raw strings to allow re to be passed the \'s. > > import re > matches = re.search (re.compile ("(.)\b(.)"), "spam and eggs are yummy") try with :... r("(.)\b(.)"), ... > if matches: > print matches.groups() > else: > print "no match" > > ...prints out "no match", and this... > > print re.sub (re.compile ("(i)"), "o\1o", "i like eggs and spam") try again with r"o\1o" HTH, -- Emile van Sebille emile@fenx.com --------- From mark.brown@rogers.com Sat Nov 16 12:04:04 2002 From: mark.brown@rogers.com (Mark Brown) Date: Sat Nov 16 12:04:04 2002 Subject: [Tutor] Any Suggestions? Message-ID: <1037466328.1475.12.camel@localhost.localdomain> Hello, I'm just learning Python and would appreciate any suggestions regarding the programs listed below. The programs do function. runit2.py #!/usr/bin/env python import runit2tk from os import system from sys import exit gui1 = runit2tk.Gui1() gui1.mainloop() if gui1.text != "": command = "%s &" % gui1.text system(command) exit(0) runit2tk.py #!/usr/bin/env python import Tkinter class Gui1: def __init__(self, text=""): self.text = text self.root = Tkinter.Tk() self.root.title('PyRun') self.label = Tkinter.Label(self.root, text="Run") self.label.pack(side="left") self.entry = Tkinter.Entry(self.root, takefocus="true") self.entry.pack(side="left", fill="x", expand="true") self.entry.bind('', self.getinput) self.entry.focus() def mainloop(self): self.root.mainloop() def getinput(self, event): self.text = self.entry.get() self.root.destroy() return self.text Thanks Mark Brown From emile@fenx.com Sat Nov 16 12:20:03 2002 From: emile@fenx.com (Emile van Sebille) Date: Sat Nov 16 12:20:03 2002 Subject: [Tutor] Re: Regexes -- \b ; re.sub References: Message-ID: Emile van Sebille: > > try with :... r("(.)\b(.)"), ... > oops... bad cut-n-paste... s/b: ... r"(.)\b(.)"), ... -- Emile van Sebille emile@fenx.com --------- From magnus@thinkware.se Sat Nov 16 13:22:02 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Sat Nov 16 13:22:02 2002 Subject: [Tutor] Regexes -- \b ; re.sub In-Reply-To: Message-ID: <5.1.0.14.0.20021116184400.02b240e0@www.thinkware.se> At 15:09 2002-11-16 +0630, John Abbe wrote: >matches = re.search (re.compile ("(.)\b(.)"), "spam and eggs are yummy") I've never seen anyone send a regular expression object to re.search like that before. I didn't even know it was possible. The manual doesn't say that it's permitted as far as I understand. re.search takes a *pattern* as it's first parameter. A pattern is a string. The result of compiling a pattern with re.compile is called a regular expression object. Calling functions with undocumented types like this might break in a future release. (It's happened before.) You can either write: pattern = re.compile(r"(.)\b(.)") matches = pattern.search("spam and eggs are yummy") or shorter matches = re.compile(r"(.)\b(.)").search("spam and eggs are yummy") or use the re.search function with an (uncompiled) pattern. matches = re.search(r"(.)\b(.)", "spam and eggs are yummy") (Note the r"" for raw string. \b in a string means backspace. The alternative to a raw string is to write "(.)\\b(.)") Then you get >>> print matches.groups() ('m', ' ') which is correct. I'm not sure why you called your match object "matches". If you want to find all non-overlapping you could use re.findall(pattern, text) or re.compile(pattern).findall(text) >print re.sub (re.compile ("(i)"), "o\1o", "i like eggs and spam") > >...prints out "oo looke eggs and spam" -- shouldn't it be "oio loioke eggs >and spam", after all this... Actually, it doesn't... But you need raw strings again. >>> print re.sub (re.compile ("(i)"), "o\1o", "i like eggs and spam") oo looke eggs and spam There are actually \1 = chr(1) = ASCII value SOH between the "o"s. Maybe they don't show up in your environment. >>> print re.sub(re.compile ("(i)"), r"o\1o", "i like eggs and spam") oio loioke eggs and spam >>> print re.sub("(i)", r"o\1o", "i like eggs and spam") oio loioke eggs and spam >>> iPat = re.compile("(i)") >>> print iPat.sub(r"o\1o", "i like eggs and spam") oio loioke eggs and spam And please don't put a space between the function name and the leading parenthesis in you function calls. It's a good thing to follow the official Python style guide: http://www.python.org/peps/pep-0008.html -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From dyoo@hkn.eecs.berkeley.edu Sat Nov 16 14:37:01 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Nov 16 14:37:01 2002 Subject: [Tutor] count words [off-topic apology] In-Reply-To: Message-ID: On Thu, 14 Nov 2002, Danny Yoo wrote: > > > I'd like to count the number of times a letter occurs in a string. > > > I've been looking at c. It seems that this type of problem is being > > > assigned in cs classes on graduate and advanced undergraduate > > > classes in the US. > > You're grossly overestimating the problem, or greatly underestimating > the CS students in US colleges. > > Frequency counting is an introductory programming problem that shows how > useful loops and containers are. It's something that's easily done with > paper and pencil, and is even easier with the use of computers. Did I actually write that? Those two paragraphs above just stink of elitism. I have to apologize to everyone for the tone of my response. I don't know why I responded so badly to the question. It's just that seeing the phrase "advanced undergraduate" attached to that frequency-count question just got me into a blind rage. That's not a good reason though. I apologize for not controlling my emotions on that one, and if I came off smug, that's probably what I was feeling at the time. But now I'm feeling extremely embarassed for responding so badly. From dyoo@hkn.eecs.berkeley.edu Sat Nov 16 15:21:01 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Nov 16 15:21:01 2002 Subject: [Tutor] Re: clear screen [Let's make a feature request in Sourceforge!] In-Reply-To: <22583.1037270724@www40.gmx.net> Message-ID: On Thu, 14 Nov 2002 lumbricus@gmx.net wrote: > > class _cls: > > def __init__(self): > > if sys.platform in ('linux-i386', 'linux2'): > > self._command = 'clear' > > There are more UNICES than Linux. As I wrote in an earlier post IMHO > os.name is the better choice, because it just spits out 'posix' for all > the different UNICES out there. Yikes! Thanks for pointing that out. Ok, that's something I'll can fix. But I'm getting the feeling that this is a reimplementation of the platform-detection code that must exist somewhere in the 'distutils' though. I should take a closer look at it to see if I can dodge this whole platform-detection issue altogether... *grin* > > I can't confirm that it works on Win32 yet; can someone check this? > > Once it checks out ok, we can submit this to Python's sourceforge as a > > feature request. Who knows? It might get in... > > IMHO clearing the screen at the beginning of a console program is a bad > habit. You loose information and gain nothing. I understand what you mean. But the same time, though, I have fond memories of writing small games in Basic that used to clear the screen quite a bit! Memory card games, for example, are all about obscuring information. For very simple programs (especially games), being able to clear the screen would be helpful: it would allow beginners to write those kind of primitive user interfaces that we know are evil and crude, but are really easy to cook up. If 'curses' were more platform independent and less difficult to use for newcomers, this would be a nonissue; curses and its erase() method would be the right solution to clearing the console. But I feel that 'curses' has a complicated feel to it, and curses doesn't quite work out-of-the-box with Python on Windows systems yet. (I might be wrong about that last comment; does anyone know if the cygwin port works better at this?) Thanks for your help! From magnus@thinkware.se Sat Nov 16 18:46:02 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Sat Nov 16 18:46:02 2002 Subject: [Tutor] Re: clear screen [Let's make a feature request in Sourceforge!] In-Reply-To: References: <22583.1037270724@www40.gmx.net> Message-ID: <5.1.0.14.0.20021117004351.02b28a10@www.thinkware.se> At 12:20 2002-11-16 -0800, Danny Yoo wrote: >For very simple programs (especially games), being able to clear the >screen would be helpful: it would allow beginners to write those kind of >primitive user interfaces that we know are evil and crude, but are really >easy to cook up. Is this really helpful? :) (Don't give in to the dark side of the force...) Somehow, I feel the bad old platform dependent os.system('cls') or os.system('clear') is better. It doesn't pretend to be more than it is. I have a feeling that we can't avoid that clearing the screen IS platform dependent. Not only depending on your OS, but also on your execution environment. It's not the same if you are running your code from the command prompt or from within IDLE etc. Using os.system('cls') etc doesn't give any impression of being more than it is... :) >If 'curses' were more platform independent and less difficult to use for >newcomers, this would be a nonissue; curses and its erase() method would >be the right solution to clearing the console. Agreed. Or if GUIs were more newbie-friendly, that could be the right path. It's obvious that many newbies want (and expect to be able) to write GUIs more or less at once. Perhaps we will have a big gap here until someone creates something like Delphi or Visual Basic for 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 fleet@teachout.org Sat Nov 16 22:48:04 2002 From: fleet@teachout.org (fleet@teachout.org) Date: Sat Nov 16 22:48:04 2002 Subject: [Tutor] while with function Message-ID: I've written a function getnum() def getnum() x=int(raw_input("get number: ") return x I'm trying to control a while loop as follows: y=0 while y==0: y=getnum() print y No matter what number I enter in response to getnum(), the while loop prints y then quits. My assumption is that if the number I enter in response to getnum() is 0, y should be printed, and getnum() should be invoked again. Any number other than 0 should cause the loop to quit. Where am I going wrong? - fleet - From darnold02@sprynet.com Sat Nov 16 23:06:01 2002 From: darnold02@sprynet.com (Don Arnold) Date: Sat Nov 16 23:06:01 2002 Subject: [Tutor] while with function References: Message-ID: <033601c28dee$9edcab70$a411ba3f@defaultcomp> ----- Original Message ----- From: To: "python tutor list" Sent: Saturday, November 16, 2002 9:46 PM Subject: [Tutor] while with function > I've written a function getnum() > > def getnum() > x=int(raw_input("get number: ") > return x > > I'm trying to control a while loop as follows: > > y=0 > while y==0: > y=getnum() > print y > > No matter what number I enter in response to getnum(), the while loop > prints y then quits. My assumption is that if the number I enter in > response to getnum() is 0, y should be printed, and getnum() should be > invoked again. Any number other than 0 should cause the loop to quit. > > Where am I going wrong? > > - fleet - > I'm not sure that you are. It works fine for me: >>> def getnum(): x=int(raw_input('get number: ')) return x >>> y = 0 >>> while y == 0: y = getnum() print y get number: 0 0 get number: 0 0 get number: 4 4 >>> Can you cut + paste your python session so we can see exactly what's going on? Don From fleet@teachout.org Sat Nov 16 23:57:01 2002 From: fleet@teachout.org (fleet@teachout.org) Date: Sat Nov 16 23:57:01 2002 Subject: [Tutor] while with function In-Reply-To: <033601c28dee$9edcab70$a411ba3f@defaultcomp> Message-ID: Sigh. If one enters a non-zero number first, the tries again WITHOUT reinitializing y, it fails (because y no longer equals 0). (Where's the lid to my hole?!) Thanks for the response. - fleet - On Sat, 16 Nov 2002, Don Arnold wrote: > > ----- Original Message ----- > From: > To: "python tutor list" > Sent: Saturday, November 16, 2002 9:46 PM > Subject: [Tutor] while with function > > > > I've written a function getnum() > > > > def getnum() > > x=int(raw_input("get number: ") > > return x > > > > I'm trying to control a while loop as follows: > > > > y=0 > > while y==0: > > y=getnum() > > print y > > > > No matter what number I enter in response to getnum(), the while loop > > prints y then quits. My assumption is that if the number I enter in > > response to getnum() is 0, y should be printed, and getnum() should be > > invoked again. Any number other than 0 should cause the loop to quit. > > > > Where am I going wrong? > > > > - fleet - > > > > I'm not sure that you are. It works fine for me: > > >>> def getnum(): > x=int(raw_input('get number: ')) > return x > > >>> y = 0 > >>> while y == 0: > y = getnum() > print y > > get number: 0 > 0 > get number: 0 > 0 > get number: 4 > 4 > >>> > > Can you cut + paste your python session so we can see exactly what's going > on? > > Don > From glingl@aon.at Sun Nov 17 03:33:01 2002 From: glingl@aon.at (Gregor Lingl) Date: Sun Nov 17 03:33:01 2002 Subject: [Tutor] Images + Tkinter References: <20021116212021.GA22802@pumuckl.redwitz79.de> Message-ID: <3DD75426.5040806@aon.at> Hallo Hans, your example (see below) seems indeed to be very strange and counterintuitive. I can't explain it. But I made the following two observations: 1. The following code displays the rectangle but not the image: import Tkinter, from Tkconstants import * def window(tk): frame=Tkinter.Frame(tk) frame.pack() canvas=Tkinter.Canvas(frame,width=400,height=500) photo=Tkinter.PhotoImage(file="boat.gif") canvas.create_image(200, 250, image=photo) canvas.create_rectangle(10,20,30,40,fill="red") canvas.pack() button=Tkinter.Button(frame, text="EXIT", command=tk.destroy) button.pack() # tk.mainloop() # ????????????????????????? root = Tkinter.Tk() window(root) root.mainloop() 2. The following code displays the image: import Tkinter from Tkconstants import * def window(tk,photo): frame=Tkinter.Frame(tk) frame.pack() canvas=Tkinter.Canvas(frame,width=400,height=500) canvas.create_image(200, 250, image=photo) canvas.pack() button=Tkinter.Button(frame, text="EXIT", command=tk.destroy) button.pack() # tk.mainloop() # ????????????????????????? root = Tkinter.Tk() photo=Tkinter.PhotoImage(file="boat.gif") window(root, photo) root.mainloop() Does anybody know the secrets, which lie behind this mystery? Gregor Hans Gubitz schrieb: >Hello, > >tk.mainloop() seems to be not in the right place. But the gif will not >be shown, when I eliminate this line. > >Any hints? > > > >import Tkinter >from Tkconstants import * > >def window(tk): > frame=Tkinter.Frame(tk) > frame.pack() > canvas=Tkinter.Canvas(frame,width=400,height=500) > photo=Tkinter.PhotoImage(file="picture.gif") > canvas.create_image(200, 250, image=photo) > canvas.pack() > button=Tkinter.Button(frame, text="EXIT", command=tk.destroy) > button.pack() > > tk.mainloop() # ????????????????????????? > >root = Tkinter.Tk() >window(root) >root.mainloop() > > > >Hans Gubitz > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From glingl@aon.at Sun Nov 17 07:06:00 2002 From: glingl@aon.at (Gregor Lingl) Date: Sun Nov 17 07:06:00 2002 Subject: [Tutor] Images + Tkinter References: <20021116212021.GA22802@pumuckl.redwitz79.de> <3DD75426.5040806@aon.at> Message-ID: <3DD78602.7000806@aon.at> Martin v. Loewis has sent me the following explanation: Gregor Lingl writes: >> Does anybody know the secrets, which lie behind this mystery? > > When you drop the last reference to an Tkinter.Image object, the image is destroyed. So always keep a reference to an image that you want to use. Regards, Martin This means, for instance, that inserting a global statement solves the problem: import Tkinter from Tkconstants import * def window(tk): global photo #### SIC! frame=Tkinter.Frame(tk) frame.pack() canvas=Tkinter.Canvas(frame,width=400,height=500) canvas.pack() photo=Tkinter.PhotoImage(file="picture.gif") canvas.create_rectangle(10,20,30,40, fill="red") canvas.create_image(200, 250, image=photo) button=Tkinter.Button(frame, text="EXIT", command=tk.destroy) button.pack() root = Tkinter.Tk() window(root) root.mainloop() From iumarumo@eidosnet.co.uk Sun Nov 17 08:25:03 2002 From: iumarumo@eidosnet.co.uk (Ibraheem Umaru-Mohammed) Date: Sun Nov 17 08:25:03 2002 Subject: [Tutor] test - please ignore. Message-ID: <20021117132245.GB24071@btinternet.com> -- From schalla@vasoftware.com Sun Nov 17 08:28:02 2002 From: schalla@vasoftware.com (shobhan) Date: Sun Nov 17 08:28:02 2002 Subject: [Tutor] Python module for PVCS (Merant PVCS SCM) Message-ID: <3DD798EC.4060706@vasoftware.com> --------------060905070209010802000901 Content-Type: text/plain; charset=us-ascii; format=flowed Content-Transfer-Encoding: 7bit Hi Pythoners, Is there any Python module available for PVCS (Merants PVCS SCM). Or are there any links which can be helpful..?? Thanks in advance Regards Schalla --------------060905070209010802000901 Content-Type: text/html; charset=us-ascii Content-Transfer-Encoding: 7bit Hi Pythoners,

Is there any Python module available for PVCS (Merants PVCS SCM).
Or are there any links which can be helpful..??

Thanks in advance

Regards
Schalla

--------------060905070209010802000901-- From iumarumo@eidosnet.co.uk Sun Nov 17 08:28:13 2002 From: iumarumo@eidosnet.co.uk (Ibraheem Umaru-Mohammed) Date: Sun Nov 17 08:28:13 2002 Subject: [Tutor] Regexes -- \b ; re.sub In-Reply-To: References: Message-ID: <20021116113256.GV2807@micromuse.com> * John Abbe [2002-11-16 09:14]: > Can someone explain to me why this... > > import re > matches = re.search (re.compile ("(.)\b(.)"), "spam and eggs are yummy") > if matches: > print matches.groups() > else: > print "no match" > > ...prints out "no match", and this... > > print re.sub (re.compile ("(i)"), "o\1o", "i like eggs and spam") > > ...prints out "oo looke eggs and spam" -- shouldn't it be "oio loioke > eggs and spam", after all this... > > print re.search (re.compile ("(i)"), "i like eggs and spam").group(1) > > ...prints out "i" > ibz@ignoramus:$ ipython Python 2.2.1 (#1, Aug 30 2002, 12:15:30) Type "copyright", "credits" or "license" for more information. IPython 0.2.14pre33 -- An enhanced Interactive Python. ? -> Introduction to IPython's features. @magic -> Information about IPython's 'magic' @ functions. help -> Python's own help system. object? -> Details about 'object'. ?object also works, ?? prints more. In [1]: import re In [2]: re.compile("(.)\b(.)").search("spam and eggs are yummy") In [3]: re.compile(r"(.)\b(.)").search("spam and eggs are yummy") Out[3]: <_sre.SRE_Match object at 0x82c4720> In [4]: re.compile(r"(.)\b(.)").search("spam and eggs are yummy").groups() Out[4]: ('m', ' ') In [5]: re.compile("(i)").sub("o\1o", "i like eggs and spam") Out[5]: 'o\x01o lo\x01oke eggs and spam' In [6]: re.compile("(i)").sub(r"o\1o", "i like eggs and spam") Out[6]: 'oio loioke eggs and spam' In [7]: re.compile("(i)").search("i like eggs and spam").group(1) Out[7]: 'i' In [8]: ibz@ignoramus:$ > Mucho thanks...Life, > John Read the following: ,---- [ "The backslash plague" ] | http://py-howto.sourceforge.net/regex/node8.html `---- HTH, --ibz. From gubitz@netcologne.de Sun Nov 17 08:53:01 2002 From: gubitz@netcologne.de (Hans Gubitz) Date: Sun Nov 17 08:53:01 2002 Subject: [Tutor] Images + Tkinter In-Reply-To: <3DD78602.7000806@aon.at> References: <20021116212021.GA22802@pumuckl.redwitz79.de> <3DD75426.5040806@aon.at> <3DD78602.7000806@aon.at> Message-ID: <20021117140913.GA803@pumuckl.redwitz79.de> On Sun, Nov 17, 2002 at 01:05:22PM +0100, Gregor Lingl wrote: > Martin v. Loewis has sent me the following explanation: ... With this explanation I found two solutions: 1) import Tkinter from Tkconstants import * def fenster(tk): frame=Tkinter.Frame(tk) frame.pack() photo=Tkinter.PhotoImage(file="bluecher.gif") canvas=Tkinter.Canvas(frame,width=400,height=500,bg="blue") canvas.create_image(200, 250, image=photo) canvas.pack() button=Tkinter.Button(frame, text="EXIT", command=tk.destroy) button.pack() return photo tk = Tkinter.Tk() ergebnis=fenster(tk) tk.mainloop() 2) import Tkinter from Tkconstants import * class Application: def __init__(self, master): frame = Tkinter.Frame(master) frame.pack() self.photo=Tkinter.PhotoImage(file="bluecher.gif") # ^^^^ canvas=Tkinter.Canvas(frame, width=self.photo.width(), height=self.photo.height()) canvas.create_image(0,0,anchor=NW,image=self.photo) canvas.pack() button = Tkinter.Button(frame, text = "Ende", command = master.destroy) button.pack() tk = Tkinter.Tk() app = Application(tk) tk.mainloop() Thank you Hans -- Hans Gubitz From alan.gauld@bt.com Sun Nov 17 11:24:02 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun Nov 17 11:24:02 2002 Subject: [Tutor] getting started Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA53@mbtlipnt02.btlabs.bt.co.uk> Just to add a little background 'why' to Magnus' post... > repeat > bla; > bla; > until condition; > > in Pascal and its derivates. > > It is sometimes argued that Python should have such a construct, > so that we could stop this "while 1:" lie. (We don't intend to run > do: > bla > bla until x seems to work for me... Adds a new keyword that might break existing code tho'... I don't like having break in the middle of a loop as a normal idiom but OTOH I'm not strongly bothered about the lack of a repeat loop. The biggest reason for having such a construct is where you want to initialise things as part of the loop. With a while loop you almost repeat the body of the loop outside it: v = testvalue x = readVal() while x != v: x = readVal() Whereas with a do loop we get: do: x = readVal() until x == v This makes maintenance easier when the x assignment gets changed to something else. Meantime we use the bodge: while 1: x = readVal() if x == v: break This seems like one of the regular debates on the comp.lang.python newsgroup though... I got tired after the second time through and now ignore it and let my purist tendencies submerge under the weight of common practice! Alan G. From alan.gauld@bt.com Sun Nov 17 11:35:02 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun Nov 17 11:35:02 2002 Subject: [Tutor] Re: catching any exception? Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA54@mbtlipnt02.btlabs.bt.co.uk> > But I've noticed that the code only works for any of the "standard" > exceptions. If I define my own exception, which is what > DCOracle does, and raise that, it's not caught: > > >>> myException = 'my sample exception' String exceptions have been deprecated in Python since(I think) v2... But since many utilities etc use them... > See, "myException" was not caught. How can I catch all exceptions, > including the ones that DCOracle defines? try: # foo except: # now use traceback module to figure out what exactly got caught! a plain "except:" will catch any kind of exception. Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld@bt.com Sun Nov 17 11:44:01 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun Nov 17 11:44:01 2002 Subject: [Tutor] Images + Tkinter Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA55@mbtlipnt02.btlabs.bt.co.uk> > tk.mainloop() seems to be not in the right place. But the gif will not > be shown, when I eliminate this line. Do the other window elements work? I tried your code without the canvas and it worked fine without the tk.mainloop() line. What exactly happens? What happens if you leave the line in but delete the root.mainloop further down? Alan G. From alan.gauld@bt.com Sun Nov 17 11:45:03 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun Nov 17 11:45:03 2002 Subject: [Tutor] Re: hex to decimal conversion. Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA56@mbtlipnt02.btlabs.bt.co.uk> > | look at the string.atoi() function. > > Don't. That has been deprecated since 2.0. Instead look at the int() > built-in. You're right, I'd forgotten about the jazzed up int() funcion until I saw all the other replies... oops. Alan g From alan.gauld@bt.com Sun Nov 17 12:05:03 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun Nov 17 12:05:03 2002 Subject: [Tutor] how to redirect sys.__stdout__ back to screen in IDLE Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA57@mbtlipnt02.btlabs.bt.co.uk> > I was fiddling IDLE (Python2.2, OS:Win32) with >>> sys.stdout = open('test.txt','w') >>> print 'foobar' >>> sys.stdout.close() >>> sys.stdout = sys.__stdout__ >>> print 'foobar' foobar >>> Works for me OK. Interestingly I got all sorts of strange error messages when I tried to check sys.__stdout__ before reassigning it to sys.__stdout__ but after assignment it was OK... >>> sys.__stdout__ Traceback (most recent call last): File "", line 1, in ? ValueError: I/O operation on closed file >>> sys.stdout = sys.__stdout__ >>> print 'foo' foo >>> sys.__stdout__ ', mode 'w' at 0x973648> >>> I don't know why that was... if anyone has a reason I'm interested. Alan G From alan.gauld@bt.com Sun Nov 17 12:10:04 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun Nov 17 12:10:04 2002 Subject: [Tutor] Regexes -- \b ; re.sub Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA58@mbtlipnt02.btlabs.bt.co.uk> > import re > matches = re.search (re.compile ("(.)\b(.)"), "spam and eggs are yummy") re.search takes a regular expression string as its first parameter, you are passing a reglar expression bject. You should be able to do either of: > matches = re.search ("(.)\b(.)", "spam and eggs are yummy") OR > matches = re.compile ("(.)\b(.)").search("spam and eggs are yummy") The latter is easier to understand if written on two lines like: REobj = re.compile ("(.)\b(.)") REobj.search("spam and eggs are yummy") HTH, Alan G. From alan.gauld@bt.com Sun Nov 17 12:22:01 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun Nov 17 12:22:01 2002 Subject: [Tutor] Any Suggestions? Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA59@mbtlipnt02.btlabs.bt.co.uk> > I'm just learning Python and would appreciate any suggestions > regarding the programs listed below. The programs do function. > > runit2.py > #!/usr/bin/env python > > import runit2tk > from os import system > from sys import exit > > gui1 = runit2tk.Gui1() > gui1.mainloop() > > if gui1.text != "": > command = "%s &" % gui1.text > system(command) Why not just add an execute button to the GUI to do this? Then you can execute many comands instead of just one... > runit2tk.py > #!/usr/bin/env python > > import Tkinter > > class Gui1: > def __init__(self, text=""): > self.text = text > self.root = Tkinter.Tk() > self.root.title('PyRun') > self.label = Tkinter.Label(self.root, text="Run") > self.label.pack(side="left") > self.entry = Tkinter.Entry(self.root, takefocus="true") > self.entry.pack(side="left", fill="x", expand="true") > self.entry.bind('', self.getinput) > self.entry.focus() You could add a Text widget to capture the output of the executed command > > def mainloop(self): > self.root.mainloop() > > def getinput(self, event): > self.text = self.entry.get() > self.root.destroy() > return self.text returning a value from an event handler is pointless... Add your execution code here but use popen() instead of system() to capture the results and dump them into the Text widget Just some ideas. Assuming you want a GUI wrapper to a command interpreter... :-) Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From gubitz@netcologne.de Sun Nov 17 12:33:01 2002 From: gubitz@netcologne.de (Hans Gubitz) Date: Sun Nov 17 12:33:01 2002 Subject: [Tutor] Images + Tkinter In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA55@mbtlipnt02.btlabs.bt.co.uk> References: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA55@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <20021117174857.GA2202@pumuckl.redwitz79.de> The thread has moved to python-de. On Sun, Nov 17, 2002 at 04:44:06PM -0000, alan.gauld@bt.com wrote: > > tk.mainloop() seems to be not in the right place. But the gif will not > > be shown, when I eliminate this line. > > Do the other window elements work? > I tried your code without the canvas and it worked fine without the > tk.mainloop() line. > > What exactly happens? The image is not shown. Martin v. Loewis sent the explanation: >When you drop the last reference to an Tkinter.Image object, the image >is destroyed. So always keep a reference to an image that you want to >use. > >Regards, >Martin Gruß Hans -- Hans Gubitz From alan.gauld@bt.com Sun Nov 17 12:35:02 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun Nov 17 12:35:02 2002 Subject: [Tutor] Re: clear screen [Let's make a feature request in Sou rceforge!] Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA5A@mbtlipnt02.btlabs.bt.co.uk> > >primitive user interfaces that we know are evil and crude, > Somehow, I feel the bad old platform dependent > os.system('cls') or os.system('clear') is better. I'm with Magnus here. I think its important for newbie programmers to learn, quite early that platform issues make a difference and that you shouldn't assume that your users terminal will work the same as yours - even on the same OS. Thats why the os.name tests are spurious. I could be working on Linux via a teletype, in which case clear() won't do anything - but thats OK I guess... or I could be working on some exotic OS that runs multiple terminal sessions on one console, interleaved with each other(mainframe operations people know what I mean! :-) Clearing the screen with 24 new lines would be incredibly unfriendly since it would ose the interleaved data from the other sessions! Better to learn the hard way that some things are not to be taken for granted. If you need to know ask the user about their environment(through a config program maybe) or use the OS (termcap etc) to see whats possible. > Perhaps we will have a big gap here until someone > creates something like Delphi or Visual Basic for > Python. I love Delphi, but I think these IDEs steer beginners in lots of bad directions, not least in assuming that the world is a GUI place. Of course being pragmatic most of us do live in GUI land, but being able to lash a GUI screen together does not a programmer make and VB/Delphi put the focus on GUI design rather than program design - a bad thing IMHO. Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld@bt.com Sun Nov 17 12:41:01 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun Nov 17 12:41:01 2002 Subject: [Tutor] while with function Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA5B@mbtlipnt02.btlabs.bt.co.uk> Once I fixed the broken syntax: > def getnum(): ^ colon needed > x=int(raw_input("get number: ") ) ^ extra paren needed > return x > > y=0 > while y==0: > y=getnum() > print y It worked as expected. Alan G. From alan.gauld@bt.com Sun Nov 17 12:49:02 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun Nov 17 12:49:02 2002 Subject: [Tutor] Images + Tkinter Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA5C@mbtlipnt02.btlabs.bt.co.uk> > Martin v. Loewis has sent me the following explanation: > When you drop the last reference to an Tkinter.Image object, the image > is destroyed. So always keep a reference to an image that you > want to use. I feel stupid. I must be missing something... > def window(tk): > global photo #### SIC! > frame=Tkinter.Frame(tk) > frame.pack() > canvas=Tkinter.Canvas(frame,width=400,height=500) > canvas.pack() > photo=Tkinter.PhotoImage(file="picture.gif") > canvas.create_rectangle(10,20,30,40, fill="red") > canvas.create_image(200, 250, image=photo) Why doesn't this retain a reference to the image and stop it being dropped? > button=Tkinter.Button(frame, text="EXIT", command=tk.destroy) > button.pack() In fact all of these objects should go out of scope at the end of the function except for the fact they are parented on tk which is global. So why does the image die but not the button? Still confused. Alan G. From alan.gauld@bt.com Sun Nov 17 12:51:02 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun Nov 17 12:51:02 2002 Subject: [Tutor] Python module for PVCS (Merant PVCS SCM) Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA5D@mbtlipnt02.btlabs.bt.co.uk> 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_01C28E62.09086700 Content-Type: text/plain; charset="iso-8859-1" Is there any Python module available for PVCS (Merants PVCS SCM). Or are there any links which can be helpful..?? Not that I know of but you could control PVCS from Python using either the commandline interface from the os module or, on Windows, using COM automation via the winall package. What exactly are you trying to do? Alan G ------_=_NextPart_001_01C28E62.09086700 Content-Type: text/html; charset="iso-8859-1"

Is there any Python module available for PVCS (Merants PVCS SCM).
Or are there any links which can be helpful..??
 
Not that I know of but you could control PVCS from Python
using either the commandline interface from the os module
or, on Windows, using COM automation via the winall package. 
 
What exactly are you trying to do?
 
Alan G
------_=_NextPart_001_01C28E62.09086700-- From gmlloyd@onlink.net Sun Nov 17 14:10:02 2002 From: gmlloyd@onlink.net (gmlloyd) Date: Sun Nov 17 14:10:02 2002 Subject: [Tutor] label widgets: double buffering, clearing label text Message-ID: <3DD7E990.B0332213@onlink.net> Good afternoon. In "An Introduction to Tkinter", Fredrik Lundh states (section 30 on Labels): "Labels are used to display texts and images. The label widget uses double buffering, so you can update the contents at any time, without annoying flicker." http://www.pythonware.com/library/tkinter/introduction/label.htm#AEN5226 Does anyone know how to use label widgets in this way? How about simply clearing label widget text in order to update the text? thank you, Geoff Lloyd From dyoo@hkn.eecs.berkeley.edu Sun Nov 17 14:39:01 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Nov 17 14:39:01 2002 Subject: [Tutor] while with function In-Reply-To: Message-ID: On Sat, 16 Nov 2002 fleet@teachout.org wrote: > Sigh. If one enters a non-zero number first, the tries again WITHOUT > reinitializing y, it fails (because y no longer equals 0). (Where's the > lid to my hole?!) Hi Fleet, > > > My assumption is that if the number I enter in response to getnum() > > > is 0, y should be printed, and getnum() should be invoked again. > > > Any number other than 0 should cause the loop to quit. By the way, here's another way to write your loop: ### while 1: y = getnum() print y if y: break ### Good luck! From magnus@thinkware.se Sun Nov 17 15:08:01 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Sun Nov 17 15:08:01 2002 Subject: [Tutor] Images + Tkinter In-Reply-To: <20021117140913.GA803@pumuckl.redwitz79.de> References: <3DD78602.7000806@aon.at> <20021116212021.GA22802@pumuckl.redwitz79.de> <3DD75426.5040806@aon.at> <3DD78602.7000806@aon.at> Message-ID: <5.1.0.14.0.20021117211032.02b530b8@www.thinkware.se> At 15:09 2002-11-17 +0100, Hans Gubitz wrote: >With this explanation I found two solutions: >def fenster(tk): ... > return photo I find it a bit confusing that a function "fenster" (means window) that creates and populates a Frame would return a photo. If I hadn't seen this discussion and saw that in a program I'd wonder what this was about. (If you need to write a comment to explain why you do a strange thing, it's a good thing to think about changing the structure of the code instead...) >class Application: > def __init__(self, master): > frame = Tkinter.Frame(master) > frame.pack() > > self.photo=Tkinter.PhotoImage(file="bluecher.gif") ># ^^^^ This is what I would do. (Maybe I'd write a comment anyway.) -- 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 fleet@teachout.org Sun Nov 17 15:12:01 2002 From: fleet@teachout.org (fleet@teachout.org) Date: Sun Nov 17 15:12:01 2002 Subject: [Tutor] while with function In-Reply-To: Message-ID: On Sun, 17 Nov 2002, Danny Yoo wrote: > > By the way, here's another way to write your loop: > > ### > while 1: > y = getnum() > print y > if y: break > ### As I read this it means: if y is any number, exit the loop? How would that differ (in results) from y=getnum() without the loop? I like the concept of "while 1:" but I've had problems getting it to break properly. I suspect I'm having "scope" problems. The "real" problem is a list of variable that I want to display (preceded by numbers) possibly repeatedly for correction (in necessary). 1. Surname=whatever 2. Given Name=whatever 3. Nickname=whatever Enter variable number to make correction or "zero" to quit. Assuming the above text is in a function called get_list(), then while 1: opt=getnum() if opt==1: s_name=raw_input("Surname: ") get_list() elif opt==2: g_name=raw_input("Given Name: ") get_list() elif opt==3: n_name="raw_input("Nickname: ") get_list() elif opt==0: break Something like this, right? Regards, - fleet - From magnus@thinkware.se Sun Nov 17 15:29:02 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Sun Nov 17 15:29:02 2002 Subject: [Tutor] Images + Tkinter In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA5C@mbtlipnt02.btlabs .bt.co.uk> Message-ID: <5.1.0.14.0.20021117211504.02b52f70@www.thinkware.se> Speculation to follow... At 17:50 2002-11-17 +0000, alan.gauld@bt.com wrote: >I feel stupid. I must be missing something... Extensive expertise in the internals of Tcl/Tk? > > canvas.create_image(200, 250, image=photo) > >Why doesn't this retain a reference to the image and stop it >being dropped? I don't know. If you look in Tkinter.py, you see that it will be handed over to tk (if I understand this) with a call like this (in Canvas._create): return getint(apply( self.tk.call, (self._w, 'create', itemType) + args + self._options(cnf, kw))) The keyword argument "image=photo" is in kw. Python doesn't keep any reference to it. Does Tcl/Tk use some kind of weak reference? Obviously it will know what image to work with if the image object doesn't go out of scope. Maybe this has something to do with not leaking memory if you swap images? > > button=Tkinter.Button(frame, text="EXIT", command=tk.destroy) > > button.pack() > >In fact all of these objects should go out of scope at the end of >the function except for the fact they are parented on tk which is >global. So why does the image die but not the button? I'm not Tkinter expert, but I think it's basically the same as with wxPython. In that case there are C++ references that makes things live on even though the seem to have gone away in the Python code. Here there are "secret" things happening in Tcl/Tk I guess. This kind of magic sometimes cause newbies to get a very warped image of how classes work in Python, that you don't need to keep references to them, but just create and throw away. I think I whined about that some weeks ago on this very list... >Still confused. Not Python's fault! ;) Blame Osterhaut! :) -- 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 rickp@telocity.com Sun Nov 17 15:33:02 2002 From: rickp@telocity.com (Rick Pasotto) Date: Sun Nov 17 15:33:02 2002 Subject: [Tutor] while with function In-Reply-To: References: Message-ID: <20021117203229.GI2933@tc.niof.net> On Sun, Nov 17, 2002 at 03:09:54PM -0500, fleet@teachout.org wrote: > On Sun, 17 Nov 2002, Danny Yoo wrote: > > > > By the way, here's another way to write your loop: > > > > ### > > while 1: > > y = getnum() > > print y > > if y: break > > ### > > As I read this it means: if y is any number, exit the loop? No. It means "if y is true" which means "if y != 0". > How would that differ (in results) from y=getnum() without the loop? > > I like the concept of "while 1:" but I've had problems getting it to break > properly. I suspect I'm having "scope" problems. > > The "real" problem is a list of variable that I want to display (preceded > by numbers) possibly repeatedly for correction (in necessary). > > 1. Surname=whatever > 2. Given Name=whatever > 3. Nickname=whatever > > Enter variable number to make correction or "zero" to quit. > > Assuming the above text is in a function called get_list(), then > > while 1: > opt=getnum() > if opt==1: > s_name=raw_input("Surname: ") > get_list() > elif opt==2: > g_name=raw_input("Given Name: ") > get_list() > elif opt==3: > n_name="raw_input("Nickname: ") > get_list() > elif opt==0: > break > > Something like this, right? Why not: def get_name(prompt): return raw_input(prompt) while 1: opt = getnum() if opt == 1: s_name = get_name("Surname: ") elif opt == 2: g_name = get_name("Given Name: ") elif opt == 3: n_name = get_name("Nickname: ") else: break Note that this will break out of the while loop if any number other than 1, 2, or 3 is entered. That may not be what you want. -- "A promiscuous person is someone who is getting more sex than you are." -- Victor Lownes Rick Pasotto rickp@telocity.com http://www.niof.net From thomi@thomi.imail.net.nz Sun Nov 17 17:29:01 2002 From: thomi@thomi.imail.net.nz (Thomi Richards) Date: Sun Nov 17 17:29:01 2002 Subject: [Tutor] speeding code along Message-ID: <20021118112754.6d408753.thomi@thomi.imail.net.nz> hey guys, thanks for your previous help with hex and tKinter. I've got it finished now. My question is: How can i speed up the following code? take a look: it is called several thousand times, and i would like to speed it up just a little... it takes (on average) around 45 seconds for teh entire program to run, and this function is where 99% of the time is being spent. i checked with the profiler: ----------- #!/usr/bin/python2.2 import sys import os from math import sqrt from string import split import Image if __name__ == "__main__": print 'Please run the "convert.py" file. This file only contains the math algorithm to convert pixels to colors in the palette' sys.exit(0) def convert(filename,inpalette,extension='-converted'): convfile = Image.open('input/%s' % (filename)) if convfile.mode != 'RGB': temp = convfile.convert('RGB') convfile = temp del(temp) for x in range(convfile.size[0] - 1): for y in range(convfile.size[1] - 1): pixel = convfile.getpixel((x,y)) tempdistance = 6000 for color in inpalette: distance = sqrt( (color[0] - pixel[0])**2 + (color[1] - pixel[1])**2 + (color[2] - pixel[2])**2 ) if distance < tempdistance: tempdistance = distance tempcolor = color if tempdistance == 0: break convfile.putpixel((x,y),tempcolor) #now we save the file! convfile.save('output/%s%s.bmp' % (split(filename,'.')[0],extension)) return 0 ------------ thanks. I realise i could try writing it in C, but i thought maybe there were some things i am doing wrong in python.... -- Thomi Richards thomi@imail.net.nz http://ddmodd.sourceforge.net/ Thomi Richards, thomi@imail.net.nz From reavey@nep.net Sun Nov 17 18:57:02 2002 From: reavey@nep.net (reavey) Date: Sun Nov 17 18:57:02 2002 Subject: [Tutor] counting in a file Message-ID: <1037577263.3737.24.camel@localhost.localdomain> Sirs: I'm trying to count the number of times a word occurs in a file. I'm trying to do this using import sys,string z = open("filename","r") a = 0 while a<10: new = z.readline().strip() a = a+1 I'm using this method because readlines() produces an unacceptable list as my lines are long. Also, if I want to count the word "a" every word in the list with an "a" is counted for example "at","and" etc. I've tried to write the z.readline().strip() output to another file I open, but I can only write to a file using the type string. I like the way the strip function makes a multi element list. The new in the above code works, however, I end up with the last line that is converted to type(list). If I try to increment the variable new, type(list) I get a type mismatch. Thanks in advance for any suggestions. RE-v From magnus@thinkware.se Sun Nov 17 19:55:02 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Sun Nov 17 19:55:02 2002 Subject: Fwd: Re: [Tutor] Tkinter problems Message-ID: <5.1.0.14.0.20021118020140.03906610@www.thinkware.se> I think Thomi meant this for the list: >Date: Mon, 18 Nov 2002 11:33:02 +1300 >From: Thomi Richards >To: Magnus Lycka >Subject: Re: [Tutor] Tkinter problems > >is it possable to have a "percent-done" metre using Tkinter?? you know, >like the things you see in file download boxes. I know how far through >the operation i am, i guess i could just print "X% done", although that >may look a little silly.... > >-- >Thomi Richards >thomi@imail.net.nz >http://ddmodd.sourceforge.net/ >Thomi Richards, >thomi@imail.net.nz -- 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 Nov 17 20:07:02 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Sun Nov 17 20:07:02 2002 Subject: [Tutor] while with function In-Reply-To: References: Message-ID: <5.1.0.14.0.20021118021112.02b75108@www.thinkware.se> At 15:09 2002-11-17 -0500, fleet@teachout.org wrote: >I like the concept of "while 1:" but I've had problems getting it to break >properly. I suspect I'm having "scope" problems. Loops and if statements don't introduce new scopes as { } does in C etc. You only nest scopes with nested functions, nested classes, methods and lambdas. (I.e. if you type def, class or lambda inside a class or function.) -- 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 thomi@thomi.imail.net.nz Sun Nov 17 20:21:01 2002 From: thomi@thomi.imail.net.nz (Thomi Richards) Date: Sun Nov 17 20:21:01 2002 Subject: [Tutor] counting in a file In-Reply-To: <1037577263.3737.24.camel@localhost.localdomain> References: <1037577263.3737.24.camel@localhost.localdomain> Message-ID: <20021118142035.44e2ae48.thomi@thomi.imail.net.nz> > I'm using this method because readlines() > produces an unacceptable list as my lines are long. I'm pretty sure you could do this: (you are trying to count the number of _words_ ina file, right? infile = open('infile.txt') Nlines = 0 for line in infile.read(): Nlines+= len(string.strip(line)) print 'there are %d words in this file) % (Nlines) i haven't tried this out, but thats roughly how I would do it. then again, I'm still learning python, So there is probably a _much_ simpler way to do this :-) -- Lord, what fools these mortals be! -- midsummer nights dream. Thomi Richards, thomi@imail.net.nz From thomi@thomi.imail.net.nz Sun Nov 17 20:22:01 2002 From: thomi@thomi.imail.net.nz (Thomi Richards) Date: Sun Nov 17 20:22:01 2002 Subject: Fwd: Re: [Tutor] Tkinter problems In-Reply-To: <5.1.0.14.0.20021118020140.03906610@www.thinkware.se> References: <5.1.0.14.0.20021118020140.03906610@www.thinkware.se> Message-ID: <20021118141641.5ad3282d.thomi@thomi.imail.net.nz> > I think Thomi meant this for the list: oops, thanks :-) -- The software required Win95 or better, so I installed Linux. Thomi Richards, thomi@imail.net.nz From shalehperry@attbi.com Sun Nov 17 20:24:02 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Sun Nov 17 20:24:02 2002 Subject: [Tutor] speeding code along In-Reply-To: <20021118112754.6d408753.thomi@thomi.imail.net.nz> References: <20021118112754.6d408753.thomi@thomi.imail.net.nz> Message-ID: <200211171722.29277.shalehperry@attbi.com> The core of this function is a 3 deep nested loop so you have N * M * X=20 performance. Image manipulation is often slow for this reason. One poss= ible=20 speedup would be to cache the results of sqrt() so if you compute the sam= e=20 values over and over it won't take as long. But in the end it is the 3 d= eep=20 loop that is killing you. Ponder the problem and maybe look for better=20 algorithms online or at the bookstore. Sorry I could not give you a quicky one liner magic solution. On Sunday 17 November 2002 14:27, Thomi Richards wrote: > > def convert(filename,inpalette,extension=3D'-converted'): > convfile =3D Image.open('input/%s' % (filename)) > if convfile.mode !=3D 'RGB': > temp =3D convfile.convert('RGB') > convfile =3D temp > del(temp) > > for x in range(convfile.size[0] - 1): > for y in range(convfile.size[1] - 1): > pixel =3D convfile.getpixel((x,y)) > tempdistance =3D 6000 > for color in inpalette: > distance =3D sqrt( (color[0] - > pixel[0])**2 + (color[1] - pixel[1])**2 + (color[2] - pixel[2])**2 ) > if distance < tempdistance: > tempdistance =3D distance > tempcolor =3D color > if tempdistance =3D=3D 0: > break > convfile.putpixel((x,y),tempcolor) > > #now we save the file! > convfile.save('output/%s%s.bmp' % > (split(filename,'.')[0],extension)) > return 0 > ------------ > > thanks. I realise i could try writing it in C, but i thought maybe ther= e > were some things i am doing wrong in python.... From magnus@thinkware.se Sun Nov 17 20:33:01 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Sun Nov 17 20:33:01 2002 Subject: [Tutor] speeding code along In-Reply-To: <20021118112754.6d408753.thomi@thomi.imail.net.nz> Message-ID: <5.1.0.14.0.20021118021357.0391a830@www.thinkware.se> At 11:27 2002-11-18 +1300, Thomi Richards wrote: >How can i speed up the following code? take a look: it is called >several thousand times, and i would like to speed it up just a little... You are looking through all of the palette for each pixel of the image for every file. That doesn't seem very effective. A loop inside a loop inside a loop? Perhaps you could precalculate the closest colour for each input colour once for all, and store that in a dict or if need be, some kind of database? Then you only make a quick lookup for each pixel. A compromise might be that once you have calculated a colur, you store it in a dict, and then you check the dict, so that you don't need to test again when you run into the same colour several times in an image. This will give a big speedup for images with few colours at least. Apart from that, I imagine there are faster methods to find the closest colour in a palette than the brute force method you use. >def convert(filename,inpalette,extension='-converted'): closestColour = {} > convfile = Image.open('input/%s' % (filename)) > if convfile.mode != 'RGB': > temp = convfile.convert('RGB') > convfile = temp > del(temp) > > for x in range(convfile.size[0] - 1): > for y in range(convfile.size[1] - 1): > pixel = convfile.getpixel((x,y)) if closestColour.hasKey(pixel): convfile.putpixel((x,y),closestColour[pixel]) continue > tempdistance = 6000 > for color in inpalette: > distance = sqrt( (color[0] - >pixel[0])**2 + (color[1] - pixel[1])**2 + (color[2] - pixel[2])**2 ) > if distance < tempdistance: > tempdistance = distance > tempcolor = color > if tempdistance == 0: > break > convfile.putpixel((x,y),tempcolor) closestColour[pixel] = tempcolor > > #now we save the file! > convfile.save('output/%s%s.bmp' % >(split(filename,'.')[0],extension)) > return 0 You could also put the dict outside the function (make it global, don't forget "global closestColour" inside the function) but then you need to use the palette in the key as well as the particular pixel: closestColour[(inpalette,pixel)] = tempcolor and so on (if inpalette is hashable in a meaningful way). To store the info persistently, you could pickle the dict to a file, or use some other persistence mechanism. I made a similar caching change to a python benchmarking program that used recursion to calculate Fibonacci numbers. That made the program roughly 6600 times faster... -- 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 thomi@thomi.imail.net.nz Sun Nov 17 20:35:01 2002 From: thomi@thomi.imail.net.nz (Thomi Richards) Date: Sun Nov 17 20:35:01 2002 Subject: [Tutor] speeding code along In-Reply-To: <200211171722.29277.shalehperry@attbi.com> References: <20021118112754.6d408753.thomi@thomi.imail.net.nz> <200211171722.29277.shalehperry@attbi.com> Message-ID: <20021118143339.109529d2.thomi@thomi.imail.net.nz> > speedup would be to cache the results of sqrt() so if you compute the > same values over and over it won't take as long. But in the end it is > the i did think about that, but decided that in the end it would probably take just as long to lookup 3 values in a list of values (by the end of the image, this list would be thousands long anyway), as it would to do the math.... ahh well... -- Thomi Richards thomi@imail.net.nz http://ddmodd.sourceforge.net/ Thomi Richards, thomi@imail.net.nz From magnus@thinkware.se Sun Nov 17 20:36:03 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Sun Nov 17 20:36:03 2002 Subject: [Tutor] counting in a file In-Reply-To: <1037577263.3737.24.camel@localhost.localdomain> Message-ID: <5.1.0.14.0.20021118024037.03916ba8@www.thinkware.se> At 18:54 2002-11-17 -0500, reavey wrote: >a = 0 >while a<10: > new = z.readline().strip() > a = a+1 To be honest, I don't understand what you try to do, but that piece of code is better written as for a in range(10): new = z.readline().strip() (which seems strange as you overwrite the nine first values in new with the next line you read in.) -- 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 thomi@thomi.imail.net.nz Sun Nov 17 20:41:02 2002 From: thomi@thomi.imail.net.nz (Thomi Richards) Date: Sun Nov 17 20:41:02 2002 Subject: [Tutor] speeding code along In-Reply-To: <5.1.0.14.0.20021118021357.0391a830@www.thinkware.se> References: <20021118112754.6d408753.thomi@thomi.imail.net.nz> <5.1.0.14.0.20021118021357.0391a830@www.thinkware.se> Message-ID: <20021118144014.2b25a6ff.thomi@thomi.imail.net.nz> > Perhaps you could precalculate the closest colour for each > input colour once for all, and store that in a dict or if need > be, some kind of database? Then you only make a quick lookup > for each pixel. ok, if you think it will be faster, I'll give it a go... > > A compromise might be that once you have calculated a colur, > you store it in a dict, and then you check the dict, so that > you don't need to test again when you run into the same colour > several times in an image. This will give a big speedup for > images with few colours at least. > yes... I'll see what happens. I remain skeptical, because we're rendering down 24 bit bitmaps, which have been made in blender. You very rarely get large blocks of the same color.... > Apart from that, I imagine there are faster methods to find > the closest colour in a palette than the brute force method > you use. > i couldn't think of any :-) Also, this method (although it does take an age), does give better results than the GIMP and paint shop pro... interesting. i wonder what algorithm they use... > > To store the info persistently, you could pickle the dict > to a file, or use some other persistence mechanism. yes, although the palette may be changed at a later date. i guess i could say "if the palette file is the same as the last palette file then:". but then again, over several weeks of using the same palette, this conversion table could grow enormous...probably affecting the speed, > > I made a similar caching change to a python benchmarking > program that used recursion to calculate Fibonacci numbers. > That made the program roughly 6600 times faster... > I'll give it a go, thanks! -- This is a subliminal message. Thomi Richards, thomi@imail.net.nz From bindas_qwerty@hotmail.com Sun Nov 17 20:45:02 2002 From: bindas_qwerty@hotmail.com (sachin mehra) Date: Sun Nov 17 20:45:02 2002 Subject: [Tutor] need some help for program!! Message-ID: Hi, I have to take a sentence as input that has had all the spaces ( and punctuation) removed and put the spaces back in. I have to use a search based algorithm on a probabilistic language model to recover spaces. It looks like to me that either I can use one of the following: Train the model with HMM & then use viterbi algorithm with beam search OR Train the model with HMM & then use A*/Best first algorithm. I am just proposing this!! If any one has better Ideas/code..plz help me. I had another question.How can I use HMM(Hidden markov models) to train a model given some text?? What do I take as intial states and state transisions for the problem stated above? Can anyone help me ? ANyone with better ideas?? Thanx, Manish _________________________________________________________________ The new MSN 8: smart spam protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From fredm@smartypantsco.com Sun Nov 17 21:02:01 2002 From: fredm@smartypantsco.com (Alfred Milgrom) Date: Sun Nov 17 21:02:01 2002 Subject: [Tutor] speeding code along In-Reply-To: <20021118112754.6d408753.thomi@thomi.imail.net.nz> Message-ID: <5.1.0.14.0.20021118125406.00a7e5f0@192.168.1.1> There are a couple of things I would do in your situation: * Your program does not need to calculate the square root of the distance. Instead of distance = sqrt( (color[0] - pixel[0])**2 + (color[1] - pixel[1])**2 + (color[2] - pixel[2])**2 ) Use distance = (color[0] - pixel[0])**2 + (color[1] - pixel[1])**2 + (color[2] - pixel[2])**2 Just use the larger value. All you want is to do is minimise that distance. * Sort your palette into 5 different quadrants based on the R and G values, so that you have R = 0 - 127 or R = 128 - 255 G = 0 - 127 or G = 128 - 255 or a fifth quadrant that covers the centre of the palette space (R = 65 - 192, G = 65 - 192) You can easily determine in which quadrant your solution will lie and get a four-fold speed increase. (The reason for sorting along R and G is that the eye is less sensitive to Blue values) I think the combination of those two effects will reduce your time from 45 seconds to 4 seconds or so. Best of luck, Fred Milgrom From Jmllr891@cs.com Sun Nov 17 21:10:03 2002 From: Jmllr891@cs.com (Jmllr891@cs.com) Date: Sun Nov 17 21:10:03 2002 Subject: [Tutor] Question about irclib Message-ID: <1a5.c21546f.2b09a58b@cs.com> --part1_1a5.c21546f.2b09a58b_boundary Content-Type: text/plain; charset="US-ASCII" Content-Transfer-Encoding: 7bit I'm messing around and trying to make a simple IRC bot that just sits in a specific channel and basically does nothing (just so I can understand how to at least make my bots connect to a server). I've downloaded the irclib library (http://python-irclib.sourceforge.net), but it has hardly any documentation. I was wondering if anybody knew where I could find some good beginner's material about using the irclib library or writing IRC bots in Python. Thanks. --part1_1a5.c21546f.2b09a58b_boundary Content-Type: text/html; charset="US-ASCII" Content-Transfer-Encoding: 7bit I'm messing around and trying to make a simple IRC bot that just sits in a specific channel and basically does nothing (just so I can understand how to at least make my bots connect to a server). I've downloaded the irclib library (http://python-irclib.sourceforge.net), but it has hardly any documentation.

I was wondering if anybody knew where I could find some good beginner's material about using the irclib library or writing IRC bots in Python. Thanks.





--part1_1a5.c21546f.2b09a58b_boundary-- From python Sun Nov 17 21:13:02 2002 From: python (python) Date: Sun Nov 17 21:13:02 2002 Subject: [Tutor] Question about irclib In-Reply-To: <1a5.c21546f.2b09a58b@cs.com> References: <1a5.c21546f.2b09a58b@cs.com> Message-ID: <98163612019.20021116181812@inkedmn.net> a couple friends of mine wrote an ircbot in python called moobot here's the project page, just poke around the cvs: http://www.sf.net/projects/moobot hth brett Jcc> I'm messing around and trying to make a simple IRC bot that just sits in a Jcc> specific channel and basically does nothing (just so I can understand how to Jcc> at least make my bots connect to a server). I've downloaded the irclib Jcc> library (http://python-irclib.sourceforge.net), but it has hardly any Jcc> documentation. Jcc> I was wondering if anybody knew where I could find some good beginner's Jcc> material about using the irclib library or writing IRC bots in Python. Jcc> Thanks. From fleet@teachout.org Sun Nov 17 22:20:35 2002 From: fleet@teachout.org (fleet@teachout.org) Date: Sun Nov 17 22:20:35 2002 Subject: [Tutor] (no subject) Message-ID: > Why not: > > def get_name(prompt): > return raw_input(prompt) > > while 1: > opt = getnum() > if opt == 1: > s_name = get_name("Surname: ") > elif opt == 2: > g_name = get_name("Given Name: ") > elif opt == 3: > n_name = get_name("Nickname: ") > else: > break > > Note that this will break out of the while loop if any number other than > 1, 2, or 3 is entered. That may not be what you want. I'll try the function, thanks. I'm not sure I see an advantage. The "else: break" would work fine; although it makes the prompt a little wordy. Regards, - fleet - From dyoo@hkn.eecs.berkeley.edu Sun Nov 17 22:40:02 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Nov 17 22:40:02 2002 Subject: [Tutor] speeding code along In-Reply-To: <5.1.0.14.0.20021118125406.00a7e5f0@192.168.1.1> Message-ID: > I think the combination of those two effects will reduce your time from > 45 seconds to 4 seconds or so. Best of luck, Fred Milgrom Hi Thomi, Hmmm! You may also want to try out the Psyco specializing compiler, and see if it does anything to that inner loop: http://psyco.sourceforge.net/ I see some heavy math in your loop that might be amendable to Psyco's optimizations. Best of wishes to you! From fleet@teachout.org Sun Nov 17 22:54:01 2002 From: fleet@teachout.org (fleet@teachout.org) Date: Sun Nov 17 22:54:01 2002 Subject: [Tutor] while with function In-Reply-To: <5.1.0.14.0.20021118021112.02b75108@www.thinkware.se> Message-ID: On Mon, 18 Nov 2002, Magnus Lycka wrote: > At 15:09 2002-11-17 -0500, fleet@teachout.org wrote: > >I like the concept of "while 1:" but I've had problems getting it to break > >properly. I suspect I'm having "scope" problems. > > Loops and if statements don't introduce new scopes as > { } does in C etc. You only nest scopes with nested > functions, nested classes, methods and lambdas. > (I.e. if you type def, class or lambda inside a class > or function.) I have two functions: def add() s_name=raw_input("Surname: ") # several more lines of the same y=1 while y>0: get_list() def get_list() print "1. Surname: "+s_name # several more lines of the same # read option while loop here I had to add "global s_name, ..., ..., etc." to add() in order to get get_list() to display the variables. I tried moving the definition of get_list() ahead of the add() definition; but that made no difference. add(), of course, is called by main_menu(). Is making the add() variables global the proper solution here? Regards, - fleet - From dyoo@hkn.eecs.berkeley.edu Sun Nov 17 23:14:02 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Nov 17 23:14:02 2002 Subject: [Tutor] speeding code along In-Reply-To: <20021118112754.6d408753.thomi@thomi.imail.net.nz> Message-ID: Hi Thomi, Let's take a look at the loop, since that's where all the action is. > for x in range(convfile.size[0] - 1): > for y in range(convfile.size[1] - 1): > pixel = convfile.getpixel((x,y)) > tempdistance = 6000 > for color in inpalette: > distance = sqrt( (color[0] - > pixel[0])**2 + (color[1] - pixel[1])**2 + (color[2] - pixel[2])**2 ) > if distance < tempdistance: > tempdistance = distance > tempcolor = color > if tempdistance == 0: > break > convfile.putpixel((x,y),tempcolor) This chunk of code is trying to match, for every pixel on your image, the closest color that's available in a list of palette colors. The innermost loop is concerned about grabbing the best palette color it can that matches an arbitrary color. We can refactor this temporarily by pulling the inner part into a separate function: ### def best_fitting_color(pixel): tempdistance = 6000 for color in inpalette: distance = sqrt( (color[0] - pixel[0])**2 + (color[1] - pixel[1])**2 + (color[2] - pixel[2])**2 ) if distance < tempdistance: tempdistance = distance tempcolor = color if tempdistance == 0: return tempcolor ### The refactoring will temporarily slow the actual program down, but will help us to concentrate on the performance critical stuff. It looks like you're trying to find the right palette color that minimizes color distance, with the following: ### for color in inpalette: distance = sqrt( (color[0] - pixel[0])**2 + (color[1] - pixel[1])**2 + (color[2] - pixel[2])**2 ) ### where you're taking the Euclidean distance of the colors. However, we really only care about picking the palette color that minimizes distance, and we really don't need to keep track of the exact distance. We can reduce some of the cost by omitting the square root calculation altogether! ### for color in inpalette: distance = (color[0] - pixel[0])**2 + (color[1] - pixel[1])**2 + (color[2] - pixel[2])**2 ) ### Also, does your palette change a lot? If not, then it might be really worth precalculating the optimum palette colors for all possible colors. If precalculation is possible, then you can do all of the calculation work up front. That way, all future color-fittings look like a very fast lookup. Sorta like this: ### class _PrecachedColorFitting: def __init__(self, palette, r_range=range(256), g_range=range(256), b_range=range(256)): self.palette = palette self.bestchoice = {} for r in r_range: for g in g_range: for b in b_range: pixel = (r,g,b) self.bestchoice[pixel] = best_fit(pixel) def best_fit(self, pixel): tempdistance = 6000 for color in self.palette: distance = ( (color[0] - pixel[0])**2 + (color[1] - pixel[1])**2 + (color[2] - pixel[2])**2 ) if distance < tempdistance: tempdistance = distance tempcolor = color if tempdistance == 0: break return tempcolor def __call__(self, pixel): return self.bestchoice[pixel] best_fitting_color = _PrecachedColorFitting ### And if calculating this is expensive at the beginning of every program start, we can always save the whole dictionary to disk, so that we only pay the cost of calculation once. Disk space is cheap: use it! *grin* With these changes, your loop will look much cleaner: ### for x in range(convfile.size[0] - 1): for y in range(convfile.size[1] - 1): pixel = convfile.getpixel((x,y)) convfile.putpixel((x,y), best_fitting_color(pixel)) ### and will probably run faster, to boot! Good luck to you! From dyoo@hkn.eecs.berkeley.edu Sun Nov 17 23:17:01 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Nov 17 23:17:01 2002 Subject: [Tutor] speeding code along [code correction] In-Reply-To: Message-ID: > class _PrecachedColorFitting: > def __init__(self, palette, > r_range=range(256), > g_range=range(256), > b_range=range(256)): > self.palette = palette > self.bestchoice = {} > for r in r_range: > for g in g_range: > for b in b_range: > pixel = (r,g,b) > self.bestchoice[pixel] = best_fit(pixel) ^^^^^^^ Doh. I meant that line to be: ### self.bestchoice[pixel] = self.best_fit(pixel) ### Sorry; I hadn't tested any of this code out yet. From dyoo@hkn.eecs.berkeley.edu Sun Nov 17 23:30:02 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Nov 17 23:30:02 2002 Subject: [Tutor] speeding code along [lists and dictionaries are fast] In-Reply-To: <20021118143339.109529d2.thomi@thomi.imail.net.nz> Message-ID: On Mon, 18 Nov 2002, Thomi Richards wrote: > > speedup would be to cache the results of sqrt() so if you compute the > > same values over and over it won't take as long. But in the end it is > > the > > i did think about that, but decided that in the end it would probably > take just as long to lookup 3 values in a list of values (by the end of > the image, this list would be thousands long anyway), as it would to do > the math.... ahh well... Lists and dictionary lookup is nearly instantaneous: we use them to trade time with space. That is, list lookup should take a constant amount of time, regardless of how large our lists are. (Well, as long as our lists aren't so large that the operating system needs to juggle virtual memory. *grin*) That's one big reason why lists are so good. This idea of constant lookup is not intuitive to people, since we imagine ourselves marching through a list to get at a result, and our intuition tells us that physical distance matters. But computers are very very good at lookup: when given an index, they don't march --- they take a flying leap! If you use a caching approach to your problem; I think you'll be pleasantly surprised with the results. From dyoo@hkn.eecs.berkeley.edu Mon Nov 18 01:01:09 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Nov 18 01:01:09 2002 Subject: [Tutor] need some help for program!! [hidden markov models?] In-Reply-To: Message-ID: On Mon, 18 Nov 2002, sachin mehra wrote: > I have to take a sentence as input that has had all the spaces ( and > punctuation) removed and put the spaces back in. I have to use a search > based algorithm on a probabilistic language model to recover spaces. Forgive me, but this really sounds like a homework problem. It's simply not right for us to help you directly on this. There's a lot of good information on the web that you can look at to better understand your problem. Check: http://datamining.anu.edu.au/software/febrl/febrldoc/node7.html in particular. > It looks like to me that either I can use one of the following: Train > the model with HMM & then use viterbi algorithm with beam search OR > Train the model with HMM & then use A*/Best first algorithm. > > I had another question.How can I use HMM(Hidden markov models) to train > a model given some text? Wait, wait. You're jumping way ahead of yourself! The first part of your question depends entirely on knowing why you want to use a HMM for this particular problem. If you don't know what the HMM is for, or how to construct one, how can you even propose to use it to solve your problem? Splitting a spaceless sentence should probably be your first priority, and it's not to hard to cook something up to do sentence partitioning. It should only take a few lines of code to write a function that does something like this: ### >>> paritition("attackatdawn") [['at', 'tack', 'at', 'dawn'], ['attack', 'at', 'dawn']] >>> partition("iscreamforicecream") [['is', 'cream', 'for', 'ice', 'cream'], ['i', 'scream', 'for', 'ice', 'cream']] >>> partition("uselesspython") [['use', 'less', 'python'], ['useless', 'python']] >>> partition("inaholetherelivedahobbit") [['in', 'a', 'hole', 'the', 're', 'lived', 'a', 'hobbit'], ['in', 'a', 'hole', 'there', 'lived', 'a', 'hobbit']] ### (My lexicon is just '/usr/dict/words' with some modifications, so the partitions aren't that inventive...) So partitioning is not (or should not be) the real heart of your problem. What's hard is figuring out, given a list of possible partitions, which one makes the most grammatical sense! When we see sentences like is cream for ice cream or i scream for ice cream How do we know which one is the "better" or "more probable" English sentence? Perhaps, in our brains, we're attaching semantic meaning to each word. Instinctively, we know that the first form "is cream for ice cream" simply doesn't make as much sense as the second "i scream for ice cream". The transition from the word "is" to "cream" just doesn't "feel" right. It's too bad we don't know exactly how our brains do it yet. But that's where the Hidden Markov Models's should come in. A Hidden Markov Model, properly trained on grammatically tagged english sentences, can eat something like "is cream for ice cream" and say "the probability of such a sentence existing in english is: 0.000001291...". Your model might not even care about the particular words, but may only pay attention to the grammatical roles of each word. ("cream" is a "noun", "for" is a preposition, etc...) So you may need to break your problem into a few steps: partitioning, stamping each possible partition with grammatical tags, and then feeding those tagged partitions into your HMM. Again, the page at: http://datamining.anu.edu.au/software/febrl/febrldoc/node7.html has an example that should help clarify why HMM's are appropriate for your problem. I hope that made some sort of sense. Good luck to you. From thomi@thomi.imail.net.nz Mon Nov 18 01:54:02 2002 From: thomi@thomi.imail.net.nz (Thomi Richards) Date: Mon Nov 18 01:54:02 2002 Subject: [Tutor] speeding code along [lists and dictionaries are fast] In-Reply-To: References: <20021118143339.109529d2.thomi@thomi.imail.net.nz> Message-ID: <20021118195138.6c90d4e3.thomi@thomi.imail.net.nz> > If you use a caching approach to your problem; I think you'll be > pleasantly surprised with the results. OK, I'll have a look at pickle then... Now all i need to do is work out how to tell if a file is the same or not. It is quite likely that someone will have two files with the same name...i could compare teh size....hmmm... just thinking aloud here :-) -- Thomi Richards thomi@imail.net.nz http://thomi.imail.net.nz/ Thomi Richards, thomi@imail.net.nz From thomi@thomi.imail.net.nz Mon Nov 18 01:54:13 2002 From: thomi@thomi.imail.net.nz (Thomi Richards) Date: Mon Nov 18 01:54:13 2002 Subject: [Tutor] speeding code along In-Reply-To: References: <20021118112754.6d408753.thomi@thomi.imail.net.nz> Message-ID: <20021118194353.6143e0fa.thomi@thomi.imail.net.nz> > Also, does your palette change a lot? If not, then it might be really > worth precalculating the optimum palette colors for all possible > colors. yes, it does. otherwise i would try to pickle the dictionary. I may still do that, although I'm not sure how much faster it would make it... I'll try a few different things out... THanks! -- "Avoid the Gates of Hell. Use Linux" Thomi Richards, thomi@imail.net.nz From dyoo@hkn.eecs.berkeley.edu Mon Nov 18 02:48:02 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Nov 18 02:48:02 2002 Subject: [Tutor] need some help for program!! [More hidden markov models in Python] In-Reply-To: Message-ID: > Again, the page at: > > http://datamining.anu.edu.au/software/febrl/febrldoc/node7.html > > has an example that should help clarify why HMM's are appropriate for > your problem. Hi Sachin, Argh, darn it! I can't help myself but look into your question some more. Why did you have to ask a question on such an interesting topic? *grin* I have to control my curiosity or else I'll end up writing this program too. There's a great source of information on Hidden Markov Models in the source code of Logilab's 'hmm' module: http://www.logilab.org/hmm/ This is a Python module that implements HMM's, and is excellent. You may need to install an extension called Numeric Python to get it to work, but it's definitely worth it: http://www.pfdubois.com/numpy/ There are some real gems in there, not just the module itself, but in the test cases they've embedded in the source code. In particular, if we take a close look at the logilab.hmm.hmm.test2() function, we'll see that they train a Hidden Markov Model to recognize French sentences (and evaluate their likelihood!). If you read and understand their test2() function, you should be able to apply that knowledge toward your problem. Another good source of information on HMM's includes the classic article, "A Tutorial on Hidden Markov Models and Selected Applications in Speech Recognition", by Lawrence R. Rabiner. Here's a link to the paper: http://www.cc.gatech.edu/ccg/paper_of_week/Rabiner-Markov.pdf I just read the first few pages, and my own fuzzy ideas about HMM's just became a lot clearer. Anyway, I must stop myself now, or else I won't be able to sleep. This is why I hate seeing homework questions... Good luck to you. From magnus@thinkware.se Mon Nov 18 02:50:03 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Nov 18 02:50:03 2002 Subject: [Tutor] counting in a file In-Reply-To: <1037577263.3737.24.camel@localhost.localdomain> Message-ID: <5.1.0.14.0.20021118085333.02b49c30@www.thinkware.se> At 18:54 2002-11-17 -0500, reavey wrote: >I'm trying to count the number of times a word occurs in a file. Untested... wordCount = {} for word in open(filename).read().split(): if not wordCount.has_key(word): wordCount[word] = 0 wordCount[word] += 1 for entry in wordCount.items(): print "%s orrurs %i times" % entry -- 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 thomi@thomi.imail.net.nz Mon Nov 18 04:29:02 2002 From: thomi@thomi.imail.net.nz (Thomi Richards) Date: Mon Nov 18 04:29:02 2002 Subject: [Tutor] py2exe Message-ID: <20021118222844.24267228.thomi@thomi.imail.net.nz> Has anyone here actually gotten py2exe to go?? My app uses the PIL, as well as a lot o stock standard python modules, so i: -installed python2.2 for windows -installed PIL for python2.2 for windows -installed py2exe for python2.2 for windows -created setup.py as per instructions and python documentation executed python setup.py py2exe it seemed to work, except that whenever i click on the executable, an error message flashs up so fast, and then dissapears, i cannot read it. finally i read it, and it was a HUGE stack trace, the origins of which were lost off the top of the screen (thats when i found out that shift+pageup doesn't work in windoze) So now I'm really frustrated. are there any other _easy_to_use_ apps which do the same thing out there? any tricks i should look into?? thanks :-) -- Thomi Richards thomi@imail.net.nz http://ddmodd.sourceforge.net/ Thomi Richards, thomi@imail.net.nz From johnca@ourpla.net Mon Nov 18 05:31:35 2002 From: johnca@ourpla.net (John Abbe) Date: Mon Nov 18 05:31:35 2002 Subject: [Tutor] Regexes -- \b ; re.sub In-Reply-To: <5.1.0.14.0.20021116184400.02b240e0@www.thinkware.se> References: <5.1.0.14.0.20021116184400.02b240e0@www.thinkware.se> Message-ID: At 7:28 PM +0100 on 2002-11-16, Magnus Lycka typed: >At 15:09 2002-11-16 +0630, John Abbe wrote: >>matches = re.search (re.compile ("(.)\b(.)"), "spam and eggs are yummy") > >I've never seen anyone send a regular expression object to re.search >like that before. Nice to know i can be original :). I'm learning mostly from the O'Reilly pocket reference, so i'm making a lot of things up as i go along. I was wondering why it was so cumbersome. >You can either write: > >pattern = re.compile(r"(.)\b(.)") >matches = pattern.search("spam and eggs are yummy") > >or shorter > >matches = re.compile(r"(.)\b(.)").search("spam and eggs are yummy") > >or use the re.search function with an (uncompiled) pattern. > >matches = re.search(r"(.)\b(.)", "spam and eggs are yummy") ... >It's a good thing >to follow the official Python style guide: >http://www.python.org/peps/pep-0008.html Thanks for the pointers. >I'm not sure why you called your match object "matches". If you want >to find all non-overlapping you >could use re.findall(pattern, text) or re.compile(pattern).findall(text) Since i had more than one parentheses, i was thinking of it as multiple matches. I guess the Python lingo for that would be "groups" and "matches" would be what you're describing here. For any interested, i've implemented a simple wiki parser for pyblosxom, and am working on TwinPages (aka SisterSites) for PikiePikie. 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://www.ourpla.net/john/ --Wes Nisker From alan.gauld@bt.com Mon Nov 18 05:31:52 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Nov 18 05:31:52 2002 Subject: [Tutor] Images + Tkinter Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA5F@mbtlipnt02.btlabs.bt.co.uk> > At 17:50 2002-11-17 +0000, alan.gauld@bt.com wrote: > >I feel stupid. I must be missing something... > > Extensive expertise in the internals of Tcl/Tk? Oddly enough I used Tcl/Tk for a long time before discovering Tkinter. But admittedly didn't dig around the innards. But I certainly never noticed any strange anomolies like this before. OTOH I didn't do very much with images... > Python doesn't keep any reference to it. Does Tcl/Tk > use some kind of weak reference? Obviously it will > know what image to work with if the image object doesn't > go out of scope. Presumably. It just seems very strange and inconsistent, normally the containment tree will delete all its children as it goes, thus taking care of the memory issues, and GC will delete any orphaned images - at least that's what I assumed up till now! > in the Python code. Here there are "secret" things happening > in Tcl/Tk I guess. Since it seems to fix the problem I guess we must assume so. I don't feel quite so stupid now... :-) Another good reason to use classes when building GUIs IMHO, and to keep references to all widgets you expect to manipulate! Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From magnus@thinkware.se Mon Nov 18 05:39:03 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Nov 18 05:39:03 2002 Subject: [Tutor] while with function In-Reply-To: References: <5.1.0.14.0.20021118021112.02b75108@www.thinkware.se> Message-ID: <5.1.0.14.0.20021118113359.02b44d70@www.thinkware.se> At 22:50 2002-11-17 -0500, fleet@teachout.org wrote: >def add() > s_name=raw_input("Surname: ") > # several more lines of the same > y=1 > while y>0: > get_list() > >def get_list() > print "1. Surname: "+s_name > # several more lines of the same > # read option while loop here > >I had to add "global s_name, ..., ..., etc." to add() in order to get >get_list() to display the variables. I tried moving the definition of >get_list() ahead of the add() definition; but that made no difference. > >add(), of course, is called by main_menu(). > >Is making the add() variables global the proper solution here? Depends on what you mean by "proper solution", but no, I think that's bad programming style. The obvious solution here is to pass s_name and what ever other variables you need get_list to be aware of as parameters. If something in get_list() changes y, then it should return y. That shouldn't be global either. I.e: def add(): s_name = ... ... y = 1 while y>0: y = get_list(s_name, ...) def get_list(s_name, ...): print ... ... return whatever_becomes_y If you know that y will be exactly 0 when it's time to quit, replace "while y > 0:" with "while y:" A shorter version would be... def add(): s_name = ... ... while get_list(s_name, ...): pass ...since you don't seem to use y for anything but the loop control in add(). -- 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 Nov 18 05:56:03 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Nov 18 05:56:03 2002 Subject: [Tutor] Regexes -- \b ; re.sub In-Reply-To: References: <5.1.0.14.0.20021116184400.02b240e0@www.thinkware.se> <5.1.0.14.0.20021116184400.02b240e0@www.thinkware.se> Message-ID: <5.1.0.14.0.20021118115232.02b62c48@www.thinkware.se> At 16:30 2002-11-18 +0630, John Abbe wrote: >Nice to know i can be original :). I'm learning mostly from the O'Reilly >pocket reference, so i'm making a lot of things up as i go along. I was >wondering why it was so cumbersome. :) You didn't invest in the thickest book available... The library reference is your friend... Obviously, the result of being "original", if that means writing programs that work by accident (or rather due to trial and error) and not because they are "correct" is that it might break in the next version of Python. So far, Guido hasn't hesitated to make Python more strict in following the documented behaviour. For instance you could once write l = [] l.append(1, 2, 3) instead of l.append((1, 2, 3)) as you should. A lot of programs stopped working when that "bug" was fixed. There was also a function in the socket library that fixed in the same way, with the same result. I'm sure we are all guilty of sometimes "testing what works", rather than studying what's supposed to work, but there is certainly a danger in his. >>I'm not sure why you called your match object "matches". If you want >>to find all non-overlapping you >>could use re.findall(pattern, text) or re.compile(pattern).findall(text) > >Since i had more than one parentheses, i was thinking of it as multiple >matches. I guess the Python lingo for that would be "groups" and "matches" >would be what you're describing here. Ok, fine. I just though that maybe you expected it to act like findall. -- 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 thomi@thomi.imail.net.nz Mon Nov 18 05:59:31 2002 From: thomi@thomi.imail.net.nz (Thomi Richards) Date: Mon Nov 18 05:59:31 2002 Subject: [Tutor] speeding code along [lists and dictionaries are fast] In-Reply-To: <20021118195138.6c90d4e3.thomi@thomi.imail.net.nz> References: <20021118143339.109529d2.thomi@thomi.imail.net.nz> <20021118195138.6c90d4e3.thomi@thomi.imail.net.nz> Message-ID: <20021118235758.67707498.thomi@thomi.imail.net.nz> > > If you use a caching approach to your problem; I think you'll be > > pleasantly surprised with the results. WOW!! 4 seconds a file! (thats on average. the first file took 10 seconds, and the next three took 2 seconds each) thanks for the advice :-) -- Lord, what fools these mortals be! -- midsummer nights dream. Thomi Richards, thomi@imail.net.nz From scot@possum.in-berlin.de Mon Nov 18 06:06:33 2002 From: scot@possum.in-berlin.de (Scot Stevenson) Date: Mon Nov 18 06:06:33 2002 Subject: [Tutor] counting in a file In-Reply-To: <5.1.0.14.0.20021118085333.02b49c30@www.thinkware.se> References: <5.1.0.14.0.20021118085333.02b49c30@www.thinkware.se> Message-ID: <200211181200.50903.scot@possum.in-berlin.de> Hi - > for word in open(filename).read().split(): > if not wordCount.has_key(word): > wordCount[word] = 0 > wordCount[word] += 1 I think you could get rid of the "if" with a line such as: wordCount[word] = 1 + wordCount.get(word, 0) but that doesn't change the basic idea. Y, Scot -- Scot W. Stevenson -- scot@possum.in-berlin.de -- Zepernick, Germany From alan.gauld@bt.com Mon Nov 18 06:10:03 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Nov 18 06:10:03 2002 Subject: [Tutor] label widgets: double buffering, clearing label text Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA62@mbtlipnt02.btlabs.bt.co.uk> > uses double buffering, so you can update the contents at any time, > without annoying flicker." > > Does anyone know how to use label widgets in this way? > > How about simply clearing label widget text in order to > update the text? The point is you don't need to. You just assign the text property to some new string: label['text'] = "A first string" label['text'] = "A new string" And Tkinter will display the new value without redrawing the entire window and hence causing any flickers. The only thing to watch out for is Tkinter may resize the window if the new string is significantly longer or shorter. To get round that put the label inside a fixed size frame.... Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld@bt.com Mon Nov 18 06:10:16 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Nov 18 06:10:16 2002 Subject: [Tutor] while with function Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA63@mbtlipnt02.btlabs.bt.co.uk> > > while 1: > > if y: break > > ### > > As I read this it means: if y is any number, exit the loop? It means if y is any number other than zero. Python considers zero false and all other numbers true. Similarly it considers empty strings false and non empty strings true. The purist in me thinks this is a nasty frig picked up from C that should be avoided. The pragmatist in me says it saves some typing and isn't really that obscure... :-) Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld@bt.com Mon Nov 18 06:16:36 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Nov 18 06:16:36 2002 Subject: [Tutor] counting in a file Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA64@mbtlipnt02.btlabs.bt.co.uk> > I'm trying to count the number of times a word occurs in a file. > Thanks in advance for any suggestions. Try checking out the case study in my tutorial. Also consider the xreadlines() function instead of readlines() BTW, I assume you mean the string.split() function not the string.strip() function as used in your post? Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld@bt.com Mon Nov 18 06:16:51 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Nov 18 06:16:51 2002 Subject: [Tutor] Tkinter problems Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA65@mbtlipnt02.btlabs.bt.co.uk> > >is it possable to have a "percent-done" metre using > Tkinter?? Try using a scroll bar widget. Alan G. From alan.gauld@bt.com Mon Nov 18 06:20:02 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Nov 18 06:20:02 2002 Subject: [Tutor] speeding code along Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA66@mbtlipnt02.btlabs.bt.co.uk> > i did think about that, but decided that in the end it would probably > take just as long to lookup 3 values in a list of values (by > the end of the image, this list would be thousands long anyway), as it > would to do the math.... ahh well... Only if it was a list. Use a dictionary and it will be orders of magnitude faster! Of course you need to find a way to identify unique keys, but that shouldn't be impossible - remember tuples can be keys too... Alan G. From alan.gauld@bt.com Mon Nov 18 06:26:02 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Nov 18 06:26:02 2002 Subject: [Tutor] speeding code along Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA67@mbtlipnt02.btlabs.bt.co.uk> > Also, this method (although it does take an age), does give better > results than the GIMP and paint shop pro... interesting. i wonder what > algorithm they use... Hmm, that's not bad going. There is one other technique that you might get some mileage out of: batching. Instead of processing N * M * X you might be better with Z * (N/Z * M * X) This keeps the list lookup smaller and the net effect is a speed improvement. Depends on how easy it is to split it up and it is a juggling act to get right. I'd try caching the pallette first! Alan g. From thomi@thomi.imail.net.nz Mon Nov 18 06:31:01 2002 From: thomi@thomi.imail.net.nz (Thomi Richards) Date: Mon Nov 18 06:31:01 2002 Subject: [Tutor] speeding code along In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA66@mbtlipnt02.btlabs.bt.co.uk> References: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA66@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <20021119003040.50c1d698.thomi@thomi.imail.net.nz> > Only if it was a list. > Use a dictionary and it will be orders of magnitude faster! > Of course you need to find a way to identify unique keys, > but that shouldn't be impossible - remember tuples can be > keys too... yeah, basically, i found out if the current pixel color was in the dictionary. if not, i worked it out the old way, if it was, i simple called the correct values out of the dictionary. simple! -- Thomi Richards thomi@imail.net.nz http://ddmodd.sourceforge.net/ Thomi Richards, thomi@imail.net.nz From alan.gauld@bt.com Mon Nov 18 06:36:02 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Nov 18 06:36:02 2002 Subject: [Tutor] while with function Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA68@mbtlipnt02.btlabs.bt.co.uk> > I have two functions: > > def add() > s_name=raw_input("Surname: ") > y=1 > while y>0: > get_list() This looks like another potential use for the while 1:..break idiom! > def get_list() > print "1. Surname: "+s_name > # read option while loop here > I had to add "global s_name, ..., ..., etc." to add() in order to get > get_list() to display the variables. > Is making the add() variables global the proper solution here? Better would be to pass the values to get_list() as a paramenter and have the results passed back as a list. However I wonder why you've split the function? They both handle user input for the same basic structure. Why not just combine them into one slightly longer structure: def add() s_name=raw_input("Surname: ") y=1 while y>0: print "1. Surname: "+s_name # read opti Sometimes longer function make more sense.... Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld@bt.com Mon Nov 18 06:47:01 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Nov 18 06:47:01 2002 Subject: [Tutor] Regexes -- \b ; re.sub Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA69@mbtlipnt02.btlabs.bt.co.uk> > Nice to know i can be original :). I'm learning mostly from the > O'Reilly pocket reference, EEEK! Thats a good pocket reference for those who already know what they are doing and need a reminder of the details. To learn anything new about Python (even if you know the other bits well) I recommend the tutor that comes with the Python documentation. Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From din22@cox.net Mon Nov 18 09:12:02 2002 From: din22@cox.net (root) Date: Mon Nov 18 09:12:02 2002 Subject: [Tutor] my newbie program Message-ID: <200211181412.gAIEC7502105@ip68-1-85-252.pn.at.cox.net> hello everyone! i am trying again to learn python and i have broken my script here. right now i am just trying to make rooms and move through them. any comments or direction would be much appreciated class room: def __init__(self): self.desc="" self.exits=[] room1=room() room2=room() room1.exits=[room2,0,0,0] room1.desc="a big room" room2.desc="an even bigger room" class player: def __init__(self): self.location=room1 def act(self): cmd = raw_input('>') if cmd == 'look': print self.location.desc if cmd == 'n': if self.location.exits[0] != 0: self.location=self.location.exits[0] else: print "you can't go that way" me=player() From mchermside@ingdirect.com Mon Nov 18 09:19:01 2002 From: mchermside@ingdirect.com (Chermside, Michael) Date: Mon Nov 18 09:19:01 2002 Subject: [Tutor] RE: catching any exception? Message-ID: <902A1E710FEAB740966EC991C3A38A8903C35B12@INGDEXCHANGEC1.ingdirect.com> > I've noticed that the code only works for any of the "standard"=20 > exceptions. If I define my own exception, which is what DCOracle = does, and=20 > raise that, it's not caught: >=20 > >>> myException =3D 'my sample exception' > >>> try: > ... raise myException > ... except Exception, thisException: > ... print 'got (%s, %s)' % (Exception, thisException) > ... raise Exception(thisException, 'sql here') > ... > Traceback (most recent call last): > File "", line 2, in ? > my sample exception >=20 > See, "myException" was not caught. How can I catch all exceptions,=20 > including the ones that DCOracle defines? >=20 > For that matter, how can I create an exception that's just like a=20 > "standard" exception? I think that's part of the problem. The string = type=20 > of exception that DCOracle defines doesn't have Exception as a parent. EXACTLY! You've got the answer, you just don't realize it yet! The problem is with strings being thrown as exceptions. Whenever you create an exception, you should subclass "Exception" - something like this would be better: >>> class myException(Exception): ... pass ...=20 >>> try: ... raise myException ... except Exception, thisException: ... print 'got (%s, %s)' % (Exception, thisException) ... raise Exception(thisException, 'sql here') ...=20 got (exceptions.Exception, ) Traceback (most recent call last): File "", line 5, in ? Exception: (<__main__.myException instance at 0x010B2988>, 'sql here') So it sounds like *YOU* know this, but unfortunately the authors of DCOracle didn't! Congratulations... you've now advanced far enough in your Python mastery to be catching errors in libraries! Throwing strings as exceptions was the original way of creating exceptions, but it's been deprecated for a LONG time (although it is still allowed so old libraries won't break). Unfortunately, (unless you feel like contributing a fix back to the DCOracle library), you're pretty much stuck with the library the way it is. So you need a work-around. I think you can probably do it with a somewhat-complicated except clause. Think of dividing everything into 3 kinds of exceptions... normal-style exceptions you want to catch (you may not have any of these), = normal-style exceptions you DON'T want to catch, and exceptions which are of the=20 obscelete string kind. I would try something like this: # WARNING: Untested code try: ... code here ... except ExceptionToCatch, err: print 'Handling exception %s, %s' % (ExceptionToCatch, err) except ExceptionNotToCatch, err: raise # a bare 'raise' will re-raise the original exception except: # catch everything else (ie, plain strings) import sys (type, value, traceback) =3D sys.exc_info() ... more handling here... I can get you ALMOST there. The above code will handle NOT catching the exceptions you want to leave alone (by catching them and then re-raising them). Using sys.exc_info() you can obtain the string itself (although I believe it appears in the first slot ("type"),=20 not the second ("value")), and you can obtain a traceback object. The only part I _don't_ know how to do is to create a new exception object to throw which will have the error message from "type", along with the sql statement (which you have available) but which will use the traceback that you have in "traceback". In other words, I don't know how to create an exception with a given traceback. But I'm guessing one of the OTHER helpful people on this list can tell BOTH of us how to accomplish that. -- Michael Chermside From magnus@thinkware.se Mon Nov 18 09:35:01 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Nov 18 09:35:01 2002 Subject: [Tutor] my newbie program In-Reply-To: <200211181412.gAIEC7502105@ip68-1-85-252.pn.at.cox.net> Message-ID: <5.1.0.14.0.20021118152540.02b43398@www.thinkware.se> At 08:12 2002-11-18 -0600, root wrote: >hello everyone! i am trying again to learn python >and i have broken my script here. right now i am >just trying to make rooms and move through them. >any comments or direction would be much appreciated This seems like a reasonable beginning... There's a lot left to do of course :) but I don't think you are headed in the wrong direction... >class room: It's common to begin ClassNames with Capitals. See http://www.python.org/peps/pep-0008.html Thus "class Room:" would be better. > def __init__(self): > self.desc="" > self.exits=[] > > >room1=room() >room2=room() >room1.exits=[room2,0,0,0] > >room1.desc="a big room" >room2.desc="an even bigger room" > >class player: > def __init__(self): > self.location=room1 > def act(self): > cmd = raw_input('>') > if cmd == 'look': > print self.location.desc > if cmd == 'n': > if self.location.exits[0] != 0: You can write this as "if self.location.exists[0]:" Being not equal to 0 is in this case the same as being I assume. (The meaning will be different if self.location.exits[0] could contain [] or "" etc, but not if it only contains numbers. Zero is "false". You could have something like directions = {'n':0, 'e':1, 's':2, 'w':3} and then: if cmd in directions.keys(): if self.location.exits[directions[cmd]]: ... > self.location=self.location.exits[0] > else: > print "you can't go that way" > >me=player() Good luck! -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From magnus@thinkware.se Mon Nov 18 10:05:02 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Nov 18 10:05:02 2002 Subject: [Tutor] RE: catching any exception? In-Reply-To: <902A1E710FEAB740966EC991C3A38A8903C35B12@INGDEXCHANGEC1.in gdirect.com> Message-ID: <5.1.0.14.0.20021118153727.03705e88@www.thinkware.se> At 09:17 2002-11-18 -0500, Chermside, Michael wrote about throwing string exceptions: >So it sounds like *YOU* know this, but unfortunately the authors >of DCOracle didn't! Hm... The DC in DCOracle stands for Digital Creations, right, later renamed to Zope Corprations. They have employees like Barry Warsaw, Jeremy Hylton, Tim Peters, Jim Fulton and what's the name of that dutch guy again? Gui...something... One could imagine that they knew how to code DCOracle. I seem to remember that there is also a DCOracle2. Is this by any change a non-current version you are using? Hm... See here http://www.zope.org/Products/DCOracle This product, DCOracle, is written using OCI 7 calls; it works with Oracle 7 and Oracle 8.0. However, maintenance on DCOracle has been discontinued in favor of the DCOracle2 product, which has been rewritten around OCI 8 calls. The problem is in ociUtil.py, there it says: error="oci.error" You might try changing this to class OciError(StandardError): pass error = OciError and then you need to change all lines that look something like raise error, 'A mutable value was passed to an output' to raise error('A mutable value was passed to an output') If you upgrade to DCOracle2, there are only two occurences of strings cast as exceptions. :( But that's two too many. There is also cx_oracle which is an option... -- 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 fleet@teachout.org Mon Nov 18 10:14:02 2002 From: fleet@teachout.org (fleet@teachout.org) Date: Mon Nov 18 10:14:02 2002 Subject: [Tutor] while with function In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA68@mbtlipnt02.btlabs.bt.co.uk> Message-ID: I split the functions because it seemed to me I *had* two functions. add() allows input for an address book; get_list() allows me to repeatedly (if necessary) display the list of variables and make corrections before adding the entry to a file. (I also had it in mind to use get_list() in an edit() function - haven't gotten there yet.) Regards, - fleet - On Mon, 18 Nov 2002 alan.gauld@bt.com wrote: > > I have two functions: > > > > def add() > > s_name=raw_input("Surname: ") > > y=1 > > while y>0: > > get_list() > > This looks like another potential use for the > while 1:..break idiom! > > > def get_list() > > print "1. Surname: "+s_name > > # read option while loop here > > > I had to add "global s_name, ..., ..., etc." to add() in order to get > > get_list() to display the variables. > > Is making the add() variables global the proper solution here? > > Better would be to pass the values to get_list() as a paramenter > and have the results passed back as a list. However I wonder why > you've split the function? They both handle user input for the > same basic structure. Why not just combine them into one slightly > longer structure: > > def add() > s_name=raw_input("Surname: ") > y=1 > while y>0: > print "1. Surname: "+s_name > # read opti > > Sometimes longer function make more sense.... > > Alan g. > Author of the 'Learning to Program' web site > http://www.freenetpages.co.uk/hp/alan.gauld > From alan.gauld@bt.com Mon Nov 18 11:54:02 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Nov 18 11:54:02 2002 Subject: [Tutor] while with function Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA6F@mbtlipnt02.btlabs.bt.co.uk> > I split the functions because it seemed to me I *had* two functions. > add() allows input for an address book; OK, so in that case I'd expect the function look like this: def add(entry, add_book):.... > get_list() allows me to repeatedly (if necessary) > display the list of variables and make corrections The interesting phrase here is "*the* list", not "a list". If a function is specific to a single list then it maybe shouldn't stand alone - ideally it should be a method of a class binding data and function together... Of course you could make it generic by passing a list of names, prompting for a value for each and returning a dictionary keyed by name.... def get_values(namelist): values = {} for name in namelist: val = raw_input(name+'? ') values[name] = val return values But this is limited to returning string values. If you passed in a list of name,type tuples then you could do the conversion there too but then the usability of your function becomes a bit strained... A better idea might be to get the data required for a single entry, in which case the function might be called get_entry and reurn the whole group of data as a tuple. def get_entry(): try: .... return (s_name, f_name, phone, etc....) except: return None That way there is no need to couple the two functions together since the add entry function call becomes: add_entry(get_entry(), addressBook) Or you have a single while loop outside the functions like so: while 1: entry = get_entry() if not entry: break else add_entry(entry, addressBook) Untangling the dependencies between functions is good design practice (with practice having both meanings here!) HTH, Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld@bt.com Mon Nov 18 12:04:03 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Nov 18 12:04:03 2002 Subject: [Tutor] my newbie program Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA71@mbtlipnt02.btlabs.bt.co.uk> > class room: > def __init__(self): > self.desc="" > self.exits=[] > > > room1=room() > room2=room() > room1.exits=[room2,0,0,0] > room1.desc="a big room" > room2.desc="an even bigger room" You could simplify that by using default args to the init method: class Room: #capitalised class names is the convention. def __init__(self, desc="", exits=[]) self.desc = desc self.exits = exits room2 = Room("an even bigger room") room1 = Room("a big room", [room2,0,0,0]) You need to watch the order to avoid using names of objects not yet created in the exi list but otherwise it saves effort.... > class Player: self.commandlist = ['look','n'] > def __init__(self): > self.location=room1 > def act(self): > cmd = raw_input('>') if cmd in self.commandlist: # bit of a sanity check > if cmd == 'look': > print self.location.desc > if cmd == 'n': > if self.location.exits[0] != 0: > self.location=self.location.exits[0] > else: > print "you can't go that way" else: print "invalid command: ", cmd > me = Player() while 1: me.act() if not map(lambda x: x != 0, me.location.exits): break OK, the map() is maybe overkill... :-) Otherwise it looks like it should work so far... What next? Alan g. From joney@clara.co.uk Mon Nov 18 12:19:02 2002 From: joney@clara.co.uk (john gennard) Date: Mon Nov 18 12:19:02 2002 Subject: [Tutor] why doesn't procbox run? Message-ID: <02111817172600.00299@Leary> I'm not sure if this question is OT or not, but I'll give it a try. For a long time, I have run Debian Potato (it's still installed). I've now installed Debian Woody as well. I filter my email on Potato with a small program called procbox which doesn't seem to be supported now, so I copied it over from Potato to Woody. Procbox is written in Python, but does not run on Woody. The error message says 'bash: /usr/local/bin/procbox.py: /usr/bin/python: bad interpreter: Permission denied' All permissions have been checked against Potato as has the integrity of the program, PATHS and so forth. There are no anomalies. The only difference between the system on which it runs and that on which it does not appears to be that Potato has Python 1.5.2 and GCC 2.95.2 whilst Woody has Python 2.1.3 and GCC 2.95.4 (there is a link /usr/bin/python to /usr/bin/python2.1). Is there any difference between Python1.5 and Python2.1 which could cause this problem? Coincidentally, I run a number of programs written in Python which got me interested and I have just started to learn it ( posted a starter problem a few days ago, got answered and am now on page 8! ). If this is not considered OT, has anyone any advice please? Regards, John. From joney@clara.co.uk Mon Nov 18 12:19:17 2002 From: joney@clara.co.uk (john gennard) Date: Mon Nov 18 12:19:17 2002 Subject: [Tutor] getting started Message-ID: <02111515151701.00299@Leary> Many thanks to Magnus Lucka and Kirk Bailey who responded to my request for assistance. They have already 'put me right' and I'm now ready to proceed. Obviously this list is friendly and helpful to newcomers to Python. I'm grateful. John. From dyoo@hkn.eecs.berkeley.edu Mon Nov 18 13:18:02 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Nov 18 13:18:02 2002 Subject: [Tutor] why doesn't procbox run? In-Reply-To: <02111817172600.00299@Leary> Message-ID: On Mon, 18 Nov 2002, john gennard wrote: > I'm not sure if this question is OT or not, but I'll give it a try. > > For a long time, I have run Debian Potato (it's still installed). I've > now installed Debian Woody as well. > > I filter my email on Potato with a small program called procbox which > doesn't seem to be supported now, so I copied it over from Potato to > Woody. > > Procbox is written in Python, but does not run on Woody. The error > message says 'bash: /usr/local/bin/procbox.py: /usr/bin/python: bad > interpreter: Permission denied' > > All permissions have been checked against Potato as has the integrity of > the program, PATHS and so forth. Hi John, That's odd! Hmmm... do you think it might be a permissions problem? '/usr/bin/python' is definitely there on your system; otherwise, you would have gotten the error message: ### bash: ./foo.py: /usr/bin/python: bad interpreter: No such file or directory ### instead of "Permission denied." Oh! Wait. http://lists.debian.org/debian-user/2002/debian-user-200210/msg06510.html Ah ha! This sounds familiar... *grin* John, check the permissions on the procbox script: I get the feeling that the script itself is not executable. The error message that you're getting is misleading by not telling that the script itself might not have the right permissions set up. Here's an example of what can happen: ### [dyoo@tesuque dyoo]$ cat foo.py #!/usr/bin/python print "hello" [dyoo@tesuque dyoo]$ ls -l foo.py -rw-r--r-- 1 dyoo users 33 Nov 18 10:12 foo.py [dyoo@tesuque dyoo]$ ./foo.py bash: ./foo.py: /usr/bin/python: bad interpreter: Permission denied [dyoo@tesuque dyoo]$ [dyoo@tesuque dyoo]$ chmod +x foo.py [dyoo@tesuque dyoo]$ ./foo.py hello [dyoo@tesuque dyoo]$ ls -l foo.py -rwxr-xr-x 1 dyoo users 33 Nov 18 10:12 foo.py ### Next time, you might also want to try the Debian-user mailing list, because it's very possible that someone else there has run into a similar issue. http://lists.debian.org/debian-user/ Good luck to you! From ramrom@earthling.net Mon Nov 18 13:20:01 2002 From: ramrom@earthling.net (Bob Gailer) Date: Mon Nov 18 13:20:01 2002 Subject: [Tutor] speeding code along [lists and dictionaries are fast] In-Reply-To: References: <20021118143339.109529d2.thomi@thomi.imail.net.nz> Message-ID: <5.2.0.9.0.20021118111042.019c1800@66.28.54.253> At 08:29 PM 11/17/2002 -0800, Danny Yoo wrote: >Lists and dictionary lookup is nearly instantaneous: we use them to trade >time with space. That is, list lookup should take a constant amount of >time, regardless of how large our lists are. I don't know how python manages lists internally, but I offer an idea from IBM's implementation of APL2. (In APL variables are arrays with 0 or more dimensions. Before APL2 all elements of an array were the same internal datatype, which made indexing extremely efficient). In APL2 each element of an array could be a value or a "nested array", making it somewhat like Python's lists, but messier; indexing now found the pointer to the element. If changing an array by element assignment resulted in all elements being the same simple datatype, the array was flagged as "not nested", and therefore subject to indexing by offset. Perhaps a future implementation of Python could do something similar. Bob Gailer 170 Forsythe Rd Nederland CO 80466 303-442-2625 From glingl@aon.at Mon Nov 18 13:23:02 2002 From: glingl@aon.at (Gregor Lingl) Date: Mon Nov 18 13:23:02 2002 Subject: [Tutor] my newbie program References: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA71@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <3DD92FF5.5000903@aon.at> alan.gauld@bt.com schrieb: >>class room: >> def __init__(self): >> self.desc="" >> self.exits=[] >> >> >>room1=room() >>room2=room() >>room1.exits=[room2,0,0,0] >>room1.desc="a big room" >>room2.desc="an even bigger room" >> >> > >You could simplify that by using default args to the init method: > >class Room: #capitalised class names is the convention. > def __init__(self, desc="", exits=[]) > here a colon is missing! > self.desc = desc > self.exits = exits > >room2 = Room("an even bigger room") >room1 = Room("a big room", [room2,0,0,0]) > >You need to watch the order to avoid using names of objects >not yet created in the exi list but otherwise it saves effort.... > > > >>class Player: >> >> > self.commandlist = ['look','n'] > I think this won't work. there is no name self here. So better either delete the self. to create a class-variable and replace self.commandlist by Player.commandlist or put this statement into __init__ > > >> def __init__(self): >> self.location=room1 >> def act(self): >> cmd = raw_input('>') >> >> > if cmd in self.commandlist: # bit of a sanity check > > >> if cmd == 'look': >> print self.location.desc >> if cmd == 'n': >> if self.location.exits[0] != 0: >> self.location=self.location.exits[0] >> else: >> print "you can't go that way" >> >> > else: print "invalid command: ", cmd > > > >>me = Player() >> >> > while 1: > me.act() > if not map(lambda x: x != 0, me.location.exits): > break > > This is a little bit disturbing. Wasn't the original concept, that exits should be a four element list, containing exits (to rooms) in the four directions if they exist and 0 otherwise? So one should better add room2.exits=[0,0,room1,0] along with some amendments Magnus suggested - which would make the game a little more interesting Gregor >OK, the map() is maybe overkill... :-) >Otherwise it looks like it should work so far... What next? > >Alan g. > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From emile@fenx.com Mon Nov 18 13:40:02 2002 From: emile@fenx.com (Emile van Sebille) Date: Mon Nov 18 13:40:02 2002 Subject: [Tutor] Re: why doesn't procbox run? References: <02111817172600.00299@Leary> Message-ID: john gennard: > Procbox is written in Python, but does not run on Woody. > The error message says 'bash: /usr/local/bin/procbox.py: > /usr/bin/python: bad interpreter: Permission denied' > I'm no familiar with this applications, but when I have seen the bad interpreter message come up, it generally is fixed by changing the shebang to use the 'other' python -- eg, change #!/usr/bin/python to #!/usr/bin/python2. HTH, Emile van Sebille emile@fenx.com From matt@ipwib.net Mon Nov 18 13:43:02 2002 From: matt@ipwib.net (Matt) Date: Mon Nov 18 13:43:02 2002 Subject: [Tutor] capturing/analysing sound data Message-ID: <3DD937A7.2080306@ipwib.net> Hello everyone, I'm currently attempting to write a small guitar tuner app (I know there are several out there, but I'm utilizing it as a learning experience.) I've searched and read docs for about 8-10 hours, but I still haven't deduced exactly how to capture sound data (I'm running Debian 3.0 with OSS) so that I can analyse it. I'm also not exactly sure how to handle constant input(sound data)/output(tone analysis), but it can be tackled after handling small test samples/analysis. If anyone has any advise or can point me in the right direction, I'd greatly appreciate it. Thanks, Matt From ramrom@earthling.net Mon Nov 18 13:43:14 2002 From: ramrom@earthling.net (Bob Gailer) Date: Mon Nov 18 13:43:14 2002 Subject: [Tutor] my newbie program In-Reply-To: <200211181412.gAIEC7502105@ip68-1-85-252.pn.at.cox.net> Message-ID: <5.2.0.9.0.20021118113445.03207bf8@66.28.54.253> At 08:12 AM 11/18/2002 -0600, root wrote: >just trying to make rooms and move through them. Shades of Colossal Cave! Can I *bare* it? Seeing class room gets me thinking of a school. I want to turn a def ear to that. del iberately. This list should include: global village while away_the_time for a_good_time.__call__ For now I'll let it pass. Bob Gailer 170 Forsythe Rd Nederland CO 80466 303-442-2625 From mongo57a@comcast.net Mon Nov 18 14:03:02 2002 From: mongo57a@comcast.net (andy surany) Date: Mon Nov 18 14:03:02 2002 Subject: [Tutor] Help please with a module location error Message-ID: <001f01c28f35$11aa3040$2502a8c0@emily.ewndsr01.nj.comcast.net> This is really strange..... I have a python221 program which works great under RH Linux 7.3. Now I am converting it to run under Windows (95, 98, 2000). Should be pretty easy. I use the MySQLdb and Numeric libs, so I downloaded the latest versions and installed them in the appropriate place (they both go to the same directory). My program begins execution as follows: from Tkinter import * from tkMessageBox import * # get standard dialogs from tkSimpleDialog import askstring import MySQLdb import string import Numeric import time Under windows (executing from IDLE) I get the following error: Traceback (most recent call last): File "", line 1, in ? File "A:\test4.py", line 6, in ? import Numeric ImportError: No module named Numeric Now MySQLdb and Numeric are in the same directory structure. When I go to the command line interpreter and execute the same code manually, everything works. Can anyone explain??????? I have no clue........ TAI -Andy From Doug.Shawhan@gecits.ge.com Mon Nov 18 14:38:04 2002 From: Doug.Shawhan@gecits.ge.com (Doug.Shawhan@gecits.ge.com) Date: Mon Nov 18 14:38:04 2002 Subject: [Tutor] Help please with a module location error Message-ID: <47B6167F8E69D31194BA0008C7918D4205C54F10@msxcvg02itscge.gecits.ge.com> Howdy Andy, Have you taken a look in C:\Python22\Lib\site-packages? You may be lacking .pth files for the various packages you installed! HTH d -----Original Message----- From: andy surany [mailto:mongo57a@comcast.net] Sent: Monday, November 18, 2002 1:03 PM To: tutor@python.org Subject: [Tutor] Help please with a module location error This is really strange..... I have a python221 program which works great under RH Linux 7.3. Now I am converting it to run under Windows (95, 98, 2000). Should be pretty easy. I use the MySQLdb and Numeric libs, so I downloaded the latest versions and installed them in the appropriate place (they both go to the same directory). My program begins execution as follows: from Tkinter import * from tkMessageBox import * # get standard dialogs from tkSimpleDialog import askstring import MySQLdb import string import Numeric import time Under windows (executing from IDLE) I get the following error: Traceback (most recent call last): File "", line 1, in ? File "A:\test4.py", line 6, in ? import Numeric ImportError: No module named Numeric Now MySQLdb and Numeric are in the same directory structure. When I go to the command line interpreter and execute the same code manually, everything works. Can anyone explain??????? I have no clue........ TAI -Andy _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From magnus@thinkware.se Mon Nov 18 14:48:02 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Nov 18 14:48:02 2002 Subject: [Tutor] why doesn't procbox run? In-Reply-To: <02111817172600.00299@Leary> Message-ID: <5.1.0.14.0.20021118204801.036c10e8@www.thinkware.se> At 17:17 2002-11-18 +0000, john gennard wrote: >Procbox is written in Python, but does not run on Woody. >The error message says 'bash: /usr/local/bin/procbox.py: >/usr/bin/python: bad interpreter: Permission denied' What about if you run $ python /usr/local/bin/procbox.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 magnus@thinkware.se Mon Nov 18 14:56:11 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Nov 18 14:56:11 2002 Subject: [Tutor] speeding code along [lists and dictionaries are fast] In-Reply-To: <5.2.0.9.0.20021118111042.019c1800@66.28.54.253> References: <20021118143339.109529d2.thomi@thomi.imail.net.nz> Message-ID: <5.1.0.14.0.20021118205009.036d6c28@www.thinkware.se> At 11:19 2002-11-18 -0700, Bob Gailer wrote: >I don't know how python manages lists internally AFAIK, it's basically an array of pointers. This means that item look-up is fast regardless of the size of the list. Basically, the base address of the list and the list index tells you where you find the address on the heap to the object you are looking for. Adding and removing objects in the end of the list is also fast. Modifying the beginning of a large list (del l[0], l.insert(0,0) etc) is on the other hand slow, since the whole array needs to be moved. (Actually, on "del l[0]" one could just move the base adress! But I don't think it works that way. :) I haven't looked at the internals of lists, but they behave as if they would be implemented as I write here, as you can easily verify with some timing tests. In reality it's probably a bit more complex. -- 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 Nov 18 15:03:01 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Nov 18 15:03:01 2002 Subject: [Tutor] getting started In-Reply-To: <02111515151701.00299@Leary> Message-ID: <5.1.0.14.0.20021118210056.036c0c08@www.thinkware.se> At 15:15 2002-11-15 +0000, john gennard wrote: >Many thanks to Magnus Lucka and Kirk Bailey who responded to my >request for assistance. They have already 'put me right' and I'm now >ready to proceed. You're welcome. It's Lyck=E5, actually, but I bet you'd never guess how to pronounce that anyway! ;) >Obviously this list is friendly and helpful to newcomers to Python. Except when I get into my monotone preaching mode! ;) I've-always-tried-to-figure-out-how-to-be-brief-but-never-quite-managed-t= o-get-it'ly=20 yours, Magnus --=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 Mon Nov 18 15:31:37 2002 From: glingl@aon.at (Gregor Lingl) Date: Mon Nov 18 15:31:37 2002 Subject: [Tutor] getting started References: <5.1.0.14.0.20021118210056.036c0c08@www.thinkware.se> Message-ID: <3DD94DF5.1000308@aon.at> Magnus Lycka schrieb: > > You're welcome. It's Lyckå, actually, but I bet you'd > never guess how to pronounce that anyway! ;) > An you, would you be so kind to reveal it to us? > > Magnus > If not, at least 'Magnus' gives us a hint to whom we are talking. Gregor From mongo57a@comcast.net Mon Nov 18 15:43:39 2002 From: mongo57a@comcast.net (andy surany) Date: Mon Nov 18 15:43:39 2002 Subject: [Tutor] Help please with a module location error Message-ID: <005701c28f43$603ebba0$2502a8c0@emily.ewndsr01.nj.comcast.net> Hey Doug, The site-packages directory has no MySQLdb.pth file (and MySQLdb does work...). It does have a Numeric.pth which simply has an entry "Numeric" in it. Is this correct? I would think that IDLE and the command line interpreter would treat paths the same way.... though, maybe not - since it is not working. Regards, Andy -----Original Message----- From: Doug.Shawhan@gecits.ge.com To: mongo57a@comcast.net ; tutor@python.org Date: Monday, November 18, 2002 2:36 PM Subject: RE: [Tutor] Help please with a module location error >Howdy Andy, > >Have you taken a look in C:\Python22\Lib\site-packages? > >You may be lacking .pth files for the various packages you installed! > >HTH > >d > >-----Original Message----- >From: andy surany [mailto:mongo57a@comcast.net] >Sent: Monday, November 18, 2002 1:03 PM >To: tutor@python.org >Subject: [Tutor] Help please with a module location error > > >This is really strange..... > >I have a python221 program which works great under RH Linux 7.3. Now I >am converting it to run under Windows (95, 98, 2000). Should be pretty >easy. I use the MySQLdb and Numeric libs, so I downloaded the latest >versions and installed them in the appropriate place (they both go to >the same directory). > >My program begins execution as follows: > >from Tkinter import * >from tkMessageBox import * # get standard >dialogs >from tkSimpleDialog import askstring >import MySQLdb >import string >import Numeric >import time > >Under windows (executing from IDLE) I get the following error: >Traceback (most recent call last): > File "", line 1, in ? > File "A:\test4.py", line 6, in ? > import Numeric >ImportError: No module named Numeric > >Now MySQLdb and Numeric are in the same directory structure. > >When I go to the command line interpreter and execute the same code >manually, everything works. > >Can anyone explain??????? I have no clue........ > >TAI > >-Andy > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From fleet@teachout.org Mon Nov 18 15:44:16 2002 From: fleet@teachout.org (fleet@teachout.org) Date: Mon Nov 18 15:44:16 2002 Subject: [Tutor] while with function In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA6F@mbtlipnt02.btlabs.bt.co.uk> Message-ID: Maybe I'd better go into some background. The "address book" entries will be created, maintained and utilized from a command line. The "add" function will display prompts for each field (using raw_input) one field at a time. I want to be able to display the entries and be able to correct any of them. I'm assuming, since I'm not using any GUI, that I will have to change (if necessary) each entry individually. Therefore, I need the ability to repeat the display however many times is necessary. When I'm satisfied with the "add" information, the variables will be concatenated (with pipe symbol delimiters) and added to an address book file as a single line. I should be able to use the editing function again if someone changes address/phone/email/etc. So maybe get_list() should be renamed edit_list(); but in any event, it refers to the list of variables for each address book entry (name, address, email, etc.). I prefer not to mess with classes at this point in my python education. I don't understand them. I chose a flatfile database over a dictionary because it can be used also by things like sed, awk, grep and can be easily edited with a text editor if I find my program interface too unwieldy or, for some reason, inconvenient. (IOW, if my program turns into a piece of junk; I still have my data in a useable form :) ) I appreciate the input from all of you; but frankly I'm having trouble following it in some cases. And none of it appears to allow me to review and correct the new address book entry before I "commit" it to the database. I probably should have explained better what I was attempting earlier; but I was trying to be "brief." I hope this clears things up a little. Regards, - fleet - On Mon, 18 Nov 2002 alan.gauld@bt.com wrote: > > I split the functions because it seemed to me I *had* two functions. > > add() allows input for an address book; > > OK, so in that case I'd expect the function look like this: > > def add(entry, add_book):.... > > > get_list() allows me to repeatedly (if necessary) > > display the list of variables and make corrections > > The interesting phrase here is "*the* list", not "a list". > > If a function is specific to a single list then it maybe > shouldn't stand alone - ideally it should be a method of > a class binding data and function together... > > Of course you could make it generic by passing a list > of names, prompting for a value for each and returning > a dictionary keyed by name.... > > def get_values(namelist): > values = {} > for name in namelist: > val = raw_input(name+'? ') > values[name] = val > return values > > But this is limited to returning string values. > If you passed in a list of name,type tuples then you > could do the conversion there too but then the usability > of your function becomes a bit strained... > > A better idea might be to get the data required for a > single entry, in which case the function might be called > get_entry and reurn the whole group of data as a tuple. > > def get_entry(): > try: > .... > return (s_name, f_name, phone, etc....) > except: return None > > That way there is no need to couple the two functions > together since the add entry function call becomes: > > add_entry(get_entry(), addressBook) > > Or you have a single while loop outside the > functions like so: > > while 1: > entry = get_entry() > if not entry: break > else add_entry(entry, addressBook) > > Untangling the dependencies between functions is good > design practice (with practice having both meanings here!) > > HTH, > > Alan g. > Author of the 'Learning to Program' web site > http://www.freenetpages.co.uk/hp/alan.gauld > From Doug.Shawhan@gecits.ge.com Mon Nov 18 15:55:03 2002 From: Doug.Shawhan@gecits.ge.com (Doug.Shawhan@gecits.ge.com) Date: Mon Nov 18 15:55:03 2002 Subject: [Tutor] Help please with a module location error Message-ID: <47B6167F8E69D31194BA0008C7918D4205C54F12@msxcvg02itscge.gecits.ge.com> > The site-packages directory has no MySQLdb.pth file (and MySQLdb does > work...). It does have a Numeric.pth which simply has an entry "Numeric" > in it. Is this correct? Looks right to me. That is how Numeric is set up on my windows 2000 box. (Does anyone else wish that python's pth files were in /etc/python/site-packages?) > I would think that IDLE and the command line interpreter would treat > paths the same way.... So would I! :-) > though, maybe not - since it is not working. It _is_ a conundrum. Numeric works just dandy for me that way. Anyone else? From reavey@nep.net Mon Nov 18 16:06:07 2002 From: reavey@nep.net (reavey) Date: Mon Nov 18 16:06:07 2002 Subject: [Tutor] count in a file Message-ID: <1037653373.4738.7.camel@localhost.localdomain> Responding to AlanG Yes , I overlooked this gem in your tutorial f.write(str(x)) where x is the type(list) result after running f.readline().split() on a file this little piece of code unlocked the door. Thanks Re-v From mongo57a@comcast.net Mon Nov 18 16:31:02 2002 From: mongo57a@comcast.net (andy surany) Date: Mon Nov 18 16:31:02 2002 Subject: [Tutor] Help please with a module location error Message-ID: <008001c28f4a$10b5d8a0$2502a8c0@emily.ewndsr01.nj.comcast.net> I think that this is a problem with IDLE. If I execute a "print" statement before the "import", it seems to work - at least the first time. In order to run the program again, I have to re-start IDLE. However, the program does execute fine from the command line interpreter AND from a "DOS" prompt. So, in reference to the expression: "if it hurts, stop doing it", I will simply run the program from the DOS prompt. Thanks Doug for helping me on this. Regards, Andy -----Original Message----- From: Doug.Shawhan@gecits.ge.com To: tutor@python.org Cc: mongo57a@comcast.net Date: Monday, November 18, 2002 3:55 PM Subject: RE: [Tutor] Help please with a module location error >> The site-packages directory has no MySQLdb.pth file (and MySQLdb does >> work...). It does have a Numeric.pth which simply has an entry "Numeric" >> in it. Is this correct? > >Looks right to me. That is how Numeric is set up on my windows 2000 box. >(Does anyone else wish that python's pth files were in >/etc/python/site-packages?) > > >> I would think that IDLE and the command line interpreter would treat >> paths the same way.... > >So would I! :-) > >> though, maybe not - since it is not working. > >It _is_ a conundrum. Numeric works just dandy for me that way. Anyone else? > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From dylan.belsey@baesystems.com Mon Nov 18 17:03:00 2002 From: dylan.belsey@baesystems.com (BELSEY, Dylan) Date: Mon Nov 18 17:03:00 2002 Subject: [Tutor] Re: catching any exception? Message-ID: <86C3892A0C52D411AF5000A0C9EAA3B98D2B36@wtntex1.baea.com.au> Is it possible to import you DCOracle module where the exceptions are defined and then perform the following: try: # Whatever except DCOracle.exception, errmsg: # handler ??? As you have said below, if DCOracle defines exceptions, why not try and use them. This is just an idea as I have not seen the definition of the DCOracle exceptions. > -----Original Message----- > From: Lance E Sloan [mailto:lsloan@umich.edu] > Sent: Saturday, 16 November 2002 07:00 > But I've noticed that the code only works for any of the "standard" > exceptions. If I define my own exception, which is what > DCOracle does, and > raise that, it's not caught: > > How can I catch all exceptions, > including the ones that DCOracle defines? > > For that matter, how can I create an exception that's just like a > "standard" exception? I think that's part of the problem. > The string type > of exception that DCOracle defines doesn't have Exception as a parent. From magnus@thinkware.se Mon Nov 18 17:17:01 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Nov 18 17:17:01 2002 Subject: [Tutor] getting started In-Reply-To: <3DD94DF5.1000308@aon.at> References: <5.1.0.14.0.20021118210056.036c0c08@www.thinkware.se> Message-ID: <5.1.0.14.0.20021118225310.036d7bd0@www.thinkware.se> At 21:30 2002-11-18 +0100, Gregor Lingl wrote: >Magnus Lycka schrieb: >>You're welcome. It's Lyck=E5, actually, but I bet you'd >>never guess how to pronounce that anyway! ;) >An you, would you be so kind to reveal it to us? Actually, an Austrian will probably be much closer than someone with English as native language... This is a bit OT, but ok. I really think I'd need to upload a wav to my web site though. :) The L isn't so difficult I guess. It's not the kind of thick L we associate with typical Americans etc. More like it's pronounced in German etc. The toungue stys flat in your mouth as you say it. A Swedish Y is very different from an English one. It's on the scale between U and I. Does is make sense if I talk of a scale from U to =DC to Y to I? I don't think the sound exists in English, and it's distictly different from the german =DC, but it's closer to =DC than to I. (I'm not sure people can imagine what a sound in between =FC and i is like before they hear it. The "ck" is just a normal, hard k-sound with an indication that the preceeding vowel "y" is short. As in clock or trick. The a with a ring over it, =E5, is pronounced as o in more. It also happens to be long as in more in this case. >If not, at least 'Magnus' gives us a hint to whom we are talking. Actually, that's not pronounced the way most of you think either! :) --=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 Mon Nov 18 17:36:02 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Nov 18 17:36:02 2002 Subject: [Tutor] while with function In-Reply-To: References: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA6F@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <5.1.0.14.0.20021118232028.036d92d0@www.thinkware.se> At 15:42 2002-11-18 -0500, fleet@teachout.org wrote: >The "address book" entries will be created, maintained and utilized from= a >command line. The "add" function will display prompts for each field >(using raw_input) one field at a time. I want to be able to display the >entries and be able to correct any of them. I'm assuming, since I'm not >using any GUI, that I will have to change (if necessary) each entry >individually. Therefore, I need the ability to repeat the display howeve= r >many times is necessary. When I'm satisfied with the "add" information, >the variables will be concatenated (with pipe symbol delimiters) and add= ed >to an address book file as a single line. raw_input is very crude. Another option could be to create a temporary file with something like: first_name: Magnus last_name: Lucka email: magnus@thinkware.se and open it in an editor, vi or notepad or whatever, depending on platform. Then people make whatever changes they like, and close the editor. (I'd change Lucka to Lyck=E5.) After that, you open the file again, parse the text, and if it makes sense, you store the changed data. That way the user gets access to reasonable editing capabilities. Notepad _is_ better than raw_input() With this approach you can show the entire record (well how ever much data you like, really) and let the user change whatever he likes, and leave whatever is ok already. He can cut and paste, search and replace etc. >>> import tempfile >>> fn =3D tempfile.mktemp('txt') >>> f =3D open(fn, 'wt') >>> print >> f, "Hello World" >>> f.close() >>> import os >>> os.system('notepad %s' % fn) [Now I'm changing the file in notepad] 0 >>> print open(fn, 'rt').read() Hello Dear --=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 lumbricus@gmx.net Mon Nov 18 18:50:03 2002 From: lumbricus@gmx.net (lumbricus@gmx.net) Date: Mon Nov 18 18:50:03 2002 Subject: [Tutor] while with function References: Message-ID: <26376.1037663335@www42.gmx.net> Hi! [ snip ] > I appreciate the input from all of you; but frankly I'm having trouble > following it in some cases. And none of it appears to allow me to review > and correct the new address book entry before I "commit" it to the > database. You want to use the GNU readline library. There is a python module, too. > Regards, [ useless fullquote snipped ] HTH and Greets, J"o! -- Wir beschliessen etwas, stellen das dann in den Raum und warten dann einige Zeit ab, was passiert. Wenn es dann kein grosses Geschrei gibt und keine Aufstaende, weil die meisten gar nicht begreifen, was da beschlossen wurde, dann machen wir weiter - Schritt fuer Schritt, bis es kein Zurueck mehr gibt. -- J-C Juncker +++ GMX - Mail, Messaging & more http://www.gmx.net +++ NEU: Mit GMX ins Internet. Rund um die Uhr für 1 ct/ Min. surfen! From dman@dman.ddts.net Mon Nov 18 19:19:02 2002 From: dman@dman.ddts.net (Derrick 'dman' Hudson) Date: Mon Nov 18 19:19:02 2002 Subject: [Tutor] Re: speeding code along [lists and dictionaries are fast] In-Reply-To: <5.1.0.14.0.20021118205009.036d6c28@www.thinkware.se> References: <20021118143339.109529d2.thomi@thomi.imail.net.nz> <5.1.0.14.0.20021118205009.036d6c28@www.thinkware.se> Message-ID: <20021119003232.GA24140@dman.ddts.net> --k1lZvvs/B4yU6o8G Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Mon, Nov 18, 2002 at 08:56:32PM +0100, Magnus Lycka wrote: | At 11:19 2002-11-18 -0700, Bob Gailer wrote: | >I don't know how python manages lists internally |=20 | AFAIK, it's basically an array of pointers. [...] | I haven't looked at the internals of lists, but they behave | as if they would be implemented as I write here, as you can | easily verify with some timing tests. The core of a Python list is PyObject* [] It is (in C) an array of pointers to Python objects. Hence it is very fast for indexed lookups, but can be slower when appending many objects to it. | In reality it's probably a bit more complex. The complexity comes in automatically growing when you append new objectsts to the end of it and in deallocating objects when/as appropriate. -D --=20 Consider what God has done: Who can straighten what He has made crooked? Ecclesiastes 7:13 =20 http://dman.ddts.net/~dman/ --k1lZvvs/B4yU6o8G 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 iEYEARECAAYFAj3ZhqAACgkQO8l8XBKTpRR35ACeP3uAjVZM9Js4YpBbRpBxuFIa bzwAoJdNvpLJB/GecI121l5olTkYSSja =1kVp -----END PGP SIGNATURE----- --k1lZvvs/B4yU6o8G-- From mark.brown@rogers.com Mon Nov 18 19:37:01 2002 From: mark.brown@rogers.com (Mark Brown) Date: Mon Nov 18 19:37:01 2002 Subject: [Tutor] Any Suggestions? In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA59@mbtlipnt02.btlabs.bt.co.uk> References: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA59@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <1037666342.1292.12.camel@localhost.localdomain> Alan, Thanks for the suggestions. I'd found the runit.py program somewhere on the web and used it to learn import, class and Tkinter so that's why it was split into two programs. I was trying to separate the GUI and the main program logic so that once the Tk GUI was working then would work on a wxWindows GUI interface. I'm considering changing the direction of the importing. Currently the main program imports the Tk GUI but do you think it should be reversed? Mark Brown On Sun, 2002-11-17 at 12:22, alan.gauld@bt.com wrote: > > I'm just learning Python and would appreciate any suggestions > > regarding the programs listed below. The programs do function. > > > > runit2.py ... From fredm@smartypantsco.com Mon Nov 18 20:03:01 2002 From: fredm@smartypantsco.com (Alfred Milgrom) Date: Mon Nov 18 20:03:01 2002 Subject: [Tutor] Percent done bar In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA65@mbtlipnt02.btlabs .bt.co.uk> Message-ID: <5.1.0.14.0.20021119115636.00a9cec0@192.168.1.1> At 11:16 AM 18/11/02 +0000, alan.gauld@bt.com wrote: > > >is it possable to have a "percent-done" metre using > > Tkinter?? > >Try using a scroll bar widget. > >Alan G. Just wanted to say I really enjoy reading this list - there's always something interesting coming up, so I thought I would contribute something back. I think a neater effect for a percent bar is obtained by using a line object on a small canvas, as in the following: (Alan: you'll notice that the code for the app, GUI, etc, is lifted directly from your tutorial) from Tkinter import * class ClearApp: def __init__(self, parent=0): self.mainWindow = Frame(parent) self.percentbar = Canvas(self.mainWindow) self.percentbar.config(height=10, width=100, bg='black') self.percentbar.create_line(0, 6, 0, 6, fill='red', width = 3, tag='bar') self.percentbar.pack() fOuter = Frame(self.mainWindow, border=1, relief="sunken") fButtons = Frame(fOuter, border=1, relief="raised") bDraw = Button(fButtons, text="Draw Bar", width=8, height=1, command=self.drawBar) bQuit = Button(fButtons, text="Quit", width=8, height=1, command=self.mainWindow.quit) bDraw.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("Percent bar") def drawBar(self): global x if x < 100 : x = x+10 app.percentbar.coords('bar', 0, 6, x, 6) app = ClearApp() x = 0 app.mainWindow.mainloop() From thomi@thomi.imail.net.nz Mon Nov 18 20:59:01 2002 From: thomi@thomi.imail.net.nz (Thomi Richards) Date: Mon Nov 18 20:59:01 2002 Subject: [Tutor] Percent done bar In-Reply-To: <5.1.0.14.0.20021119115636.00a9cec0@192.168.1.1> References: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA65@mbtlipnt02.btlabs.bt.co.uk> <5.1.0.14.0.20021119115636.00a9cec0@192.168.1.1> Message-ID: <20021119145332.4c46fd78.thomi@thomi.imail.net.nz> > I think a neater effect for a percent bar is obtained by using a line > object on a small canvas, as in the following: > (Alan: you'll notice that the code for the app, GUI, etc, is lifted > directly from your tutorial) ahaaa!! that much better! I couldn't figure out that text scroll bar (surely that's meant to be for scrolling text??).. Hope you don't mind if i use this :-) > > from Tkinter import * > > class ClearApp: > def __init__(self, parent=0): > self.mainWindow = Frame(parent) > self.percentbar = Canvas(self.mainWindow) > self.percentbar.config(height=10, width=100, bg='black') > self.percentbar.create_line(0, 6, 0, 6, fill='red', width = 3, > tag='bar') > self.percentbar.pack() > > > fOuter = Frame(self.mainWindow, border=1, relief="sunken") > fButtons = Frame(fOuter, border=1, relief="raised") > bDraw = Button(fButtons, text="Draw Bar", > width=8, height=1, command=self.drawBar) > bQuit = Button(fButtons, text="Quit", > width=8, height=1, > command=self.mainWindow.quit) > bDraw.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("Percent bar") > > def drawBar(self): > global x > if x < 100 : x = x+10 > app.percentbar.coords('bar', 0, 6, x, 6) > > > app = ClearApp() > x = 0 > app.mainWindow.mainloop() > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- This is a subliminal message. Thomi Richards, thomi@imail.net.nz From dyoo@hkn.eecs.berkeley.edu Mon Nov 18 21:26:51 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Nov 18 21:26:51 2002 Subject: [Tutor] capturing/analysing sound data In-Reply-To: <3DD937A7.2080306@ipwib.net> Message-ID: On Mon, 18 Nov 2002, Matt wrote: > I'm currently attempting to write a small guitar tuner app (I know > there are several out there, but I'm utilizing it as a learning > experience.) I've searched and read docs for about 8-10 hours, but I > still haven't deduced exactly how to capture sound data (I'm running > Debian 3.0 with OSS) so that I can analyse it. Hi Matt, I'm doing some random hunting through the web with Google. Here's what I've found so far: http://mail.python.org/pipermail/edu-sig/2001-December/001898.html http://indra.com/~tim/ossmodule/ossmodule.html http://www.onlamp.com/pub/a/python/2001/01/31/numerically.html http://klaveness.info/roger/sw/SndPy/ http://www.linuxsound.at/ The last link in the list doesn't have Python-specific resources, but may still be helpful since it provides a bunch of recording software for Linux. The 'ossmodule' looks promising, though I haven't tested it yet. Good luck! From fleet@teachout.org Mon Nov 18 22:08:01 2002 From: fleet@teachout.org (fleet@teachout.org) Date: Mon Nov 18 22:08:01 2002 Subject: [Tutor] while with function In-Reply-To: <5.1.0.14.0.20021118232028.036d92d0@www.thinkware.se> Message-ID: The only person who will use this is me. From the command line. What would you recommend to replace raw_input? FYI, I'm using Python 1.5. I have 2.0 installed; but keep forgetting to use "python2" instead of "python." I suspect for this level of programming it makes no difference. Regards, - fleet - On Mon, 18 Nov 2002, Magnus Lycka wrote: > At 15:42 2002-11-18 -0500, fleet@teachout.org wrote: > >The "address book" entries will be created, maintained and utilized fr= om a > >command line. The "add" function will display prompts for each field > >(using raw_input) one field at a time. I want to be able to display t= he > >entries and be able to correct any of them. I'm assuming, since I'm n= ot > >using any GUI, that I will have to change (if necessary) each entry > >individually. Therefore, I need the ability to repeat the display howe= ver > >many times is necessary. When I'm satisfied with the "add" information= , > >the variables will be concatenated (with pipe symbol delimiters) and a= dded > >to an address book file as a single line. > > raw_input is very crude. > > Another option could be to create a temporary file with > something like: > > first_name: Magnus > last_name: Lucka > email: magnus@thinkware.se > > and open it in an editor, vi or notepad or whatever, > depending on platform. > > Then people make whatever changes they like, and close > the editor. (I'd change Lucka to Lyck=E5.) > > After that, you open the file again, parse the text, > and if it makes sense, you store the changed data. That > way the user gets access to reasonable editing > capabilities. Notepad _is_ better than raw_input() > > With this approach you can show the entire record (well > how ever much data you like, really) and let the user > change whatever he likes, and leave whatever is ok already. > He can cut and paste, search and replace etc. > > >>> import tempfile > >>> fn =3D tempfile.mktemp('txt') > >>> f =3D open(fn, 'wt') > >>> print >> f, "Hello World" > >>> f.close() > >>> import os > >>> os.system('notepad %s' % fn) > > [Now I'm changing the file in notepad] > > 0 > >>> print open(fn, 'rt').read() > Hello Dear > > > > From fleet@teachout.org Mon Nov 18 22:10:04 2002 From: fleet@teachout.org (fleet@teachout.org) Date: Mon Nov 18 22:10:04 2002 Subject: [Tutor] while with function In-Reply-To: <5.1.0.14.0.20021118232028.036d92d0@www.thinkware.se> Message-ID: On Mon, 18 Nov 2002, Magnus Lycka wrote: > At 15:42 2002-11-18 -0500, fleet@teachout.org wrote: > >The "address book" entries will be created, maintained and utilized from a > >command line. That's a Linux command line, btw. - fleet - From matt@ipwib.net Mon Nov 18 22:39:02 2002 From: matt@ipwib.net (Matt) Date: Mon Nov 18 22:39:02 2002 Subject: [Tutor] regexes, thanks References: Message-ID: <3DD9B560.5070108@ipwib.net> I'm working on a renaming utility for use in renaming mp3's that I ripped from cd while using Windows (and consequently using my preferred naming convention at the time, which I no longer wish to use). I created a file listing, then tried manipulating it. I wanted to make it change every word (defined by only letter sequences) to have the first letter changed to uppercase. Only it doesn't seem that regexes are fully implemented in python (\u,\U)... So, I tried using a function: def upper(a) return(string.capitalize(a)) words = re.compile('([a-zA-Z]+)') new_filename = words.sub(upper, filename) Only this doesn't work, as it doesn't pass the matched string, but a MatchObject. This seemed really strange to me. Eventually I came up with this: def upper(a): return(string.capitalize(a.string[a.start():a.end()])) words = re.compile('([a-zA-Z]+)') new_filename = words.sub(upper, filename) This seems like a really complicated way to do something that I thought would be relatively simple. Is this the best way to do it? Or am I off track and creating unnecessary complexity? Btw, thanks to Danny Yoo for helping me out with python audio information. Several of the sites have proved extremely helpful. -Matt From lumbricus@gmx.net Mon Nov 18 23:53:04 2002 From: lumbricus@gmx.net (lumbricus@gmx.net) Date: Mon Nov 18 23:53:04 2002 Subject: [Tutor] regexes, thanks References: <3DD9B560.5070108@ipwib.net> Message-ID: <6007.1037681493@www42.gmx.net> Hi! > def upper(a) > return(string.capitalize(a)) This already exists: >>> "hello".upper() 'HELLO' > words = re.compile('([a-zA-Z]+)') > new_filename = words.sub(upper, filename) > > Only this doesn't work, as it doesn't pass the matched string, but a > MatchObject. This seemed really strange to me. >>> help(re.compile) Help on function compile: compile(pattern, flags=0) Compile a regular expression pattern, returning a pattern object. > > def upper(a): > return(string.capitalize(a.string[a.start():a.end()])) > > words = re.compile('([a-zA-Z]+)') > new_filename = words.sub(upper, filename) Something along import glob for f in glob.glob("*.mp3"): new=f.upper() might be what you want? HTH, J"o! -- sigfault -- Wir beschliessen etwas, stellen das dann in den Raum und warten dann einige Zeit ab, was passiert. Wenn es dann kein grosses Geschrei gibt und keine Aufstaende, weil die meisten gar nicht begreifen, was da beschlossen wurde, dann machen wir weiter - Schritt fuer Schritt, bis es kein Zurueck mehr gibt. -- J-C Juncker +++ 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 Mon Nov 18 23:59:02 2002 From: lumbricus@gmx.net (lumbricus@gmx.net) Date: Mon Nov 18 23:59:02 2002 Subject: [Tutor] while with function References: Message-ID: <8245.1037681883@www42.gmx.net> Hi! > lumbricus@gmx.net said: > > > You want to use the GNU readline library. > > There is a python module, too. > > I can do this on a linux command line already. Am I missing something? If your shell is compiled with readline support - yes. I understood your post correctly, you wanted this feature in your python script. So you would 'import readline' and use readline.readline() instead of raw_input(). > Regards, HTH, J"o! > >From GNU Readline Manual: [ snip ] -- Wir beschliessen etwas, stellen das dann in den Raum und warten dann einige Zeit ab, was passiert. Wenn es dann kein grosses Geschrei gibt und keine Aufstaende, weil die meisten gar nicht begreifen, was da beschlossen wurde, dann machen wir weiter - Schritt fuer Schritt, bis es kein Zurueck mehr gibt. -- J-C Juncker +++ 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 Nov 19 00:04:01 2002 From: lumbricus@gmx.net (lumbricus@gmx.net) Date: Tue Nov 19 00:04:01 2002 Subject: [Tutor] regexes, thanks References: <6007.1037681493@www42.gmx.net> Message-ID: <11105.1037682230@www42.gmx.net> Me wrote: > Hi! > > > def upper(a) > > return(string.capitalize(a)) > > This already exists: > >>> "hello".upper() > 'HELLO' *Arghl* of course that's not the same. But you would pollute your namespace by naming this function upper. I don't see the point in just renaming the function string.capitalize() by redefining it either. So... import glob for f in glob.glob("*.mp3"): new=f.capitalize() > might be what you want? > > HTH, J"o! -- Wir beschliessen etwas, stellen das dann in den Raum und warten dann einige Zeit ab, was passiert. Wenn es dann kein grosses Geschrei gibt und keine Aufstaende, weil die meisten gar nicht begreifen, was da beschlossen wurde, dann machen wir weiter - Schritt fuer Schritt, bis es kein Zurueck mehr gibt. -- J-C Juncker +++ GMX - Mail, Messaging & more http://www.gmx.net +++ NEU: Mit GMX ins Internet. Rund um die Uhr für 1 ct/ Min. surfen! From bralzd@hotmail.com Tue Nov 19 00:33:01 2002 From: bralzd@hotmail.com (DAVID BRALLIER) Date: Tue Nov 19 00:33:01 2002 Subject: [Tutor] bEGINNING PROGRAMMER NEEDS HELP WITH CLASSES. CHECK CODE Message-ID: I'm trying to write a program that manages a small cash account. (Not really it's a school assignment) I have to use classes and implement them in the program. Here is what I have so far: Pretty sure the problem lies in the def init line. Can anyone help? #Account manager program from time import time, ctime initial = input("Type in the initial balance of your account:") def __init__(self, initial): return initial def deposit(initial, amt): return initial + amt def withdraw(initial,amt): return initial - amt def getbalance(initial,amt): return balance # Get the users transaction print "Please select a transaction: " print "1 Deposit" print "2 Withdrawal" print "3 Balance inquiry" # Users choice: def deposit(initial, amt): return initial + amt transaction = input("> ") if transaction == 1: print "How much do you want to deposit?" amt= input(">") print deposit print "The time of your transaction is:",ctime(time()) elif transaction == 2: amt = input("How much do you want to withdraw?: ") print withdraw print "Your balance is:", balance print "The time of your transaction is:", ctime (time()) else: print "Your balance is:", initial print "The time of your inquiry is:",ctime (time()) _________________________________________________________________ MSN 8 with e-mail virus protection service: 2 months FREE* http://join.msn.com/?page=features/virus From alan.gauld@bt.com Tue Nov 19 04:00:02 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Nov 19 04:00:02 2002 Subject: [Tutor] my newbie program Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA75@mbtlipnt02.btlabs.bt.co.uk> > > self.commandlist = ['look','n'] > > > I think this won't work. there is no name self here. So better > either delete the self. to create a class-variable Oops. Yes that's what I intended! > > while 1: > > me.act() > > if not map(lambda x: x != 0, me.location.exits): > > break > > > > > This is a little bit disturbing. Wasn't the original concept, > that exits should be a four element list, containing exits Dunno, I assumed it was just a list of exits with no numerical restriction. I guess 4 makes sense tho'. Shouldn't change the above tho' it still checks for a list of all zeros... The real point was to do more than just call act() once! Alan G. From alan.gauld@bt.com Tue Nov 19 04:11:43 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Nov 19 04:11:43 2002 Subject: [Tutor] while with function Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA76@mbtlipnt02.btlabs.bt.co.uk> > So maybe get_list() should be renamed edit_list(); but in any > event, it refers to the list of variables for each address book entry OK So in that case pass the entry in as a parameter. You can have a default parameter of None and if None is passed it effectively creates a new entry. The modified(or created) entry is then returned This avoids the nightmare of accessing the same set of global variables from lots of different functions. > I prefer not to mess with classes at this point in my python > education. Thats OK, It just happens that this is one application where they are perfectly suited, but you an do it without... > following it in some cases. And none of it appears to allow > me to review and correct the new address book entry before > I "commit" it to the database. Well we didn't know until now that that was a requirement. Personally I'd use two functions, one to dsplay and entry and a separate one to edit an entry. You then have a loop something like: def is_ok(entry): # display entry content # ask if user is happy # return y/n def edit_entry(entry=None): if entry == None: # create new entry with default values #foreach field in entry #get input per field return entry while not is_ok(entry): entry = edit_entry(entry) save_entry(entry) Alan G. From thomi@thomi.imail.net.nz Tue Nov 19 04:24:01 2002 From: thomi@thomi.imail.net.nz (Thomi Richards) Date: Tue Nov 19 04:24:01 2002 Subject: [Tutor] bEGINNING PROGRAMMER NEEDS HELP WITH CLASSES. CHECK CODE In-Reply-To: References: Message-ID: <20021119222209.4b54ba79.thomi@thomi.imail.net.nz> > Pretty sure the problem lies in the def init line. Can anyone help? OKJ, I'm not yet very good with clases, but shouldn't it be something like this: > > #Account manager program > from time import time, ctime > initial = input("Type in the initial balance of your account:") Class blah(blah blah blah) > def __init__(self, initial): > return initial > def deposit(initial, amt): > return initial + amt > def withdraw(initial,amt): > return initial - amt > def getbalance(initial,amt): > return balance > etc. etc. etc.?? Take a look at the classes page in teh python tutorial. It does a fairly good job of explaining it. -- Thomi Richards thomi@imail.net.nz http://ddmodd.sourceforge.net/ Thomi Richards, thomi@imail.net.nz From magnus@thinkware.se Tue Nov 19 04:30:42 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Nov 19 04:30:42 2002 Subject: [Tutor] Any Suggestions? In-Reply-To: <1037666342.1292.12.camel@localhost.localdomain> References: < <5104D4DBC598D211B5FE0000F8FE7EB20E66CA59@mbtlipnt02.btlabs.bt.co.uk> <5104D4DBC598D211B5FE0000F8FE7EB20E66CA59@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <5.1.0.14.0.20021119102430.02aa4830@www.thinkware.se> At 19:38 2002-11-18 -0500, Mark Brown wrote: >Alan, >Thanks for the suggestions. I'd found the runit.py program somewhere on >the web and used it to learn import, class and Tkinter so that's why it >was split into two programs. I was trying to separate the GUI and the >main program logic so that once the Tk GUI was working then would work >on a wxWindows GUI interface. I'm considering changing the direction of >the importing. Currently the main program imports the Tk GUI but do you >think it should be reversed? Logically, it's typically the GUI that depends on the underlying logic, while the logic could be utilized in a non-GUI context, maybe in a CGI-script, or as a library module in some larger program. Also, automated unit tests are always a good thing, and they are much more complicated to do with a GUI. Thus. I try to keep my logic independent from any user interface code (be it GUI, Web UI or anything else) and to make a thin GUI layer that imports the logic. -- 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 thomi@thomi.imail.net.nz Tue Nov 19 05:27:01 2002 From: thomi@thomi.imail.net.nz (Thomi Richards) Date: Tue Nov 19 05:27:01 2002 Subject: [Tutor] speeding code along In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA66@mbtlipnt02.btlabs.bt.co.uk> References: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA66@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <20021119232609.1047bfe5.thomi@thomi.imail.net.nz> OK, i just thought I'd share the results I've been getting here. With no pickled lookup table: bash-2.05b$ ./convert.py finished file wall-01.jpg, taking 5.194403 seconds finished file wall-04.jpg, taking 0.995965 seconds finished file wall-06.jpg, taking 0.673277 seconds finished file wall-08.jpg, taking 1.808828 seconds finished file guardhouse.jpg, taking 11.651091 seconds there were 16140 keys in the colortable! saving colortable then on the next run, with the same images, and the lookup table from before: bash-2.05b$ ./convert.py finished file wall-01.jpg, taking 0.740770 seconds finished file wall-04.jpg, taking 0.199411 seconds finished file wall-06.jpg, taking 0.203241 seconds finished file wall-08.jpg, taking 0.794629 seconds finished file guardhouse.jpg, taking 6.424407 seconds there were 16140 keys in the colortable! saving colortable of course, this is using the same images, so it's actually never working it out at all, but still, This is a HUGE improvement, over the 45 second periods i was waiting in the first version of this program. thanks to all who helped :-) -- Lord, what fools these mortals be! -- midsummer nights dream. Thomi Richards, thomi@imail.net.nz From glingl@aon.at Tue Nov 19 05:33:01 2002 From: glingl@aon.at (Gregor Lingl) Date: Tue Nov 19 05:33:01 2002 Subject: [Tutor] my newbie program References: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA75@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <3DDA131E.4020303@aon.at> alan.gauld@bt.com schrieb: >>> self.commandlist = ['look','n'] >>> >>> >>> >>I think this won't work. there is no name self here. So better >>either delete the self. to create a class-variable >> >> > >Oops. Yes that's what I intended! > > > >>> while 1: >>> me.act() >>> if not map(lambda x: x != 0, me.location.exits): >>> break >>> >>> >>> >>> >>This is a little bit disturbing. Wasn't the original concept, >>that exits should be a four element list, containing exits >> >> > >Dunno, I assumed it was just a list of exits with no numerical >restriction. I guess 4 makes sense tho'. Shouldn't change the >above tho' it still checks for a list of all zeros... > > I don't think, that this does, what you expect: >>> map(lambda x: x!=0, [0,0,0,0]) [0, 0, 0, 0] >>> not map(lambda x: x!=0, [0,0,0,0]) 0 # no break ..... but: >>> not map(lambda x: x!=0, []) 1 # break Regards, Gregor >The real point was to do more than just call act() once! > >Alan G. > > > > From glingl@aon.at Tue Nov 19 06:01:02 2002 From: glingl@aon.at (Gregor Lingl) Date: Tue Nov 19 06:01:02 2002 Subject: [Tutor] bEGINNING PROGRAMMER NEEDS HELP WITH CLASSES. CHECK CODE References: <20021119222209.4b54ba79.thomi@thomi.imail.net.nz> Message-ID: <3DDA19CF.4090506@aon.at> Thomi Richards schrieb: >>Pretty sure the problem lies in the def init line. Can anyone help? >> >> > >OKJ, I'm not yet very good with clases, but shouldn't it be something >like this: > > > > >>#Account manager program >>from time import time, ctime >>initial = input("Type in the initial balance of your account:") >> >> >Class blah(blah blah blah) > > def __init__(self, initial): > > return initial > > def deposit(initial, amt): > > return initial + amt > > def withdraw(initial,amt): > > return initial - amt > > def getbalance(initial,amt): > > return balance > > > Unfortunately this is still far from what is - presumably - desired: class account: # (doesn't inherit from blah blah) def __init__(self, initial): self.balance = initial # you have to create an instance-Variable # so the account will remember its balance def deposit(self, amount): self.balance += amount .... etc. To work successfully with classes needs certainly reading some introductory material - I think Alan's tutor wouold be a fine starting point: http://www.crosswinds.net/~agauld/ Gregor > >etc. etc. etc.?? > >Take a look at the classes page in teh python tutorial. It does a fairly >good job of explaining it. > > > From magnus@thinkware.se Tue Nov 19 06:15:03 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Nov 19 06:15:03 2002 Subject: [Tutor] while with function In-Reply-To: References: <5.1.0.14.0.20021118232028.036d92d0@www.thinkware.se> Message-ID: <5.1.0.14.0.20021119104413.02ad0c40@www.thinkware.se> At 22:05 2002-11-18 -0500, fleet@teachout.org wrote: >The only person who will use this is me. From the command line. > >What would you recommend to replace raw_input? Your favourite editor! I tried to describe the process in my previous mail. This will make it possible for the user to mess things up by fiddling with the labels, but if you are the only user, that's probably not a big issue. You get a much better chance to use your normal editing facilities, get an overview of the data, and to change whatever you want in the order that suits you best. You can also use cut and paste, macros, get data from other files etc. Check this out! # edit.py (c) Magnus Lyck=E5, magnus@thinkware.se, 2002 import os, tempfile def edit(keyValuePairs, sep=3D':', editor=3D'$EDITOR'): fileName =3D tempfile.mktemp('txt') data =3D [] for key, value in keyValuePairs: assert key.find(sep) =3D=3D -1 if key: data.append('%s%s %s\n' % (key, sep, value)) else: data.append(value+'\n') # Save data to temporary file f =3D open(fileName, 'wt') f.writelines(data) f.close() # Edit temporary file os.system('%s %s' % (editor, fileName)) # Read data from temporary file data =3D open(fileName, 'rt').readlines() # Remove temporary file os.unlink(fileName) output =3D [] for row in data: if row.find(sep) !=3D -1: key, value =3D row.split(sep, 1) output.append((key.strip(), value.strip())) else: output.append(('',row.strip())) return output def test(): data =3D [('','# Grades for Python training'), ('student','Zerblatt'), ('grade', 'A'), ('','#'), ('student','Ernie'), ('grade', 'C'), ('','#'), ('student','Sid'), ('grade', 'F'), ('','#')] data =3D edit(data) # Depending on settings and preferences you might # want to change this to: # data=3Dedit(data, editor=3D'notepad.exe') # data=3Dedit(data, editor=3D'vi') # data=3Dedit(data, editor=3D'emacs') # or whatever... for row in data: print "%s %s" % row if __name__ =3D=3D '__main__': test() --=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 Tue Nov 19 06:21:13 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Nov 19 06:21:13 2002 Subject: [Tutor] regexes, thanks In-Reply-To: <3DD9B560.5070108@ipwib.net> References: Message-ID: <5.1.0.14.0.20021119121903.02acb8b0@www.thinkware.se> At 22:52 2002-11-18 -0500, Matt wrote: > return(string.capitalize(a)) return is a statement, not a function. Please write return XXX NOT return(XXX) It doesn't change the way things work, but there is no more reason to type "return(xxx)" than to type "print(xxx);" See PEP 8 -- 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 thomi@thomi.imail.net.nz Tue Nov 19 06:27:02 2002 From: thomi@thomi.imail.net.nz (Thomi Richards) Date: Tue Nov 19 06:27:02 2002 Subject: [Tutor] Tkinter problems In-Reply-To: <20021116111044.4802c270.thomi@thomi.imail.net.nz> References: <5104D4DBC598D211B5FE0000F8FE7EB21877A51A@mbtlipnt02.btlabs.bt.co.uk> <20021116111044.4802c270.thomi@thomi.imail.net.nz> Message-ID: <20021120002635.493d9a2c.thomi@thomi.imail.net.nz> Slight problem: I've noticed that as soon as i create a message box using the tkMessageBox module, it creates a blank root window on the screen. I would like to utilise that root window. is there a way? I guess i need to know what the name of the root window object is, so i can do something like: lstatus = Tkinter.Label(tkMessageBox.rootwindow,text="testing, testing...") lstatus.pack() blah blah blah. I had a look at the source of that module, but couldn't make head or tail of it. Can anyone help? -- Thomi Richards thomi@imail.net.nz http://thomi.imail.net.nz/ Thomi Richards, thomi@imail.net.nz From thomi@thomi.imail.net.nz Tue Nov 19 06:27:18 2002 From: thomi@thomi.imail.net.nz (Thomi Richards) Date: Tue Nov 19 06:27:18 2002 Subject: [Tutor] bEGINNING PROGRAMMER NEEDS HELP WITH CLASSES. CHECK CODE In-Reply-To: <20021119222209.4b54ba79.thomi@thomi.imail.net.nz> References: <20021119222209.4b54ba79.thomi@thomi.imail.net.nz> Message-ID: <20021120002333.256cc933.thomi@thomi.imail.net.nz> This is a multi-part message in MIME format. --Multipart_Wed__20_Nov_2002_00:23:33_+1300_08850df0 Content-Type: text/plain; charset=US-ASCII Content-Transfer-Encoding: 7bit actually, this got me thinking about classes, and to test my knowledge... view the attachment :-) -- Lord, what fools these mortals be! -- midsummer nights dream. Thomi Richards, thomi@imail.net.nz --Multipart_Wed__20_Nov_2002_00:23:33_+1300_08850df0 Content-Type: application/octet-stream; name="bank.py" Content-Disposition: attachment; filename="bank.py" Content-Transfer-Encoding: base64 IyEvdXNyL2Jpbi9weXRob24KCgpjbGFzcyBhY2NvdW50OgoJZGVmIF9faW5pdF9fKHNlbGYsbmFt ZSxiYWxhbmNlPTApOgoJCXNlbGYuYmFsYW5jZSA9IGJhbGFuY2UKCQlzZWxmLm5hbWUgPSBuYW1l CglkZWYgZGVwb3NpdChzZWxmLGFtb3VudCk6CgkJc2VsZi5iYWxhbmNlKz1hbW91bnQKCWRlZiB3 aXRoZHJhdyhzZWxmLGFtb3VudCk6CgkJc2VsZi5iYWxhbmNlLT1hbW91bnQKCWRlZiBzdGF0ZW1l bnQoc2VsZik6CgkJcmV0dXJuICclcywgeW91ciBhY2NvdW50IGhhcyAkJWQgaW4gaXQhJyAlIChz ZWxmLm5hbWUsc2VsZi5iYWxhbmNlKQoKc2F2aW5ncyA9IGFjY291bnQoJ1Rob21pIFJpY2hhcmRz JykKY2hlcXVlID0gYWNjb3VudCgnVGhvbWkgUmljaGFyZHMnLDUxMikKCmNoZXF1ZS5kZXBvc2l0 KDgpCnNhdmluZ3MuZGVwb3NpdCgxMTIpCgpwcmludCBjaGVxdWUuc3RhdGVtZW50KCkKcHJpbnQg c2F2aW5ncy5zdGF0ZW1lbnQoKQoJCg== --Multipart_Wed__20_Nov_2002_00:23:33_+1300_08850df0-- From fleet@teachout.org Tue Nov 19 07:23:13 2002 From: fleet@teachout.org (fleet@teachout.org) Date: Tue Nov 19 07:23:13 2002 Subject: [Tutor] Re: Tutor digest, Vol 1 #2066 - 15 msgs In-Reply-To: <20021119112113.532.32632.Mailman@mail.python.org> Message-ID: test.py import readline s=readline.readline("Name: ") [~/python]$ python2 test.py Traceback (most recent call last): File "test.py", line 3, in ? s=readline.readline("name: ") AttributeError: 'module' object has no attribute 'readline' ??? - fleet - On Tue, 19 Nov 2002 tutor-request@python.org wrote: > Send Tutor mailing list submissions to > tutor@python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request@python.org > > You can reach the person managing the list at > tutor-admin@python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. RE: while with function (fleet@teachout.org) > 2. regexes, thanks (Matt) > 3. Re: regexes, thanks (lumbricus@gmx.net) > 4. RE: while with function (lumbricus@gmx.net) > 5. Re: regexes, thanks (lumbricus@gmx.net) > 6. bEGINNING PROGRAMMER NEEDS HELP WITH CLASSES. CHECK CODE (DAVID BRALLIER) > 7. RE: my newbie program (alan.gauld@bt.com) > 8. RE: while with function (alan.gauld@bt.com) > 9. Re: bEGINNING PROGRAMMER NEEDS HELP WITH CLASSES. CHECK CODE (Thomi Richards) > 10. RE: Any Suggestions? (Magnus Lycka) > 11. Re: speeding code along (Thomi Richards) > 12. Re: my newbie program (Gregor Lingl) > 13. Re: bEGINNING PROGRAMMER NEEDS HELP WITH CLASSES. CHECK CODE (Gregor Lingl) > 14. RE: while with function (Magnus Lycka) > 15. Re: regexes, thanks (Magnus Lycka) > > --__--__-- > > Message: 1 > Date: Mon, 18 Nov 2002 22:07:33 -0500 (EST) > From: > Reply-To: > To: Magnus Lycka > cc: > Subject: RE: [Tutor] while with function > > On Mon, 18 Nov 2002, Magnus Lycka wrote: > > > At 15:42 2002-11-18 -0500, fleet@teachout.org wrote: > > >The "address book" entries will be created, maintained and utilized from a > > >command line. > > That's a Linux command line, btw. > > - fleet - > > > > --__--__-- > > Message: 2 > Date: Mon, 18 Nov 2002 22:52:00 -0500 > From: Matt > To: tutor@python.org > Subject: [Tutor] regexes, thanks > > I'm working on a renaming utility for use in renaming mp3's that I > ripped from cd while using Windows (and consequently using my preferred > naming convention at the time, which I no longer wish to use). I > created a file listing, then tried manipulating it. I wanted to make it > change every word (defined by only letter sequences) to have the first > letter changed to uppercase. Only it doesn't seem that regexes are > fully implemented in python (\u,\U)... So, I tried using a function: > > def upper(a) > return(string.capitalize(a)) > > words = re.compile('([a-zA-Z]+)') > new_filename = words.sub(upper, filename) > > Only this doesn't work, as it doesn't pass the matched string, but a > MatchObject. This seemed really strange to me. Eventually I came up > with this: > > def upper(a): > return(string.capitalize(a.string[a.start():a.end()])) > > words = re.compile('([a-zA-Z]+)') > new_filename = words.sub(upper, filename) > > This seems like a really complicated way to do something that I thought > would be relatively simple. Is this the best way to do it? Or am I off > track and creating unnecessary complexity? > > Btw, thanks to Danny Yoo for helping me out with python audio > information. Several of the sites have proved extremely helpful. > > -Matt > > > > --__--__-- > > Message: 3 > Date: Tue, 19 Nov 2002 05:51:33 +0100 (MET) > From: lumbricus@gmx.net > To: tutor@python.org > Subject: Re: [Tutor] regexes, thanks > > Hi! > > > def upper(a) > > return(string.capitalize(a)) > > This already exists: > >>> "hello".upper() > 'HELLO' > > > words = re.compile('([a-zA-Z]+)') > > new_filename = words.sub(upper, filename) > > > > Only this doesn't work, as it doesn't pass the matched string, but a > > MatchObject. This seemed really strange to me. > > >>> help(re.compile) > Help on function compile: > > compile(pattern, flags=0) > Compile a regular expression pattern, returning a pattern object. > > > > > def upper(a): > > return(string.capitalize(a.string[a.start():a.end()])) > > > > words = re.compile('([a-zA-Z]+)') > > new_filename = words.sub(upper, filename) > > Something along > > import glob > for f in glob.glob("*.mp3"): > new=f.upper() > > might be what you want? > > HTH, J"o! > > From lumbricus@gmx.net Tue Nov 19 07:32:01 2002 From: lumbricus@gmx.net (lumbricus@gmx.net) Date: Tue Nov 19 07:32:01 2002 Subject: [Tutor] Re: Tutor digest, Vol 1 #2066 - 15 msgs References: Message-ID: <11145.1037709058@www45.gmx.net> Hi! > test.py > import readline > > s=readline.readline("Name: ") > > [~/python]$ python2 test.py > Traceback (most recent call last): > File "test.py", line 3, in ? > s=readline.readline("name: ") > AttributeError: 'module' object has no attribute 'readline' > > ??? "http://www.python.org/doc/current/lib/module-readline.html" [ tons of stuff snipped ] :-\ HTH, J"o! -- -- Wir beschliessen etwas, stellen das dann in den Raum und warten dann einige Zeit ab, was passiert. Wenn es dann kein grosses Geschrei gibt und keine Aufstaende, weil die meisten gar nicht begreifen, was da beschlossen wurde, dann machen wir weiter - Schritt fuer Schritt, bis es kein Zurueck mehr gibt. -- J-C Juncker +++ 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 Tue Nov 19 07:48:27 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Nov 19 07:48:27 2002 Subject: [Tutor] while with function In-Reply-To: References: <5.1.0.14.0.20021119104413.02ad0c40@www.thinkware.se> Message-ID: <5.1.0.14.0.20021119134218.02afd088@www.thinkware.se> At 07:11 2002-11-19 -0500, fleet@teachout.org wrote: >On Tue, 19 Nov 2002, Magnus Lycka wrote: > > > Check this out! > > > > # edit.py (c) Magnus Lyck=E5, magnus@thinkware.se, 2002 > > import os, tempfile > >Saved the file, ran with python2, get following error: >sh: /tmp/@9273.0txt: Permission denied This is because $EDITOR isn't set. Then you will basically try to execute the file /tmp/@9273.0txt, and its execution flag isn't set. (Wouldn't do much good anyay...) As I wrote in the code, $EDITOR must be set, or you have to use one of the commented out variants. Either run $ export EDITOR=3Dvi (assuming that you use bash) or change the source to data =3D edit(data, editor=3D'vi') (or joe, or xemacs or whatever editor you prefer) --=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 din22@cox.net Tue Nov 19 08:26:01 2002 From: din22@cox.net (sheri) Date: Tue Nov 19 08:26:01 2002 Subject: [Tutor] my newbie program Message-ID: <001301c28fcf$3aeb5a20$fc550144@pn.at.cox.net> This is a multi-part message in MIME format. ------=_NextPart_000_0010_01C28F9C.F027B740 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable hello and thanks for the help on my program so far. what i am wondering is how hard would it be to implement a dig command that would create room objects while the game is running. also the appropriate exits. so something like dig(north) would create a new exit to a new room with an exit back to the room you dug from. i am guessing pretty hard but then, i am a=20 rank beginner so maybe its easy. or are=20 vague questions like this off topic here? i havent written any code for this because=20 i wouldnt know where to start. ------=_NextPart_000_0010_01C28F9C.F027B740 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
hello and thanks for the help on my=20 program
so far. what i am wondering is how hard = would
it be to implement a dig command that=20 would
create room objects while the game is=20 running.
also the appropriate exits. so = something=20 like
dig(north) would create a new exit to a = new=20 room
with an exit back to the room you dug=20 from.
i am guessing pretty hard but then, i = am a=20
rank beginner so maybe its easy. = or are
vague questions like this off topic=20 here?
i havent written any code=20 for this because
i = wouldnt know where to start.
 
------=_NextPart_000_0010_01C28F9C.F027B740-- From din22@cox.net Tue Nov 19 10:57:11 2002 From: din22@cox.net (sheri) Date: Tue Nov 19 10:57:11 2002 Subject: [Tutor] re:my newbie program Message-ID: <001601c28fe4$5b6d4b40$fc550144@pn.at.cox.net> This is a multi-part message in MIME format. ------=_NextPart_000_0013_01C28FB2.10A080A0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable wow. i'll be studying that for a while i think. thanks. ------=_NextPart_000_0013_01C28FB2.10A080A0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
wow. i'll be studying that for a while = i=20 think.
thanks.
------=_NextPart_000_0013_01C28FB2.10A080A0-- From matt@ipwib.net Tue Nov 19 11:21:02 2002 From: matt@ipwib.net (Matt) Date: Tue Nov 19 11:21:02 2002 Subject: [Tutor] regexes, thanks References: <3DD9B560.5070108@ipwib.net> <6007.1037681493@www42.gmx.net> Message-ID: <3DDA67E2.4040201@ipwib.net> I was actually wanting to take a list of filenames, for example: Pink Floyd - 02 - Dogs.mp3 Japanese_Noh_Music_--_Gaku.mp3 asu - searching_2001_edit.MP3 ...and pass it through a sequence of regexes (of which this is just one) to produce consistent filenames along the lines of: Pink_Floyd-02-Dogs.mp3 Japanese_Noh_Music--Gaku.mp3 Asu--Searching_2001_Edit.mp3 I first read in the filenames, then produce a list of tuples [filename, new_filename], which are used for renaming at the end. So, I need to perform operations on certain parts of the filename, not just the whole thing. It seems that there would be a simple way to perform this stage. Like, new_filename = words.sub('([a-zA-Z]+)', '\u\1', filename) But I couldn't get \1, \2 substitution working (had to use '\g<1>') and it doesn't look like python supports \u and \U ('man perlre' for info), so that I couldn't just put '\u\1' in the substitution string. I'm just wondering if what I came up with is the most efficient method for performing what I need at this stage. Anyway... Thanks for the help. I hadn't looked at globs before, so that will be very helpful. -Matt lumbricus@gmx.net wrote: [snip!] >> >> def upper(a): >> return(string.capitalize(a.string[a.start():a.end()])) >> >> words = re.compile('([a-zA-Z]+)') >> new_filename = words.sub(upper, filename) > > > Something along > > import glob > for f in glob.glob("*.mp3"): > new=f.upper() > > might be what you want? > > HTH, J"o! From lumbricus@gmx.net Tue Nov 19 11:42:01 2002 From: lumbricus@gmx.net (lumbricus@gmx.net) Date: Tue Nov 19 11:42:01 2002 Subject: [Tutor] regexes, thanks References: <3DDA67E2.4040201@ipwib.net> Message-ID: <18021.1037724078@www45.gmx.net> Hello! > I was actually wanting to take a list of filenames, for example: > > Pink Floyd - 02 - Dogs.mp3 > Japanese_Noh_Music_--_Gaku.mp3 > asu - searching_2001_edit.MP3 > > ...and pass it through a sequence of regexes (of which this is just one) > to produce consistent filenames along the lines of: > > Pink_Floyd-02-Dogs.mp3 > Japanese_Noh_Music--Gaku.mp3 > Asu--Searching_2001_Edit.mp3 Dashes in file names are pure evil - avoid them. > I first read in the filenames, then produce a list of tuples [filename, > new_filename], which are used for renaming at the end. So, I need to > perform operations on certain parts of the filename, not just the whole > thing. It seems that there would be a simple way to perform this stage. > Like, > > new_filename = words.sub('([a-zA-Z]+)', '\u\1', filename) > But I couldn't get \1, \2 substitution working (had to use '\g<1>') and group() > it doesn't look like python supports \u and \U ('man perlre' for info), capitalize()? > -Matt I'm not so good in Pythons re - sorry. HTH anyway, J"o! -- Wir beschliessen etwas, stellen das dann in den Raum und warten dann einige Zeit ab, was passiert. Wenn es dann kein grosses Geschrei gibt und keine Aufstaende, weil die meisten gar nicht begreifen, was da beschlossen wurde, dann machen wir weiter - Schritt fuer Schritt, bis es kein Zurueck mehr gibt. -- J-C Juncker +++ GMX - Mail, Messaging & more http://www.gmx.net +++ NEU: Mit GMX ins Internet. Rund um die Uhr für 1 ct/ Min. surfen! From alan.gauld@bt.com Tue Nov 19 13:14:10 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Nov 19 13:14:10 2002 Subject: [Tutor] my newbie program Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA77@mbtlipnt02.btlabs.bt.co.uk> > I don't think, that this does, what you expect: > > >>> map(lambda x: x!=0, [0,0,0,0]) > [0, 0, 0, 0] Doh! should be filter() not map! Alan G. From alan.gauld@bt.com Tue Nov 19 13:34:02 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Nov 19 13:34:02 2002 Subject: [Tutor] bEGINNING PROGRAMMER NEEDS HELP WITH CLASSES. CHECK C ODE Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA7A@mbtlipnt02.btlabs.bt.co.uk> > To work successfully with classes needs certainly reading some > introductory material - I think Alan's tutor wouold be a fine > starting > point: > > http://www.crosswinds.net/~agauld/ > > Gregor Thanks for the plug and in this case it would certainly be applicable since it implements a BankAccount example... However the up to date url is as in my sig below... The Crosswinds one is still there but not updated regularly. Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld@bt.com Tue Nov 19 13:38:04 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Nov 19 13:38:04 2002 Subject: [Tutor] Tkinter problems Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA7B@mbtlipnt02.btlabs.bt.co.uk> > I've noticed that as soon as i create a message box using the > tkMessageBox module, it creates a blank root window on the screen. Sounds like you are misusing the message box module somehow. What does some sample code look like? Alan G. From alan.gauld@bt.com Tue Nov 19 13:52:02 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Nov 19 13:52:02 2002 Subject: [Tutor] my newbie program Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA7C@mbtlipnt02.btlabs.bt.co.uk> > dig(north) would create a new exit to a new room > with an exit back to the room you dug from. Something like: class Rooom: # as before... directions = ['north','east',west,'south'] def dig(self, direction): self.exits[direction] = Room("My new room") dirindex = directions.index(direction) newdir = directions[-dirindex+1] # get inverse direction self.exits[direction].exits[newdir] = self Note I've changed exits from a list to a dictionary keyed by direction. I add the new room as the new exit of the current room. I find the index of the direction in the list I take the inverse by using the negative index - try it out by hand... I add the exising room as an exit to the new one... All untested of course but might form a basis??? Alan g. From fleet@teachout.org Tue Nov 19 15:29:01 2002 From: fleet@teachout.org (fleet@teachout.org) Date: Tue Nov 19 15:29:01 2002 Subject: [Tutor] Dang! Message-ID: > [ tons of stuff snipped ] :-\ My abject apoligies to the list for including the whole D*** digest! - fleet - From joney@clara.co.uk Tue Nov 19 16:04:28 2002 From: joney@clara.co.uk (john gennard) Date: Tue Nov 19 16:04:28 2002 Subject: [Tutor] why doesn't procbox run? In-Reply-To: References: Message-ID: <02111920434701.00300@Leary> On Monday 18 November 2002 18:17, Danny Yoo wrote: > On Mon, 18 Nov 2002, john gennard wrote: Hi Danny, I've solved the problem, but I don't why what I did cleared matters up, and I suppose now I never will. My permissions were exactly the same as those in Potato - I checked every one in detail. I have Potato and Woody on the same machine, so it was easy to mount one onto the other and check 'side by side' (I even printed everything out to study/compare). /usr/local/bin/procbox.py was definitely 0755. I deleted Python and procbox and shutdown. After a cuppa I reinstalled both and the program ran without difficulty. I've checked all permissions against my print out and there's no variation (except that the program now runs) [snip] > > > > Procbox is written in Python, but does not run on Woody. The > > error message says 'bash: /usr/local/bin/procbox.py: > > /usr/bin/python: bad interpreter: Permission denied' > > > > All permissions have been checked against Potato as has the > > integrity of the program, PATHS and so forth. > > Hi John, > > That's odd! Hmmm... do you think it might be a permissions > problem? '/usr/bin/python' is definitely there on your system; > otherwise, you would have gotten the error message: > > ### > bash: ./foo.py: /usr/bin/python: bad interpreter: No such file or > directory > ### > > > instead of "Permission denied." > > > Oh! Wait. > > > http://lists.debian.org/debian-user/2002/debian-user-200210/msg065 >10.html > > Ah ha! This sounds familiar... *grin* > > > John, check the permissions on the procbox script: I get the > feeling that the script itself is not executable. The error > message that you're getting is misleading by not telling that the > script itself might not have the right permissions set up. Here's > an example of what can happen: > > ### > [dyoo@tesuque dyoo]$ cat foo.py > #!/usr/bin/python > > print "hello" > [dyoo@tesuque dyoo]$ ls -l foo.py > -rw-r--r-- 1 dyoo users 33 Nov 18 10:12 foo.py > [dyoo@tesuque dyoo]$ ./foo.py > bash: ./foo.py: /usr/bin/python: bad interpreter: Permission > denied [dyoo@tesuque dyoo]$ > [dyoo@tesuque dyoo]$ chmod +x foo.py > [dyoo@tesuque dyoo]$ ./foo.py > hello > [dyoo@tesuque dyoo]$ ls -l foo.py > -rwxr-xr-x 1 dyoo users 33 Nov 18 10:12 foo.py > ### > > > Next time, you might also want to try the Debian-user mailing > list, because it's very possible that someone else there has run > into a similar issue. > > http://lists.debian.org/debian debian-user is my 'home list'. I tried this list first, because I had no way of knowing whether to problem was python or Debian specific. And, of course, I still do not. The suggestion from Magnus gave me 'can't open file' and that from Emile didn't make any difference. Many thanks to you all for the suggestions and support. With gratitude, John. From joney@clara.co.uk Tue Nov 19 16:04:48 2002 From: joney@clara.co.uk (john gennard) Date: Tue Nov 19 16:04:48 2002 Subject: was: [Tutor] getting started In-Reply-To: <5.1.0.14.0.20021118210056.036c0c08@www.thinkware.se> References: <5.1.0.14.0.20021118210056.036c0c08@www.thinkware.se> Message-ID: <02111823063800.00380@Leary> On Monday 18 November 2002 20:03, Magnus Lycka wrote: > At 15:15 2002-11-15 +0000, john gennard wrote: > >Many thanks to Magnus Lucka and Kirk Bailey who responded to my > >request for assistance. They have already 'put me right' and I'm > > now ready to proceed. > > You're welcome. It's Lyckå, actually, but I bet you'd > never guess how to pronounce that anyway! ;) > Surprisingly, I would! I'm well into my seventies and many years ago (more than I want to remember), it was necessary that I obtained a working knowledge of both Swedish and Finnish. Little now remains to me. I remember finding Swedish quite easy to learn but a bit of a b.... to pronounce (especially late in the evening - your drink laws being a lot different in those days). Finnish was a different kettle of fish - not helped as native speakers were few and far between were I was ( I believe they are not very numerous even now ). You assume English is my mother tongue - I wonder then why you assume I would have a Swedish keyboard 'just handy'. I have a GB one and you come across as 'Lyck=E5', now that I can't pronounce. I'm going to enjoy this list! The banter is refreshing and the answers to questions go straight to the point. Many thanks for your help with my initial problem. > >Obviously this list is friendly and helpful to newcomers to > > Python. > > Except when I get into my monotone preaching mode! ;) > > > I've-always-tried-to-figure-out-how-to-be-brief-but-never-quite-ma >naged-to-get-it'ly yours, > > Magnus From magnus@thinkware.se Tue Nov 19 17:14:49 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Nov 19 17:14:49 2002 Subject: Fwd: RE: [Tutor] while with function Message-ID: <5.1.0.14.0.20021119223426.02b63400@www.thinkware.se> >From: >Ok. I fixed the EDITOR problem. But I still don't know how I'm supposed >use this. As I understood your application, you have a number of parameters, and you should be able to enter new data as well as update existing data. Below is an example of how my edit module could be used. Save the code below to a file called edittest.py, and make sure that the previous edit.py is in the same directory. Then: $ python -i edittest.py >>> p = Person() >>> p.edit() # Now you are inside your editor. Write some nice values # after the colons and save and quit. (ZZ in vi) >>> print p # Now you should see what you wrote. Oops, you misspelled # a surname. >>> p.edit() # You see all the previously entered values. Correct what # needs to be corrected. Save and quit. >>> print p # Nice, it seems right now. # Are these really normal parameters? >>> print p.firstName >>> print p.phone # So it seems... If you like, you could use the edit module so that you list and permit editing of many, maybe all, your database values at once. Maybe you want to search and replace an area code for telephone numbers. Just use the normal editor features! You have all the editing features at your disposal. If you mess up, quit without saving, and you're back where you started. Isn't this better than raw_input? I hope te use of getattr and setattr below isn't too confusing. Basically getattr(a,'x') is the same as a.x, and a.y = 5 is the same as setattr(a, 'y', 5). Using getattr and setattr, it's easy to keep as list (_params) that tells which attributes we want to be able to edit and in what order to present and edit them, without all too much repetetive code. If we imagine several classes with different types of parameters, we could use the methods below in a base class, and then just change the class attribute _params in each derivate class. Nice, isn't it? ######################### import edit class Person: _params = ['firstName', 'lastName', 'phone', 'email'] def edit(self): data = [] for param in self._params: if hasattr(self, param): value = getattr(self, param) else: value = "" data.append((param, value)) data = edit.edit(data) for param, value in data: if param in self._params: setattr(self, param, value) def __str__(self): data = [] for param in self._params: if hasattr(self, param): value = getattr(self, param) else: value = "" data.append("%s = %s" % (param, value)) return "\n".join(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 magnus@thinkware.se Tue Nov 19 17:33:03 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Nov 19 17:33:03 2002 Subject: was: [Tutor] getting started In-Reply-To: <02111823063800.00380@Leary> References: <5.1.0.14.0.20021118210056.036c0c08@www.thinkware.se> <5.1.0.14.0.20021118210056.036c0c08@www.thinkware.se> Message-ID: <5.1.0.14.0.20021119231955.02b0e210@www.thinkware.se> At 20:18 2002-11-19 +0000, john gennard wrote: >Surprisingly, I would! :) Trevligt! >I'm well into my seventies It's an amazing mix of people here. Obviously not only geographically and professionally, but also age-wise. Few ladies though... >You assume English is my mother tongue I was "talking aloud" on the mailing list... Most people won't get it right. That's for sure. >- I wonder then why you >assume I would have a Swedish keyboard 'just handy'. I have a GB one >and you come across as 'Lyck=E5', now that I can't pronounce. :) You don't need any particular keyboard. Just a mail client that manages to present Quoted Printable right. I see a lot of stuff on my screen that I don't have keys for... I'm surprised that it came as QP though. I have turned that of (at least that was my intention--maybe Eudora is playing tricks with me), and just send 8 bit (wildly assuming that people will be using Latin 1 or some similar code page). That way, some people might not see it correctly, but fewer will see that QP garbage. It messes up the python code! >I'm going to enjoy this list! The banter is refreshing and the >answers to questions go straight to the point. Except possibly when we wander completely off topic like this. ;) I guess this where I should stop. -- 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 thomi@thomi.imail.net.nz Tue Nov 19 17:53:02 2002 From: thomi@thomi.imail.net.nz (Thomi Richards) Date: Tue Nov 19 17:53:02 2002 Subject: [Tutor] yet more Tkinter+class problems Message-ID: <20021120114218.10be3a94.thomi@thomi.imail.net.nz> hmmm... for some reason, anything in "statusframe" doesn't show up. heres the source, is there something i am doing really wrong? Do frames have to be nested inside each other?? surely not... (sorry about the indenting, sylpheed cuts the lines short...) ---- from Tkinter import * class convertapp: def __init__(self,): self.parent = Tk() self.mainframe = Frame(self.parent) self.mainframe.pack() self.buttonframe = Frame(self.mainframe) self.buttonframe.pack(side='top') self.statusframe = Frame(self.mainframe) self.buttonframe.pack(side='bottom') #buttons: self.gobutton = Button(self.buttonframe,text="Go!",command=self.testbar) self.gobutton.pack(side='left') self.quitbutton = Button(self.buttonframe,text="Quit",command=self.mainframe.quit) self.quitbutton.pack(side='left') #percent bar, and status text: self.statustext = Label(self.statusframe,text="Initialising") self.statustext.pack(side='top') self.percentbar = Canvas(self.statustext,height=20,width=200,bg='black') self.percentbar.create_line(0,6,0,6, fill='red', width=6, tag='bar') self.percentbar.pack(side='bottom') def testbar(self,x=10): if (x > 0) and (x < 200): self.percentbar.coords('bar', 0, 6, x, 6) else: self.percentbar.coords('bar', 0, 6, 50, 6) def start(self): self.mainframe.mainloop() app = convertapp() app.start() ---- thanks -- Lord, what fools these mortals be! -- midsummer nights dream. Thomi Richards, thomi@imail.net.nz From rickp@telocity.com Tue Nov 19 18:02:18 2002 From: rickp@telocity.com (Rick Pasotto) Date: Tue Nov 19 18:02:18 2002 Subject: [Tutor] yet more Tkinter+class problems In-Reply-To: <20021120114218.10be3a94.thomi@thomi.imail.net.nz> References: <20021120114218.10be3a94.thomi@thomi.imail.net.nz> Message-ID: <20021119230157.GA5315@tc.niof.net> On Wed, Nov 20, 2002 at 11:42:18AM +1300, Thomi Richards wrote: > > hmmm... for some reason, anything in "statusframe" doesn't show up. > heres the source, is there something i am doing really wrong? Do frames > have to be nested inside each other?? surely not... You pack the buttonframe twice and never pack the status frame. > self.buttonframe = Frame(self.mainframe) > self.buttonframe.pack(side='top') > > self.statusframe = Frame(self.mainframe) > self.buttonframe.pack(side='bottom') -- We recognize the right of every man to perform services for himself or to serve others according to conditions arrived at through free bargaining. Communism denies this right, since it places all services in the hands of an arbitrary, central authority. -- Frédéric Bastiat (1801-1850) Rick Pasotto rickp@telocity.com http://www.niof.net From thomi@thomi.imail.net.nz Tue Nov 19 18:29:03 2002 From: thomi@thomi.imail.net.nz (Thomi Richards) Date: Tue Nov 19 18:29:03 2002 Subject: [Tutor] yet more Tkinter+class problems In-Reply-To: <20021119230157.GA5315@tc.niof.net> References: <20021120114218.10be3a94.thomi@thomi.imail.net.nz> <20021119230157.GA5315@tc.niof.net> Message-ID: <20021120122648.40e24337.thomi@thomi.imail.net.nz> > You pack the buttonframe twice and never pack the status frame. ahhh!! so stupid!!! thanks :-) -- This is a subliminal message. Thomi Richards, thomi@imail.net.nz From bralzd@hotmail.com Tue Nov 19 19:49:01 2002 From: bralzd@hotmail.com (DAVID BRALLIER) Date: Tue Nov 19 19:49:01 2002 Subject: [Tutor] Help with Code (beginner) Error message Message-ID: Trying to make a simple program that manages a small bank account. (College assignment) I get an error message saying that "deposit is not defined" but as you can see I have defined it. Here is the code: #Account manager program from time import time, ctime class account: def __init__(self,initial): self.balance = initial def withdraw(self,amt): return initial - amt def deposit(self, amt): self.balance = self.balance + amt def getbalance(self): return self.balance list = [deposit(550.23),deposit(100), withdraw(50)] for transaction in list: print "The balance is: ", transaction.getbalance() print "The time of your transaction is: ", ctime (time()) _________________________________________________________________ MSN 8 helps eliminate e-mail viruses. Get 2 months FREE*. http://join.msn.com/?page=features/virus From op73418@mail.telepac.pt Tue Nov 19 20:04:01 2002 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Tue Nov 19 20:04:01 2002 Subject: [Tutor] Help with Code (beginner) Error message References: Message-ID: <000b01c29031$73179dc0$ae110dd5@violante> ----- Original Message ----- From: "DAVID BRALLIER" To: Sent: Wednesday, November 20, 2002 12:47 AM Subject: [Tutor] Help with Code (beginner) Error message > Trying to make a simple program that manages a small bank account. (College > assignment) I get an error message saying that "deposit is not defined" but > as you can see I have defined it. Here is the code: > > > > #Account manager program > from time import time, ctime > class account: A point of style: class names are usually capitalized, e.g. Account. > def __init__(self,initial): > self.balance = initial > def withdraw(self,amt): > return initial - amt What is initial here? it is not defined anywhere. Shouldn't it be self.balance? Besides, if you are *withdrawing* money it should be self.balance = self.balance - amount Why the return statement? > def deposit(self, amt): > self.balance = self.balance + amt > def getbalance(self): > return self.balance > > > list = [deposit(550.23),deposit(100), withdraw(50)] You are calling deposit as if it were a global function. While above you declared deposit as method of the class account - two very different things. That is you get the error you get - there is no global deposit function. What you want is probably instantiate the account class as in a = account(0) and *then* call a.deposit(550.23), etc. You should prolly go through the tutorial that comes with every Python distro and lookup the topic on classes to review the subject. Or go to the newbies page in www.python.org to find links to other tutorials. > for transaction in list: > print "The balance is: ", transaction.getbalance() > print "The time of your transaction is: ", ctime (time()) > > HTH, G. Rodrigues From magnus@thinkware.se Tue Nov 19 20:56:32 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Nov 19 20:56:32 2002 Subject: [Tutor] Help with Code (beginner) Error message In-Reply-To: <000b01c29031$73179dc0$ae110dd5@violante> References: Message-ID: <5.1.0.14.0.20021120024701.02b72f60@www.thinkware.se> >----- Original Message ----- >From: "DAVID BRALLIER" > > Trying to make a simple program that manages a small bank account. >(College > > assignment) At 01:09 2002-11-20 +0000, Gon=E7alo Rodrigues wrote: [Quite a lot] I'm not sure exactly how we should treat this, but I do think that school assignments should be done by the students, not by the mailing list. I'm glad that David was open about this, I get irritated when students post what is so obviously school work and pretend otherwise. Helping people who study, whether in school or by themselves is a good thing, but maybe we should try to restrain ourselves to giving small hints, maybe some question about what they meant by this or that... In these cases, the meaning of the assignment is NOT to get a certian program to work, but to learn things, and a certain amount of resistance makes us learn more I think. I certainly learn more if I have to struggle with something than if someone tells me the answers as soon as I get a little stuck... --=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 Tue Nov 19 21:02:19 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Nov 19 21:02:19 2002 Subject: [Tutor] Python in education Message-ID: <5.1.0.14.0.20021120025720.02a91c18@www.thinkware.se> We obviously have some students in the mailing list. (Come on now, don't be shy.) I'm curious. How much is Python used in education? Did you have to use python or could you use a language of your choice? At what level is python used in education, how central is it to the education, what kind of courses is it used in? What books do you use? How do you like 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 magnus@thinkware.se Tue Nov 19 21:06:49 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Nov 19 21:06:49 2002 Subject: [Tutor] Images + Tkinter In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA5F@mbtlipnt02.btlabs .bt.co.uk> Message-ID: <5.1.0.14.0.20021120030502.02b38d48@www.thinkware.se> At 10:30 2002-11-18 +0000, alan.gauld@bt.com wrote: > > At 17:50 2002-11-17 +0000, alan.gauld@bt.com wrote: > > >I feel stupid. I must be missing something... There's a thread at comp.lang.python called Tkinter wart: bug or feature? about this very issue of keeping references to images (if I understood the posts I saw). -- 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 Tue Nov 19 22:41:00 2002 From: Jmllr891@cs.com (Jmllr891@cs.com) Date: Tue Nov 19 22:41:00 2002 Subject: [Tutor] A good Pygame tutorial for beginners? Message-ID: <11c.1aa34650.2b0c5de5@cs.com> --part1_11c.1aa34650.2b0c5de5_boundary Content-Type: text/plain; charset="US-ASCII" Content-Transfer-Encoding: 7bit I've read through the line-by-line Chimp tutorial that comes as part of the Pygame documentation, but that just doesn't do it for me. As a whole, the "tutorial" explains what the functions and classes do and why they are there...but it doesn't explain the most of the individual parts of those functions and classes (many of which are new to me because they are part of the Pygame library). Any suggestions as to where I might look for a Pygame tutorial for beginners, but a bit more detailed than the line-by-line Chimp tutorial? --part1_11c.1aa34650.2b0c5de5_boundary Content-Type: text/html; charset="US-ASCII" Content-Transfer-Encoding: 7bit I've read through the line-by-line Chimp tutorial that comes as part of the Pygame documentation, but that just doesn't do it for me. As a whole, the "tutorial" explains what the functions and classes do and why they are there...but it doesn't explain the most of the individual parts of those functions and classes (many of which are new to me because they are part of the Pygame library).

Any suggestions as to where I might look for a Pygame tutorial for beginners, but a bit more detailed than the line-by-line Chimp tutorial?
--part1_11c.1aa34650.2b0c5de5_boundary-- From dyoo@hkn.eecs.berkeley.edu Wed Nov 20 01:31:01 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Nov 20 01:31:01 2002 Subject: [Tutor] Help with Code (beginner) Error message In-Reply-To: Message-ID: > Trying to make a simple program that manages a small bank account. > (College assignment) I get an error message saying that "deposit is not > defined" Hi David, We cannot give direct help on your homework assignment. We'll do what we can to point you in the general direction, but it's your homework. > but as you can see I have defined it. If you've gotten this far in a college programming class, you have to realize how relentlessly faithful a computer is. I can't think of a subtle way to say this: you have to be humbler about your computer programs. All too often, the computer is far too perfect a servant: it obeys the schemes and machinations of imperfect beings --- it follows only what we type, and not what we mean. > class account: > def __init__(self,initial): > self.balance = initial > def withdraw(self,amt): > return initial - amt > def deposit(self, amt): > self.balance = self.balance + amt > def getbalance(self): > return self.balance Have you tested your account class? Have you tried out all the methods in your class? Which parts still behave buggily? More importantly, which parts appear to be working well, and why? Just as functions can be tested by calling them and by looking at their return values, classes too can be tested by instantiating them and trying out their methods. You really need to try out your code, especially since this is all very new stuff. There are a few references and tutorials on the web that you can use as examples of defining classes. Many of them are linked from the Newcomer's page on python.org: http://python.org/doc/Newbies.html Here are two pages in particular that may help you: http://www.ibiblio.org/obp/thinkCSpy/chap12.htm http://www.freenetpages.co.uk/hp/alan.gauld/ They pages show ways of instantiating and calling methods, so you may want to try those examples out first. You may find that going through these tutorials will help you with your original problem. Good luck to you. From thomi@thomi.imail.net.nz Wed Nov 20 04:05:04 2002 From: thomi@thomi.imail.net.nz (Thomi Richards) Date: Wed Nov 20 04:05:04 2002 Subject: [Tutor] yet more Tkinter problems (sorry guys) Message-ID: <20021120220405.7a042cb7.thomi@thomi.imail.net.nz> Heh, sorry about this, i hope you do not consider the sheer volume of questions comming from me to be spam =P i have yet another problem: i have the main loop of that graphics problem i was working on recently. well for some reason the main loop is stopping Tkinter from updating. i thought it was the percent bar i had drawn, but i commented that section of code out, and it still happens. Is there a way to force Tkinter to update more often? i think it's simply a problem of tkinter not being able to get enough cpu cycles to update itself - when my program runs, it uses all 99.8% of my AMD XP1800+.. any ideas?? thanks or your time. -- "Avoid the Gates of Hell. Use Linux" Thomi Richards, thomi@imail.net.nz From magnus@thinkware.se Wed Nov 20 06:13:04 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Wed Nov 20 06:13:04 2002 Subject: [Tutor] Help with Code (beginner) Error message In-Reply-To: <5.1.0.14.0.20021120024701.02b72f60@www.thinkware.se> References: <000b01c29031$73179dc0$ae110dd5@violante> Message-ID: <5.1.0.14.0.20021120115424.06915160@www.thinkware.se> At 02:57 2002-11-20 +0100, I wrote: >At 01:09 2002-11-20 +0000, Gon=E7alo Rodrigues wrote: >[Quite a lot] > >I'm not sure exactly how we should treat this, but I do think >that school assignments should be done by the students, not by >the mailing list. ... I realized that this mail of mine might be seen as an attack on Gon=E7alo and I just want to make clear this this wasn't at all my intent. I do think we have a problem with school assignments, ranging all the way from direct attempts at cheating in some cases, to completely open questions like this from David who honestly stated that this was his schoolwork. I don't think we really help students to learn if we solve their problems for them, and I certainly don't think we should help spoiling our own profession by helping people to get grades they don't deserve. I don't know how many times I've done this without being aware of it... (I guess the python teachers should follow both c.l.py and tutor to see how "creative" their students are...) I think the right solution is to point people to tutorials like Danny did, or to explain general concepts that the student doesn't seem to grasp. But not modifying their own code to show this. It seems to me that scopes is a tricky issue for many people, and I haven't seen so many tutorials that really clarifies this well. I think some people might also have been confused by the implicit this pointers of some other languages... (There are even some people (mislead by the poor design of other languages I'd like to say) who see the explicit use of self as a wart in Python. They need to "import this" more often.) --=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 Nov 20 06:26:01 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Wed Nov 20 06:26:01 2002 Subject: [Tutor] yet more Tkinter problems (sorry guys) In-Reply-To: <20021120220405.7a042cb7.thomi@thomi.imail.net.nz> Message-ID: <5.1.0.14.0.20021120121539.06915598@www.thinkware.se> At 22:04 2002-11-20 +1300, Thomi Richards wrote: >Is there a way to force Tkinter to >update more often? i think it's simply a problem of tkinter not being >able to get enough cpu cycles to update itself - when my program runs, >it uses all 99.8% of my AMD XP1800+.. The main loop will call your callback functions as the events happen that trigger them. Nothing else will happen while a function/method you defined is running. Control won't return to the main loop until your method/function exits. There are several ways to handle long running tasks. On is to divide your work in many function calls and cause some event to be generated for each file. Another is to use different threads. I'm more used to wxPython than to Tkinter though. Maybe you can get some ideas from this page (not that the code examples will be of any use...) http://wiki.wxpython.org/index.cgi/LongRunningTasks -- 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 Wed Nov 20 08:20:01 2002 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Wed Nov 20 08:20:01 2002 Subject: [Tutor] Help with Code (beginner) Error message References: <000b01c29031$73179dc0$ae110dd5@violante> <5.1.0.14.0.20021120115424.06915160@www.thinkware.se> Message-ID: <004601c29098$6daae420$03190dd5@violante> ----- Original Message ----- From: "Magnus Lycka" To: "Gonçalo Rodrigues" ; Sent: Wednesday, November 20, 2002 11:13 AM Subject: Re: [Tutor] Help with Code (beginner) Error message >At 02:57 2002-11-20 +0100, I wrote: >>At 01:09 2002-11-20 +0000, Gonçalo Rodrigues wrote: >>[Quite a lot] >> >>I'm not sure exactly how we should treat this, but I do think >>that school assignments should be done by the students, not by >>the mailing list. ... >I realized that this mail of mine might be seen as an >attack on Gonçalo and I just want to make clear this >this wasn't at all my intent. I do not feel attacked at all. In all honesty, it just bypassed me David's little confession that this was homework assignment and so I just jumped ahead. >I do think we have a problem with school assignments, >ranging all the way from direct attempts at cheating in >some cases, to completely open questions like this from >David who honestly stated that this was his schoolwork. >I don't think we really help students to learn if we solve >their problems for them, and I certainly don't think we >should help spoiling our own profession by helping people >to get grades they don't deserve. >I don't know how many times I've done this without being >aware of it... (I guess the python teachers should follow >both c.l.py and tutor to see how "creative" their students >are...) >I think the right solution is to point people to tutorials >like Danny did, or to explain general concepts that the >student doesn't seem to grasp. But not modifying their own >code to show this. I agree. As a teacher, I definitely *would not* like if somebody else did my student's homework. He would not learn anything. I'll try to be more attentive next time. With my best regards, Gonçalo Rodrigues From din22@cox.net Wed Nov 20 10:03:02 2002 From: din22@cox.net (sheri) Date: Wed Nov 20 10:03:02 2002 Subject: [Tutor] my newbie program References: <5.1.0.14.0.20021119155331.02b0ced0@www.thinkware.se> Message-ID: <000701c290a5$ec709540$fc550144@pn.at.cox.net> so i make a map object that has a dictionary to keep track of rooms indexed by xy coords as keys. and i think i get the placeRoom method. i am working through the rest. i guess right now my question is: does thinking like this get any easier with practice? because my brain is starting to hurt. > > class Map: > ... > > class Room: > map = Map() # Shared between instances. > > I don't remember exactly what your code so far > looks like, but I guess the interface to Room > can look the same, but instead of looking in an > internal list a room makes a call to: > self.map.hasOpening(self, direction). > > In Room.__init__ you have something like > self.map.placeRoom(self, x, y) so that the map > can keep track of where each room is. > > So, in class Map you will have something like: > > class Map: > '''Keep track of rooms and connections''' > # DirectionSymbol: (deltaX, deltaY) Assumes 0,0 lower left corner > directions = {'n': (1, 0), 's': (-1, 0), 'w': (-1, 0), 'e': (1, 9)} > > def __init__(self): > self.grid = {} > self.connections = [] # or {}??? > > def placeRoom(self, room, x, y): > if self.grid.has_key((x, y)): > raise KeyError, "Location taken!" > self.grid[(x, y)] = room > > def _getXY(self, theRoom): > '''Where is a room''' > for aKoord, aRoom in self.grid.items(): > if aRoom == theRoom: > return aKoord > # Didn't find it > raise KeyError, "Room not found" > > def _relativeCoord(self, room, direction): > thisX, thisY = self._getXY(room) > deltaX, deltaY = self.directions[direction] > return (thisX + deltaX, thisY + deltaY) > > def dig(self, room, direction): > # A lot of checks needs to be added in this method > newX, newY = self._relativeCoord(room, direction) > try: > otherRoom = self.grid[(newX, newY)] > except KeyError: #No room where we dug > otherRoom = Room(newX, newY) > self._makeConnection(room, otherRoom) > > def move(self, room, direction): > '''Return the room we get to when we move in a > certain direction''' > newX, newY = self._relativeCoord(room, direction) > try: > otherRoom = self.grid[(newX, newY)] > if self.hasConnection(room, otherRoom): > return otherRoom > else: # Stay where we are > reurn room > except: #Stay where we are > return room > # Another approach is to cast an exception if we can't move. > > def _makeConnection(self, room1, room2): > ... > > def _hasConnection(self, room1, room2): > ... > return xxx # 1 (yes) or 0 (no) > > > I'm not sure about how to store connections (i.e. openings / doors). > A connection could be stored like a pair of coordinates as above. > "((thisX, thisY), (newX, newY))". But how do we see in a simple > way that the above is equivalent with > "((newX, newY), (thisX, thisY))"? Or isn't it? Can there be one > way connections? Should we store both directions when we dig? > Should we sort before we store? > > > > -- > 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 din22@cox.net Wed Nov 20 10:12:03 2002 From: din22@cox.net (sheri) Date: Wed Nov 20 10:12:03 2002 Subject: [Tutor] my newbie program References: <5104D4DBC598D211B5FE0000F8FE7EB20E66CA7C@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <001201c290a7$349ae5e0$fc550144@pn.at.cox.net> thanks. this seems clear except for -dirindex+1 i dont see how thats evaluated. and self.exits[direction].exits[newdir] = self i'm not understanding this syntax. very nice tutorial btw. how about adding a case study of building a little text adventure? :) ----- Original Message ----- From: To: ; Sent: Tuesday, November 19, 2002 12:52 PM Subject: RE: [Tutor] my newbie program > > dig(north) would create a new exit to a new room > > with an exit back to the room you dug from. > > Something like: > > class Rooom: > # as before... > directions = ['north','east',west,'south'] > def dig(self, direction): > self.exits[direction] = Room("My new room") > dirindex = directions.index(direction) > newdir = directions[-dirindex+1] # get inverse direction > self.exits[direction].exits[newdir] = self > > Note I've changed exits from a list to a dictionary keyed by direction. > I add the new room as the new exit of the current room. > I find the index of the direction in the list > I take the inverse by using the negative index - try it out by hand... > I add the exising room as an exit to the new one... > > All untested of course but might form a basis??? > > Alan g. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From ATrautman@perryjudds.com Wed Nov 20 10:12:20 2002 From: ATrautman@perryjudds.com (Alan Trautman) Date: Wed Nov 20 10:12:20 2002 Subject: [Tutor] my newbie program Message-ID: <0BA95581EDA7D611841B00A0C9AD25DD2B58FB@mail.pjinet.com> Sheri, IMO and experience after working at it a while there is a magic point where you will "get it" and if your like me you'll want to go back and fix everything you've done. It will be much easier until you try to do something way over you head. Then there is a whole new set of ideas for handling that. That's the interesting part of programming/system design. Alan -----Original Message----- From: sheri [mailto:din22@cox.net] Sent: Wednesday, November 20, 2002 9:03 AM To: Magnus Lycka Cc: tutor@python.org Subject: Re: [Tutor] my newbie program so i make a map object that has a dictionary to keep track of rooms indexed by xy coords as keys. and i think i get the placeRoom method. i am working through the rest. i guess right now my question is: does thinking like this get any easier with practice? because my brain is starting to hurt. > > class Map: > ... > > class Room: > map = Map() # Shared between instances. > > I don't remember exactly what your code so far > looks like, but I guess the interface to Room > can look the same, but instead of looking in an > internal list a room makes a call to: > self.map.hasOpening(self, direction). > > In Room.__init__ you have something like > self.map.placeRoom(self, x, y) so that the map > can keep track of where each room is. > > So, in class Map you will have something like: > > class Map: > '''Keep track of rooms and connections''' > # DirectionSymbol: (deltaX, deltaY) Assumes 0,0 lower left corner > directions = {'n': (1, 0), 's': (-1, 0), 'w': (-1, 0), 'e': (1, 9)} > > def __init__(self): > self.grid = {} > self.connections = [] # or {}??? > > def placeRoom(self, room, x, y): > if self.grid.has_key((x, y)): > raise KeyError, "Location taken!" > self.grid[(x, y)] = room > > def _getXY(self, theRoom): > '''Where is a room''' > for aKoord, aRoom in self.grid.items(): > if aRoom == theRoom: > return aKoord > # Didn't find it > raise KeyError, "Room not found" > > def _relativeCoord(self, room, direction): > thisX, thisY = self._getXY(room) > deltaX, deltaY = self.directions[direction] > return (thisX + deltaX, thisY + deltaY) > > def dig(self, room, direction): > # A lot of checks needs to be added in this method > newX, newY = self._relativeCoord(room, direction) > try: > otherRoom = self.grid[(newX, newY)] > except KeyError: #No room where we dug > otherRoom = Room(newX, newY) > self._makeConnection(room, otherRoom) > > def move(self, room, direction): > '''Return the room we get to when we move in a > certain direction''' > newX, newY = self._relativeCoord(room, direction) > try: > otherRoom = self.grid[(newX, newY)] > if self.hasConnection(room, otherRoom): > return otherRoom > else: # Stay where we are > reurn room > except: #Stay where we are > return room > # Another approach is to cast an exception if we can't move. > > def _makeConnection(self, room1, room2): > ... > > def _hasConnection(self, room1, room2): > ... > return xxx # 1 (yes) or 0 (no) > > > I'm not sure about how to store connections (i.e. openings / doors). > A connection could be stored like a pair of coordinates as above. > "((thisX, thisY), (newX, newY))". But how do we see in a simple > way that the above is equivalent with > "((newX, newY), (thisX, thisY))"? Or isn't it? Can there be one > way connections? Should we store both directions when we dig? > Should we sort before we store? > > > > -- > 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 din22@cox.net Wed Nov 20 10:18:02 2002 From: din22@cox.net (sheri) Date: Wed Nov 20 10:18:02 2002 Subject: [Tutor] my newbie program References: <0BA95581EDA7D611841B00A0C9AD25DD2B58FB@mail.pjinet.com> Message-ID: <001901c290a8$02c278c0$fc550144@pn.at.cox.net> thanks. thats really encouraging. but i must confess i am david. sheri is my wife. i'm using her mail account. i should get on fixing that. ----- Original Message ----- From: Alan Trautman To: Sent: Wednesday, November 20, 2002 9:10 AM Subject: RE: [Tutor] my newbie program > Sheri, > > IMO and experience after working at it a while there is a magic point where > you will "get it" and if your like me you'll want to go back and fix > everything you've done. It will be much easier until you try to do something > way over you head. Then there is a whole new set of ideas for handling that. > That's the interesting part of programming/system design. > > Alan From glingl@aon.at Wed Nov 20 11:51:02 2002 From: glingl@aon.at (Gregor Lingl) Date: Wed Nov 20 11:51:02 2002 Subject: [Tutor] Help with Code (beginner) Error message References: <000b01c29031$73179dc0$ae110dd5@violante> <5.1.0.14.0.20021120115424.06915160@www.thinkware.se> Message-ID: <3DDBBD55.7000402@aon.at> Magnus Lycka schrieb: > At 02:57 2002-11-20 +0100, I wrote: > >> At 01:09 2002-11-20 +0000, Gonçalo Rodrigues wrote: >> [Quite a lot] >> >> I'm not sure exactly how we should treat this, but I do think >> that school assignments should be done by the students, not by >> the mailing list. ... > > .... > > I don't think we really help students to learn if we solve > their problems for them, and I certainly don't think we > should help spoiling our own profession by helping people > to get grades they don't deserve. > > I don't know how many times I've done this without being > aware of it... (I guess the python teachers should follow > both c.l.py and tutor to see how "creative" their students > are...) > > I think the right solution is to point people to tutorials > like Danny did, or to explain general concepts that the > student doesn't seem to grasp. But not modifying their own > code to show this. > Agreed. Just let me add a few points: 1. There are many ways, students can find solutions for their assignments, not only from mailinglists like tutor, but also e. g. from friends, collegues, books, from elsewhere in the internet. 2. Teachers, i suppose, have different means to find out if their students have understood, what they "produce". 3. So it's not our responsibility to assure that students do their work properly or to hinder them to cheat. 4. Of course it would be waste of time and effort, if the gurus of lists like this would endlessly repeat explanations of the most simple things - i think Danny explained in a concise and clear way how top proceed instead.. 5. On the other hand: trying to explain things is a very rewarding and efficient way to learn as well as to test if one has understood things well. I occurred not only once at tutor's, that "Newbies" developed to tutors, and began to propagate their just acquired knowledge to others just arriving at the list. I think, we should encourage this, which would possibly result in a even more colorful and diversified communication. how could this be accompished? - perhaps not each and every tiny question should be answered by the masters here. Especially not for the 2nd or 3rd time. (I'm far from beeing able to answer every question posted here, but even if have an answer i sometimes wait, if somebody else posts a reply.) - We - the 'ordinary' members - should make every effort to give "good" explanations, by learning from the excellent writing style and educational approach (?) of the 'gurus'. So every member could give as well as recieve thus producing a lively equilibrium. I hope some of my ideas survived their translation int my rather poor English. Regards, Gregor From hall@nhn.ou.edu Wed Nov 20 15:26:02 2002 From: hall@nhn.ou.edu (Ike Hall) Date: Wed Nov 20 15:26:02 2002 Subject: [Tutor] xml parsing Message-ID: <200211202024.gAKKOlP21957@creek-clued0.fnal.gov> Hi all, Im having a little trouble reading the documentation to some of the xml parsing modules in order to get them to do what I want them to. Here is what I need to do: I recieve an XML string of the form: ' 1.0 1.234> 6.4 4 ' where I have placed indentations for clarity. the string I recieve has no whitespace or linebreaks. What I want to do, is to turn this string into a python dictionary that would look like this for that string: {'block1':{'item1':1.0,'item2':1.234},'block2':{'item1':6.4,'item2':4}} I have not been able to see clearly how to use the XML modules xmllib or xml.sax in order to do this, and I was wondering how this may be accomplished with a minimum of writing. I know I could just write a function to parse this string using only builtin python commands, but I do not think that this is the easiest solution. Thanks Ike From am@fx.ro Wed Nov 20 16:25:03 2002 From: am@fx.ro (am@fx.ro) Date: Wed Nov 20 16:25:03 2002 Subject: [Tutor] Unbound methods Message-ID: <20021121021020.A579@coto> Hello all! I am new to both python and this list. I am trying to write my first silly script containing a class with a few methods (this script might become someday a part of a WAV player): class WavSet: def __init__(self): print 'Init' def open(self): print 'Open' def close(self): print 'Close' def play(self,wav_id): print 'Play %d'%(wav_id,) w=WavSet print w.open() print w.close() I got an error that i don't understand: TypeError: unbound method must be called with class instance 1st argument I have found a paragraph in the Reference (types.html) about unbound methods, but i still have no clue about what am i doing wrong. Please help. Best regards, Adrian Maier (am@fx.ro) From dman@dman.ddts.net Wed Nov 20 17:22:02 2002 From: dman@dman.ddts.net (Derrick 'dman' Hudson) Date: Wed Nov 20 17:22:02 2002 Subject: [Tutor] Re: Unbound methods In-Reply-To: <20021121021020.A579@coto> References: <20021121021020.A579@coto> Message-ID: <20021120223524.GA10811@dman.ddts.net> --6TrnltStXW4iwmi0 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Thu, Nov 21, 2002 at 02:10:21AM +0200, am@fx.ro wrote: | Hello all! |=20 | I am new to both python and this list. |=20 | I am trying to write my first silly script containing a class=20 | with a few methods (this script might become someday a part | of a WAV player): |=20 | class WavSet: | def __init__(self): | print 'Init' | def open(self): | print 'Open' | def close(self): | print 'Close' | def play(self,wav_id): | print 'Play %d'%(wav_id,) |=20 | w=3DWavSet w=3DWavSet() ^^ | print w.open() | print w.close() |=20 | I got an error that i don't understand:=20 | TypeError: unbound method must be called with class instance 1st argument =20 | I have found a paragraph in the Reference (types.html) about unbound | methods, but i still have no clue about what am i doing wrong. | Please help. You need to create an instance of the class, then invoke methods on it. The above noted change (puting parenthesis after the class name) will do that. HTH, -D --=20 There are 10 types of people in the world: those who understand binary, and those who do not. =20 http://dman.ddts.net/~dman/ --6TrnltStXW4iwmi0 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 iEYEARECAAYFAj3cDiwACgkQO8l8XBKTpRT6xwCdEC1/+nZIrdG22CW4/Q8I7OC2 iuQAn3fM/t0XVdYBO81GK8LopoqmhnrC =xd4+ -----END PGP SIGNATURE----- --6TrnltStXW4iwmi0-- From francois.granger@free.fr Wed Nov 20 17:23:02 2002 From: francois.granger@free.fr (=?iso-8859-1?Q?Fran=E7ois?= Granger) Date: Wed Nov 20 17:23:02 2002 Subject: [Tutor] Unbound methods In-Reply-To: <20021121021020.A579@coto> References: <20021121021020.A579@coto> Message-ID: At 2:10 +0200 21/11/02, in message [Tutor] Unbound methods, am@fx.ro wrote: >Hello all! > >I am new to both python and this list. > >I am trying to write my first silly script containing a class >with a few methods (this script might become someday a part >of a WAV player): > >class WavSet: > def __init__(self): > print 'Init' > def open(self): > print 'Open' > def close(self): > print 'Close' > def play(self,wav_id): > print 'Play %d'%(wav_id,) > >w=WavSet >print w.open() >print w.close() > >I got an error that i don't understand: >TypeError: unbound method must be called with class instance 1st argument Python 2.2.2 (#138, Oct 25 2002, 23:10:42) [CW CARBON GUSI2 THREADS GC] on mac Type "copyright", "credits" or "license" for more information. >>> class WavSet: def __init__(self): print 'Init' def open(self): print 'Open' def close(self): print 'Close' def play(self,wav_id): print 'Play %d'%(wav_id,) w=WavSet print w.open() print w.close() ... ... ... ... ... ... ... ... ... >>> >>> Traceback (most recent call last): File "", line 1, in ? TypeError: unbound method open() must be called with WavSet instance as first argument (got nothing instead) >>> Traceback (most recent call last): File "", line 1, in ? TypeError: unbound method close() must be called with WavSet instance as first argument (got nothing instead) >>> >>> w=WavSet() Init >>> print w.open() Open None >>> print w.close() Close None >>> the line w=WavSet bind the name w to the WavSet class but does not create an instance of the class. You could use w instead of WavSet anywhere. The line w=WavSet() create an instance of WavSet and bind this instance to w. Then you can call methodes on w. HTH -- Le courrier électronique 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 : http://minilien.com/?IXZneLoID0 - http://marc.herbert.free.fr/mail/ http://expita.com/nomime.html From magnus@thinkware.se Wed Nov 20 17:28:03 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Wed Nov 20 17:28:03 2002 Subject: [Tutor] Unbound methods In-Reply-To: <20021121021020.A579@coto> Message-ID: <5.1.0.14.0.20021120231723.02ac95a8@www.thinkware.se> At 02:10 2002-11-21 +0200, am@fx.ro wrote: >w=WavSet This means that w is now a synonym for WavSet. I think you meant to do: w = WavSet() # Note parenthesis >print w.open() First of all, this is as you (now) understand just another way of saying WavSet.open() If you first do: w = WavSet() then w.open() is really just a shorter way of writing WavSet.open(w) where the instance variable 'w' ends up being called self inside the method. Right? Since you had forgotten the () above, you wrote the equivalent of WavSet.open() and of course, that's not bound to an instance. Ok? There's another issue. You use a print inside the method and the don't return anything (which is the same as returning None). Then you type "print w.open()" which means that first you print 'Open' inside the method, and then you print the return value. So if you add the () your program will print: Open None Close None You should probably either change your methods to: def open(self): return 'Open' etc, or skip the print when you call them. No big issue now, since I imagine that the body of the methods will change though... -- 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 dman@dman.ddts.net Wed Nov 20 17:28:15 2002 From: dman@dman.ddts.net (Derrick 'dman' Hudson) Date: Wed Nov 20 17:28:15 2002 Subject: [Tutor] Re: Python in education In-Reply-To: <5.1.0.14.0.20021120025720.02a91c18@www.thinkware.se> References: <5.1.0.14.0.20021120025720.02a91c18@www.thinkware.se> Message-ID: <20021120224129.GB10811@dman.ddts.net> --wzJLGUyc3ArbnUjN Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Wed, Nov 20, 2002 at 03:01:42AM +0100, Magnus Lycka wrote: | We obviously have some students in the mailing list. | (Come on now, don't be shy.) |=20 | I'm curious. How much is Python used in education? | Did you have to use python or could you use a language | of your choice? At what level is python used in education, | how central is it to the education, what kind of courses | is it used in? What books do you use? How do you like it? So far (5th year, Software Engineering, RIT, I graduate in May) the only time I've used python in school was in a course where we were allowed to choose our implementation and I managed to convince the rest of my group that it would work well for us. We ended up using jython and a swing GUI and Moshe's "pms" package. The unfortunate part for us is that due to jythonc limitations the GUI couldn't be written in Java (which is what the rest of the group knew). I don't use any books, but then again I knew how to program before I heard of python and as such Guido's tutorial and the library reference was sufficient for me. I like python a lot and wish I could use it more :-). Speaking of which, a friend has asked me to develop a point-of-sale system for his small business. I intend to use python for it, and am considering using Zope for the backend and ncurses and xml-rpc for the thin clients using. -D --=20 The lot is cast into the lap, but its every decision is from the Lord. Proverbs 16:33 =20 http://dman.ddts.net/~dman/ --wzJLGUyc3ArbnUjN 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 iEYEARECAAYFAj3cD5kACgkQO8l8XBKTpRRlIgCgoUsOjhQpoKDNe3Gu6tes1Sy0 1J8Anjr1aapgyQE3+4ASNWJG8vt52WnU =PF1g -----END PGP SIGNATURE----- --wzJLGUyc3ArbnUjN-- From bindas_qwerty@hotmail.com Wed Nov 20 19:01:01 2002 From: bindas_qwerty@hotmail.com (sachin mehra) Date: Wed Nov 20 19:01:01 2002 Subject: [Tutor] question on python! Message-ID: This is a multi-part message in MIME format. ------=_NextPart_000_2ea9_25a4_5eca Content-Type: text/plain; format=flowed _________________________________________________________________ MSN 8 with e-mail virus protection service: 2 months FREE* http://join.msn.com/?page=features/virus ------=_NextPart_000_2ea9_25a4_5eca Content-Type: message/delivery-status Reporting-MTA: dns;hotmail.com Received-From-MTA: dns;mail.hotmail.com Arrival-Date: Wed, 20 Nov 2002 15:58:21 -0800 Final-Recipient: rfc822;tutor@ptython.org Action: failed Status: 5.0.0 ------=_NextPart_000_2ea9_25a4_5eca Content-Type: message/rfc822 Received: from mail pickup service by hotmail.com with Microsoft SMTPSVC; Wed, 20 Nov 2002 15:58:21 -0800 Received: from 128.138.177.36 by sea2fd.sea2.hotmail.msn.com with HTTP; Wed, 20 Nov 2002 23:58:21 GMT X-Originating-IP: [128.138.177.36] From: "sachin mehra" To: dyoo@hkn.eecs.berkeley.edu Cc: tutor@ptython.org Bcc: Subject: Re: [Tutor] need some help for program!! [More hidden markov models in Python] Date: Thu, 21 Nov 2002 05:28:21 +0530 Mime-Version: 1.0 Content-Type: text/plain; format=flowed Message-ID: X-OriginalArrivalTime: 20 Nov 2002 23:58:21.0490 (UTC) FILETIME=[B4841120:01C290F0] Hi Danny, I had another question for you. I want to incorporate some unix commands in my python program.How can i do it? How about I want to execute 3-4 unix commands continuously?? Please let me know. thanx, Manish >From: Danny Yoo >To: sachin mehra >CC: tutor@python.org >Subject: Re: [Tutor] need some help for program!! [More hidden markov >models in Python] >Date: Sun, 17 Nov 2002 23:47:18 -0800 (PST) > > > > > Again, the page at: > > > > http://datamining.anu.edu.au/software/febrl/febrldoc/node7.html > > > > has an example that should help clarify why HMM's are appropriate for > > your problem. > >Hi Sachin, > >Argh, darn it! I can't help myself but look into your question some more. >Why did you have to ask a question on such an interesting topic? *grin* I >have to control my curiosity or else I'll end up writing this program too. > > >There's a great source of information on Hidden Markov Models in the >source code of Logilab's 'hmm' module: > > http://www.logilab.org/hmm/ > >This is a Python module that implements HMM's, and is excellent. You may >need to install an extension called Numeric Python to get it to work, but >it's definitely worth it: > > http://www.pfdubois.com/numpy/ > > >There are some real gems in there, not just the module itself, but in the >test cases they've embedded in the source code. In particular, if we take >a close look at the logilab.hmm.hmm.test2() function, we'll see that they >train a Hidden Markov Model to recognize French sentences (and evaluate >their likelihood!). If you read and understand their test2() function, >you should be able to apply that knowledge toward your problem. > > >Another good source of information on HMM's includes the classic article, >"A Tutorial on Hidden Markov Models and Selected Applications in Speech >Recognition", by Lawrence R. Rabiner. Here's a link to the paper: > > http://www.cc.gatech.edu/ccg/paper_of_week/Rabiner-Markov.pdf > >I just read the first few pages, and my own fuzzy ideas about HMM's just >became a lot clearer. > > >Anyway, I must stop myself now, or else I won't be able to sleep. This is >why I hate seeing homework questions... > >Good luck to you. > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ Tired of spam? Get advanced junk mail protection with MSN 8. http://join.msn.com/?page=features/junkmail ------=_NextPart_000_2ea9_25a4_5eca-- From reavey@nep.net Wed Nov 20 19:06:09 2002 From: reavey@nep.net (reavey) Date: Wed Nov 20 19:06:09 2002 Subject: [Tutor] help with code Message-ID: <1037837014.5252.20.camel@localhost.localdomain> Sirs: 1. As a teacher, it's difficult to know when you've reached the point of spoon-feeding your student. 2. Also, in a forum like this it's impossible to know whether the person you're helping is more lazy than stupid. 3. The tutorials and books available often go to extremes of too simplistic to too abstract. The core question is: whether what you're doing is worthwhile? I read the list daily. I say emphatically, YES and THANK YOU. RE-V From magnus@thinkware.se Wed Nov 20 19:14:03 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Wed Nov 20 19:14:03 2002 Subject: [Tutor] question on python! In-Reply-To: Message-ID: <5.1.0.14.0.20021121010732.06953de0@www.thinkware.se> At 05:30 2002-11-21 +0530, sachin mehra wrote: >I want to incorporate some unix commands in my python program.How can i do >it? How about I want to execute 3-4 unix commands continuously?? Perhaps you can show what you would do from the unix command line. Typically you use os.system('ls -l') or whatever if you don't need to process the output of the unix commands in the python program. If you need the output, you do something like pingData = os.popen('ping www.python.org').readlines() etc. You can obviously use the ordinary unix shell magic fo run more than one command in os.system or os.popen. It's easier to say if you show what you need to do. -- 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 scot@possum.in-berlin.de Wed Nov 20 19:31:01 2002 From: scot@possum.in-berlin.de (Scot Stevenson) Date: Wed Nov 20 19:31:01 2002 Subject: [Tutor] my newbie program In-Reply-To: <000701c290a5$ec709540$fc550144@pn.at.cox.net> References: <5.1.0.14.0.20021119155331.02b0ced0@www.thinkware.se> <000701c290a5$ec709540$fc550144@pn.at.cox.net> Message-ID: <200211210127.44002.scot@possum.in-berlin.de> Hi - > i am working through the rest. i guess right now > my question is: does thinking like this get any > easier with practice? because my brain is starting > to hurt. As somebody who has just reached the point where he can program small things without having to reach for the book more than once every ten minutes, I can say with great certainty: Yes, if you keep at it, it will get easier up to the point where you have problems understanding what your problems were. I remember banging my head against the wall because I didn't understand how the index system worked with splicing - you know, the stuff on page six - and now I find myself doing the indicis without thinking. Scary in a way, but satisfying. Remember, you probably used to think multiplication was hard, too, and now you just /know/ that 12 times 3 is 42 ...er... Y, Scot -- Scot W. Stevenson -- scot@possum.in-berlin.de -- Zepernick, Germany From bindas_qwerty@hotmail.com Wed Nov 20 19:33:01 2002 From: bindas_qwerty@hotmail.com (sachin mehra) Date: Wed Nov 20 19:33:01 2002 Subject: [Tutor] Re:[Tutor]Question on python Message-ID: Hi, Well I want to use the following commands: tr -cs '[:aplha:]' '[\n*]' < *.txt | uniq -c | sort -rm | more Which would give me a count of unique words in a .txt file.. How can i use this..I have already tried the os.system option!! I may need to use this command(or similar type) a few more times..How can I do it in python? Thanx, manish _________________________________________________________________ Help STOP SPAM with the new MSN 8 and get 2 months FREE* http://join.msn.com/?page=features/junkmail From dyoo@hkn.eecs.berkeley.edu Wed Nov 20 19:57:04 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Nov 20 19:57:04 2002 Subject: [Tutor] Re:[Tutor]Question on python In-Reply-To: Message-ID: On Thu, 21 Nov 2002, sachin mehra wrote: > Well I want to use the following commands: > > tr -cs '[:alpha:]' '[\n*]' < *.txt | uniq -c | sort -rn | more Hi Sachin, It sounds like you're looking for the os.popen() function: http://www.python.org/doc/lib/os-newstreams.html#os-newstreams os.system() pays attention to the exit "errorcode" of the external command, but doesn't really listen in on the output. os.popen(), on the other hand, lets us grab that program output as if it were a file. For example: ### >>> my_python_files = os.popen('ls *.py').readlines() >>> my_python_files ['Editor.py\n', 'find_munged_abstracts.py\n', 'foo.py\n', 'gamma_function.py\n', 'genomic_sequence_generator.py\n', 'http_regular_expression.py\n', 'indentation_to_tree.py\n', 'jsptransport.py\n', 'make_xml_descriptor.py\n', 'maximum_digit_total.py\n', 'mg_get.py\n', 'parse_urls.py\n', 'rpn.py\n', 'sampletest.py\n', 'test_bac.py\n', 'test_email.py\n', 'test_genbank.py\n', 'test_lineno.py\n', 'test.py\n', 'test_unbinding.py\n', 'tim_parser.py\n', 'wolfram.py\n'] ### Unfortuntately, the pipeline that you're using is buggy. That is, if you try the following input into your pipeline: ### a b a ### you will probably see some silly results: ### 1 a 1 b 1 a ### Take a look at the documentation on the 'uniq' command; the 'man' page on your system should explain why 'uniq' behaves in this way. Good luck! From fredm@smartypantsco.com Wed Nov 20 20:35:02 2002 From: fredm@smartypantsco.com (Alfred Milgrom) Date: Wed Nov 20 20:35:02 2002 Subject: [Tutor] xml parsing In-Reply-To: <200211202024.gAKKOlP21957@creek-clued0.fnal.gov> Message-ID: <5.1.0.14.0.20021121123051.00a81e40@192.168.1.1> Hi Ike: I don't know anything about XML, and I don't know whether the example you gave covers everything you want to do (for example, are there more levels of nesting or different keywords). However, using the string functions it is easy to develop the dictionaries you want as follows: import string def stringToDict (data, key) : dict = {} dataList = data.split(key) for word in dataList : if '<' not in word : break if word.index('>') < word.index('<'): word = word[word.index('>')+1:] split = word.index('>') key = word[:split].replace('<',"") value = word[split+1:] dict[key]=value return dict XMLstring = "1.01.2346.44" XMLdictionary = stringToDict(XMLstring, 'Hi all, >Im having a little trouble reading the documentation to some of the xml >parsing modules in order to get them to do what I want them to. > >Here is what I need to do: >I recieve an XML string of the form: > >' > 1.0 > 1.234> > > > 6.4 > 4 >' > >where I have placed indentations for clarity. the string I recieve has no >whitespace or linebreaks. What I want to do, is to turn this string into a >python dictionary that would look like this for that string: > >{'block1':{'item1':1.0,'item2':1.234},'block2':{'item1':6.4,'item2':4}} > >I have not been able to see clearly how to use the XML modules xmllib or >xml.sax in order to do this, and I was wondering how this may be accomplished >with a minimum of writing. >I know I could just write a function to parse this string using only builtin >python commands, but I do not think that this is the easiest solution. > >Thanks >Ike > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From thomi@thomi.imail.net.nz Wed Nov 20 23:12:02 2002 From: thomi@thomi.imail.net.nz (Thomi Richards) Date: Wed Nov 20 23:12:02 2002 Subject: [Tutor] yet more Tkinter problems (sorry guys) In-Reply-To: <5.1.0.14.0.20021120121539.06915598@www.thinkware.se> References: <20021120220405.7a042cb7.thomi@thomi.imail.net.nz> <5.1.0.14.0.20021120121539.06915598@www.thinkware.se> Message-ID: <20021121163048.683fe0b6.thomi@thomi.imail.net.nz> hmmm.. maybe i should have learnt wxpython instead. still, i guess it's not too late to start, but Tkinter was fairly easy for me, is wxwindows any harder? -- "Avoid the Gates of Hell. Use Linux" Thomi Richards, thomi@imail.net.nz From am@fx.ro Wed Nov 20 23:15:02 2002 From: am@fx.ro (am@fx.ro) Date: Wed Nov 20 23:15:02 2002 Subject: [Tutor] Unbound methods In-Reply-To: <5.1.0.14.0.20021120231723.02ac95a8@www.thinkware.se>; from magnus@thinkware.se on Wed, Nov 20, 2002 at 11:28:59PM +0100 References: <20021121021020.A579@coto> <5.1.0.14.0.20021120231723.02ac95a8@www.thinkware.se> Message-ID: <20021121090042.A283@coto> Thank you all for the answers. > w = WavSet() # Note parenthesis > Since you had forgotten the () above, you wrote the > equivalent of WavSet.open() > and of course, that's not bound to an instance. Ok? Yes, it's clear now. Bye, Adrian Maier, (am@fx.ro) From dman@dman.ddts.net Wed Nov 20 23:32:01 2002 From: dman@dman.ddts.net (Derrick 'dman' Hudson) Date: Wed Nov 20 23:32:01 2002 Subject: [Tutor] Re: [Tutor]Question on python In-Reply-To: References: Message-ID: <20021121044530.GA13193@dman.ddts.net> --82I3+IH0IqGh5yIs Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Thu, Nov 21, 2002 at 06:01:25AM +0530, sachin mehra wrote: |=20 | Hi, | Well I want to use the following commands: | tr -cs '[:aplha:]' '[\n*]' < *.txt | uniq -c | sort -rm | more If you want to use shell commands, why not just write a shell script? I use shell scripts for shell-type operations and python for things that aren't well suited for shell scripts. | Which would give me a count of unique words in a .txt file.. How about this? http://www.uselesspython.com/count.py (found from http://www.uselesspython.com/uselesspython4.html) | How can i use this..I have already tried the os.system option!! os.system( "/bin/sh -c 'tr ...'" ) You need to run the shell command in a shell. | I may need to use this command(or similar type) a few more times.. #!/bin/bash # (I'm not sure if this runs in /bin/sh or if it requires bash) for $((i=3D0 ; i<3 ; i+=3D1)) ; do tr -cs '[:aplha:]' '[\n*]' < *.txt | uniq -c | sort -rm | more done | How can I do it in python? for _ in range( 3 ) : os.system( "/bin/sh -c 'tr ...'" ) It would be easier to suggest a solution if we knew the problem you are trying to solve and what context it is in. It's possible that there is a better solution or a better way to do it. Also take note of Danny's mention of the error in the shell command. HTH, -D --=20 "...the word HACK is used as a verb to indicate a massive amount of nerd-like effort." -Harley Hahn, A Student's Guide to Unix =20 http://dman.ddts.net/~dman/ --82I3+IH0IqGh5yIs 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 iEYEARECAAYFAj3cZOoACgkQO8l8XBKTpRR+PwCeMeg7CJgbagdd+BpEbDLBehcN XCkAn0ZaPbnyT4CpnrTTaTsZQU2/bbbs =1Ppm -----END PGP SIGNATURE----- --82I3+IH0IqGh5yIs-- From dman@dman.ddts.net Wed Nov 20 23:42:02 2002 From: dman@dman.ddts.net (Derrick 'dman' Hudson) Date: Wed Nov 20 23:42:02 2002 Subject: [Tutor] Re: regexes, thanks In-Reply-To: <18021.1037724078@www45.gmx.net> References: <3DDA67E2.4040201@ipwib.net> <18021.1037724078@www45.gmx.net> Message-ID: <20021121045532.GB13193@dman.ddts.net> --R3G7APHDIzY6R/pk Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Tue, Nov 19, 2002 at 05:41:18PM +0100, lumbricus@gmx.net wrote: | Hello! |=20 | > I was actually wanting to take a list of filenames, for example: | >=20 | > Pink Floyd - 02 - Dogs.mp3 | > Japanese_Noh_Music_--_Gaku.mp3 | > asu - searching_2001_edit.MP3 | >=20 | > ...and pass it through a sequence of regexes (of which this is just one= )=20 | > to produce consistent filenames along the lines of: | >=20 | > Pink_Floyd-02-Dogs.mp3 | > Japanese_Noh_Music--Gaku.mp3 | > Asu--Searching_2001_Edit.mp3 |=20 | Dashes in file names are pure evil - avoid them. Why do you say that? I see how a dash (or two) at the beginning of a filename can cause trouble, but not how dashes in the middle have any effect. (for those who need a workaround for a file starting with dashes, programmatically the os.rename() function can be used to rename the file; alternatively many commands use the argument "--" to indicate that the rest of the arguments are not options but are literal data (eg a filename for 'rm' or 'mv')) | > I first read in the filenames, then produce a list of tuples [filename,= =20 | > new_filename], which are used for renaming at the end. So, I need to= =20 | > perform operations on certain parts of the filename, not just the whole= =20 | > thing. It seems that there would be a simple way to perform this stage= .=20 | > Like, | >=20 | > new_filename =3D words.sub('([a-zA-Z]+)', '\u\1', filename) Try this to see what the problem is : print '\u\1' then try print r'\u\1' and print '\\u\\1' | > But I couldn't get \1, \2 substitution working (had to use '\g<1>') and= =20 |=20 | group() |=20 | > it doesn't look like python supports \u and \U ('man perlre' for info),= =20 |=20 | capitalize()? You can put this together like thus (untested) : the_re =3D re.compile( "(...)" ) # the ellipsis means put the real pa= ttern here possible_match =3D the_re.search( some_text_string ) if possible_match is not None : first_part_of_new_name =3D possible_match.group( 1).capitalize() else : print "no match" # whatever you want to do if there's no match The idea here is that when a regex matches a string, the result is a "match" object which encapuslates the various aspects of the match. One of the aspects is the groups that the pattern created. You can access each group individually and then to whatever string processing you want on it. Depending on what you want to do with the strings, it may be easier to write out the operations like this than to try and do it all in a single substitution. Choose the method that works and which is best suited for the situation. I don't know if python's regex engine supports \u. You can check in the library reference. HTH, -D --=20 Whoever loves discipline loves knowledge, but he who hates correction is stupid. Proverbs 12:1 =20 http://dman.ddts.net/~dman/ --R3G7APHDIzY6R/pk 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 iEYEARECAAYFAj3cZ0QACgkQO8l8XBKTpRTrjwCggwHc7yPTueHKgV3OTAtg83TU S5MAnikzmArRhHoSbQkzIDKxK9bROMzX =qZv9 -----END PGP SIGNATURE----- --R3G7APHDIzY6R/pk-- From din22@cox.net Wed Nov 20 23:49:02 2002 From: din22@cox.net (david) Date: Wed Nov 20 23:49:02 2002 Subject: [Tutor] my newbie program References: <5.1.0.14.0.20021119155331.02b0ced0@www.thinkware.se> Message-ID: <002801c29119$560e8fc0$fc550144@pn.at.cox.net> could you please explain the shared object? i am not clear on how Room is using one of Maps methods. thanks, david > I think you need a shared map object > though, that keeps track of how rooms > are connected, rather than letting > each room know where you get if you > go in a certain direction. > class Map: > ... > > class Room: > map = Map() # Shared between instances. > > I don't remember exactly what your code so far > looks like, but I guess the interface to Room > can look the same, but instead of looking in an > internal list a room makes a call to: > self.map.hasOpening(self, direction). > > In Room.__init__ you have something like > self.map.placeRoom(self, x, y) so that the map > can keep track of where each room is. > > So, in class Map you will have something like: > > class Map: > '''Keep track of rooms and connections''' > # DirectionSymbol: (deltaX, deltaY) Assumes 0,0 lower left corner > directions = {'n': (1, 0), 's': (-1, 0), 'w': (-1, 0), 'e': (1, 9)} > > def __init__(self): > self.grid = {} > self.connections = [] # or {}??? > > def placeRoom(self, room, x, y): > if self.grid.has_key((x, y)): > raise KeyError, "Location taken!" > self.grid[(x, y)] = room > > def _getXY(self, theRoom): > '''Where is a room''' > for aKoord, aRoom in self.grid.items(): > if aRoom == theRoom: > return aKoord > # Didn't find it > raise KeyError, "Room not found" > > def _relativeCoord(self, room, direction): > thisX, thisY = self._getXY(room) > deltaX, deltaY = self.directions[direction] > return (thisX + deltaX, thisY + deltaY) > > def dig(self, room, direction): > # A lot of checks needs to be added in this method > newX, newY = self._relativeCoord(room, direction) > try: > otherRoom = self.grid[(newX, newY)] > except KeyError: #No room where we dug > otherRoom = Room(newX, newY) > self._makeConnection(room, otherRoom) > > def move(self, room, direction): > '''Return the room we get to when we move in a > certain direction''' > newX, newY = self._relativeCoord(room, direction) > try: > otherRoom = self.grid[(newX, newY)] > if self.hasConnection(room, otherRoom): > return otherRoom > else: # Stay where we are > reurn room > except: #Stay where we are > return room > # Another approach is to cast an exception if we can't move. > > def _makeConnection(self, room1, room2): > ... > > def _hasConnection(self, room1, room2): > ... > return xxx # 1 (yes) or 0 (no) > > > I'm not sure about how to store connections (i.e. openings / doors). > A connection could be stored like a pair of coordinates as above. > "((thisX, thisY), (newX, newY))". But how do we see in a simple > way that the above is equivalent with > "((newX, newY), (thisX, thisY))"? Or isn't it? Can there be one > way connections? Should we store both directions when we dig? > Should we sort before we store? > > > > -- > 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 Wed Nov 20 23:50:04 2002 From: lumbricus@gmx.net (lumbricus@gmx.net) Date: Wed Nov 20 23:50:04 2002 Subject: [Tutor] Re: [Tutor]Question on python References: <20021121044530.GA13193@dman.ddts.net> Message-ID: <30350.1037854168@www22.gmx.net> Hi! > #!/bin/bash > # (I'm not sure if this runs in /bin/sh or if it requires bash) > for $((i=0 ; i<3 ; i+=1)) ; do *brr* Bashism. Works only in newer bash and ksh IIRC. > tr -cs '[:aplha:]' '[\n*]' < *.txt | uniq -c | sort -rm | more ^^^^^ I'm not sure, but does this have any effect? Why not '\n'? > done typeset -i i=0 while [ "$i" -lt 3 ]; do $CMD; i=`expr $i + 1`; done for i in 0 1 2; do $CMD; done if seq is available: for i in `seq 3`; do ... > HTH, > -D Dito, J"o! -- Wir beschliessen etwas, stellen das dann in den Raum und warten dann einige Zeit ab, was passiert. Wenn es dann kein grosses Geschrei gibt und keine Aufstaende, weil die meisten gar nicht begreifen, was da beschlossen wurde, dann machen wir weiter - Schritt fuer Schritt, bis es kein Zurueck mehr gibt. -- J-C Juncker +++ 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 Wed Nov 20 23:59:02 2002 From: lumbricus@gmx.net (lumbricus@gmx.net) Date: Wed Nov 20 23:59:02 2002 Subject: [Tutor] Re: regexes, thanks References: <20021121045532.GB13193@dman.ddts.net> Message-ID: <1866.1037854692@www22.gmx.net> Hi! > | Dashes in file names are pure evil - avoid them. > > Why do you say that? I see how a dash (or two) at the beginning of a > filename can cause trouble, but not how dashes in the middle have any > effect. If it followes a space :-) Well yes you _can_ use them, but I rather don't. > (for those who need a workaround for a file starting with dashes, > programmatically the os.rename() function can be used to rename the > file; alternatively many commands use the argument "--" to indicate > that the rest of the arguments are not options but are literal data > (eg a filename for 'rm' or 'mv')) or give it the path. $ touch ./test > HTH, > -D Dito, J"o! -- Wir beschliessen etwas, stellen das dann in den Raum und warten dann einige Zeit ab, was passiert. Wenn es dann kein grosses Geschrei gibt und keine Aufstaende, weil die meisten gar nicht begreifen, was da beschlossen wurde, dann machen wir weiter - Schritt fuer Schritt, bis es kein Zurueck mehr gibt. -- J-C Juncker +++ GMX - Mail, Messaging & more http://www.gmx.net +++ NEU: Mit GMX ins Internet. Rund um die Uhr für 1 ct/ Min. surfen! From scot@possum.in-berlin.de Thu Nov 21 00:21:36 2002 From: scot@possum.in-berlin.de (Scot Stevenson) Date: Thu Nov 21 00:21:36 2002 Subject: [Tutor] my newbie program In-Reply-To: <000701c290a5$ec709540$fc550144@pn.at.cox.net> References: <5.1.0.14.0.20021119155331.02b0ced0@www.thinkware.se> <000701c290a5$ec709540$fc550144@pn.at.cox.net> Message-ID: <200211210133.07709.scot@possum.in-berlin.de> Hi there, This looks like a typo: > > # DirectionSymbol: (deltaX, deltaY) Assumes 0,0 lower left corner > > directions = {'n': (1, 0), 's': (-1, 0), 'w': (-1, 0), 'e': (1, 9)} You probably want 'e' to be (1,0) and not (1,9)... Y, Scot -- Scot W. Stevenson -- scot@possum.in-berlin.de -- Zepernick, Germany From glingl@aon.at Thu Nov 21 00:29:01 2002 From: glingl@aon.at (Gregor Lingl) Date: Thu Nov 21 00:29:01 2002 Subject: [Tutor] my newbie program References: <5.1.0.14.0.20021119155331.02b0ced0@www.thinkware.se> <000701c290a5$ec709540$fc550144@pn.at.cox.net> <200211210133.07709.scot@possum.in-berlin.de> Message-ID: <3DDC6F08.6070502@aon.at> Scot Stevenson schrieb: >Hi there, > >This looks like a typo: > > > >>> # DirectionSymbol: (deltaX, deltaY) Assumes 0,0 lower left corner >>> directions = {'n': (1, 0), 's': (-1, 0), 'w': (-1, 0), 'e': (1, 9)} >>> >>> > >You probably want 'e' to be (1,0) and not (1,9)... > ... in which case 'e' equaled 'n' (?) so something like directions = {'n': (0, 1), 's': ( 0, -1), 'w': (-1, 0), 'e': (1, 0)} would serve better? (Or vice versa) Gregor > >Y, Scot > > > From idiot1@netzero.net Thu Nov 21 00:39:01 2002 From: idiot1@netzero.net (Kirk Bailey) Date: Thu Nov 21 00:39:01 2002 Subject: [Tutor] os.remove question Message-ID: <3DDC7191.2090304@netzero.net> .remove support the use of wildcards? for instance: os.remove(listname+'.*') to remove all file with a specified name, and ANY nameextension after the period. If not, how do I effect this? -- end Respectfully, Kirk D Bailey +---------------------"Thou Art Free." -Eris-----------------------+ | http://www.howlermonkey.net mailto:highprimate@howlermonkey.net | | KILL spam dead! http://www.scambusters.org/stopspam/#Pledge | | http://www.tinylist.org +--------+ mailto:grumpy@tinylist.org | +------------------Thinking| NORMAL |Thinking----------------------+ +--------+ --------------------------------------------- Introducing NetZero Long Distance 1st month Free! Sign up today at: www.netzerolongdistance.com From lumbricus@gmx.net Thu Nov 21 00:49:02 2002 From: lumbricus@gmx.net (lumbricus@gmx.net) Date: Thu Nov 21 00:49:02 2002 Subject: [Tutor] os.remove question References: <3DDC7191.2090304@netzero.net> Message-ID: <27462.1037857700@www22.gmx.net> Hi! > .remove support the use of wildcards? No standard function I know of does this. > If not, how do I effect this? import glob glob.glob("*") HTH, J"o! -- Wir beschliessen etwas, stellen das dann in den Raum und warten dann einige Zeit ab, was passiert. Wenn es dann kein grosses Geschrei gibt und keine Aufstaende, weil die meisten gar nicht begreifen, was da beschlossen wurde, dann machen wir weiter - Schritt fuer Schritt, bis es kein Zurueck mehr gibt. -- J-C Juncker +++ GMX - Mail, Messaging & more http://www.gmx.net +++ NEU: Mit GMX ins Internet. Rund um die Uhr für 1 ct/ Min. surfen! From Simon.Wittber@perth.maptek.com.au Thu Nov 21 00:55:02 2002 From: Simon.Wittber@perth.maptek.com.au (Simon Wittber (Maptek)) Date: Thu Nov 21 00:55:02 2002 Subject: A basic MUD system. RE: [Tutor] my newbie program Message-ID: <10F0E58C0018054484E329DC494C4D7F01ADD3@mexper1.maptek.net.au> This is a multi-part message in MIME format. --------------InterScan_NT_MIME_Boundary Content-Type: multipart/alternative; boundary="----_=_NextPart_001_01C29122.6E4C779E" ------_=_NextPart_001_01C29122.6E4C779E Content-Type: text/plain; charset="us-ascii" Content-Transfer-Encoding: quoted-printable Hi there, =20 I wrote a basic MUD system to teach myself Python and sockets programming at the same time! =20 I recently rewrote the entire thing, it has lots of cryptic commands for creating rooms and objects while the game is playing.. =20 I had a World object which contained a list of Locations. Each Locations contained a dictionary of current Objects and Users in the Location. =20 To join rooms together, I created a Portal object, which linked one room to another in a specified direction. I.e. the room had a dictionary of Portals, with the dictionary key being the desired direction.=20 =20 This meant that the Portal was one way... so get around this I created another Portal coming in the opposite direction from the opposite room. I wrapped both Portals in a Gate object, which controlled the state of both Portals, eg (locked, visible, open, closed etc) =20 Another cool feature is you can attach python code to objects. Eg attach a 'kick' verb to the 'rabbit' object which executes code. Its fairly basic as MUD systems go, but its 100% Python and uses asynchronous sockets, and should work 'out of the box' on any system... =20 If anyone wants this code, drop me an email. =20 sw. -----Original Message----- From: sheri [mailto:din22@cox.net]=20 Sent: Tuesday, 19 November 2002 9:26 PM To: tutor@python.org Subject: [Tutor] my newbie program hello and thanks for the help on my program so far. what i am wondering is how hard would it be to implement a dig command that would create room objects while the game is running. also the appropriate exits. so something like dig(north) would create a new exit to a new room with an exit back to the room you dug from. i am guessing pretty hard but then, i am a=20 rank beginner so maybe its easy. or are=20 vague questions like this off topic here? i havent written any code for this because=20 i wouldnt know where to start. =20 ------_=_NextPart_001_01C29122.6E4C779E Content-Type: text/html; charset="us-ascii" Content-Transfer-Encoding: quoted-printable Message
Hi=20 there,
 
I=20 wrote a basic MUD system to teach myself Python and sockets programming = at the=20 same time!
 
I=20 recently rewrote the entire thing, it has lots of cryptic commands for = creating=20 rooms and objects while the game is playing..
 
I had=20 a World object which contained a list of Locations. Each Locations = contained a=20 dictionary of current Objects and Users in the = Location.
 
To=20 join rooms together, I created a Portal object, which linked one room to = another=20 in a specified direction. I.e. the room had a dictionary of Portals, = with the=20 dictionary key being the desired direction.
 
This=20 meant that the Portal was one way... so get around this I created = another Portal=20 coming in the opposite direction from the opposite room. I wrapped both = Portals=20 in a Gate object, which controlled the state of both Portals, eg = (locked,=20 visible, open, closed etc)
 
Another cool feature is you can attach python code to objects. = Eg attach=20 a 'kick' verb to the 'rabbit' object which executes code. Its fairly = basic as=20 MUD systems go, but its 100% Python and uses asynchronous sockets, and = should=20 work 'out of the box' on any system...
 
If=20 anyone wants this code, drop me an email.
 
sw.
-----Original = Message-----
From: sheri=20 [mailto:din22@cox.net]
Sent: Tuesday, 19 November 2002 9:26=20 PM
To: tutor@python.org
Subject: [Tutor] my newbie=20 program

hello and thanks for the help on my=20 program
so far. what i am wondering is how = hard=20 would
it be to implement a dig command that = would
create room objects while the game is = running.
also the appropriate exits. so = something=20 like
dig(north) would create a new exit to = a new=20 room
with an exit back to the room you dug = from.
i am guessing pretty hard but then, i = am a=20
rank beginner so maybe its easy. = or are
vague questions like this off topic=20 here?
i havent written any code=20 for this because
i = wouldnt know where to start.
 
=00 ------_=_NextPart_001_01C29122.6E4C779E-- --------------InterScan_NT_MIME_Boundary-- From wesc@deirdre.org Thu Nov 21 03:50:38 2002 From: wesc@deirdre.org (wesc@deirdre.org) Date: Thu Nov 21 03:50:38 2002 Subject: [Tutor] ANN: Python Programming course (Silicon Valley, CA) Message-ID: <200211210836.gAL8a2M29177@alpha.ece.ucsb.edu> "Python Programming" course UC Santa Cruz, Winter Quarter 2002 Jan 6 - Mar 10, 2003 (except Jan 20 and Feb 17) Monday nights, 6:30 - 9:30pm Sunnyvale, California http://artemis.ucsc-extension.edu/~wesc/013e44cd.htm Register online, or contact Sherry at 408-861-3765 or smirkarimi@ucsc-extension.edu to enroll. Sign up soon! Early registration deadline is December 20, 2002. Hope to see some of you there! I will be giving a Python Programming 2 course which follows this one in the Spring. Alternatively, an introduction to programming course using Python will also be offered this Winter with another instructor -- ask Sherry for more details. -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 dyoo@hkn.eecs.berkeley.edu Thu Nov 21 04:08:03 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Nov 21 04:08:03 2002 Subject: [Tutor] Re:[Tutor]Question on python (fwd) Message-ID: Hi Sachin, Forgive me: I need to sleep. *grin* I'm almost positive, though, that on the other side of the globe, there's are Python tutors who can help answer your question. Whenever you're replying to something posted on Tutor, it's often a good idea to keep the conversation on the list, so that people are free to jump in at any time. I will forward your question to the rest of the Tutor list. Sincerely, Danny Yoo ---------- Forwarded message ---------- Date: Thu, 21 Nov 2002 06:36:17 +0530 From: sachin mehra To: dyoo@hkn.eecs.berkeley.edu Subject: Re: [Tutor] Re:[Tutor]Question on python hi Danny, > > tr -cs '[:alpha:]' '[\n*]' < *.txt | uniq -c | sort -rm | more >Take a look at the documentation on the 'uniq' command; the 'man' page on >your system should explain why 'uniq' behaves in this way. This command I have used has worked allright for me!!I ran a text with this command & it gave me count of all the unique words in that text & the words itself.. So for the useage of popen(command[, mode[, bufsize]]).. ..is there a specific buffer size? manish _________________________________________________________________ Add photos to your messages with MSN 8. Get 2 months FREE*. http://join.msn.com/?page=features/featuredemail From magnus@thinkware.se Thu Nov 21 04:50:02 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Thu Nov 21 04:50:02 2002 Subject: [Tutor] yet more Tkinter problems (sorry guys) In-Reply-To: <20021121163048.683fe0b6.thomi@thomi.imail.net.nz> References: <5.1.0.14.0.20021120121539.06915598@www.thinkware.se> <20021120220405.7a042cb7.thomi@thomi.imail.net.nz> <5.1.0.14.0.20021120121539.06915598@www.thinkware.se> Message-ID: <5.1.0.14.0.20021121102349.02b47300@www.thinkware.se> At 16:30 2002-11-21 +1300, Thomi Richards wrote: >hmmm.. maybe i should have learnt wxpython instead. still, i guess it's >not too late to start, but Tkinter was fairly easy for me, is wxwindows >any harder? I'm not at all sure this will be easier in wxPython. Jacob Hall=E9n has written a Cookbook recipe on using Tkinter with threading. I'm sure you can adapt that. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/82965 In processIncoming you will update your progress bar, and in workerThread1 you will do your long running processing, and queue the progress messages for the progress bar at regular intervals. Fredrik Lundh's Introduction to Tkinter describes things like after_idle (section 44 - Alarm handlers and other non-event callbacks) that works similar to EVT_IDLE in wx. http://www.pythonware.com/library/tkinter/introduction/index.htm If you don't want to use threading, that's another option, but I haven't really seen any example of that, but I guess you can find that if you Google for after_idle. --=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 thomi@thomi.imail.net.nz Thu Nov 21 04:57:01 2002 From: thomi@thomi.imail.net.nz (Thomi Richards) Date: Thu Nov 21 04:57:01 2002 Subject: [Tutor] ANN: Python Programming course (Silicon Valley, CA) In-Reply-To: <200211210836.gAL8a2M29177@alpha.ece.ucsb.edu> References: <200211210836.gAL8a2M29177@alpha.ece.ucsb.edu> Message-ID: <20021121224458.71966ceb.thomi@thomi.imail.net.nz> an extramural course would be good. I haven't managed to find one yet though :-) -- Lord, what fools these mortals be! -- midsummer nights dream. Thomi Richards, thomi@imail.net.nz From thomi@thomi.imail.net.nz Thu Nov 21 05:02:02 2002 From: thomi@thomi.imail.net.nz (Thomi Richards) Date: Thu Nov 21 05:02:02 2002 Subject: [Tutor] yet more Tkinter problems (sorry guys) In-Reply-To: <5.1.0.14.0.20021121102349.02b47300@www.thinkware.se> References: <5.1.0.14.0.20021120121539.06915598@www.thinkware.se> <20021120220405.7a042cb7.thomi@thomi.imail.net.nz> <5.1.0.14.0.20021120121539.06915598@www.thinkware.se> <5.1.0.14.0.20021121102349.02b47300@www.thinkware.se> Message-ID: <20021121230129.04376a42.thomi@thomi.imail.net.nz> > I'm not at all sure this will be easier in wxPython. yes, at least from first looks, wxwindows looks more complicated then either Tkinter of GTK... is there any reason NOT to learn Tkinter?? I mean, people have said that it does things a little differently, but i'm guessing that it does the job as well as any other.... -- The software required Win95 or better, so I installed Linux. Thomi Richards, thomi@imail.net.nz From magnus@thinkware.se Thu Nov 21 06:33:03 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Thu Nov 21 06:33:03 2002 Subject: [Tutor] my newbie program In-Reply-To: <002801c29119$560e8fc0$fc550144@pn.at.cox.net> References: <5.1.0.14.0.20021119155331.02b0ced0@www.thinkware.se> Message-ID: <5.1.0.14.0.20021121121421.0691ba20@www.thinkware.se> At 22:49 2002-11-20 -0600, david wrote: >could you please explain the shared object? >i am not clear on how Room is using one >of Maps methods. Sure. > > class Room: > > map = Map() # Shared between instances. Since we instanciate a map object here, in the class scope which is executed only once, and not in __init__ which is executed one time for every Room object, we get *one* map, which all room objects can access, either as Room.map or as self.map as long as they don't hide it by doing "self.map = somethingElse". Actually, since it's a public attribute of the Room class, any piece of code in your program can access it as Room.map, but of course, if it's not a Room instance, self.map won't work. > > In Room.__init__ you have something like > > self.map.placeRoom(self, x, y) so that the map > > can keep track of where each room is. You see? if a room object is instanciated with (or somehow finds out) it's x and y coordinates, it can do: self.map.placeRoom(self, x, y) or if you wish: Room.map.placeRoom(self, x, y) It will get a reference to the common map object and call its placeRoom method with itself and the coordinates. Then the map knows where a certain room should be located, and it can store that information. See below in the Map class: > > def placeRoom(self, room, x, y): > > if self.grid.has_key((x, y)): > > raise KeyError, "Location taken!" > > self.grid[(x, y)] = room You could also make map into a global object. I did like I did because I felt that sometime in the future there might be several maps, and then you'd have to change the room class so that each room object gets the right map. If all the room objects always use "self.map" you will only have to remove the map=Map() from the current location and give the rooms their correct map in Room.__init__. If they accessed a global map, and that was changed, you'd have to change every place where the map objects use the map. It's usually not a good idea to make things very complicated just in case it might be needed in the future, but avoiding global objects is usually a good idea. Using self.map instead of just map doesn't feel like hard work... -- 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 max_ig@yahoo.com Thu Nov 21 07:04:01 2002 From: max_ig@yahoo.com (MIG) Date: Thu Nov 21 07:04:01 2002 Subject: point-of-sale in python / Re: [Tutor] Re: Python in education In-Reply-To: <20021120224129.GB10811@dman.ddts.net> Message-ID: <20021121120248.93460.qmail@web11307.mail.yahoo.com> D, I'm currently working on a point-of-sale for a small store I'm planning to open, so I'd like to contact your friend if he/she finally picked up python for it to share some feedback and ideas. (Or anybody in this mailing list who has worked in a project like this). I'm using Python with PMW and MySQL for data management. Besides the POS, I worked out a small and simple accounting program and an inventory control system. All of these prgs are or will be linked. The program is not the best program in the world (I'm not a professional on IT, in fact my background is on business), but I managed to keep it as simple as possible. Up to now, the code is half way to be completed (let's say 80% completed but full of things to improve). Perhaps when Í'll finish it, I'll put it somewhere on the web for free download. I'll be waiting for comments, Max --- Derrick 'dman' Hudson wrote: > I like python a lot and wish I could use it more :-). Speaking of > which, a friend has asked me to develop a point-of-sale system for > his > small business. I intend to use python for it, and am considering > using Zope for the backend and ncurses and xml-rpc for the thin > clients using. > __________________________________________________ Do you Yahoo!? Yahoo! Mail Plus – Powerful. Affordable. Sign up now. http://mailplus.yahoo.com From magnus@thinkware.se Thu Nov 21 07:20:02 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Thu Nov 21 07:20:02 2002 Subject: [Tutor] yet more Tkinter problems (sorry guys) In-Reply-To: <20021121230129.04376a42.thomi@thomi.imail.net.nz> References: <5.1.0.14.0.20021121102349.02b47300@www.thinkware.se> <5.1.0.14.0.20021120121539.06915598@www.thinkware.se> <20021120220405.7a042cb7.thomi@thomi.imail.net.nz> <5.1.0.14.0.20021120121539.06915598@www.thinkware.se> <5.1.0.14.0.20021121102349.02b47300@www.thinkware.se> Message-ID: <5.1.0.14.0.20021121125031.069728c8@www.thinkware.se> At 23:01 2002-11-21 +1300, Thomi Richards wrote: > > I'm not at all sure this will be easier in wxPython. > >yes, at least from first looks, wxwindows looks more complicated then >either Tkinter of GTK... is there any reason NOT to learn Tkinter?? No. Learning things are always educational. :) >I >mean, people have said that it does things a little differently, but i'm >guessing that it does the job as well as any other.... Well... all these tool kits have different strengths and weaknesses. I used to feel that Tkinter had too few features, and that if you need to add a third party tool kit such as PMW, you might as well use wxPython. wxPython certainly offers a lot more features than Tkinter + PMW. But now, Python comes with Tix included, and that seems to be the kind of extension Tkinter needs. Still not all the features of wxPython, but on the other hand it comes with the standard kit... I don't know any other GUI tool kit than wxPython well enough to make any educated comparisions though. I'd like to write something non-trivial with Tkinter/Tix. For me, it's fairly important that my software works reliably at reasoneble costs in both Windows and Linux. That narrows down the number of tool kits fairly much. QT is expensive on Windows. I'm sceptical about Gtk on Windows. MFC is out of course. Fox and FLTK have to little features and too small userbase. That pretty much leaves Tkinter/Tix and wxPython as the main contenders. Having worked with wxPython for over a year now, I have mixed feelings. Robin Dunn is doing a really good job, both in development and in community support, but the very fact that he personally answers most of the non-trivial questions in the wxpython mailing-list certainly indicates a problem in wxPython. It must be too difficult to use it right. I think you are right in saying that it's complicated. It also seems to me that the development of the C++ version, wxWindows is a bit chaotic. I'm not involved in that, but that's the impression I get. A lot of things work, break, work again and break again as we see new versions coming. A problem here might be that Robin has based wxPython on non-stable versions of wxWindows, but that's what we get. Also documentation is not always in sync with the code. I suggested that the docs should be included in the source and generated from it, to make it easier to keep the docs updated, but it seems Julian Smart, the original developer of wxWindows, opposes that. A particular problems that makes me worried, and has scared off other users is the poor handling of non US keyboards. Particularly in the grid widget. An interesting development for wxPython is that Mitch Kapor's (he's the guy who wrote 1-2-3 and founded Lotus Corp) new open source project will use Python, wxPython, ZODB etc for their MS Outlook killer. They have hired Robin Dunn for six months, so he will be working full time on wxPython and wxWindows now. Hopefully that will improve things. Although his main job seems to be to get the MacOS X version in shape, so I don't know how much it will mean for stability and uniformity in the Win32 or GTK versions, or for documentation. -- 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 Thu Nov 21 07:20:16 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu Nov 21 07:20:16 2002 Subject: [Tutor] how to redirect sys.__stdout__ back to screen in IDLE Message-ID: <7497DCA1C240C042B28F6657ADFD8E0974DA4F@i2km11-ukbr.domain1.systemhost.net> > I tried several times on Python Shell (IDLE 0.8) Aha! The penny drops. That's the problem, you are using IDLE. Look at this: >>> import sys >>> sys.stdout >>> sys.__stdout__ ', mode 'w' at 0x007554A0> >>> sys.__stdout__ holds the original stdout value when Python starts. However, IDLE replaces sys.stdout with its own stream. Thus you are replacing the IDLE stdout with a file then trying to restore the *original* console stdout, not the IDLE one. In IDLE you need to save stdout yourself: >>> old = sys.stdout >>> sys.stdout = open("text.txt",'w') >>> old.write(`sys.stdout`) >>> print 'bye!' >>> sys.stdout = old >>> sys.stdout This will then restore IDLEs stdout correctly as you can see. The advantage of this technique is that it should work whether inside IDLE or not since externally oldOut will be the same as __stdout__ The great thing about the >>> prompt is it lets you examine your environment to see whats happening, learn to use that functionality and it helps a lot... Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld@bt.com Thu Nov 21 07:32:01 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu Nov 21 07:32:01 2002 Subject: [Tutor] my newbie program Message-ID: <7497DCA1C240C042B28F6657ADFD8E097021F0@i2km11-ukbr.domain1.systemhost.net> > thanks. this seems clear except for > -dirindex+1 i dont see how thats > evaluated. I find the index of the command within the list of commands. -dirindex+1 simply takes the negative value after adding one to it. Thus is the index is 0(the first item) we need to use -1(the last item) If the index is 1(2nd item) we need -2(2nd last item)=-(1+1) etc... You did realise we can access lists from the end as well as the beginning using negative indices? >>> L = [1,2,3] >>> print L[0],L[-1] 1,3 >>> > very nice tutorial btw. how about adding > a case study of building a little text adventure? I know very little about text adventures. The paper book version does have a guessing game case study however.... Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld > > dirindex = directions.index(direction) > > newdir = directions[-dirindex+1] # get inverse direction Probably should read: newdir = directions[-(dirindex+1)] # get inverse direction > > self.exits[direction].exits[newdir] = self > > > > I find the index of the direction in the list > > I take the inverse by using the negative index - try it out > by hand... > > I add the exising room as an exit to the new one... From magnus@thinkware.se Thu Nov 21 07:34:01 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Thu Nov 21 07:34:01 2002 Subject: [Tutor] Re:[Tutor]Question on python In-Reply-To: Message-ID: <5.1.0.14.0.20021121105153.0691bdc0@www.thinkware.se> At 06:01 2002-11-21 +0530, sachin mehra wrote: >Well I want to use the following commands: >tr -cs '[:aplha:]' '[\n*]' < *.txt | uniq -c | sort -rm | more First of all, you must have a "sort" before "uniq", and I think you mean "sort -rn", not "sort -rm". I can't imagine that you want the 'more' part if you intend to use the output in a python script though. I'm not sure it's a good idea to make these kinds of mixing language shortcuts. This is certainly more compact than the corresponding solution in python, which would probably land on ten lines or so, but I think it's more difficult to maintain. The maintainer has to manage two different languages, at the same time. It's certainly less portable! -- 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 Nov 21 07:36:37 2002 From: magnus@thinkware.se (Magnus Lycka) Date: Thu Nov 21 07:36:37 2002 Subject: point-of-sale in python / Re: [Tutor] Re: Python in education In-Reply-To: <20021121120248.93460.qmail@web11307.mail.yahoo.com> References: <20021120224129.GB10811@dman.ddts.net> Message-ID: <5.1.0.14.0.20021121132221.06970e18@www.thinkware.se> At 04:02 2002-11-21 -0800, MIG wrote: >I'm currently working on a point-of-sale for a small store I'm planning >to open, so I'd like to contact your friend if he/she finally picked up >python for it to share some feedback and ideas. (Or anybody in this >mailing list who has worked in a project like this). > >I'm using Python with PMW and MySQL for data management. Besides the >POS, I worked out a small and simple accounting program and an >inventory control system. All of these prgs are or will be linked. The >program is not the best program in the world (I'm not a professional on >IT, in fact my background is on business), Good. I'm sure you have knowledge that most programmers lack. >but I managed to keep it as >simple as possible. That's always a good thing. >Up to now, the code is half way to be completed >(let's say 80% completed but full of things to improve). Perhaps when >=CD'll finish it, I'll put it somewhere on the web for free download. Don't wait. Put it up now! Then you might even get some help getting it done! (There are obviously others on this very list who might be interested. Perhaps they will do most of the remaining job?) Why not make it into a SourceForge proect? I feel that business administration software is an area where python should be used much more. Maybe there is a lot of programs like that written, but not made available, I don't know. But I'm sure there are many in your position who develop software not to sell it, but to use it, who would have a lot to gain from sharing source code and knowledge. I've never worked with any POS system, but I have some ideas about other kinds of business administration software that I'd like to write when I get the time (he he), and I have a few routines that I use. One idea is to make some kind of Meta-project for business administration software at Sourceforge, and to make things like my Swedish income tax calculations and your POS, inventory etc into sub-projects. --=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 yduppen@xs4all.nl Thu Nov 21 07:49:02 2002 From: yduppen@xs4all.nl (Yigal Duppen) Date: Thu Nov 21 07:49:02 2002 Subject: [Tutor] my newbie program In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E097021F0@i2km11-ukbr.domain1.systemhost.net> References: <7497DCA1C240C042B28F6657ADFD8E097021F0@i2km11-ukbr.domain1.systemhost.net> Message-ID: <200211211348.19863.yduppen@xs4all.nl> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 > I find the index of the command within the list of commands. > -dirindex+1 simply takes the negative value after adding one to it. Tsk tsk. I would not have expected this coming from you ;-) - -dirindex+1 takes the negative value of dirindex and *then* adds one to it. - -(dirindex + 1) takes the negative value after adding one to it. Which only goes to show: when in doubt, use brackets. YDD - -- http://www.xs4all.nl/~yduppen -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.0 (GNU/Linux) iD8DBQE93NYTLsKMuCf5EdwRAne6AKDpgk/DB+n29poYY1owRBmy3iKbHACgkLqL c8qbGmqMtu9nHMgcZy6PuUA= =KOSV -----END PGP SIGNATURE----- From hall@nhn.ou.edu Thu Nov 21 11:07:10 2002 From: hall@nhn.ou.edu (Ike Hall) Date: Thu Nov 21 11:07:10 2002 Subject: [Tutor] xml parsing In-Reply-To: <5.1.0.14.0.20021121123051.00a81e40@192.168.1.1> References: <5.1.0.14.0.20021121123051.00a81e40@192.168.1.1> Message-ID: <200211211604.gALG4XS27365@creek-clued0.fnal.gov> Thank you Alfred, This is very close to what I wish to do, (I also know nothing about XML, just that this is the format the data I wish to do something with will come to me as). In my case though, there are arbirtary levels of nesting, along with arbitrary keywords. However, upon looking at both this example and a little bit of documentation of the re module, I think I may be able to figure out how to do this for the general situation if I can come to understand the re module somewhat correctly. Thank you Ike On Wednesday 20 November 2002 08:34 pm, you wrote: > Hi Ike: > > I don't know anything about XML, and I don't know whether the example you > gave covers everything you want to do (for example, are there more levels > of nesting or different keywords). > > However, using the string functions it is easy to develop the dictionaries > you want as follows: > > import string > > def stringToDict (data, key) : > dict = {} > dataList = data.split(key) > for word in dataList : > if '<' not in word : break > if word.index('>') < word.index('<'): > word = word[word.index('>')+1:] > split = word.index('>') > key = word[:split].replace('<',"") > value = word[split+1:] > dict[key]=value > return dict > > > XMLstring = > "1.01.2346.4< >/item1>4" > > XMLdictionary = stringToDict(XMLstring, ' print XMLdictionary > for key in XMLdictionary : > XMLdictionary[key] = stringToDict(XMLdictionary[key], ' print XMLdictionary > > The output from this is: > > {'block2': {'item2': '4', 'item1': '6.4'}, 'block1': {'item2': '1.234', > 'item1': '1.0'}} > > HTH > > Fred Milgrom > > At 02:24 PM 20/11/02 -0600, you wrote: > >Hi all, > >Im having a little trouble reading the documentation to some of the xml > >parsing modules in order to get them to do what I want them to. > > > >Here is what I need to do: > >I recieve an XML string of the form: > > > >' > > 1.0 > > 1.234> > > > > > > 6.4 > > 4 > >' > > > >where I have placed indentations for clarity. the string I recieve has no > >whitespace or linebreaks. What I want to do, is to turn this string into > > a python dictionary that would look like this for that string: > > > >{'block1':{'item1':1.0,'item2':1.234},'block2':{'item1':6.4,'item2':4}} > > > >I have not been able to see clearly how to use the XML modules xmllib or > >xml.sax in order to do this, and I was wondering how this may be > > accomplished with a minimum of writing. > >I know I could just write a function to parse this string using only > > builtin python commands, but I do not think that this is the easiest > > solution. > > > >Thanks > >Ike > > > >_______________________________________________ > >Tutor maillist - Tutor@python.org > >http://mail.python.org/mailman/listinfo/tutor From alan.gauld@bt.com Thu Nov 21 12:14:51 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu Nov 21 12:14:51 2002 Subject: [Tutor] yet more Tkinter problems (sorry guys) Message-ID: <7497DCA1C240C042B28F6657ADFD8E097021FA@i2km11-ukbr.domain1.systemhost.net> > hmmm.. maybe i should have learnt wxpython instead. still, i > guess it's not too late to start, but Tkinter was fairly easy wxPython is pretty straightforward. Personally I find its layout management more complex (albeit more powerful). It doesn't general;ly require any more lines than Tkinter if thats any kind of metric. My web tutor has a comparitive example of the two in the GUI topic... Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From dyoo@hkn.eecs.berkeley.edu Thu Nov 21 12:15:05 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Nov 21 12:15:05 2002 Subject: [Tutor] Re:[Tutor]Question on python In-Reply-To: <5.1.0.14.0.20021121105153.0691bdc0@www.thinkware.se> Message-ID: On Thu, 21 Nov 2002, Magnus Lycka wrote: > At 06:01 2002-11-21 +0530, sachin mehra wrote: > >Well I want to use the following commands: > >tr -cs '[:aplha:]' '[\n*]' < *.txt | uniq -c | sort -rm | more > > First of all, you must have a "sort" before "uniq", and I think Here's a page that explains more about this: http://unix.about.com/library/weekly/aa061702a.htm Good luck! From alan.gauld@bt.com Thu Nov 21 12:20:01 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu Nov 21 12:20:01 2002 Subject: A basic MUD system. RE: [Tutor] my newbie program Message-ID: <7497DCA1C240C042B28F6657ADFD8E097021FC@i2km11-ukbr.domain1.systemhost.net> Why not comment it extensively, zip it up and send it to Useless Python? :-) Alan g > basic as MUD systems go, but its 100% Python and uses asynchronous > sockets, and should work 'out of the box' on any system... > > If anyone wants this code, drop me an email. From alan.gauld@bt.com Thu Nov 21 12:28:02 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu Nov 21 12:28:02 2002 Subject: [Tutor] os.remove question Message-ID: <7497DCA1C240C042B28F6657ADFD8E097021FB@i2km11-ukbr.domain1.systemhost.net> > os.remove(listname+'.*') > to remove all file with a specified name, and ANY > nameextension after the period. > > If not, how do I effect this? Use the glob module to generate the list of files then iterate over the list. Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld@bt.com Thu Nov 21 12:45:16 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu Nov 21 12:45:16 2002 Subject: [Tutor] yet more Tkinter problems (sorry guys) Message-ID: <7497DCA1C240C042B28F6657ADFD8E097021FD@i2km11-ukbr.domain1.systemhost.net> > either Tkinter of GTK... is there any reason NOT to learn Tkinter?? No, in fact there's a very good reason to learn Tkinter. It is based on Tk which is also the default GUI tool for Perl and Tcl, two other popular scripting languages... If you know Tkinter learning their GUI toolkits will be very easy. OTOH wxPyuthon is useful too because it is much more similar in style to things like Microsoft MFC(and the .NET class framework) so that if you ever have to use them wxPython knowlege will help more than Tkinter. They typify two types of approach to GUI toolkit design, both equally valid. Ideally learn both, then use the one you find most natural - for me thats Tkinter, but my GUI needs are very basic... If I had to build a sophisticated GUI I'd probably use something else(like Delphi!). Alan G. From lumbricus@gmx.net Thu Nov 21 12:45:50 2002 From: lumbricus@gmx.net (lumbricus@gmx.net) Date: Thu Nov 21 12:45:50 2002 Subject: [Tutor] Re:[Tutor]Question on python References: Message-ID: <3679.1037900026@www23.gmx.net> Hi! > Here's a page that explains more about this: > > http://unix.about.com/library/weekly/aa061702a.htm |