From finite.automaton at gmail.com Fri Apr 7 15:14:53 2006 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 7 Apr 2006 12:14:53 -0700 Subject: Screen placement based on screen resolution In-Reply-To: References: Message-ID: <1144437293.086701.49990@v46g2000cwv.googlegroups.com> Tkinter takes strings as its arguments; it's TCL's legacy. You can use string formatting for this: x = width/2-40 y = height/2-30 root.geometry('%ldx%ld+%ld+%ld' % (width, height, x, y)) From fulvio at pc.jaring.my Fri Apr 7 05:58:04 2006 From: fulvio at pc.jaring.my (Fulvio) Date: Fri, 7 Apr 2006 17:58:04 +0800 Subject: How can I get the text under the cusor ? In-Reply-To: <4436914B.3070402@gmail.com> References: <4436914B.3070402@gmail.com> Message-ID: <200604071758.04288.fulvio@pc.jaring.my> Alle 00:20, sabato 08 aprile 2006, Bo Yang ha scritto: > I want to develop an application to record some of the best words and > ideas On linux and KDE desktop is easy as a breathing, by Klipper applet:-) And also no virus prone like windowz. Pls no flame, just a consideration. F From tim.hochberg at ieee.org Mon Apr 17 23:57:46 2006 From: tim.hochberg at ieee.org (Tim Hochberg) Date: Mon, 17 Apr 2006 20:57:46 -0700 Subject: PEP 359: The "make" Statement In-Reply-To: <1145327067.281826.250030@j33g2000cwa.googlegroups.com> References: <1145318176.952461.203240@i39g2000cwa.googlegroups.com> <1145327067.281826.250030@j33g2000cwa.googlegroups.com> Message-ID: Carl Banks wrote: > Mike Orr wrote: > >>>I think this PEP is going off the rails. It's primary virtue was that it >> >>was a simpler, clearer way to write: >> >> class Foo(args): >> __metaclass__ = some_metaclass >> #... >> >>And it doesn't even do that. What's wrong with "class Foo: >>__metaclass__ = blah"? Two lines of code, and the double underscores >>indicate something special is happening. > > > I think you're missing the point somewhat. The real point isn't to > make using metaclasses easier; it's to let the useful semantics of the > class statement be used for things that aren't classes. I can see how you might get the impression from the above paragraph, but you'd be wrong. > > Example: I can define the following "metaclass": > > def PropertyMaker(name,bases,pdict): > fget = pdict.get("get",None) > fset = pdict.get("set",None) > fdel = pdict.get("delete",None) > doc = pdict.get("__doc__",None) > return property(fget,fset,fdel,doc) > > Then, I could define a property inside some class definition like this: > > class some_attribute: > __metaclass__ = PropertyMaker > def get(self): > whatever > def set(self,value): > whatever > > But the thing is, if I did that, I'd be lying bastard. I'd be using > the class statement and the __metaclass__ property; however, the object > I'm creating is not a class (it's a property), and the thing I'm > assigning to __metaclass__ is not a metaclass (it's a factory > function). With the make statement, I could instead write: > > make property some_attribute: > def get(self): > # etc. > > Then I'm not lying about it, and I'm using a more straightforward > syntax. > > If this proposal were just about metaclasses, I agree that wouldn't be > important enough to justify a new statement. Metaclasses aren't too > common, and are generally used by experts who don't need the > straightforwardness the make statement would provide. > > But, properties, dicts, and other things could benefit from some of the > semantics the class statement, and with the make statement, the average > user could take advantage of that without having to worry about all > this circumlocative metaclass hackiness. Here you've missed the point of my post. The post itself was not all that clear, I admit, but had you read the subsequent followups, it would have been clear that I wasn't arguing against the utility of the statement (nor was I arguing for it), I was arguing against complicating it for a useless use case. In particular making the namespace associated with make statement into some sort of quasi namespace in order to support the generating of HTML seems foolish for two reasons. First, it doesn't actually work in any but the most trivial of cases. Second, there is an existing syntax (as of 2.5) that can fill the same roll, only it actually works, specifically the 'with' statement. Regards, -tim From sakcee at gmail.com Wed Apr 26 00:15:44 2006 From: sakcee at gmail.com (Sakcee) Date: 25 Apr 2006 21:15:44 -0700 Subject: how to save python interpreter's command history Message-ID: <1146024944.913060.146710@y43g2000cwc.googlegroups.com> this has been a problem for me for some time. I want to save the interpretters command history to a file, there is a history file in my user directory .pyhistory but it saves only like 500 or so how can I make it save all the commands and not delete it, any other suggestions that people use is welcome thanks From gregor.jan at NOSPAMquick.cz Mon Apr 17 03:48:25 2006 From: gregor.jan at NOSPAMquick.cz (Jan Gregor) Date: Mon, 17 Apr 2006 09:48:25 +0200 Subject: installation of jython program Message-ID: Hello, I've done database console in jython called jydbconsole. It's now available on sourceforge. As you can guess console needs jdbc drivers. The script that runs jython itself doesn't public -cp option to add another classpaths. Yes I need to add jdbc drivers to classpath ... Of course I see solution to modify the jython script and distribute it with my program but is there cleaner solution ? Thanks, Jan From peter at engcorp.com Thu Apr 6 08:47:08 2006 From: peter at engcorp.com (Peter Hansen) Date: Thu, 06 Apr 2006 08:47:08 -0400 Subject: "The World's Most Maintainable Programming Language" In-Reply-To: References: <44331897$0$12009$c3e8da3@news.astraweb.com> Message-ID: Mirco Wahab wrote: > Hi Ralf >>So we should rename Python into Cottonmouth >>to get more attention. > > No, always take some word that relates to > something more or less 'feminine', its about > 96% of young males who sit hours on programming > over their beloved 'languages' ;-) > > Pythia? (http://en.wikipedia.org/wiki/Pythia) I guess that would make our motto "Pythia: now you're programming with ethylene." -Peter From aleaxit at yahoo.com Fri Apr 21 00:01:06 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 20 Apr 2006 21:01:06 -0700 Subject: Looking for a programming resource for newbees References: <1145581209.588428.249770@v46g2000cwv.googlegroups.com> Message-ID: <1he4264.174kdqrjlz9frN%aleaxit@yahoo.com> bambooforest wrote: > Hi all, > > I'm from a Linguistics background and am new(er) to programming. Could Welcome! Some of my best memories date from back when I did computational linguistics (with emphasis on the 'computational', but in close cooperation with people with emphasis on the 'linguistics', such as that wonderful scholar and gentleman, Tullio de Mauro). > I've looked at the online Python tutorial at python.org and resources > like O'Reilly's Python in a Nutshell, but they seem to teach you > language syntax and concepts like data types, or assume you already > know how to program. As the author of said Nutshell, I concur: it *most definitely* does not teach you programming!!! > I'm searching for something that teaches > programming. I suggest Alex From nicola.musatti at gmail.com Wed Apr 5 08:38:01 2006 From: nicola.musatti at gmail.com (Nicola Musatti) Date: 5 Apr 2006 05:38:01 -0700 Subject: Standalone Python functions in UML? In-Reply-To: References: <1144145349.186395.44890@z34g2000cwc.googlegroups.com> Message-ID: <1144240680.996369.7690@e56g2000cwe.googlegroups.com> Roman Susi wrote: [...] > Also, my argument that Python is quite good at communicating design > ideas is supported by the fact that Python developers do not use UML (or > other modelling tools/languages) as often as say Java programmers, nor > feel the need to. And probably Python is too dynamic for UML. That is > another reason rountrip tools aren't there. Another reason is probably the problem you started this thread with; UML class diagrams are very much centered around Java style object orientation. Other paradigms, like the procedural and the generic ones, do not fit well. Nor is it well suited to represent the shift to a meta level that is involved when you start creating types at execution time. Cheers, Nicola Musatti From richard at nospam.com Sat Apr 29 13:47:48 2006 From: richard at nospam.com (Richard Townsend) Date: Sat, 29 Apr 2006 18:47:48 +0100 Subject: How to get computer name References: <1146328920.066207.236540@e56g2000cwe.googlegroups.com> <1146330279.267574.73240@i39g2000cwa.googlegroups.com> Message-ID: <1uhk232xzjsh4.2fei0w3zwf42.dlg@40tude.net> On 29 Apr 2006 10:04:39 -0700, pitarda wrote: > Thanks! :) > > Though,... I think once I saw something like: getComputerByName but > can't find it anymore,... > > :) >>> import socket >>> print socket.gethostname() blade >>> print socket.gethostbyname('blade') # will print IP address -- Richard From ndbecker2 at gmail.com Wed Apr 26 09:51:46 2006 From: ndbecker2 at gmail.com (Neal Becker) Date: Wed, 26 Apr 2006 09:51:46 -0400 Subject: MinGW and Python References: <1145861223.509630.247350@y43g2000cwc.googlegroups.com> <444C79D7.4060007@v.loewis.de> <1145968496.649214.100040@i40g2000cwc.googlegroups.com> <1hec9xh.m7rzefh64am3N%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > sturlamolden wrote: > >> Robert Kern wrote: >> >> > Dunno. Depends on the machine. Depends on the program. Depends on how >> > the interpreter and any extension modules and underlying libraries were >> > built. Depends on which Linux and which Windows. >> > >> > I'm sorry, but your question is a non sequitur. I don't understand its >> > relevance to this thread. >> >> The relevance: Python is built with GCC on Linux. Do you or do you not >> see a performance hit on Linux? >> >> MinGW is GCC. Will you get a performance hit when building Python with >> MinGW? > > I cannot predict this, though it would be great if somebody who does > have both VS2003 and mingw could give it a try. > > What I did just post on another thread over the last couple of days is > about MacOSX, which also uses gcc: 14% faster pybench using Python 2.4.3 > under Win2000 under Parallels Workstation beta, compared to 2.4.3 > Universal directly on MacOSX -- the standard build of 2.4.3 in either > cause, i.e., the one built with MS compilers on Windows, vs the one > built with Apple's gcc on MacOSX. > > > Alex Please when quoting such benchmarks include gcc version. gcc >= 4.1 is supposed to have a lot of performance improvements. This is the current release. Since mingw is usually current, I haven't checked, but they may be using 4.1 now. From tjreedy at udel.edu Mon Apr 24 02:35:11 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 24 Apr 2006 02:35:11 -0400 Subject: Generate a sequence of random numbers that sum up to 1? References: <1145825688.099549.195040@j33g2000cwa.googlegroups.com> Message-ID: "fumanchu" wrote in message news:1145825688.099549.195040 at j33g2000cwa.googlegroups.com... > I'm surprised noone has pursued a course of subtraction rather than > division. I believe someone did mention the subtraction method in one of the initial responses. But the problem is this. If you independently sample n numbers from a given distribution and then rescale, then the scaled numbers still all have the same distribution (and are uniform in that sense). In the subtraction method, each comes from a differnt distribution, as others explained, with the nth being radically different from the first. Terry Jan Reedy From aahz at pythoncraft.com Tue Apr 11 11:01:43 2006 From: aahz at pythoncraft.com (Aahz) Date: 11 Apr 2006 08:01:43 -0700 Subject: Why new Python 2.5 feature "class C()" return old-style class ? References: <1144752553.305591.88050@j33g2000cwa.googlegroups.com> <443ba5a9$0$14281$626a54ce@news.free.fr> <1144763398.243329.231380@g10g2000cwb.googlegroups.com> <443bbdbe$0$15517$626a54ce@news.free.fr> Message-ID: In article <443bbdbe$0$15517$626a54ce at news.free.fr>, bruno at modulix wrote: > >Please repeat this 101 times each morning: >"thou shall not use old-style classes for they are deprecated". Classic classes are *NOT* deprecated. And Python for Dummies will make that clear (though we will note that there are people in the community who believe as you do). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "LL YR VWL R BLNG T S" From DavidRushby at gmail.com Sun Apr 23 13:03:59 2006 From: DavidRushby at gmail.com (David Rushby) Date: 23 Apr 2006 10:03:59 -0700 Subject: MS VC++ Toolkit 2003, where? In-Reply-To: <1he8pss.1yk7ug81rv7pw2N%aleaxit@yahoo.com> References: <1he8pss.1yk7ug81rv7pw2N%aleaxit@yahoo.com> Message-ID: <1145811839.042394.73260@t31g2000cwb.googlegroups.com> Alex Martelli wrote: > So -- does anybody know if the 2003-level Toolkit is STILL available for > download somewhere... http://www.microsoft.com/downloads/details.aspx?FamilyId=272BE09D-40BB-49FD-9CB0-4BFA122FA91B&displaylang=en From thulben at no-spam.com Sun Apr 2 19:48:42 2006 From: thulben at no-spam.com (Ben Thul) Date: Sun, 02 Apr 2006 18:48:42 -0500 Subject: Assignment in a while? In-Reply-To: References: <123071lnngm15da@corp.supernews.com> Message-ID: <1230omrqm50o4a5@corp.supernews.com> The inline iterator version fits very well with my sensibilities. The problem that I have with fetchall is that sometimes you need to deal with a very large dataset. Calling fetchall() on it will put the whole thing in memory, which is no good. Better to iterate over it one row at a time, IMO. Thanks a ton! Ben Duncan Booth wrote: > none wrote: > > >>If I try to run the above code, I get a SyntaxError indicating that I >>can't do an assignment in the while loop. I found a way around this >>(see the commented out while loop), but it seems hackish. Assignment >>within a while loop seems like a pretty standard thing, so I'm just >>curious what I'm missing. >> > > > Not much, you cannot assign to a variable in the controlling expression > of a while loop. However, for loops do assign values to variables, so if > the form with the break offends you, try restructuring your code as a for > loop. For example: > > for results in iter(sth.fetchone, None): > print results > > or in many cases you can just fetch everything in one go: > > for results in sth.fetchall(): > print results From paul at boddie.org.uk Sun Apr 2 15:02:24 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 2 Apr 2006 12:02:24 -0700 Subject: Assignment in a while? References: <123071lnngm15da@corp.supernews.com> Message-ID: <1144004544.270588.24720@t31g2000cwb.googlegroups.com> none/Ben wrote: > > Assignment within a while loop seems like a pretty standard thing, so I'm just > curious what I'm missing. The FAQ on this subject? ;-) http://www.python.org/doc/faq/general/#why-can-t-i-use-an-assignment-in-an-expression It's "standard" in C-flavoured languages, certainly, but probably not ubiquitous. Paul From kkylheku at gmail.com Fri Apr 28 16:28:07 2006 From: kkylheku at gmail.com (Kaz Kylheku) Date: 28 Apr 2006 13:28:07 -0700 Subject: (was Re: Xah's Edu Corner: Criticism vs Constructive Criticism) In-Reply-To: <4452258e$0$655$bed64819@news.gradwell.net> References: <1145992903.834316.198370@u72g2000cwu.googlegroups.com> <4GM3g.3084$TT.1768@twister.nyroc.rr.com> <1146231280.733609.143230@e56g2000cwe.googlegroups.com> <4452258e$0$655$bed64819@news.gradwell.net> Message-ID: <1146256087.184361.147730@g10g2000cwb.googlegroups.com> Chris Uppal wrote: > Tagore Smith wrote: > > > It's much easier to use a killfile than to complain to an ISP, and I > > think that that should be the preferred response to messages you don't > > like. > > I'm inclined to agree. The problem is not Xah Lee (whom I have killfiled), but What is the point of killfiling Xah Lee? Xah Lee does not enter into random debates. He always starts a new thread, which you can clearly identify by its subject line and who it is from. Xah Lee does not use sock puppets, nor does he otherwise conceal himself. He almost goes out of his way to be clearly identifiable. If you don't want to read Xah Lee, it is extremely easy to do so without killfile support. Intelligent people have learned that Xah Lee threads are extremely well identified and easy to avoid. So that leaves behind only complete idiots, and Xah Lee fans. :) > the people who insist on making my killfile useless by posting loads of > follow-ups saying things amounting to "stop this insane gibberish". Every > bloody time. This means that you are going into that thread anyway! Maybe if you un-killfiled Xah Lee, you would see the root article of the thread and then avoid stepping into it. Maybe you are stepping into these threads because you want to. If you truly don't like this stuff, maybe you should killfile by thread: kill the root article by Xah Lee, and, recursively, anything else which refers to it directly or transitively by parent references. But then, even that is superfluous if you have a threaded reader, since the thread is condensed to a single line on the screen which you have to explicitly open. From sybrenUSE at YOURthirdtower.com.imagination Thu Apr 6 05:59:02 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Thu, 6 Apr 2006 11:59:02 +0200 Subject: How to catch python's STDOUT References: <1144314684.986767.131650@j33g2000cwa.googlegroups.com> <1144316619.928494.224270@t31g2000cwb.googlegroups.com> Message-ID: praveenkumar.117 at gmail.com enlightened us with: > I have python script in which i have some print statements. I dont > want the outputs of print to be displayed on the console since it is > used my fellow-workers But i need those prints for debugging purpose > So some how i want to capture those prints can u please suggest I suggest you remove the print statements and start using the logging module instead. It's much more powerful, and allows you to put debug statements in a file, for instance. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From deets at nospam.web.de Wed Apr 5 14:56:27 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 05 Apr 2006 20:56:27 +0200 Subject: PIL question about crop method In-Reply-To: References: Message-ID: <49ii6rFoffn9U1@uni-berlin.de> John Salerno schrieb: > I might be way off target even looking into this method for what I need > to do, but I'm still a little confused about the description of it: > > crop > im.crop(box) => image > > Returns a rectangular region from the current image. The box is a > 4-tuple defining the left, upper, right, and lower pixel coordinate. > > I'm probably just being a little dense again, but how exactly do you > write the tuple? Wouldn't a coordinates parameter be a tuple of tuples? > It sounds like here you only need four numbers, but I don't understand > what 'left, upper, right, and lower pixel coordinate' means. It doesn't > seem like it's asking for a set of coordinates for each corner of the > box, or for a set at all. How do four separate numbers make up coordinates? You can think of a rect as two coordinates - e.g. (10, 20), (30, 100) Alternatively you can see it as boundary lines, in the order left, top, right, bottom. (10, 20, 30, 100) The latter is what you need. Diez From dadapapa at googlemail.com Sat Apr 22 12:43:28 2006 From: dadapapa at googlemail.com (harold) Date: 22 Apr 2006 09:43:28 -0700 Subject: problems when unpacking tuple ... In-Reply-To: References: <1145722900.647531.272680@i39g2000cwa.googlegroups.com> Message-ID: <1145724208.006080.138280@i40g2000cwc.googlegroups.com> Rene Pijlman schrieb: > harold: > >The output (when given the data I want to parse) is: > > If you'd told us that data, and told us what version of Python you're > using, we could have reproduced the problem to look into it. > Thank you for the answers and sorry that I did not provide more information in the first place. My data file is white space seperated data (space seperated data to be precise) and I am using python 2.4.2 As can be seen, the output of the print statement in the lines except ValueError , err: print line.split() raise err has exactly four values... > >ValueError: need more than 3 values to unpack > > > >Why does python think that I want to unpack the outcome of > >line.split() into three values instead of four? > > That's not what it says. It says there are only 3 values in the outcome, > and it needs more (4 to be precise). A similar error happens in an interpreter session, when typing >>> for line in ["1 2 3 4"] : ... for a,b,c,d in line.split() : ... pass ... Traceback (most recent call last): File "", line 2, in ? ValueError: need more than 1 value tyo unpack maybe this might help to track down the error. Thanks! - harold - From ldo at geek-central.gen.new_zealand Wed Apr 19 03:16:07 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 19 Apr 2006 19:16:07 +1200 Subject: Activating Batch Files from Python References: <1145417944.549477.198510@g10g2000cwb.googlegroups.com> Message-ID: In article <1145417944.549477.198510 at g10g2000cwb.googlegroups.com>, "Jeff Groves" wrote: >How can I use the .bat file to set environmental vars from Python? How about sourcing it from a shell, then using that same shell instance to run the programs? From floris.vannee at gmail.com Fri Apr 7 16:36:49 2006 From: floris.vannee at gmail.com (floris.vannee at gmail.com) Date: 7 Apr 2006 13:36:49 -0700 Subject: win32com In-Reply-To: <4436b74a$0$20180$8fcfb975@news.wanadoo.fr> References: <1144429099.614139.139750@z34g2000cwc.googlegroups.com> <4436b74a$0$20180$8fcfb975@news.wanadoo.fr> Message-ID: <1144442209.882091.121990@z34g2000cwc.googlegroups.com> Thanks :) For people who are also having this problem. The VB .NET code to import that COM object is: dim com_object as object com_object = CreateObject("Python.TestServer") 'Python.TestServer in this case, but for different programs, different names of course. And in order to get it work you need to remove this code of python line: _reg_desc_ = "Python Test COM Server" I dont know why, but it didn't work with that line, and it did work without the line. Floris From iainking at gmail.com Wed Apr 26 11:09:03 2006 From: iainking at gmail.com (Iain King) Date: 26 Apr 2006 08:09:03 -0700 Subject: wxpython warnings In-Reply-To: <444f7d79$0$29099$5fc30a8@news.tiscali.it> References: <1146054739.094951.278490@e56g2000cwe.googlegroups.com> <444f7d79$0$29099$5fc30a8@news.tiscali.it> Message-ID: <1146064143.511494.33660@g10g2000cwb.googlegroups.com> Michele Petrazzo wrote: > Philippe Martin wrote: > > I had a similar but simple problem (the file was missing) and had to > > check by hand before calling wxPython. > > > > Can you check the tag by hand before calling wxPython ? > > > > > > Philippe > > > > > > Hi, > also I have the same problem with g3/g4 images. My solution was convert > that image *before* to .png before... Very bad hack, but work. > I think that is an internal wxWidgets message (warning), passed to the > wxPython subsystem. > This is actually exactly what I did. (well, I converted to jpg, because they're going to end up as jpg anyway). bah Iain From brochu121 at gmail.com Thu Apr 20 17:23:16 2006 From: brochu121 at gmail.com (david brochu jr) Date: Thu, 20 Apr 2006 17:23:16 -0400 Subject: search a string Message-ID: <9583ed900604201423k5671242en7d4345e695ea7000@mail.gmail.com> Hello, I have a text file with the following string: ['\r\n', 'Pinging www.ebayyy.com [207.189.104.86] with 32 bytes of data:\r\n', '\r\n', 'Request timed out.\r\n', '\r\n', 'Ping statistics for 207.189.104.86:\r\n', ' Packets: Sent = 1, Received = 0, Lost = 1 (100% loss),\r\n'] How would I search to find out if the string contained "Request" and report if "Request" was found or not in the string? -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Sat Apr 1 02:14:36 2006 From: steve at holdenweb.com (Steve Holden) Date: Sat, 01 Apr 2006 02:14:36 -0500 Subject: Python 2.5 licensing: stop this change Message-ID: As the only director of the Python Software Foundation to vote against a recent Board motion to implement the change in licensing terms described in http://pyfound.blogspot.com/2006/04/python-25-licensing-change.html I would like to place on record my protest against this change. I think it will harm the Python language and ultimately be counter-productive, reducing the user base and discouraging open source programmers from contributing to the code base. If you disagree with this proposed change it's not too late to do something about it. If this change goes ahead it will be the end of Python as we know it. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd www.holdenweb.com Love me, love my blog holdenweb.blogspot.com From rpdooling at gmail.com Wed Apr 26 18:05:19 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 26 Apr 2006 15:05:19 -0700 Subject: print names of dictionaries References: <1146085818.242086.206290@e56g2000cwe.googlegroups.com> <1146087140.319985.36690@u72g2000cwu.googlegroups.com> Message-ID: <1146089119.905723.306200@v46g2000cwv.googlegroups.com> Yikes, I'll have to come back to the OO way in a month or two ;) This works for now. I just added their names as values: def printdict(dictionaries=[apps, dirs, sites]): for dictionary in dictionaries: print dictionary["name"] keys = dictionary.keys() keys.sort() for key in keys: if key != "name": print key, ":",dictionary[key] print '\n', Thank you both for your help. rpd From roy at panix.com Tue Apr 18 15:40:34 2006 From: roy at panix.com (Roy Smith) Date: Tue, 18 Apr 2006 19:40:34 +0000 (UTC) Subject: Missing interfaces in Python... References: <1145306373.781129.305840@z34g2000cwc.googlegroups.com><20060417210541.GV7561@vulcan.cprogrammer.org> Message-ID: Peter Maas wrote: > He probably means that with interfaces one could test compliance > with the interface as a whole instead of testing each member and > each signature as a single piece. All interfaces (as implemented by Java) prove is that your class has a bunch of methods with the right names and signatures. It doesn't prove that those methods do the right things. It's like having a bouncer in front of a nightclub stopping people saying, "You can't come in here unless you tell me you're over 21 and aren't wearing scruffy jeans". OK, I'm happy to tell you that, but if you don't check to make sure it's true, you're going to have a lot of scruffy 18 year olds crashing your party. From pmartin at snakecard.com Thu Apr 27 14:01:52 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Thu, 27 Apr 2006 13:01:52 -0500 Subject: OOP techniques in Python References: <1146158190.320947.108480@t31g2000cwb.googlegroups.com> Message-ID: Why is that ? to me it makes sense when I see self.__m_var that I'm dealing with a member variable taht derived classes will not see/access. Philippe Steven Bethard wrote: > Panos Laganakos wrote: >> we usually define private properties and provide public functions >> to access them, in the form of: >> get { ... } set { ... } >> >> Should we do the same in Python: >> >> self.__privateAttr = 'some val' >> >> def getPrivateAttr(self): >> return self.__privateAttr >> >> Or there's no point in doing so? > > There is no point in doing so. You should use plain attributes whenever > possible (that is, whenever you're really just doing a get or a set, > with no computation). The only reason to use getters and setters is so > that you can change the implementation later if you need to. But python > allows you to do this with properties: > > >>> class C(object): > ... def __init__(self, x): > ... self.x = x > ... > >>> C(42).x > 42 > >>> class C(object): > ... def _get_x(self): > ... return self._x * 2 > ... def _set_x(self, value): > ... self._x = value / 2 > ... x = property(_get_x, _set_x) > ... def __init__(self, x): > ... self.x = x > ... > >>> C(42).x > 42 > > Which should not be interpreted as saying you should start writing a > bunch of properties now. ;) Instead, only introduce a property when you > find that something must remain an attribute (presumably for backwards > compatibility reasons) but for whatever reason it now needs some > additional computation. > > STeVe From piet at cs.uu.nl Tue Apr 18 06:22:09 2006 From: piet at cs.uu.nl (Piet van Oostrum) Date: Tue, 18 Apr 2006 12:22:09 +0200 Subject: Queue can result in nested monitor deadlock References: <1145284326.177062.230120@v46g2000cwv.googlegroups.com> <1145292096.906390.254280@e56g2000cwe.googlegroups.com> Message-ID: >>>>> "Paul McGuire" (PM) wrote: >PM> "Jonathan Amsterdam" wrote in message >PM> news:1145292096.906390.254280 at e56g2000cwe.googlegroups.com... >>> If you don't want to call it deadlock, fine, but the program execution >>> I describe will make no progress to the end of time. Thread 2 can never >>> put anything in the queue, because Thread 1 holds M, and Thread 1 will >>> never release M because that can only happen if someone puts something >>> on the queue. >>> >PM> Ah, I get it now, and yes as you describe it, this is a deadlock. But why >PM> do you need both mutex M and a Queue, then? You should release M before >PM> calling Queue.get(). Then if you need to, you should reacquire it >PM> afterward. What Jonathan says is that in his example M and the mutex for the Queue should be the same to solve the problem. And that the Queue API should allow you to do that. I think he is right. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From phil at riverbankcomputing.co.uk Sat Apr 29 06:09:33 2006 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Sat, 29 Apr 2006 11:09:33 +0100 Subject: PyQt 4.0beta1 Released Message-ID: <200604291109.33883.phil@riverbankcomputing.co.uk> Riverbank Computing is pleased to announce the release of PyQt v4.0beta1 available from http://www.riverbankcomputing.co.uk/pyqt/. PyQt is a comprehensive set of Qt bindings for the Python programming language and supports the same platforms as Qt (Windows, Linux and MacOS/X). Like Qt, PyQt is available under the GPL and a commercial license. PyQt v4 supports Qt v4 (http://www.trolltech.com/products/qt/index.html). PyQt v3 is still available to support earlier versions of Qt. PyQt v4 is implemented as a set of 8 extension modules containing approximately 400 classes and 6,000 functions and methods. QtCore The non-GUI infrastructure including event loops, threads, i8n, Unicode, signals and slots, user and application settings. QtGui A rich collection of GUI widgets. QtNetwork A set of classes to support TCP and UDP socket programming and higher level protocols (eg. HTTP). QtOpenGL A set of classes that allows PyOpenGL to render onto Qt widgets. QtSql A set of classes that implement SQL data models and interfaces to industry standard databases. Includes an implementation of SQLite. QtSvg A set of classes to render SVG files onto Qt widgets. QtXML A set of classes that implement DOM and SAX parsers. QtAssistant A set of classes that enables the Qt Assistant online help browser to be integrated with an application. A Windows installer is provided for the GPL version of PyQt to be used with the GPL version of Qt v4 (http://www.trolltech.com/download/qt/windows.html). It enabes a complete PyQt environment to be installed on Windows without the need for a C++ compiler. PyQt includes the pyuic utility which generates Python code to implement user interfaces created with Qt Designer in the same way that the uic utility generates C++ code. It is also able to load Designer XML files dynamically. From edreamleo at charter.net Fri Apr 28 10:58:01 2006 From: edreamleo at charter.net (Edward K. Ream) Date: Fri, 28 Apr 2006 09:58:01 -0500 Subject: ANN: Leo 4.4 rc1 released Message-ID: <04q4g.28$9R.27@fe04.lga> Leo 4.4 release candidate 1 is now available at: http://sourceforge.net/project/showfiles.php?group_id=3458&package_id=29106 This version fixes a few minor bug reported in 4.4b4 and adds 9 new commands. The open-outline-by-name command supports filename completion. Leo is a text editor, data organizer, project manager and much more. See: http://webpages.charter.net/edreamleo/intro.html The highlights of Leo 4.4: -------------------------- - An Emacs-like mini-buffer: you can now execute any command by typing its long name, with tab completion. - Many new commands, including cursor and screen movement, basic character, word and paragraph manipulation, and commands to manipulate buffers, the kill ring, regions and rectangles. You can use Leo without using a mouse. - Flexible key bindings and input modes. You can emulate the operation of Emacs, Vim, or any other editor. - A tabbed log pane. The Find and Spell Check commands now use tabs instead of dialogs, making those commands much easier to use. Plugins or scripts can easily create new tabs. The Completion tab shows possible typing completions. - Autocompletion and calltips. - Dozens of other new features and bug fixes since Leo 4.3.3. Links: ------ Leo: http://webpages.charter.net/edreamleo/front.html Home: http://sourceforge.net/projects/leo/ Download: http://sourceforge.net/project/showfiles.php?group_id=3458 CVS: http://leo.tigris.org/source/browse/leo/ Quotes: http://webpages.charter.net/edreamleo/testimonials.html Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From rridge at csclub.uwaterloo.ca Wed Apr 26 17:38:33 2006 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: 26 Apr 2006 14:38:33 -0700 Subject: MinGW and Python References: <1145861223.509630.247350@y43g2000cwc.googlegroups.com> <444C79D7.4060007@v.loewis.de> <444DC62B.7000702@v.loewis.de> <1145985979.369429.114040@i39g2000cwa.googlegroups.com> <444e7d85$0$12131$9b622d9e@news.freenet.de> <1145999256.027851.132780@y43g2000cwc.googlegroups.com> <444FA782.6040503@v.loewis.de> Message-ID: <1146087513.773086.64370@u72g2000cwu.googlegroups.com> Ross Ridge wrote: > MSVCRT.DLL has been a standard system compent of Windows since at least > Windows 98. Many other system components depend on it. Essentially, > MSVCRT.DLL is an "undocumented" part of the Windows API. It's not > exactly "endorsed", Microsoft would rather you use it's current > compiler and runtime, but it is the standard "official" Windows system > C library. Martin v. L?wis wrote: > http://msdn2.microsoft.com/en-us/library/abx4dbyh(VS.80).aspx > > 'The msvcrt.dll is now a "known DLL," meaning that it is a system > component owned and built by Windows. It is intended for future use only > by system-level components.' Exactly, it's the standard Windows system C library. > The SDK stopped including an import library for it (I believe earlier > versions of the SDK still had an import library). An import library for it is easy enough to obtain. You can make your own, or just grab the one from MinGW. If you insist on a Microsoft source for it then you can find it in the Windows DDK. > Regardless, there is no version of the MS C++ library that links against > msvcrt.dll. The version of the MS C++ library in Visual Studio C++ 6 links against MSVCRT.DLL. > So if Python is linked against msvcrt.dll, you can't really build C++ > extensions anymore (with MSVC), unless you are certain that > mixing CRTs causes no harm for your application. Python 2.4 is linked against MSVCR71.DLL, so you can't really build C or C++ extensions anymore with Microsoft's current compiler either. Ross Ridge From dreedmac at columbus.rr.com Sat Apr 8 19:11:35 2006 From: dreedmac at columbus.rr.com (David Reed) Date: Sat, 8 Apr 2006 19:11:35 -0400 Subject: how relevant is C today? In-Reply-To: <871ww7elvu.fsf@ieee.org> References: <44381ee4$0$4209$c3e8da3@news.astraweb.com> <871ww7elvu.fsf@ieee.org> Message-ID: On Apr 8, 2006, at 6:35 PM, Jorge Godoy wrote: > Mirco Wahab writes: > >> "The Dice" (find tech jobs) has offerings >> (last 7 days, U.S. + unrestricted) for: >> *SQL 14,322 >> C/C++ 11,968 >> Java 10,143 >> ... >> Perl 3,332 >> PHP 730 >> *Python* 503 >> Fortran 119 >> Ruby 108 >> open*gl 66 >> >> That is what the industry looks for. >> You understand the ratios? > > Of course! You need 23 C/C++ people to do the job of one > Pythoneer ;-) > > -- > Jorge Godoy +1 QOTW Dave From bdesth.quelquechose at free.quelquepart.fr Sat Apr 8 13:41:13 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 08 Apr 2006 19:41:13 +0200 Subject: Programming Tutorial for absolute beginners In-Reply-To: <1144446605.916499.24470@i39g2000cwa.googlegroups.com> References: <1144439148.751062.16590@t31g2000cwb.googlegroups.com> <1144444872.962395.3310@z34g2000cwc.googlegroups.com> <1144446605.916499.24470@i39g2000cwa.googlegroups.com> Message-ID: <4437c7cd$0$11330$636a55ce@news.free.fr> Clodoaldo Pinto a ?crit : > bill pursell wrote: > (snip) >>2) In the section on installing, you begin with: >>"Python is an interpreted, interactive, object-oriented programming >>language.". The complete novice sees those words and expects >>them to be explained, but there is no definition given. I would >>recommend simplifying that sentence, or explaining the terms. > > Ok, i will think about something, or just delete it. FWIW, being "interpreted" is not a feature of a language but of a given implementation of a language - and actually, the reference implementation (CPython) is byte-compiled, not interpreted. As for interactivity, it comes from a program (the Python shell) that ships with the reference implementation - not from the laguage itself. This leaves us with "Python is an object-oriented programming language", which is not 100% accurate since Python - even if strongly OO - also supports the procedural and functional paradigms !-) From martin at v.loewis.de Sun Apr 9 03:53:39 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 09 Apr 2006 09:53:39 +0200 Subject: how relevant is C today? In-Reply-To: References: <44381ee4$0$4209$c3e8da3@news.astraweb.com> <44382711.10403@v.loewis.de> Message-ID: <4438BD83.1080405@v.loewis.de> John Zenger wrote: > Your message makes me sad, as if I heard someone say "never read a book > without a specific inducement; if you know someone is going to ask you > about the book, start reading it today, but if you don't know what you > are going to use the book for, reading it will be a waste of time." Ah. I wasn't actually talking about reading a C book. I was talking about learning the programming language. You should, of course, read a book about C - but I don't believe you can learn to program C by just reading a book (or any other programming language, for that matter). You will read the book, and might be able to *read* C programs afterwards. To be able to write them, you need practice, and, for that, you need a specific inducement. Regards, Martin From fredrik at pythonware.com Thu Apr 6 08:30:28 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 6 Apr 2006 14:30:28 +0200 Subject: How to change the docs - a case study References: <4434fcb8$1_3@newspeer2.tds.net> Message-ID: Kent Johnson wrote: > Here is an example. This morning I noticed a minor discrepancy in the > docs for the 'rot13' encoding. I posted a bug to SourceForge at 10:05 > GMT. At 10:59 someone commented that maybe the code was broken rather > than the docs. At 11:18 another poster responded that the code should > stay the same. At 11:25, less than two hours after my original report, a > fixed was checked in. how many manhours did this take, in total ? did you clock your own efforts ? > The complete exchange is here: > https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1465619&group_id=5470 the 2.4.3 doc is still broken: http://docs.python.org/lib/standard-encodings.html (and if I hadn't kicked people around a couple of months ago, even the development documentation, which still hasn't been updated, btw, would remain broken for another 4-6 months.) > The point being that there is a system in place that in my experience works pretty > well. so you're saying that we cannot do better, and that people who try should do some- thing else with their time ? From fredrik at pythonware.com Sat Apr 8 02:30:41 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 8 Apr 2006 08:30:41 +0200 Subject: very strange problem in 2.4 References: <1144454473.488240.271200@t31g2000cwb.googlegroups.com> <2tCdnYMo5LbIkqrZnZ2dnUVZ_u2dnZ2d@comcast.com> Message-ID: John Zenger wrote: > Your list probably contains several references to the same object, > instead of several different objects. This happens often when you use a > technique like: > > list = [ object ] * 100 > > ..because although this does make copies when "object" is an integer, it > just makes references in other cases. it always creates new references. the only thing that distinguishes immutable objects (like integers) from mutable objects (like lists) is that integers don't have any methods that let you modify their contents. there's no "this object is mutable" flag inside the object, and there's no code in the list multiply operation, or anywhere else, that looks for such a flag. From martin at v.loewis.de Wed Apr 26 13:01:54 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 26 Apr 2006 19:01:54 +0200 Subject: MinGW and Python In-Reply-To: <1145999256.027851.132780@y43g2000cwc.googlegroups.com> References: <1145861223.509630.247350@y43g2000cwc.googlegroups.com> <444C79D7.4060007@v.loewis.de> <444DC62B.7000702@v.loewis.de> <1145985979.369429.114040@i39g2000cwa.googlegroups.com> <444e7d85$0$12131$9b622d9e@news.freenet.de> <1145999256.027851.132780@y43g2000cwc.googlegroups.com> Message-ID: <444FA782.6040503@v.loewis.de> Ross Ridge wrote: > MSVCRT.DLL has been a standard system compent of Windows since at least > Windows 98. Many other system components depend on it. Essentially, > MSVCRT.DLL is an "undocumented" part of the Windows API. It's not > exactly "endorsed", Microsoft would rather you use it's current > compiler and runtime, but it is the standard "official" Windows system > C library. See http://msdn2.microsoft.com/en-us/library/abx4dbyh(VS.80).aspx 'The msvcrt.dll is now a "known DLL," meaning that it is a system component owned and built by Windows. It is intended for future use only by system-level components.' The SDK stopped including an import library for it (I believe earlier versions of the SDK still had an import library). Regardless, there is no version of the MS C++ library that links against msvcrt.dll. So if Python is linked against msvcrt.dll, you can't really build C++ extensions anymore (with MSVC), unless you are certain that mixing CRTs causes no harm for your application. Regards, Martin From anthony at ataribaby.org Fri Apr 28 20:45:02 2006 From: anthony at ataribaby.org (Keen Anthony) Date: Fri, 28 Apr 2006 17:45:02 -0700 Subject: Recommendations for a PostgreSQL db adapter, please? Message-ID: Hello, I am currently using psycopg 2 as my db adapter for a mod_python & PostgreSQL web app. It's works fine, and I haven't any complaints. I would appreciate some input on what other pythonistas like in an adapter. There were several different options available to me, but there was no particular informed reason for me to choose psycopg. Am I missing anything? ~ Anthony From tim.peters at gmail.com Thu Apr 27 20:02:47 2006 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 27 Apr 2006 20:02:47 -0400 Subject: how to free the big list memory In-Reply-To: <004f01c669e2$6f307590$350aa8c0@kyom> References: <004f01c669e2$6f307590$350aa8c0@kyom> Message-ID: <1f7befae0604271702l74fb99c3h1c9a60a775c1664a@mail.gmail.com> [kyo guan] > Python version 2.4.3 > > >>> l=range(50*1024*100) > > after this code, you can see the python nearly using about 80MB. > > then I do this > > >>> del l > > after this, the python still using more then 60MB, Why the python don't free my > memory? It's that you've created 5 million integers simultaneously alive, and each int object consumes 12 bytes. "For speed", Python maintains an internal free list for integer objects. Unfortunately, that free list is both immortal and unbounded in size. floats also use an immortal & unbounded free list. > Is there any way to force the python free my memory? Stop the process. Short of that, do you really need a list containing 5 million integers? I never do ;-) Something like for i in xrange(50*1024*100): # note the "x" in "xrange" whatever consumes a trivial amount of memory, because only two integers in the range are simultaneously alive at any point, and the free list makes reusing their space fast. From zdwang at xinces.com Sun Apr 9 22:20:41 2006 From: zdwang at xinces.com (zdwang at xinces.com) Date: 9 Apr 2006 19:20:41 -0700 Subject: a unicode question? In-Reply-To: <1144633431.375745.77670@z34g2000cwc.googlegroups.com> References: <1144631034.049820.62550@u72g2000cwu.googlegroups.com> <1144633431.375745.77670@z34g2000cwc.googlegroups.com> Message-ID: <1144635641.430975.285860@e56g2000cwe.googlegroups.com> Mr. John Machin, Thank you very much! From peter at engcorp.com Mon Apr 10 12:02:21 2006 From: peter at engcorp.com (Peter Hansen) Date: Mon, 10 Apr 2006 12:02:21 -0400 Subject: can't pass command-line arguments In-Reply-To: <1144684150.332160.293190@z34g2000cwc.googlegroups.com> References: <1144681621.999659.78880@z34g2000cwc.googlegroups.com> <1144684150.332160.293190@z34g2000cwc.googlegroups.com> Message-ID: BartlebyScrivener wrote: >>>You missed the other option: if PATHEXT has .pyc in front of .py then you >>>get exactly the described behaviour. > > That's it!! > > Trust me, I didn't do it. It was either ActiveState, Wing, or Komodo > Dragon, or some combination thereof. > > So remove .pyc from pathext? Doing that will prevent a leftover .pyc file in a directory earlier in the PATH from overriding a .py file later on in the PATH. If that was the specific problem, definitely remove it. Duncan, the answer to "why anyone would want to put .pyc into PATHEXT" is at least "because that's how it's almost always recommended". At least, I have been using that myself, probably for the same reason Rick did, and I can see lots of search results that list it that way. I'm just glad it was he who got caught by this and found the problem, and not me. ;-) I think the only reason one would want .pyc in the PATHEXT is if one ever wanted to run .pyc files that didn't have matching .py files, without having to specify the extension. That's certainly not a common enough usecase to justify making ".pyc;.py" the recommended or standard thing to add to PATHEXT. -Peter From no-spam at no-spam-no-spam.com Wed Apr 26 07:57:36 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Wed, 26 Apr 2006 13:57:36 +0200 Subject: KeybordInterrupts and friends In-Reply-To: <1146044514.173026.323700@i39g2000cwa.googlegroups.com> References: <1146044514.173026.323700@i39g2000cwa.googlegroups.com> Message-ID: aurelien.campeas at free.fr wrote: > Hello, > > I have a problem with the following code fragment : > > -------------------- > import sys > > while True: > try: > raw_input() > except EOFError: > print "C-d" > except KeyboardInterrupt: > print "C-c" > -------------------- > > The following behaviour seems bogus to me : > > auc at musca:~$ python test.py > C-c > C-c > C-d > C-d > Traceback (most recent call last): > File "test.py", line 5, in ? > raw_input() > KeyboardInterrupt > > The crash happens when I type C-c another time (always *after* atleast > one C-d has been issued). > > What's wrong ? My expectations ? CPython (2.3 and 2.4 on debian exhibit > the same problem). > Is this a FAQ ? maybe consider signal.signal(signal.SIGINT,... -robert From onurb at xiludom.gro Fri Apr 28 08:13:25 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 28 Apr 2006 14:13:25 +0200 Subject: Non-web-based templating system In-Reply-To: <4bec7mF10pfe5U1@uni-berlin.de> References: <1146221757.653214.115090@g10g2000cwb.googlegroups.com> <4bec7mF10pfe5U1@uni-berlin.de> Message-ID: <4452073b$0$23034$626a54ce@news.free.fr> Diez B. Roggisch wrote: > qscomputing at gmail.com wrote: > > >>Hi, >> >>I'm creating a small application in Python that uses lists and >>dictionaries to create a rudimentary database. I'd like to create some >>"fill-in-the-blanks" reports from this data, ideally by taking an RTF >>or plaintext file as a template and replacing placeholder tags with my >>data. >>Are there any good pre-written systems that would allow me to do this? > > > Maybe the built-in string interpolation is sufficient? > > print "Hello %(name)s" % dict(name="Peter Pan") > Else you may want to look at: - http://www.python.org/doc/2.4.2/whatsnew/node5.html - empy : http://www.alcyone.com/pyos/empy/ - cheetah : http://www.cheetahtemplate.org/ HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From fredrik at pythonware.com Mon Apr 17 18:01:54 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 18 Apr 2006 00:01:54 +0200 Subject: ANN: the experimental python faq wiki Message-ID: encouraged by the great response to the python tutorial wiki, I've set up another semi-open wiki for the Python FAQ: http://pyfaq.infogami.com/ the immediate goal is to get the FAQ ready for the 2.5 release, by using the wiki to collect comments. for more on future plans, see this page: http://pyfaq.infogami.com/process anyway, if you have some time to spare, why not drop by, pick some random article, and let us know how it can be improved. From nobody at 127.0.0.1 Wed Apr 26 15:41:55 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 26 Apr 2006 19:41:55 GMT Subject: A defense for bracket-less code References: Message-ID: <72Q3g.20605$tN3.18334@newssvr27.news.prodigy.net> Stelios Xanthakis wrote: > Also, I think that perl does that because otherwise code like > > if ($x) $y++ if $z; else $z--; > > would be even more confusing :) With or without braces, that's not legal code. A one-line if can't be followed by an else. The closest you can do is this: $y++ if $z; $z-- if !$z; but that's two statements. Your example would need braces even if they were optional. From prikryl at skil.cz Thu Apr 20 02:11:01 2006 From: prikryl at skil.cz (Petr Prikryl) Date: Thu, 20 Apr 2006 08:11:01 +0200 Subject: BIOCHIP --->>> NO GOOD !! References: <1144327915.817708.140010@z34g2000cwc.googlegroups.com> <1144388603.163595.42860@e56g2000cwe.googlegroups.com> Message-ID: rainbow.cougar wrote in message > okay wrote: > > To Archbishop Christodoulos Paraskevaides of the Greek Orthodox Church > > in Athens and Greece Archbishop, > > I talked with a Greek Orthodox believer in Australia and he told me two > > I'm thinking a list comprehension... Possibly some filter(map(....)) for the really orthodox believers... From grflanagan at yahoo.co.uk Fri Apr 21 16:11:08 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 21 Apr 2006 13:11:08 -0700 Subject: how to append to a list twice? References: Message-ID: <1145650268.104715.312980@g10g2000cwb.googlegroups.com> John Salerno wrote: > If I want to create a list of the form [100, 99, 99, 98, 98, 97, 97...] > (where each item is repeated twice after the first one), how might I do > that most efficiently? > > Right now I have this: > > series = [100] > for x in range(10): # just for testing > series.append(series[-1] - 1) > > But of course that only does it once, and I don't want to have to copy > and paste the append line. Perhaps there's a better way than this. > > Thanks. series = [100] + [ t for t in range(99,90,-1) for _ in [0,1] ] (what's wrong with two appends again...?) From pthibault33 at yahoo.ca Wed Apr 5 23:09:26 2006 From: pthibault33 at yahoo.ca (pierreth) Date: 5 Apr 2006 20:09:26 -0700 Subject: Installing Python 2.4 on RedHat Message-ID: <1144292966.511167.84410@t31g2000cwb.googlegroups.com> Hello, I made some programming wit Python 2.4 but Red Hat comes with version 2.3 as default. So I would like to install the last version of Python on a production server but I am a bit afraid. As I know, if I install the new version, the default version will still be 2.3, right? I would like to know if someone as experienced problems by installing a newer version of Python in a server environment? I think that things are going to be fine but I want to check before. ----------------- Pierre From vieri.delbianco at gmail.com Thu Apr 27 11:33:58 2006 From: vieri.delbianco at gmail.com (adam) Date: 27 Apr 2006 08:33:58 -0700 Subject: ILOG Server integration Message-ID: <1146152037.950079.251950@u72g2000cwu.googlegroups.com> Does anybody have experiences of Python and ILOG Server (distribution framework) integration? I need to access to a server application "exposed" through ILOG Server. Thanks Vieri From kent at kentsjohnson.com Tue Apr 4 10:59:18 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Tue, 04 Apr 2006 10:59:18 -0400 Subject: how to comment lot of lines in python In-Reply-To: References: <1143760897.940841.285300@i39g2000cwa.googlegroups.com> <44310867$1_1@newspeer2.tds.net> <44311ecd$1_3@newspeer2.tds.net> Message-ID: <4432846f_3@newspeer2.tds.net> Rick Zantow wrote: >> Thank you! I don't suppose you have any tricks to make it work with >> UTF-8 data outside the cp1252 character set, do you? >> > > Sadly, I don't. TP claims Unicode support, but I'm not sure what they > mean; it does seem to be restricted to cp1252. TP will correctly read and write UTF-8 files if they use only the characters available in cp1252. So there is a little Unicode support but it breaks down pretty quickly with, e.g. Chinese or even Polish. Kent From onurb at xiludom.gro Wed Apr 26 11:03:05 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 26 Apr 2006 17:03:05 +0200 Subject: Inherit from array In-Reply-To: <1146060853.950843.108950@i39g2000cwa.googlegroups.com> References: <1146057315.721573.196140@u72g2000cwu.googlegroups.com> <444f79a8$0$5191$626a54ce@news.free.fr> <1146060853.950843.108950@i39g2000cwa.googlegroups.com> Message-ID: <444f8bfe$0$13219$626a54ce@news.free.fr> TG wrote: > Obviously, there is something I didn't catch in python's inheritance. Nope. Obviously, array.array doesn't respect the usual rules. > from array import array > class Vector(array): > def __init__(self,size): > print self.typecode > array.__init__(self,'f') > > >>>>v = Vector('c') > > c > > Here, it says the typecode is 'c' - I thought such an information was > initalized during the array.__init__(self,'f') but obviously I was > wrong. > > Maybe the typecode is defined before, during the call to __new__ method I think this must be something along this line. > ... But here i'm getting lost. > Let's see : from array import array class Vector(array): def __new__(cls, size): v = super(Vector, cls).__new__(cls, 'f') #print "v is %s" % v return v def __init__(self, size): self.size = size v = Vector(42) print v HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From sleytr at gmail.com Thu Apr 6 09:07:23 2006 From: sleytr at gmail.com (Evren Esat Ozkan) Date: 6 Apr 2006 06:07:23 -0700 Subject: =?iso-8859-1?q?Re:_urllib.urlencode_wrongly_encoding_=B1_character?= In-Reply-To: <1144327797.796852.192050@i40g2000cwc.googlegroups.com> References: <1144287250.071811.296390@i39g2000cwa.googlegroups.com> <1144315212.179762.108490@t31g2000cwb.googlegroups.com> <1144327797.796852.192050@i40g2000cwc.googlegroups.com> Message-ID: <1144328843.939033.278760@j33g2000cwa.googlegroups.com> I'm just discovered that I don't have to remove that line, just change utf-8 to iso-8859-9 and it worked again. But I want to use utf-8. Please advise... From veracon at gmail.com Sun Apr 30 13:26:36 2006 From: veracon at gmail.com (veracon) Date: 30 Apr 2006 10:26:36 -0700 Subject: Hierarchy - how? Message-ID: <1146417996.915773.304250@j73g2000cwa.googlegroups.com> I'd like to know how to make the following string: food fruit red cherry yellow banana meat pork foo bar baz qux Result in a dictionary like this: {'food': {'fruit': {'red': 'cherry', 'yellow': 'banana'}, 'meat': 'pork'}, 'foo': {'bar': 'baz', 'qux': {}}} Or something like that (if you understand). What would be the best way of doing so? I'm thinking re.finditer might be appropriate, but I'm not sure. I'd prefer not looping TOO much, since it's actually made using a loop or two. Actually, if anyone has a better idea of how to do the entire thing, that'd be even better: def hierarchy(data, parent='', level=0, out=''): for item in which_parent(data, parent): out += ' ' * level + item + '\n' out = hierarchy(data, item, level + 1, out) return out def which_parent(data, parent): return filter(None, [item[1] == parent and item[0] or None for item in data]) data = (('food', ''), ('fruit', 'food'), ('red', 'fruit'), ('yellow', 'fruit'), ('cherry', 'red'), ('banana', 'yellow'), ('meat', 'food'), ('pork', 'meat'), ('foo', ''), ('bar', 'foo'), ('baz', 'bar'), ('qux', 'foo')) print hierarchy(data) -- Keep in mind that I don't want a string, I want a dictionary (but I can't figure out how to do it). From arne.meissner at gmx.de Thu Apr 13 17:45:06 2006 From: arne.meissner at gmx.de (Arne) Date: Thu, 13 Apr 2006 23:45:06 +0200 Subject: telnet read_sb_data Message-ID: Hello! Task: Connecting to a unix server and getting the directory list . OS: XP Connecting to the server via telnet is no problem. I also want to get the directory list. I know by using read_all I can get all the output (starting from the login up to the end). 1. What I look for is the option to get only certain parts of the output. It seems to me that the command "read_sb_data" can do this. The documentation says, that I will get the data between the SB/SE pair. But I don't know how to invoke the SE command in Unix. Even I don't know the SE command. 2. I thing when this command work I can also get the directory size for each directory in root (using df and du Unix commands) Using os.stat(path) doesen't work on XP, I am always getting a 0 return (i.e. (16895, 0L, 3, 1, 0, 0, 0L, 315529200, 315529200, 315529200)) Please be so kind and post a little bit of a code. Thanks a lot! Arne From steve at rueb.com Mon Apr 10 21:19:37 2006 From: steve at rueb.com (Steve Bergman) Date: 10 Apr 2006 18:19:37 -0700 Subject: Sorting a list of objects by multiple attributes Message-ID: <1144718377.331845.56390@z34g2000cwc.googlegroups.com> Hi, I am trying to come up with a clean and simple way to sort a list of objects (in this case SQLObject instances) by multiple attributes. e.g. a Person object may have an age, a lastName, and a firstName. I'd like to be able to arbitrarily sort by any combination of those in any order. I would especially like it to be clear and simple, since I am converting a web app from using SQL to using an ORM only and so the sorting will actually be controlled by variables coming from SELECTs in a web form. In SQL this is easy enough to accomplish, and I can do it in python with L.sort(key=lambda i: i.whatever). But for the multiple attribute case, I'm at a bit of a loss. Thanks for any help. -Steve From invalidemail at aerojockey.com Wed Apr 19 22:43:16 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 19 Apr 2006 19:43:16 -0700 Subject: Missing interfaces in Python... References: <1145306373.781129.305840@z34g2000cwc.googlegroups.com> <1145430546.625634.194710@g10g2000cwb.googlegroups.com> <7lrb429tg5c6dt1bt99d1131cafuulvqap@4ax.com> <4445f7f8$0$9451$626a54ce@news.free.fr> <1145438118.179643.140390@e56g2000cwe.googlegroups.com> Message-ID: <1145500996.149358.23470@g10g2000cwb.googlegroups.com> Ben wrote: > It seems to me that a lot of python projects reimplement interfaces or > adaption of some kind once they reach a certain size (Zope, PEAK, eggs, > TurboGears, etc), which implies that they really do have some benefits, > particularly in documentation. Yes. On my current largish project I've noticed that, as I refactor code and make it more and more concise, my classes have aquired pretty mature interfaces. I've begun thinking that a little inline tool to check compliance would be helpful at this point. However, all that refactoring I did to get my classes to that point would have been much more tedious if I'd been using interface definitions in early development; changing the interface definition every time some new problem came up would have been a pain. So I'm leery of having them in the languge even if we're not forced to use them. I'm afraid people will start writing interface definitions first, when they should be taking advantage of the duck typing to allow easy design changes when necessary. Only after a lot of effort, a lot of refactoring, and a large part of the problem space explored, will the interfaces be mature enough that writing interface definitions would be useful and not a burden. (And let's face it: there aren't many projects that get that far. :) Adaptation I have no comment about, not having needed it (yet). Carl Banks From deets at nospam.web.de Fri Apr 28 06:15:47 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 28 Apr 2006 12:15:47 +0200 Subject: Foriegn contents in Python Packages... References: <1146189287.607212.228630@j73g2000cwa.googlegroups.com> Message-ID: <4be8asF10li80U1@uni-berlin.de> redefined.horizons at gmail.com wrote: > Is it possible to store "non-python" files in a directory that serves > as a Python Package? (Like an image file or an XML file.) > > Is this allowed for sub-directories that are not Python Packages? In > other words, can I have a Python Package that contains other Python > Packages and also folders that aren't Python Packages? Yes. And the __file__-attribute of an imported module gives you the location in the filesystem, so that you can access the contents in a path-agnostic way. AFAIK there is even some builtin stuff in setuptools to handle data files - go google :) Diez From duncan.booth at invalid.invalid Thu Apr 13 03:40:34 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 13 Apr 2006 07:40:34 GMT Subject: list.clear() missing?!? References: <1144870852.886477.238570@u72g2000cwu.googlegroups.com> Message-ID: Peter Hansen wrote: >> * learning slices is basic to the language (this lesson shouldn't be >> skipped) > > And yet it doesn't appear to be in the tutorial. I could have missed > it, but I've looked in a number of the obvious places, without > actually going through it (again) from start to finish. Also, > googling for "slice site:docs.python.org", you have to go to the > *sixth* entry before you can find the first mention of "del x[:]" and > what it does. I think given the current docs it's possible to learn > all kinds of things about slicing and still not make the non-intuitive > leap that "del x[slice]" is actually how you spell "delete contents of > list in-place". Looking in the 'obvious' place in the Tutorial, section 5.1 'More on Lists' I found in the immediately following section 5.2 'The del statement': > There is a way to remove an item from a list given its index instead > of its value: the del statement. Unlike the pop()) method which > returns a value, the del keyword is a statement and can also be used > to remove slices from a list (which we did earlier by assignment of an > empty list to the slice). The 'earlier showing assignment of an empty list to a slice' is a reference to section 3.1.4 'Lists': > Assignment to slices is also possible, and this can even change the > size of the list: > > >>>> # Replace some items: > ... a[0:2] = [1, 12] >>>> a > [1, 12, 123, 1234] >>>> # Remove some: > ... a[0:2] = [] >>>> a > [123, 1234] > Both of these talk about ways to remove slices from a list. Perhaps the wording could be clearer to make it obvious that they can also be used to clear a list entirely (using the word 'clear' would certainly help people Googling for the answer). So maybe 'this can even change the size of the list or clear it completely' would be a good change for 3.1.4. From Andreas.Ames at comergo.com Tue Apr 25 08:49:29 2006 From: Andreas.Ames at comergo.com (Ames Andreas) Date: Tue, 25 Apr 2006 14:49:29 +0200 Subject: MinGW and Python Message-ID: <552B6B925278EF478EA8887D7F9E5AC3814452@tndefr-ws00024.tenovis.corp.lan> > -----Original Message----- > From: python-list-bounces+andreas.ames=comergo.com at python.org > [mailto:python-list-bounces+andreas.ames=comergo.com at python.or > g] On Behalf Of sturlamolden > Sent: Tuesday, April 25, 2006 2:27 PM > Subject: Re: MinGW and Python > > > Robert Kern wrote: > > > - gcc does not optimize particularly well. > > That is beyond BS. The more recent gcc releases optimize as > well as any > commercial compiler. GCC 4 may even optimize better than MSVC. Not to talk of standard compliance (msvc-c99 anyone?). cheers, aa -- Andreas Ames | Programmer | Comergo GmbH | Voice: +49 69 7505 3213 | ames AT avaya . com From mensanator at aol.com Sat Apr 15 20:47:20 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 15 Apr 2006 17:47:20 -0700 Subject: multiple parameters in if statement... In-Reply-To: References: Message-ID: <1145148440.290181.6340@u72g2000cwu.googlegroups.com> Kun wrote: > I am trying to make an if-statement that will not do anything and print > 'nothing entered' if there is nothing entered in a form. I have the > following code that does that, however, now even if I enter something Yes, but did you enter everything? > into the form, the code still outputs 'nothing entered'. The logic doesn't imply "nothing", it implies "not everything". The else clause will execute if ANY item is not enetered. > This violates > the if statement and I am wondering what I did wrong. > > if form.has_key("delete_id") and form["delete_id"].value != "" and > form.has_key("delete_date") and form["delete_date"].value != "" and > form.has_key("delete_purchasetype") and > form["delete_purchasetype"].value != "" and form.has_key("delete_price") > and form["delete_price"].value != "" and form.has_key("delete_comment") > and form["delete_comment"].value != "": > delete_id=form['delete_id'].value > delete_date=form['delete_date'].value > delete_purchasetype=form['delete_purchasetype'].value > delete_price=form['delete_price'].value > delete_comment=form['delete_comment'].value > else: > print "ERROR: Nothing entered!" > raise Exception From fredrik at pythonware.com Thu Apr 27 14:56:14 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 27 Apr 2006 20:56:14 +0200 Subject: os.system call problem References: <1146163334.760244.216780@u72g2000cwu.googlegroups.com> Message-ID: "questions?" wrote: > I use os.system to call a display program, e.g. > > os.system(displayblah blah) to call display. the program starts and > display things I wanted. When I kill display, somehow the python > program don't understand I want to move on, keep calling > os.system(displayblah blah) again and again. > I have to kill terminal to quit them all. > > How can I migrate back to my python program after I kill the display > program? Python doesn't run os.system() over and over again by itself, so there's probably something wrong with your code. how about posting the relevant code, so we don't have to guess ? (if you have some time to spare, reading http://www.catb.org/~esr/faqs/smart-questions.html won't hurt either) From tzot at sil-tec.gr Tue Apr 18 07:31:01 2006 From: tzot at sil-tec.gr (Christos Georgiou) Date: Tue, 18 Apr 2006 14:31:01 +0300 Subject: Shell like syntax for subprocess.Popen # overloading >, <, | References: <1145349423.908658.53180@g10g2000cwb.googlegroups.com> Message-ID: On 18 Apr 2006 01:37:03 -0700, rumours say that "jelle" might have written: >Hi, > >I use python quite a bit to couple different programs together. >Doing so has been a _lot_ easier since subprocess came around, but >would really like to be able to use the succinct shell syntax; >, <, | > >That really shouldn't be too hard to wrap in a class, but so far I >didn't succeed to do so this well, since I'm facing some trouble with >operator precedence that I do not know how to overcome. [snip] Overload the __or__ special function (ie the 'pipe' operator) instead of the __gt__ operator. I remember I have seen such a proposition (mentioning pump, filters and sinks) but I couldn't find it in google.groups.com --I think Aahz had something to do with it, but ICBW. Ah, I found it: http://mail.python.org/pipermail/python-dev/2004-April/044205.html I don't know why I remembered Aahz about it :) Check this too: http://groups.google.gr/group/comp.lang.python/browse_thread/thread/674a821ed7003b69/777efd4d3aa490ed?lnk=st&q=python+overload+pipe+syntax&rnum=1&hl=en#777efd4d3aa490ed -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From bssoft at tin.it Thu Apr 6 10:29:04 2006 From: bssoft at tin.it (bssoft at tin.it) Date: 6 Apr 2006 07:29:04 -0700 Subject: kinterbas and Python In-Reply-To: <1144286425.983622.311530@j33g2000cwa.googlegroups.com> References: <1144169752.389326@anc-srv.fastnet.it> <1144286425.983622.311530@j33g2000cwa.googlegroups.com> Message-ID: <1144333744.572728.314820@t31g2000cwb.googlegroups.com> Ok, thank..my python is 2.4.2 kinterbas is 3.2a1 Firebird is 1.5 on FEDORA CORE 4 my program code is run under winxp.... my actual code is equal above and when i past the code i forgot the quote but in my code the quote is correctly. My error code is : concorrency level error use kinterbas.init(concurrency_level=?) to set the concurrency level legally... thanks in advanced. From caseyhHAMMER_TIME at istar.ca Tue Apr 11 14:20:13 2006 From: caseyhHAMMER_TIME at istar.ca (Casey Hawthorne) Date: Tue, 11 Apr 2006 18:20:13 GMT Subject: About classes and OOP in Python References: <1144678797.749000.155010@t31g2000cwb.googlegroups.com> <1144743716.408970.23840@z34g2000cwc.googlegroups.com> Message-ID: <00rn321nv3oqbjesmqpdl4p0s3tgdj7o2f@4ax.com> >I think it's important not to wrongly confuse 'OOP' with ''data hiding' >or any other aspect you may be familiar with from Java or C++. The >primary concept behind OOP is not buzzwords such as abstraction, >encapsulation, polymorphism, etc etc, but the fact that your program >consists of objects maintaining their own state, working together to >produce the required results, as opposed to the procedural method where >the program consists of functions that operate on a separate data set. Isn't "inheritance" an important buzzword for OOP? -- Regards, Casey From deets at nospam.web.de Wed Apr 19 12:06:16 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 19 Apr 2006 18:06:16 +0200 Subject: accessing a classes code References: Message-ID: <4an5g9Fu22qqU1@uni-berlin.de> Ryan Krauss wrote: > I have a set of Python classes that represent elements in a structural > model for vibration modeling (sort of like FEA). Some of the > parameters of the model are initially unknown and I do some system > identification to determine the parameters. After I determine these > unknown parameters, I would like to substitute them back into the > model and save the model as a new python class. To do this, I think > each element needs to be able to read in the code for its __init__ > method, make the substitutions and then write the new __init__ method > to a file defining a new class with the now known parameters. > > Is there a way for a Python instance to access its own code > (especially the __init__ method)? And if there is, is there a clean > way to write the modified code back to a file? I assume that if I > can get the code as a list of strings, I can output it to a file > easily enough. > > I am tempted to just read in the code and write a little Python script > to parse it to get me the __init__ methods, but that seems like > reinventing the wheel. Use dictionaries for those parameters, and set them on your instances. class Foo(object): def __init__(self, **unknown_params): for key, value in unknown_params: setattr(self, key, value) HTH, Diez From mhoward736 at gmail.com Tue Apr 11 20:31:41 2006 From: mhoward736 at gmail.com (Mike Howard) Date: 11 Apr 2006 17:31:41 -0700 Subject: Help needed on COM issue In-Reply-To: <1144800704.082281.133290@v46g2000cwv.googlegroups.com> References: <1144800704.082281.133290@v46g2000cwv.googlegroups.com> Message-ID: <1144801901.572802.221330@u72g2000cwu.googlegroups.com> Should read ... I'm doing some conversion of vb code to python code and I have a problem with a COM object Specifically in VB I can do Set oR = oA.Action debug.print oR.Item(1,2) [returns say "1"] oR.Item(1,2)="4" debug.print oR [returns "4"] oR.Update [saves the record with the new item] In Python I need to do .. oR=oA.Action() print oR.Item(1,2)[0] [returns say "1"] But when I ty to update the value oR.Item(1,2)[0]="4" I get a TypeError : object doesn't support item assignment. I presume this is because Python is returning oR as a tupe - hence the need to refer to Item(1,2)[0] - but I can't figure out the equivalent method to update the value I need. Any help appreciated. From cablepuff at hotmail.com Wed Apr 26 15:47:21 2006 From: cablepuff at hotmail.com (chun ping wang) Date: Wed, 26 Apr 2006 12:47:21 -0700 Subject: modifying iterator value. Message-ID: Hi, I have something simple i want to do. i want to modify an iterator value. for x in someList x = 1 is it possible to do that..if not how do i modify a list using iteration. _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today - it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From rrr at ronadam.com Thu Apr 6 15:50:09 2006 From: rrr at ronadam.com (Ron Adam) Date: Thu, 06 Apr 2006 14:50:09 -0500 Subject: good style guides for python-style documentation ? In-Reply-To: References: Message-ID: > (reposted from doc-sig, which seems to be mostly dead > these days). > > over at the pytut wiki, "carndt" asked: > > Are there any guidelines about conventions concerning > punctuation, text styles and language style (e.g. how > to address the reader)? > > any suggestions from this list ? > > Well there's: PEP 8 -- Style Guide for Python Code http://www.python.org/dev/peps/pep-0008/ But I presume you already know that one. It covers doc strings some, but not general documentation. A how-to on documenting would be nice. Cheers, Ron From jos at xos.nl Sat Apr 15 08:03:57 2006 From: jos at xos.nl (Jos Vos) Date: Sat, 15 Apr 2006 14:03:57 +0200 Subject: XML-RPC server via xinetd Message-ID: <20060415140357.A2759@xos037.xos.nl> Hi, I'm trying to figure out how to implement a XML-RPC server that is called by xinetd i.s.o. listening on a TCP socket itself. I already have implemented a stand-alone XML-RPC server using SimpleXMLRPCServer, but I now want something similar, that is started via xinetd (i.e. reading/writing via stdin/stdout). Any hints or code examples? Thanks, -- -- Jos Vos -- X/OS Experts in Open Systems BV | Phone: +31 20 6938364 -- Amsterdam, The Netherlands | Fax: +31 20 6948204 From http Sun Apr 9 00:05:16 2006 From: http (Paul Rubin) Date: 08 Apr 2006 21:05:16 -0700 Subject: programming puzzles? References: <44381f2f$0$4209$c3e8da3@news.astraweb.com> <1144532090.213069.191600@i39g2000cwa.googlegroups.com> <4438428e$0$11362$c3e8da3@news.astraweb.com> <1144543413.421821.132730@e56g2000cwe.googlegroups.com> <7xpsjrwhm6.fsf@ruckus.brouhaha.com> <1144554696.748228.12310@g10g2000cwb.googlegroups.com> Message-ID: <7xlkufwg03.fsf@ruckus.brouhaha.com> "mensanator at aol.com" writes: > The trouble with word lists is when you run across something > you don't recognize, like "ixodid", you can't tell if it's a word or > an acronym or an abbreviation. Well, once they told us the winner was "ixodid", we found that word quickly in a dictionary. But we'd certainly never heard it before. From tjgolden at gmail.com Thu Apr 27 03:58:23 2006 From: tjgolden at gmail.com (Tim Golden) Date: 27 Apr 2006 00:58:23 -0700 Subject: Can one query full name (or version) of selected packages at pypi? In-Reply-To: <1146000912.061888.264870@v46g2000cwv.googlegroups.com> References: <1145525161.975827.277860@u72g2000cwu.googlegroups.com> <444b268e$0$9543$9b622d9e@news.freenet.de> <1146000912.061888.264870@v46g2000cwv.googlegroups.com> Message-ID: <1146124703.692484.95740@j33g2000cwa.googlegroups.com> [Caleb Hattingh] > My big problem, being in South Africa, is > that I have to get any distros on cover CDs or order from > distro-resellers, and they never have Testing or Unstable. Broadband > hasn't exactly hit the local market, although things might be looking > up in a few years or so. I have no idea how useful the following will be, but I've bought CDs several times from linuxemporium.co.uk and they've always been very obliging when I've contacted them directly for updates etc. Obviously I can't speak for them, but I don't imagine it's any harder for them to burn Debian Unstable/Testing than burning any other download. They're UK-based, but maybe a distributor in your part of the world might be equally obliging. TJG From fredrik at pythonware.com Sat Apr 29 19:49:22 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 30 Apr 2006 01:49:22 +0200 Subject: Can we create an_object = object() and add attribute like fora class? References: <1hek76f.48x7rvw33771N%aleaxit@yahoo.com> Message-ID: Pierre Rouleau wrote: > I can understand the design decision not to give object a __dict__, but > I wonder if i'd be a good idea to have a class that derives from object > and has a __dict__ to be in the standard library. so you can replace one line of code in some of your programs with an import statement ? cute. From peter at engcorp.com Wed Apr 12 20:39:14 2006 From: peter at engcorp.com (Peter Hansen) Date: Wed, 12 Apr 2006 20:39:14 -0400 Subject: Iterating command switches from a data file - have a working solution but it seems inefficient In-Reply-To: <123r6925duev9b2@corp.supernews.com> References: <123r6925duev9b2@corp.supernews.com> Message-ID: News wrote: > Hi everyone, > > My goal is to pull command switches/options from a file and then assign > the values to select variables which would eventually be included in a > class object. > > The data file looks something like this but the switches could be in any > order and not all may be used. > > -m quemanager -s server -p port -k key -o object -c 20 -t test at email.com > > Also, please keep in mind that the source code will have more than one > line in it and each has to be treaded separately. I think you could just use getopt or optparse, passing in each line after doing a simple .split() on it. The resulting handling of the arguments would be much simpler and cleaner than what you have. That won't work perfectly well if you can have quoted arguments with spaces in them, however, but the example above does not. -Peter From skip at pobox.com Sat Apr 22 07:50:45 2006 From: skip at pobox.com (skip at pobox.com) Date: Sat, 22 Apr 2006 06:50:45 -0500 Subject: repr() for Perl? Message-ID: <17482.6293.121041.659562@montanaro.dyndns.org> Sorry to ask a Perl question here, but... Does Perl have something like Python's repr() function? I want to print out a string and have CR print as \r, LF as \n, etc. I looked in the Perl/Python phrasebook: http://wiki.python.org/moin/PerlPhrasebook but saw nothing along those lines. Thx, Skip From skip at pobox.com Sat Apr 22 08:03:18 2006 From: skip at pobox.com (skip at pobox.com) Date: Sat, 22 Apr 2006 07:03:18 -0500 Subject: what has python added to programming languages? (lets be esoteric, shall we ;) In-Reply-To: <4448D6CA.6080702@freakmail.de> References: <4448D6CA.6080702@freakmail.de> Message-ID: <17482.7046.866133.456308@montanaro.dyndns.org> Wildemar> Are there any concepts that python has not borrowed, concepts Wildemar> that were not even inspired by other languages? I'd say Guido's willingness to borrow heavily from the best ideas present in other languages ranks right up there as one of its key concepts. Skip From tim.golden at viacom-outdoor.co.uk Wed Apr 5 03:46:16 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: 5 Apr 2006 00:46:16 -0700 Subject: CD Burning References: Message-ID: <1144223176.314145.250790@u72g2000cwu.googlegroups.com> Albert Leibbrandt wrote: > Hi > > Can anybody tell me which windows API or python module they are using > for writing cd's / dvd's with python? Other people have offered sound suggestions about using cdrecord etc. under Cygwin. Just to make the point, though, XP (and above, presumably) does have an inbuilt interface for burning CDs. I've never used it, and I don't know how feasible it would be to access it from Python. (Helpful, eh?) The interface is ICDBurn and it should be possible to wrap it with ctypes / ctypes.com but I haven't the time at the moment to try it out. (And I haven't a CD writer in this machine either!) Ultimately, it might still be easier to install Cygwin and use the cdrecord approach. I just wanted to make the point that there *was* an in-built mechanism. ICDBurn: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc/platform/shell/reference/ifaces/icdburn/icdburn.asp ctypes.com: http://starship.python.net/crew/theller/ctypes/com.html TJG From aleaxit at yahoo.com Mon Apr 24 11:07:22 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 24 Apr 2006 08:07:22 -0700 Subject: MS VC++ Toolkit 2003, where? References: <1he8pss.1yk7ug81rv7pw2N%aleaxit@yahoo.com> <1145811839.042394.73260@t31g2000cwb.googlegroups.com> <1he8sbx.dqqp3q10n5thaN%aleaxit@yahoo.com> <1145849491.347970.112150@e56g2000cwe.googlegroups.com> <1he9m4m.9d8okx1x7mxeaN%aleaxit@yahoo.com> <444C7896.9040104@v.loewis.de> Message-ID: <1heagzk.1pzfash1awhj3eN%aleaxit@yahoo.com> "Martin v. L?wis" wrote: > Alex Martelli wrote: > > As suggested to me by David Rushby 10 hours ago, > > > > http://www.microsoft.com/downloads/details.aspx?FamilyId=272BE09D-40BB-4 > > 9FD-9CB0-4BFA122FA91B&displaylang=en > > > > does work. > > Can you please try this again: I'm also getting the error message > that AIM is getting. Try tinyurl http://tinyurl.com/gv8wr please. I've also tinyurl'd your URL for the 1.1 SDK, to http://tinyurl.com/5flob . ((I suspect the problem has to do with a limitation of 80 characters/line in NNTP messages, which my favorite newsreader enforces unconditionally)). Alex From ccurvey at gmail.com Wed Apr 12 08:46:09 2006 From: ccurvey at gmail.com (Chris Curvey) Date: 12 Apr 2006 05:46:09 -0700 Subject: example of logging w/ user-defined keywords? Message-ID: <1144845969.595683.185750@i40g2000cwc.googlegroups.com> Several things that I've read lead me to think this is possible, but I can't figure out how to do it. I have some information (a "job number") that I would like logged on every log message, just like the time or the severity. I saw some mail threads that suggested that there was an easy way to do this, but I havent' found any examples. Is there a simple way to do this, or do I need to write my own logger subclass? From tzot at sil-tec.gr Tue Apr 4 03:28:35 2006 From: tzot at sil-tec.gr (Christos Georgiou) Date: Tue, 04 Apr 2006 10:28:35 +0300 Subject: Find similar images using python References: <1143637570.842988.44030@z34g2000cwc.googlegroups.com> <442db42e$1@nntp0.pdx.net> Message-ID: On Fri, 31 Mar 2006 15:10:11 -0800, rumours say that Scott David Daniels might have written: >Christos Georgiou wrote: >> .... I did make a module based on imgseek, and together with PIL, >> I manage my archive of email attachments (it's incredible how many >> different versions of the same picture people send you: gif, jpg >> in different sizes etc) and it works fairly well. >> >> E-mail me if you want the module, I don't think I have it currently online >> anywhere. >This sounds like a great recipe for the cookbook: > http://aspn.activestate.com/ASPN/Cookbook/Python Actually, it should go to the CheeseShop, since it is a python module that is a bridge between PIL and the C module (I don't believe multi-file modules are appropriate for the cookbook, but ICBW); however, my web space is out of reach for some months now (in a web server at a previous company I worked for), and I'm in the process of fixing that :) -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From diffuser78 at gmail.com Sat Apr 8 23:08:53 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 8 Apr 2006 20:08:53 -0700 Subject: Automated Graph Plotting in Python Message-ID: <1144552132.926125.222210@i39g2000cwa.googlegroups.com> My python program spits lot of data. I take that data and plot graphs using OfficeOrg spredsheet. I want to automate this task as this takes so much of time. I have some questions. 1. Which is the best graph plotting utility in python or linux. Can I write a code in such a way that my python code automatically gives me a graph. I know little about gnuplot. If you know any better tool without much learning curve please tell me in Linux. 2. I want to write a script such that my python code writes to a file, some graph utility like gnuplot takes that data from the file and I get my graph ready made. Do you think its possible ? Any feedback regarding above is appreciated. Thanks From python.list at tim.thechases.com Wed Apr 19 10:14:06 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 19 Apr 2006 09:14:06 -0500 Subject: items in an array In-Reply-To: <1145455441.531332.295700@e56g2000cwe.googlegroups.com> References: <1145455441.531332.295700@e56g2000cwe.googlegroups.com> Message-ID: <444645AE.8010802@tim.thechases.com> > list_array = [] > list = item1,item2,itemN... My first recommendation would be that you not use "list" as an identifier, as it's a builtin function. Odd bugs might start happening if you redefine it. > I can get list to be how I want it if I use the index value as follows: > > list = ("%s" + "," + "%s", ...) % (list_array[0], list_array[1], ... If I understand correctly what you want, you're looking to create a string that consists of commas separating each element of your array. In such case, what you want is result = ",".join(list_array) or if you want spaces after your commas, the boringly trivial modification: result = ", ".join(list_array) If instead you want the result as a tuple, you can just use the tuple() function: tuple_result = tuple(list_array) If you want a tuple containing just the one string (which it strangely seems like your example is doing), you can do one_string_tuple = (",".join(list_array),) (note the peculiar "trailing comma in parens creates a one-element tuple" syntax...it often catches new Python programmers off-guard) HTH, -tim From martin at v.loewis.de Fri Apr 14 12:18:43 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 14 Apr 2006 18:18:43 +0200 Subject: Passing a packed C structure to a c module In-Reply-To: <3OP%f.811$9c6.333@dukeread11> References: <3OP%f.811$9c6.333@dukeread11> Message-ID: <443fcb63$0$3177$9b622d9e@news.freenet.de> Philippe Martin wrote: > Is it possible to define a packed C structure in python and pass it to the c > module, or should the wrapper do that ? You can create a packed structure using string concatenation, and with the help of the struct module. However, this gives you a string object in the end, which you still need to pass into your C library. It is better to fill the struct in the wrapper. Regards, Martin From micah.dylan at gmail.com Tue Apr 11 22:11:46 2006 From: micah.dylan at gmail.com (mrdylan) Date: 11 Apr 2006 19:11:46 -0700 Subject: How can I determine the property attributes on a class or instance? Message-ID: <1144807906.646773.279510@i40g2000cwc.googlegroups.com> Given a class like so: ------------------------------- class TestMe(object): def get(self): pass def set(self, v): pass p = property( get, set ) t = TestMe() type(t.p) #returns NoneType, what??? t.p.__str__ #returns ----------------------------------- What is the best way to determine that the attribute t.p is actually a property object? Obviously I can test the __str__ or __repr__ attributes using substring comparison but there must be a more elegant idiom. thanks! From aldonnelley at gmail.com Wed Apr 26 09:55:08 2006 From: aldonnelley at gmail.com (aldonnelley at gmail.com) Date: 26 Apr 2006 06:55:08 -0700 Subject: blob problems in pysqlite Message-ID: <1146059708.820551.7250@i39g2000cwa.googlegroups.com> Hi there. I'm a long-time lurker and (I think) first time poster. Only relatively new to python, and I'm trying to get pysqlite to work with binary data, and having a tough time of it. I want to set up a table with: - a URL, - some filenames related to that URL, - and some simple generated HTML. Problem is, when I try to do this, and query, say, the filenames from the filename field 'Images', I'm not getting a result. Just []... I've been googling this one for days (documentation for this seems really scant), and I've tried a whole bunch of things, but my code as it is now is attached. Can anyone give me some idea what i'm doing wrong (or if this is indeed possible)? Any and all help much appreciated. Cheers, Al. #script starts from pysqlite2 import dbapi2 as sqlite HTMLoutputFile = open('ImageResults.html', 'wb') cPickle.dump(OutputHTML, HTMLoutputFile) # outputHTML is a standard html page HTMLoutputFile.close() DBfilelistFile = open('DBFilesList.txt', 'wb') cPickle.dump(DBfilelist, DBfilelistFile) # DBfileList is a list of filenames in the form ['XXX.jpg', 'XXX.jpg' etc] DBfilelistFile.close() DBURL = 'http://www.myhomepage.html' blobdata = open('ImageResults.html', 'rb').read() blobfiles = open('DBFilesList.txt', 'rb').read() db = sqlite.connect("ImageInfoDatabase.db") c = db.cursor() try: c.execute("create table FileURLInfo (URL CHAR(100), Images, HTML)") except: print 'database exists' c.execute("INSERT INTO FileURLInfo VALUES (?,?,?);", (DBURL, sqlite.Binary(blobfiles), sqlite.Binary(blobdata)),) c.execute("select Images from FileURLInfo where URL = 'http://www.myhomepage.html'",) DBImageResult = c.fetchall() print DBImageResult #script ends From siona at chiark.greenend.org.uk Thu Apr 6 10:27:29 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 06 Apr 2006 15:27:29 +0100 (BST) Subject: pre-PEP: The create statement References: <59Wdnbd8EazRCqnZnZ2dnUVZ_vudnZ2d@comcast.com> <1144328362.729594.173160@z34g2000cwc.googlegroups.com> Message-ID: <13B*uLudr@news.chiark.greenend.org.uk> Kay Schluehr wrote: >Steven Bethard wrote: >> Python-Version: 2.6 >Have you a rough estimation how many modules will be broken when >"create" is introduced as a keyword? A quick scan of the standard library suggests that it will have a grand total of 3 modules requiring a fix (it's a method name in imaplib and a named argument in a couple of places in bsddb and distutils). Your own code my fare worse (mine does, but not by much). -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From ssimpson at interchangeusa.com Thu Apr 27 19:52:54 2006 From: ssimpson at interchangeusa.com (Scott Simpson) Date: Thu, 27 Apr 2006 16:52:54 -0700 Subject: How to import whole namespace into global symbol table? (newbie) Message-ID: Suppose I have the following python program: def func(): from sys import stderr, exit try: f = open("foo", 'r') except IOError: print >> stderr, "Input file foo does not exist" exit(1) def main(): import sys if len(args) != 0: sys.exit(1) func() if __name__ == '__main__': main() Notice that I have two "import sys" statements, one for each function. Is there any way to import the "sys" stuff to the global symbol table so I don't need two "import" statements? Lastly, is there an equivalent of Perl's "die" function? I'm writing to stderr and dieing above but I'm not quite sure if this is the "correct" way. From kadeko at gmail.com Thu Apr 27 06:27:14 2006 From: kadeko at gmail.com (looping) Date: 27 Apr 2006 03:27:14 -0700 Subject: can anyone advise me References: <1146131326.328919.285430@t31g2000cwb.googlegroups.com> Message-ID: <1146133634.111993.75790@i40g2000cwc.googlegroups.com> try something like this: x = 0 while x < 10: z = 0 print '-' + str(x) + '-' x = x + 1 while z < x: print '.' + str(z) + '.', z = z + 1 From fredrik at pythonware.com Thu Apr 6 14:07:10 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 6 Apr 2006 20:07:10 +0200 Subject: Quickie: converting r"\x2019" to int References: <4435501d$1_2@newspeer2.tds.net> Message-ID: Just wrote: > > Robin Haswell wrote: > > > Hey guys. This should just be a quickie: I can't figure out how to convert > > > r"\x2019" to an int - could someone give me a hand please? > > > > Is this what you mean? > > In [9]: int(r'\x2019'[2:], 16) > > Out[9]: 8217 > > > > or maybe you meant this: > > In [6]: ord(u'\u2019') > > Out[6]: 8217 > > Or even: > > >>> import struct > >>> struct.unpack("q", "\0\0"+ r'\x2019')[0] > 101671307850041L > >>> > > Who knows :) I think we can be pretty sure that he didn't mean >>> import unicodedata >>> unicodedata.numeric(u"\u2019") Traceback (most recent call last): File "", line 1, in ? ValueError: not a numeric character though... >>> unicodedata.name(u"\u2019") 'RIGHT SINGLE QUOTATION MARK' From johnmc at velseis.com.au Tue Apr 4 19:33:22 2006 From: johnmc at velseis.com.au (John McMonagle) Date: Wed, 05 Apr 2006 09:33:22 +1000 Subject: tkinter canvas In-Reply-To: <3753823.post@talk.nabble.com> References: <3753823.post@talk.nabble.com> Message-ID: <1144193602.772.18.camel@cornell> On Tue, 2006-04-04 at 14:47 -0700, fxe wrote: > Hi, > I am using tkinter and I have a canvas that with several rectangles drawn > on it. The rectangles need to have bindings to move and resize them. No > problem here, but I also need to display a grid on the same canvas, for > which I am using create_line. My problem is I do not want the grid lines to > be able to move and resize . > > Is this doable or any suggestions on an alternative.Maybe another way to > display my grid on top of the canvas? > When you create your canvas items use the tags option to differentiate items you wish to group together. For example, canvas.create_line(x1,y1,x2,y2,fill='#000000',tags='grid') canvas.create_rectangle(x1,y1,x2,y2,fill='#FF0000',outline='#FF0000',tags='rect') You can ensure that the grid lines are always displayed below the rectangles by using the tag_lower method: canvas.tag_lower('grid', 'rect') You can bind events to the named tags rather than the canvas as a whole: canvas.tag_bind('rect', '', startMove) canvas.tag_bind('rect', '', moveRect) canvas.tag_bind('rect', '', finishMove) Now when you click on a canvas item with a 'grid' tag nothing will happen, but if you click on a canvas item with a 'rect' tag you will invoke the appropriate function. HTH, John McMonagle -- This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean. From brianlum at gmail.com Mon Apr 3 01:16:00 2006 From: brianlum at gmail.com (brianlum at gmail.com) Date: 2 Apr 2006 22:16:00 -0700 Subject: Obtaining the Python Control Flow Graph Message-ID: <1144041360.431388.187650@i40g2000cwc.googlegroups.com> Hi, I have been looking for a good way to convert python code into a control flow graph. I know of Python functions that will convert an expression into an abstract syntax tree (i.e. ast = parser.expr('(x+5)*5') then t = ast.totuple() then t), but I am not sure how to obtain a CFG. I've gone through the compiler and it has code that converts the AST into a CFG (described here: http://www.python.org/doc/peps/pep-0339/#ast-to-cfg-to-bytecode). Basically, PyAST_Compile() in Python/compile.c coverts the AST to a CFG and outputs final bytecode from the CFG by calling two functions: PySymtable_Build() in Python/symtable.c and compiler_mod() in Python/compile.c. PySymtable_Build() will build a symtable and compiler_mod() will create the CFG. PyPy also offers a way to obtain a control flow graph: http://codespeak.net/pypy/dist/pypy/doc/objspace.html#the-flow-model I was wondering if anyone had any advice on the best way to obtain a control flow graph. I need the control flow graph because I am trying figure out if there is a way to bound the integer ranges and list lengths at compile time. Thank you for your help From sjmachin at lexicon.net Tue Apr 25 04:34:30 2006 From: sjmachin at lexicon.net (John Machin) Date: Tue, 25 Apr 2006 18:34:30 +1000 Subject: Counting elements in a list wildcard In-Reply-To: References: <1145921582.526072.120480@u72g2000cwu.googlegroups.com> <444d90a1$0$2568$ed2619ec@ptn-nntp-reader02.plus.net> Message-ID: <444ddf2f$1@news.eftel.com> On 25/04/2006 3:15 PM, Edward Elliott wrote: > Phoneme matching seems overly complex and might > grab things like Tsu-zi. It might *only* if somebody had a rush of blood to the head and devised yet another phonetic key "algorithm". Tsuzi does *not* give the same result as any of Suzi, Suzie, Susi, and Susie when pushed through any of the following; Soundex, NYSIIS, Metaphone, Dolby, and Caverphone. None of them throw away the 'T' sound. From sturlamolden at yahoo.no Mon Apr 3 12:58:09 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 3 Apr 2006 09:58:09 -0700 Subject: string building In-Reply-To: References: Message-ID: <1144083489.015954.141360@t31g2000cwb.googlegroups.com> John Salerno wrote: > Out of curiosity, is there any kind of equivalent in Python to the > StringBuilder class in C#? You can just append each string to a list and call "".join(list) on the list. Here is a mock-up StringBuilder class: class StringBuilder: def __init__(self): self.strlist = list() def Append(self,str): self.strlist.append(str) def ToString(self): return "".join(self.strlist) Implementing the rest of the .NET StringBuilder class is left as an exercise: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemtextstringbuilderclasstopic.asp http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemtextstringbuildermemberstopic.asp From ray_usenet at yahoo.com Mon Apr 10 00:50:11 2006 From: ray_usenet at yahoo.com (Ray) Date: 9 Apr 2006 21:50:11 -0700 Subject: how relevant is C today? In-Reply-To: <44398651$0$4206$c3e8da3@news.astraweb.com> References: <44381ee4$0$4209$c3e8da3@news.astraweb.com> <44382711.10403@v.loewis.de> <44393fbe$0$19226$c3e8da3@news.astraweb.com> <44398651$0$4206$c3e8da3@news.astraweb.com> Message-ID: <1144644611.512055.193260@i39g2000cwa.googlegroups.com> John Salerno wrote: > > At which level in the 'python challenge' did > > you get stuck - and why? > > Ugh, don't remind me! :) > > I'm stuck on level 12, which is yet another image processing puzzle. I'm > getting tired of those, and I think it's really a shame that there is a This is EXACTLY why I am still stuck on level 12 for many months. The first few ones are fun. That sequence thing is also particularly fun. But after a while, it seems that it's an image after image after image after image. I just got sick of PIL :) From codecraig at gmail.com Fri Apr 21 16:20:54 2006 From: codecraig at gmail.com (abcd) Date: 21 Apr 2006 13:20:54 -0700 Subject: Jython: exec a string Message-ID: <1145650854.705377.270060@v46g2000cwv.googlegroups.com> I have a single jython file, foo.py which contains multiple classes. I read that into a string and try to exec it....but I get errors saying something like unable to load class. It seems to work fine if foo.py only contains a single class, any ideas? From pascal.parent at free.fr Mon Apr 24 10:12:58 2006 From: pascal.parent at free.fr (pascal.parent at free.fr) Date: 24 Apr 2006 07:12:58 -0700 Subject: Subclass str: where is the problem? References: <1145882577.827728.54960@j33g2000cwa.googlegroups.com> <1145883907.466748.325610@t31g2000cwb.googlegroups.com> <1145886773.533093.65420@t31g2000cwb.googlegroups.com> Message-ID: <1145887978.854945.58040@v46g2000cwv.googlegroups.com> Effectively. Thanks a lot Peter and Harold. From da.martian at gmail.com Mon Apr 10 10:11:13 2006 From: da.martian at gmail.com (ChaosKCW) Date: 10 Apr 2006 07:11:13 -0700 Subject: Convertion of Unicode to ASCII NIGHTMARE In-Reply-To: <1144659373.400071.293290@j33g2000cwa.googlegroups.com> References: <1144079830.734516.8390@z34g2000cwc.googlegroups.com> <1144081137.137744.253790@i39g2000cwa.googlegroups.com> <34b9g3-ku8.ln1@home.rogerbinns.com> <1144150561.389856.302670@v46g2000cwv.googlegroups.com> <2enbg3-kr8.ln1@home.rogerbinns.com> <1144658233.045395.213570@j33g2000cwa.googlegroups.com> <1144659373.400071.293290@j33g2000cwa.googlegroups.com> Message-ID: <1144678273.036360.144000@e56g2000cwe.googlegroups.com> > > When python tries to concatenate a byte string and a unicode string, it > assumes that the byte string is encoded ascii and tries to convert from > encoded ascii to unicode. It calls ascii decoder to do the decoding. If > decoding fails you see message from ascii decoder about the error. > > Serge Ok I get it now. Sorry for the slowness. I have to say as a lover of python for its simplicity and clarity, the charatcer set thing has been harder than I would have liked to figure out. Thanks for all the help. From sjmachin at lexicon.net Sat Apr 29 17:47:02 2006 From: sjmachin at lexicon.net (John Machin) Date: Sun, 30 Apr 2006 07:47:02 +1000 Subject: Need help removing list elements. In-Reply-To: References: <1146316090.540227.278230@j73g2000cwa.googlegroups.com> Message-ID: <4453ded7$1@news.eftel.com> On 30/04/2006 12:22 AM, Max Erickson wrote: > nuffnough at gmail.com wrote in > news:1146316090.540227.278230 at j73g2000cwa.googlegroups.com: > >> But this gives me "IndexError: list out of range > > You are making the list shorter as you are iterating. By the time your > index is at the end of the original list, it isn't that long any more. If you are hell-bent on conditionally deleting items from a list in situ, you need to do it backwards: for i in xrange(len(alist)-1, -1, -1): if not_interested(alist[i]): del alist[i] > Creating a new list and appending the elements you want to keep avoids > the problem. Or you can just use a list comprehension(untested): > > returned_lines=[line for line in open("lines.txt", 'rb') Call me crazy, but I wouldn't open the file in BINARY mode :-) > if line != ""] > > or just > > returned_lines=[line for line in open("lines.txt") if line] For a modicum of extra effort, the condition "if line.strip()" throws away lines containing only whitespace. However I don't see the point of creating a list of lines, then throwing out only *some* of the uninteresting ones. IMHO the OP might be better advised to read the file one line at a time, ignoring blank/empty/comment lines, then *validate* the remainder. Hint: with the semi-squished-list approach, you can't report the original line number of any erroneous line without extra effort. The OP might be even better advised to (read the source of, use) an existing config file parser module. Hope some of this helps, John From bbands at gmail.com Tue Apr 18 07:13:04 2006 From: bbands at gmail.com (BBands) Date: 18 Apr 2006 04:13:04 -0700 Subject: Tokens? References: <59Wdnbd8EazRCqnZnZ2dnUVZ_vudnZ2d@comcast.com> <1144328362.729594.173160@z34g2000cwc.googlegroups.com> <1144331431.696334.248850@u72g2000cwu.googlegroups.com> Message-ID: <1145358784.706043.182540@u72g2000cwu.googlegroups.com> In the invaluable 'Dr. Dobb's Python-URL! - weekly Python news and links' of April 17 Peter Otten writes: "Michele Simionato's little script lets you search for a name in Python scripts, avoiding false positives that a standard tool like grep would yield." Can someone explain why this is so? I have attached the script below. import sys, tokenize, token def count_name(name, script): "Count the occurrences of a Python name in a script" counter = 0 for tok_code, tok_value, (srow, scol), (erow, ecol), line in \ tokenize.generate_tokens(file(script).readline): if tok_code == token.NAME and tok_value == name: counter += 1 print 'line %s: %s' %(srow, line), if counter: print '*** %s ***\n' % script return counter if __name__ == '__main__': name = sys.argv[1] scripts = sys.argv[2:] total = sum(count_name(name, script) for script in scripts) print 'Found %d occurrences of %r' % (total, name) jab--who laments the day that Doctor Dobbs' Journal of Computer Callisthenics and Orthodontics changed its name. From panos.laganakos at gmail.com Mon Apr 24 12:29:53 2006 From: panos.laganakos at gmail.com (Panos Laganakos) Date: 24 Apr 2006 09:29:53 -0700 Subject: Packing a list of lists with struct.pack() In-Reply-To: <1145895732.963584.231100@j33g2000cwa.googlegroups.com> References: <1145895732.963584.231100@j33g2000cwa.googlegroups.com> Message-ID: <1145896193.873286.89900@i40g2000cwc.googlegroups.com> Just came up with this: litemp = [] [litemp.extend(i) for i in li] Seems to give me a list with all the inner elements of li, not sure if struct.pack will accept it now, but I'll give it a try. From amorgan at xenon.Stanford.EDU Wed Apr 5 20:02:16 2006 From: amorgan at xenon.Stanford.EDU (Alan Morgan) Date: Wed, 5 Apr 2006 17:02:16 -0700 (PDT) Subject: efficiency of range() and xrange() in for loops References: Message-ID: In article , Erik Max Francis wrote: >Alan Morgan wrote: > >> In article , >> Giovanni Bajo wrote: > > >>>Because you assume that the only use-case of range() is within a for-loop. >>>range() is a builtin function that can be used in any Python expression. For >>>instance: >>> >>>RED, GREEN, BLUE, WHITE, BLACK = range(5) >> >> Hmmm, this worked fine when I used xrange as well. Am I missing something? > >Not in your use case. Tuple unpacking will iterate, and so it doesn't >matter whether it's an actual list or an iterator: > > >>> a, b, c = xrange(3) > >>> a >0 > >>> b >1 > >>> c >2 > >There are certainly contexts where a sequence and its iterator are not >interchangeable. You missed an obvious one: > > >>> range(3) == xrange(3) >False I thought that one was sufficiently obvious as not to need mentioning. There was never any argument that range() and xrange() returned different things; the question (as I understood it) was if you could generally use the things they return in the same way and not *care* about the difference (the answer being "Yes, except when you can't"). Alan -- Defendit numerus From jeff_barish at earthlink.net Tue Apr 25 15:27:32 2006 From: jeff_barish at earthlink.net (Jeffrey Barish) Date: Tue, 25 Apr 2006 13:27:32 -0600 Subject: Multithreading and Queue Message-ID: Several methods in Queue.Queue have warnings in their doc strings that they are not reliable (e.g., qsize). I note that the code in all these methods is bracketed with lock acquire/release. These locks are intended to protect the enclosed code from collisions with other threads. I am wondering whether I understand correctly that the reason these methods are still not reliable is that from the point where a thread calls qsize (for example) to the point in Queue where a thread acquires a lock there is a bunch of code, none of which is protected by a lock, (and moreover there is another bunch of code between the point where a thread releases a lock and then actually returns to the calling program) and so despite the locks in Queue it is still possible for values to change before a thread acts on them. -- Jeffrey Barish From nobody at 127.0.0.1 Sat Apr 22 14:57:25 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Sat, 22 Apr 2006 18:57:25 GMT Subject: perspective on ruby In-Reply-To: References: <1145555339.316764.123210@i39g2000cwa.googlegroups.com> <1he41sz.r7aasv1oo5lfN%aleaxit@yahoo.com> Message-ID: robert wrote: > Yes - start them explore. I'd not want to be "teached" a specific > _language_ in a course longer that one day. A language cannot be teached. > Who of the posters in this thread want themselves to be _teached_ more > than one day on a language? > > Isn't the fun, finding the right tools for certain purposes one-self? That holds for bright, motivated students. The problem is the others. Some people are totally lost when you throw them a book and say "learn this". So the choices are: 1. Do it and watch the rank-and-file students abandon the major 2. Provide more language-specific instruction Now places like Berkeley and MIT can afford to take route 1. They already have a surplus of bright, motivated students. But at many (most?) schools, route 2 is in the dept's best interest. Number of majors affects prestige, influence, and at many state schools funding. Telling the rank-and-file to shove off is shooting themselves in the foot, and ultimately hurts the good students as well with a lesser dept. These depts are walking a tightrope as they try hard to maintain minimum standards. It's not a binary choice really, it's a spectrum. So while route 1 may be better for the profession as a whole, the current educational system has some pretty strong pressures for route 2. From jon+usenet at unequivocal.co.uk Wed Apr 19 05:38:37 2006 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: 19 Apr 2006 09:38:37 GMT Subject: 2.5 excitement (was Re: Java Developer Exploring Python) References: <1145290449.735642.120860@i40g2000cwc.googlegroups.com> <1204021.LzRF60KP7e@jupiter.g2ctech> Message-ID: In article , Fredrik Lundh wrote: >> Apologies if I'm being obtuse, but how does including the pysqlite >> wrapper module change anything? You still need to download and install >> SQLite > > I'm pretty sure the distributors will do this for you, just as > they've included zlib, dbm, tcl/tk, openssl, and many other standard > libraries over the years. "The distributors"? Que? I guess I just don't get why the inclusion of the pysqlite wrapper is so exciting if all it's doing is changing the situation from "Python does not come with a DB, but you can install extra software to provide one" to "Python does not come with a DB, but you can install extra software to provide one". From scott.daniels at acm.org Sun Apr 30 14:40:14 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Sun, 30 Apr 2006 11:40:14 -0700 Subject: Add file to zip, or replace file in zip In-Reply-To: <1146257509.963417.250250@g10g2000cwb.googlegroups.com> References: <1146226281.040805.252450@j33g2000cwa.googlegroups.com> <1146257509.963417.250250@g10g2000cwb.googlegroups.com> Message-ID: <4455010f@nntp0.pdx.net> Roger Miller wrote: > First note that zipfile is a plain Python module, so reading > Python.../Lib/zipfile.py will reveal all its secrets. > > I don't think it is possible to replace archive members using the > module. You could copy all the files into a new zip file, replacing the > ones you want to change as you go. But it might be easier just to use > os.system() or something similar to run an external zip program. > It is not currently possible to delete or replace individual elements in a zip file, nor (in all likelihood) would you want to do so. It would require having the zip[ file in a broken state for some time as you copy data from one area of the zip to another. Any error (or raised exception like Control-C) during this process is likely to leave you with an inconsistent and therefore unreadable zip file. The typical technique is to mark some files "deleted" in the directory, add new files (possibly the replacements for the deleted files), and, in one pass, copy all non-deleted files to a new zip (which you can then swap for the original zip). Shortcutting this process puts all data in your zip file at risk. --Scott David Daniels scott.daniels at acm.org From forum at anton.e4ward.com Fri Apr 14 09:11:38 2006 From: forum at anton.e4ward.com (forum at anton.e4ward.com) Date: 14 Apr 2006 06:11:38 -0700 Subject: Loop with float increments (frange)? Message-ID: <1145020298.842177.97830@e56g2000cwe.googlegroups.com> Hi! what's the standard way for a "for" loop with float increments? Anton From amk at amk.ca Tue Apr 18 10:14:53 2006 From: amk at amk.ca (A.M. Kuchling) Date: Tue, 18 Apr 2006 09:14:53 -0500 Subject: [OT] Any Python lullabies? References: Message-ID: On Tue, 18 Apr 2006 07:07:27 -0500, Tim Chase wrote: > >>> [horse for horse in horses if horse.pretty] I'm familiar with this one as: all(pony for pony in ponies if pony.pretty). Never knew there was a version with "horse", not "pony". Jane Siberry does a nice rendition of the pony version. There's also: if brother_john.is_sleeping(): pass if brother_john.is_sleeping(): pass assert bells['morning'].is_ringing() assert bells['morning'].is_ringing() --amk From felipe.lessa at gmail.com Tue Apr 11 12:53:51 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Tue, 11 Apr 2006 13:53:51 -0300 Subject: list.clear() missing?!? In-Reply-To: References: <1144767680.583085.310160@v46g2000cwv.googlegroups.com> Message-ID: <1144774431.11151.5.camel@kenshin.CASA> Em Ter, 2006-04-11 ?s 10:42 -0600, Steven Bethard escreveu: > one of:: > > del lst[:] > > lst[:] = [] > > or if you don't need to modify the list in place, > > lst = [] > > Personally, I tend to go Fredrik's route and use the first. I love benchmarks, so as I was testing the options, I saw something very strange: $ python2.4 -mtimeit 'x = range(100000); ' 100 loops, best of 3: 6.7 msec per loop $ python2.4 -mtimeit 'x = range(100000); del x[:]' 100 loops, best of 3: 6.35 msec per loop $ python2.4 -mtimeit 'x = range(100000); x[:] = []' 100 loops, best of 3: 6.36 msec per loop $ python2.4 -mtimeit 'x = range(100000); del x' 100 loops, best of 3: 6.46 msec per loop Why the first benchmark is the slowest? I don't get it... could someone test this, too? Cheers, -- Felipe. From juanernestof at hotmail.com Thu Apr 27 14:48:23 2006 From: juanernestof at hotmail.com (JUAN ERNESTO FLORES BELTRAN) Date: Thu, 27 Apr 2006 18:48:23 +0000 Subject: fwd: Advanced Treeview Filtering Help Message-ID: by the way, iam using pygtk to develop the GUI Regards.- From felipe.lessa at gmail.com Sun Apr 9 22:46:48 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Sun, 09 Apr 2006 23:46:48 -0300 Subject: can't pass command-line arguments In-Reply-To: <1144636890.976327.253000@i39g2000cwa.googlegroups.com> References: <1144636890.976327.253000@i39g2000cwa.googlegroups.com> Message-ID: <1144637208.13607.0.camel@kenshin.CASA> Em Dom, 2006-04-09 ?s 19:41 -0700, BartlebyScrivener escreveu: > for path in all_files(sysargv[1], sysargv[2]): Instead of sysargv, use sys.argv. -- Felipe. From mailadmin at bgopen.net Mon Apr 24 07:17:24 2006 From: mailadmin at bgopen.net (mailadmin at bgopen.net) Date: Mon, 24 Apr 2006 14:17:24 +0300 Subject: YOUR MESSAGE HAS BEEN BLOCKED In-Reply-To: <200604241358.k3ODwVwb014064@gate.teleopen.net> References: <200604241358.k3ODwVwb014064@gate.teleopen.net> Message-ID: <200604241117.k3OBHO42002414@bgopen.net> Message Delivery BLOCKED Reason: Virus found in message. Our Virus scanner found a virus in the message that you sent. Virus scanning report - 24 April 2006 @ 14:17 F-PROT ANTIVIRUS Program version: 4.3.2 Engine version: 3.14.7 VIRUS SIGNATURE FILES SIGN.DEF created 21 April 2006 SIGN2.DEF created 21 April 2006 MACRO.DEF created 21 April 2006 Search: /var/tmp/emailscan2388/attachment Action: Automatic deletion Files: "Dumb" scan of all files Switches: -ARCHIVE -PACKED -LIST /var/tmp/emailscan2388/attachment/1-MChVEs5 /var/tmp/emailscan2388/attachment/body.zip->body.scr Infection: W32/Mytob.K at mm Virus-infected files in archives cannot be deleted. Results of virus scanning: Files: 2 MBRs: 0 Boot sectors: 0 Objects scanned: 3 Infected: 1 Suspicious: 0 Disinfected: 0 Deleted: 0 Renamed: 0 Time: 0:00 From fredrik at pythonware.com Sun Apr 9 12:20:43 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 9 Apr 2006 18:20:43 +0200 Subject: Tkinter References: <1144538582.829134.82040@e56g2000cwe.googlegroups.com> <1144585947.495767.186190@v46g2000cwv.googlegroups.com> Message-ID: "Jay" wrote: > Now I just get this error message. > > AttributeError: 'int' object has no attribute 'image' > > But the picture appears so I am almost their. > > ---START--- > > from Tkinter import * > > class App: > def __init__(self, root): > self.MainFrame = Canvas(root) > self.MainFrame.pack(fill=BOTH, expand=1) > > BackgroundFile = PhotoImage(file="Background.GIF") > Background = self.MainFrame.create_image(0, 0, > image=BackgroundFile) > Background.image = BackgroundFile # keep a reference! the example on that page attaches the image to a widget instance, not a canvas object handle (which is an integer; unlike user-defined classes, integers don't allow you to attach arbitrary attributes to them). if you just want to display a single image, just attach it to self: BackgroundFile = PhotoImage(file="Background.GIF") Background = self.MainFrame.create_image(0, 0, image=BackgroundFile) self.image = BackgroundFile # keep a reference! if you want to display multiple images on the canvas, use a dictionary or a list to hold active image references. From larry.bates at websafe.com Thu Apr 20 16:18:14 2006 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 20 Apr 2006 15:18:14 -0500 Subject: newbie OO question In-Reply-To: References: Message-ID: <-oKdnfQ5EsAScdrZRVn-ug@comcast.com> Jeremy Winters wrote: > class SegmentValue: > def > __init__(self,seg=[0,0,0,0,0,0],value=0,description=""): > self.segment=seg > self.value=value > self.description=description > > #that's my class! note the default of a 6 item list > for the seg parameter... which is then bound(?) to the > segment attribute of the instance... > > now here's the session I just did > >>>> from SegmentValue import * >>>> a=SegmentValue([1,2,3,4,5,6],22,"segment a") >>>> b=SegmentValue() >>>> c=SegmentValue() >>>> b.segment[0]=1 >>>> b.segment > [1, 0, 0, 0, 0, 0] >>>> c.segment > [1, 0, 0, 0, 0, 0] >>>> a.segment > [1, 2, 3, 4, 5, 6] > > so... what I'm seeing here is that when I explicitly > set seg during instantiation... it creates a unique > sequence that can be manipulated without affecting > other instances... but if I instantiate using the > default... it seems to refer back to the default when > maniuplating the segment attribute. > > in a continuation of the session... > >>>> d=SegmentValue() >>>> d.segment > [1, 0, 0, 0, 0, 0] > > ...you'll note that any new instances now refer to the > *modified default sequence*. > > what is going on here? how do I instantiate without > explicitly defining a new sequence each time? or is > this even possible? > > thanks in advance, > jeremy > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com It trips up almost everyone at first. You should not use a list (mutable) as a default keyword argument. >From Python Language Reference Manual by Guido van Rossum and Fred L. Drake, Jr.: 6.3.4 Calls Default values are calculated, once, when the function is defined; thus, a mutable object such as a list or dictionary used as default value will be shared by all calls that don't specify an argument value for the corresponding slot; this should usually be avoided. Change to something like: __init__(self,seg=None,value=0,description=""): self.segment=seg or [0,0,0,0,0,0] self.value=value self.description=description -Larry Bates From scott.daniels at acm.org Sat Apr 1 13:07:55 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Sat, 01 Apr 2006 10:07:55 -0800 Subject: newbie string conversion question In-Reply-To: <1143901061.088986.41120@v46g2000cwv.googlegroups.com> References: <1143901061.088986.41120@v46g2000cwv.googlegroups.com> Message-ID: <442ebed0@nntp0.pdx.net> Rohit wrote: > As part of a proprietary socket based protocol I have to convert a > string of length 10, > > say, "1234567890" > > to send it as 5 characters such that their hex values are > > 0x21 0x43 0x65 0x87 0x09 > > (Hex value of each character is got by transposing two digits at a > time) > > How can I do this in python? I would like the result to be available > as a string since I am concatenating it to another string before > sending it out. > > Thanks, > Rohit > For a horrendously obscure version, try: def mangle(digits): length = (len(digits) + 1) >> 1 v = int(digits, 16) mask = int('0F' * length, 16) smunch = (v ^ (v >> 4)) & mask swapped = v ^ (smunch | (smunch << 4)) return ''.join(chr(255 & (swapped >> (8 * n))) for n in reversed(range(length))) --Scott David Daniels scott.daniels at acm.org From sturlamolden at yahoo.no Tue Apr 25 08:27:06 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 25 Apr 2006 05:27:06 -0700 Subject: MinGW and Python In-Reply-To: References: <1145861223.509630.247350@y43g2000cwc.googlegroups.com> <444C79D7.4060007@v.loewis.de> Message-ID: <1145968025.903148.140700@i39g2000cwa.googlegroups.com> Robert Kern wrote: > - gcc does not optimize particularly well. That is beyond BS. The more recent gcc releases optimize as well as any commercial compiler. GCC 4 may even optimize better than MSVC. GCC is the compiler used to build the Linux kernel and MacOSX. If it can deal with this I say it can handle Python as well. My guess is you will not notice any performance difference for the Python interpreter. Doesn't Python run well on Linux? GCC is used to build Python on Linux. MinGW is GCC. MinGW on Windows creates the same binary code as GCC on Linux. From codeshepherd at gmail.com Wed Apr 26 09:37:19 2006 From: codeshepherd at gmail.com (Deepan Chakravarthy) Date: Wed, 26 Apr 2006 19:07:19 +0530 Subject: pyumlgraph for multiple files. In-Reply-To: References: <1146039200.264901.317920@j33g2000cwa.googlegroups.com> <1146041466.290523.15010@v46g2000cwv.googlegroups.com> Message-ID: <444F778F.3030503@gmail.com> Hello, I had used pyumlgraph to generate dot files for single python script. Is it possible to use pyumlgraph to generate dot files for multiple python scripts ??? Or is it automatically done if i generate a dot file for the final python script that imports all other files? Thanks Deepan Chakravarthy N www.codeshepherd.com From rpdooling at gmail.com Thu Apr 13 13:25:28 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 13 Apr 2006 10:25:28 -0700 Subject: Python editing with emacs/wordstar key bindings. References: <1144887253.027194.198750@i39g2000cwa.googlegroups.com> Message-ID: <1144949128.068372.129600@t31g2000cwb.googlegroups.com> >> When all I started looking for was a more robust editor for Python ;-) Both WingIDE and Komodo Dragon allow for customization of keyboard bindings. They aren't free, but they cost only $30.00 or so. Cheap for what you get, especially in the case of Komodo because it makes a nice editor for many languages--Perl, PHP, HTML etc. I tried Xemacs several times over the years on Win XP. Something usually breaks, and then--yes--you have to learn Lisp to fix it. rpd From atbusbook at aol.com Sat Apr 1 00:06:24 2006 From: atbusbook at aol.com (atbusbook at aol.com) Date: 31 Mar 2006 21:06:24 -0800 Subject: DO NOT USE JAVA BECAUSE IT IS NOT OPEN SOURCE In-Reply-To: <1143867556.814290.321740@i40g2000cwc.googlegroups.com> References: <1143867556.814290.321740@i40g2000cwc.googlegroups.com> Message-ID: <1143867984.457038.24960@g10g2000cwb.googlegroups.com> A Propriatary Languige Is An Oxymorron!!!! A propriatary OS is An Oxymoron!!!! Take Pro-DOS for example A Knock-off of MS-DOG, the worst operating system it did not use ONE IOTA OF MS CODE BUT IT was a sucsefull knockoff. same thing will happen to JAVA!!!! ______________________________________________________________________________________________________________ GEORGE ROGERS From rpdooling at gmail.com Sun Apr 9 22:53:53 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 9 Apr 2006 19:53:53 -0700 Subject: can't pass command-line arguments In-Reply-To: References: <1144636890.976327.253000@i39g2000cwa.googlegroups.com> Message-ID: <1144637633.814788.150270@i40g2000cwc.googlegroups.com> Duh! Headsmack. Thanks. But also, I discovered something else. If I name the script findmyfiles.py and run it from the command line while in the directory where it is stored (on windows), I must run it as: findmyfiles.py d:/notes notes*.* I was used to being able to run scripts by just typing the script name, even without the .py extension, but findmyfiles d:/notes notes*.* does not work Thank you, Felipe From fabiofz at gmail.com Mon Apr 24 12:58:55 2006 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Mon, 24 Apr 2006 13:58:55 -0300 Subject: Pydev and Pydev Extensions 1.0.6 release Message-ID: Hi All, Pydev and Pydev Extensions 1.0.6 have been released Check http://www.fabioz.com/pydev for details on Pydev Extensions and http://pydev.sf.net for details on Pydev Release Highlights in Pydev Extensions: ----------------------------------------------------------------- - New Feature: Show hierarchy (F4) -- Still in a beta state (currently only looks for subclasses on the same project). - Analysis happens in a Thread, so, you should now always have the latest parse without any halts (this happened only when the option was set to analyze only on save). - Class variable marked as error when self ommitted - when an undefined import is found within a try..except ImportError, it will not be reported. - Allow changing the keybinding for activating the Interactive Console (Ctrl+Enter) - Added a simple text-search that looks for in all .py and .pyw files (will be improved in the future to make a real python-like search). - The keywords that match the 'simple' keywords completion do not show up. Release Highlights in Pydev: ---------------------------------------------- - Assign variables to attributes (Ctrl+2+a): Contributed by Joel Hedlund (this is the first contribution using the new jython scripting engine). - 3 minor 'quirks' were fixed in the indentation engine - The debugger had some changes (so, if you had halts with it, please try it again). - Allow changing the keybinding for activating the Find next problem (Ctrl+.) - The debugger step-return had its behaviour changed. - Additional scripts location added to pythonpath in the jython scripting engine - Transversal of nested references improved - Fixed problems with compiled modules when they had 'nested' module structures (e.g.: wx.glcanvas) What is PyDev? --------------------------- PyDev is a plugin that enables users to use Eclipse for Python and Jython development -- making Eclipse a first class Python IDE -- It comes with many goodies such as code completion, syntax highlighting, syntax analysis, refactor, debug and many others. Cheers, -- Fabio Zadrozny ------------------------------------------------------ Software Developer ESSS - Engineering Simulation and Scientific Software http://www.esss.com.br Pydev Extensions http://www.fabioz.com/pydev Pydev - Python Development Enviroment for Eclipse http://pydev.sf.net http://pydev.blogspot.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From rocky at panix.com Sat Apr 8 12:22:33 2006 From: rocky at panix.com (R. Bernstein) Date: 08 Apr 2006 12:22:33 -0400 Subject: debug CGI with complex forms References: <1144311210.793799.181980@i40g2000cwc.googlegroups.com> Message-ID: "Sullivan WxPyQtKinter" writes: > When the form in one HTML is very complex with a lot of fields(input, > button,radio,checkbox etc.), setting the environment is quite > burdernsome, so I usually change the stdout and stderr of the submit > processing script to a file object to see the output directly from that > file. This just can do, but still inconvinient. > Anyone has more suggestions? The extended Python debugger (http://bashdb.sourceforge.net/pydb) has the ability to give POSIX-style line tracing, and to change the debugger stdout/stderr to a file you direct it. For example, pydb --trace --output=/tmp/dbg.log --error=/tmp/error.log my-cgi Rather than trace the entire CGI, if there is a specific portion that you want traced that can be done too by changing the CGI. Create a files called "/tmp/trace-on" and "/tm/trace-off". "/tmp/trace-on" might contain this: # Issue debugger commands to set debugger output to # go to a file, turn on line tracing, and continue set logging file /tmp/dbg.log # uncomment the following line if you want to wipe out old dbg.log # set logging overwrite on set logging redirect on set logging on set linetrace on continue and /tmp/trace-off: # Issue debugger commands to turn off line tracing and continue set linetrace off continue In your CGI (in the above command-line example the CGI was called "my-cgi") add: import pydb # needs to be done only once ... pydb.set_trace("/tmp/trace-on") # This and subsequent lines will be traced ... pydb.set_trace("/tmp/trace-off") Of course modify the file names in the examples above, my-cgi, /tmp/dbg.log /tmp/trace-on, /tmp/trace-off as appropriate. I notice that line tracing at present doesn't show the text of traced lines just the position (file name, line number, and possibly function/method name). I will probably change this pretty soon in CVS though. Finally, I don't know if any of this will help, but I guess if it doesn't it would be interesting to understand how it fails. (If my past experience in c.l.p holds here, if nothing else, my having posted this will at least motivate someone else to give other method(s). ;-) From jelleferinga at gmail.com Tue Apr 18 04:37:03 2006 From: jelleferinga at gmail.com (jelle) Date: 18 Apr 2006 01:37:03 -0700 Subject: Shell like syntax for subprocess.Popen # overloading >, <, | Message-ID: <1145349423.908658.53180@g10g2000cwb.googlegroups.com> Hi, I use python quite a bit to couple different programs together. Doing so has been a _lot_ easier since subprocess came around, but would really like to be able to use the succinct shell syntax; >, <, | That really shouldn't be too hard to wrap in a class, but so far I didn't succeed to do so this well, since I'm facing some trouble with operator precedence that I do not know how to overcome. Consider the following: A = 'inputString' B = Process('process.exe') C = cStringIO.StringIO() # output bucket A > B > C A is being piped to B and processed, but the output of B is not being piped to C executing A > B; B > C works as expected however. Which is disappointing, since what I'm trying to achieve is a sugar syntax for Popen processes, where directly sees the chain of commands... Any suggestions to overcome this issue are greatly appreciated! cheers, -jelle ------------------------------------------------------------------------- class Process(Popen, object): def __init__(self, commandString, wait=False): assert isinstance(commandString, str) cmd = commandString.split() self.cmd = commandString self.exe = cmd.pop(0) ## self.args = cmd self.process = Popen(self.cmd, shell=True, stdin=PIPE, stdout=PIPE, close_fds=False) self.stdout = self.process.stdout self.stderr = self.process.stderr def __repr__(self): return 'Process instance ( %s ) ' % (self.exe) def __or__(self, other): # PIPE ''' returns the output of Process A -> Process B takes a Process instance as argument ''' assert isinstance(other, Process), '%s\n is not a Process instance' % (other) print 'PIPE' self > other def __lt__(self, other): # STDIN ''' takes a StringIO, file or string objectas argument ''' print '>' print 'STDIN' if isinstance(other, str): self.process.communicate(other) else: self.stdout, self.stderr = self.process.communicate(other.read()) self.process.wait() def __gt__(self, other): # STDOUT ''' takes a StringIO, file or string object as argument returns the result of an external process ''' print '<' print 'STDOUT' assert hasattr(other, 'write') or isinstance(other, str) if isinstance(other, str): other += self.stdout else: other.write(self.stdout) ------------------------------------------------------------------------- From robin at reportlab.com Fri Apr 7 08:36:14 2006 From: robin at reportlab.com (Robin Becker) Date: Fri, 07 Apr 2006 13:36:14 +0100 Subject: OT: job offering in Milan In-Reply-To: <1144402806.087904.164860@i39g2000cwa.googlegroups.com> References: <1144402806.087904.164860@i39g2000cwa.googlegroups.com> Message-ID: <44365CBE.7010406@chamonix.reportlab.co.uk> Michele Simionato wrote: ...... > The Company > StatPro, a leader Company in the field of portfolio analytics for the > global asset management market, is looking for a Senior Systems/Network > Engineering Specialist, who is ready for a new challenge. > .... > real pity, I used to do portfolio analytics for Bita Plus and SBC; minimax risk curves were just my bag etc etc :). My math skills are now so degraded I have difficulty reading about conic programming using Nesterov's barrier functions etc etc. Oh well back to web scraping :( -- Robin Becker From cygnus at cprogrammer.org Mon Apr 17 17:31:07 2006 From: cygnus at cprogrammer.org (Jonathan Daugherty) Date: Mon, 17 Apr 2006 14:31:07 -0700 Subject: Missing interfaces in Python... In-Reply-To: References: <20060417212336.GW7561@vulcan.cprogrammer.org> Message-ID: <20060417213107.GX7561@vulcan.cprogrammer.org> # enforced by whom, at what point ? In the case of Java, I think the JVM enforces interface implementation (probably at the parser level). -- Jonathan Daugherty http://www.parsed.org From eurleif at ecritters.biz Sun Apr 9 16:28:05 2006 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Sun, 09 Apr 2006 16:28:05 -0400 Subject: How to determine if a line of python code is a continuation of the line above it In-Reply-To: <1144520644.233293.81050@u72g2000cwu.googlegroups.com> References: <1144520644.233293.81050@u72g2000cwu.googlegroups.com> Message-ID: <44396df0$0$3694$4d3efbfe@news.sover.net> Sandra-24 wrote: > I'm not sure how complex this is, I've been brainstorming a little, and > I've come up with: from tokenize import generate_tokens, NL, NEWLINE from cStringIO import StringIO def code_lines(source): """Takes Python source code (as either a string or file-like object) and yields a tuple of (is_new_logical, code) for each physical line of code. """ if isinstance(source, basestring): source = StringIO(source) buffer = [] new_logical = True for token_type, source, sloc, eloc, line in \ generate_tokens(source.readline): buffer.append(source) if token_type == NL: yield new_logical, ''.join(buffer) buffer = [] new_logical = False elif token_type == NEWLINE: yield new_logical, ''.join(buffer) buffer = [] new_logical = True if buffer: yield new_logical, ''.join(buffer) From mensanator at aol.com Wed Apr 26 20:32:59 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 26 Apr 2006 17:32:59 -0700 Subject: I have problems with creating the classic game Wumpus. the file: http://esnips.c References: <1145986162.065611.168330@j33g2000cwa.googlegroups.com> <1145990271.018812.306050@e56g2000cwe.googlegroups.com> <1146012810.912414.69650@t31g2000cwb.googlegroups.com> <1146053581.589720.306560@v46g2000cwv.googlegroups.com> Message-ID: <1146097979.236858.10010@y43g2000cwc.googlegroups.com> conny.ledin at gmail.com wrote: > i just mailed it to you. Thanks for looking at it. Returning. Comments added by me start #m. I tried to keep all your original lines commented out and added my fixes with #m on either side, but there were so many errors I had to give up. I tried to preserve the code of the first mistake and simply deleted multiple repetitions of the same mistake. Note I made a couple structural changes, move some variables and deleted others. This in addition to fixing the goofy errors you made trying to move to the next room. Movement now works correctly (I think, did not verify the map, it doesn't allow you to go back the way you came). In addition to now correctly printing the room number, I added the room contents in square brackets. You'll need to know that in order to handle the traps. You've got a lot of code still commented out, better get moving. # -*- coding: cp1252 -*- #Belzebub #Conny Ledin import random from Tkinter import * #creates a room class class room(object):#,trap): def __init__(self, trap): self.trap = trap #inserts content in rooms #m #m why do you need get_trap()? #m room_list[current_room].trap will return the trap content #m def get_trap(): return trap #creates a room list with content room_list = [] #0=Nothing, 1=fire trap, 2=acid trap, 3=teleporter, 4=belzebub trap_list = [0,0,0,0,0,0,0,0,0,1,1,2,2,3,3,3,3,3,3,4] random.shuffle(trap_list) for i in range(0,20): r = room(trap_list[i]) #crates a room object whith content (trap) room_list.append(r) #creates a list with rooms nextto_list1 = range(0,20) #shuffles the list with rooms for movement in east/west direction random.shuffle(nextto_list1) #shuffles another list with rooms for movement in north/south direction #m #m this line doesn't work, nextt0_list2==None #m nextto_list2 = random.shuffle (nextto_list1) #m nextto_list2 = range(0,20) random.shuffle(nextto_list2) #m #m placed here, current_room is a global variable current_room = 0 #m root = Tk() #creates GUI class application(Frame): def __init__(self, master): #creates frame Frame.__init__(self, master) self.grid() self.create_widgets() def create_widgets(self): Label(self,text = "Whats your next move?").grid(row = 0, column = 0, sticky = W) Label(self, text = "Choose one: ").grid(row = 1, column = 0, sticky = W) self.choice = StringVar() #creates text box self.results_txt = Text(self, width = 60, height = 10, wrap = WORD) self.results_txt.grid(row = 7, column = 0, columnspan = 4) #creates radiobutton for north Radiobutton(self, text = "Go North", variable = self.choice, value = "north", command = self.move ).grid(row = 2, column = 0, sticky = W) #creates radiobutton for east Radiobutton(self, text = "Go East", variable = self.choice, value = "east", command = self.move ).grid(row = 3, column = 0, sticky = W) #creates radiobutton for south Radiobutton(self, text = "Go South", variable = self.choice, value = "south", command = self.move ).grid(row = 4, column = 0, sticky = W) #creates radiobutton for west Radiobutton(self, text = "Go West", variable = self.choice, value = "west", command = self.move ).grid(row = 5, column = 0, sticky = W) #creates radiobutton for shooting Radiobutton(self, text = "Deploy bomb", variable = self.choice, value = "shoot", command = self.shoot ).grid(row = 6, column = 0, sticky = W) #creates a function for movement def move(self): #m tell move() that current_room is a global and not local #m to this block global current_room #m message = "" message += self.choice.get() print message if message == "north": #m I modified next_room to pass the direction, you don't need it saved #m direction = 2 #m #m next_room() returns the new room index, but you aren't saving it, #m so it's being lost #m next_room() #m #m ok, that's better, you're trying to save it, but what you #m forgot the (), so you're saving the location of the function, #m not calling it. note we can't make that mistake if we have to pass #m parameters to the function #m current_room = next_room current_room = next_room(current_room,2) #m message = "You enter the next room to the north " message += str(current_room) #m show what's in the room message += ' [' + str(room_list[current_room].trap) + ']' #m if message == "south": #m current_room = next_room(current_room,-2) #m message = "You enter the next room to the south " message += str(current_room) #m show what's in the room message += ' [' + str(room_list[current_room].trap) + ']' #m elif message == "east": #m current_room = next_room(current_room,1) #m message = "You enter the next room to the east " message += str(current_room) #m show what's in the room message += ' [' + str(room_list[current_room].trap) + ']' #m elif message == "west": #m current_room = next_room(current_room,-1) #m message = "You enter the next room to the west " message += str(current_room) #m show what's in the room message += ' [' + str(room_list[current_room].trap) + ']' #m self.results_txt.delete(0.0, END) self.results_txt.insert(0.0, message) root.title("Chasing Belzebub") #creates a function for shooting def shoot(self): message = "" message += self.choice.get() print message ## if message == "shoot": ## belzebub.die() #creates a randomized grid with rooms that the player can move trough #m #m changed to pass function current_room and desired direction #m def next_room(cr,d):#direction, current_room): #east/west #m these need to be global? #m current_room = 1 #m direction = 1 # no need for this at all #m #m if cr == 0 and d == -1: #m next_room is the name of the function, use a different name for variable #m otherwise you're returning the function address, not the result #m if current_room == 0 and direction == -1: #m next_room = nextto_list1[19] nr = nextto_list1[19] elif cr == 19 and d == 1: nr = nextto_list1[0] elif d == 1 or d == -1: nr = nextto_list1[cr + d] #north/south elif cr == 0 and d == -2: nr = nextto_list2[19] elif cr == 19 and d == 2: nr = nextto_list2[0] elif d == 2: nr = nextto_list2[cr + 1] elif d == -2: nr = nextto_list2[cr - 1] # return next_room return nr ###creates a player class ##class player(object): ## def __init__(self): ## ## #all the ways the player can die and GAME OVER displays ## def die(self, fire_trap, acid_trap, belzebub): ## if acid_trap.kill: ## print "Im sorry to say that you have melted./n" ## "Better luck next time/n" ## "GAME OVER!" ## elif fire_trap.kill: ## print "Oh my! Your hair is on fire./n" ## "GAME OVER!" ## elif belzebub.kill: ## print "Belzebub got you, have a lovely time in HELL!/n" ## "GAME OVER" ## ###creates a fire trap class ##class fire_trap(object): ## def __init__(self): ## #ser till att spelaren d?r ## def kill(self, player): ## player.die() ## ###creates a fire trap class ##class acid_trap(object): ## def __init__(self): ## #ser till att spelaren d?r ## def kill(self, player): ## player.die() ## ###creates a Belzebub class ##class belzebub(object): ## def __init__(self): ## #ser till att spelaren d?r ## def kill(self, player): ## player.die() ## ##ser till att belzebub d?r ## def die(self, player): ## if bomb #### def main(): app = application(root) root.mainloop() ## for i in nextto_list1 or nextto_list2: ## #skapa ett rum main() From ToddLMorgan at gmail.com Sun Apr 23 08:47:01 2006 From: ToddLMorgan at gmail.com (ToddLMorgan) Date: 23 Apr 2006 05:47:01 -0700 Subject: Looking for resources for making the jump from Java to Python easier and more productive In-Reply-To: References: <1145691651.385835.298600@u72g2000cwu.googlegroups.com> Message-ID: <1145796421.128834.276110@g10g2000cwb.googlegroups.com> I've actually managed to find some other links by backtracking through some of the links that you provided. The most comprehensive so far is this one http://www.razorvine.net/python/PythonForJavaProgrammers and a summary version (on the same site) http://www.razorvine.net/python/PythonComparedToJava The site owner (Irmen de Jong) appears to be be compiling a decent migration path from Java to Python on a Moin-Moin Wiki so perhaps he'll be harvesting more useful information from here and other places in the near future as the pages only appears a few days ago. There was also a follow up to http://naeblis.cx/rtomayko/2004/12/15/the-static-method-thing with http://naeblis.cx/rtomayko/2005/01/20/getters-setters-fuxors Hopefully this will prove helpful to some other folks :- ) I'm still working my way up to the practice sites (python and math challenge) ... I want to do a bit more reading first :- ) ciao & thanks Todd From rpdooling at gmail.com Fri Apr 14 18:29:58 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 14 Apr 2006 15:29:58 -0700 Subject: Fixing Python instalation in win2000 by hand In-Reply-To: References: <7YP%f.393$nK2.12@newsfe22.lga> <1145035088.113942.264660@e56g2000cwe.googlegroups.com> Message-ID: <1145053798.560072.305950@i40g2000cwc.googlegroups.com> >> I'll try from C: but..... Definitely do that. None of the .msi installers are working for me from any drive except C. Been that way for months. Here's some helpful tips from an ActiveState email of a few months back. Note especially that you need version 2.0 or greater of the installer: Here are some tips for troubleshooting MSI installer problems. You may want to try disabling any anti-virus software you have running as they frequently cause software installation failures. MSI Installers have a known issue with mapped network drives; please copy the installer to the c:\ root drive and try running the installation again. If you are using the NTFS file system, please make sure that the SYSTEM account has full rights over the target installation directory, the directory containing the installer file, AND the Windows Installer directory, located at either c:\WINNT\Installer\ (WINNT 4 / Windows 2000) or c:\Windows\Installer\ (Windows XP). This may be the result of an altered Windows Scripting Host installation. The best workaround is to reinstall this Windows component. Windows Scripting Host can be downloaded from: http://www.microsoft.com/downloads/details.aspx?FamilyID=c717d943-7e4b-4622-86eb-95a22b832caa&DisplayLang=en ( for Windows 200 / XP ) or http://www.microsoft.com/downloads/details.aspx?FamilyID=0a8a18f6-249c-4a72-bfcf-fc6af26dc390&DisplayLang=en ( for Windows 9x / Me / NT4 ) You will need to be logged in as an administrator of the target computer. You will also need to ensure that you have full permissions to install on the drive you have chosen. You must have Microsoft Windows Installer version 2.0 or greater to run the MSI package. There is a link to download the correct Windows Installer for your platform on the System Requirements page: http://activestate.com/Products/ActivePerl/system_requirements.plex The MSI file may be corrupt. You may also want to try re-downloading the installation package and trying the installation again. If you have trouble downloading the file, you may want to try getting it via FTP: ftp://ftp.activestate.com or http://downloads.activestate.com If you are still seeing errors after the re-installation attempt, it would be helpful if you could send us a log of the installation process. You can perform Microsoft Installer logging using the msiexec command: C:\> msiexec /I installer_file_name.msi /L*v install.log Send us the resultant install.log file and we will investigate further. Let me know if you have any further questions or comments. From johnjsal at NOSPAMgmail.com Sat Apr 8 19:07:28 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sat, 08 Apr 2006 19:07:28 -0400 Subject: programming puzzles? In-Reply-To: <1144532090.213069.191600@i39g2000cwa.googlegroups.com> References: <44381f2f$0$4209$c3e8da3@news.astraweb.com> <1144532090.213069.191600@i39g2000cwa.googlegroups.com> Message-ID: <4438428e$0$11362$c3e8da3@news.astraweb.com> mensanator at aol.com wrote: > Personally, I am an avid reader of rec.puzzles. Not because > I like doing stupid puzzles per se, but I look at them from the > viewpoint "how would I write a program to solve this?" > Even simple word problems sometimes involves more trouble than > the puzzle is worth, but it teaches you how to write algorithms to > generate permutations, combinations, partitions, etc. Sounds like what I'm interested in. I'll check it out! From kent at kentsjohnson.com Sat Apr 1 16:45:17 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Sat, 01 Apr 2006 16:45:17 -0500 Subject: running IDLE from another program? In-Reply-To: <442ee151$0$9423$c3e8da3@news.astraweb.com> References: <442d7a45$1_2@newspeer2.tds.net> <442dba0f$0$11191$c3e8da3@news.astraweb.com> <442e0913$1_3@newspeer2.tds.net> <442e1333$0$2459$c3e8da3@news.astraweb.com> <442e6011_3@newspeer2.tds.net> <442ee151$0$9423$c3e8da3@news.astraweb.com> Message-ID: <442eef26_1@newspeer2.tds.net> John Salerno wrote: > Kent Johnson wrote: >>One thing that is really useful about running in an editor window is >>that (in TextPad, anyway) I can double-click on an error message and go >>directly to the line with the error. > > > Interesting. The way I have it now, it shows errors the way I want to, > but it shows them just in a text file, nothing special, and I don't seem > to be able to double-click them. Is this just a feature of TextPad, or > did you have to set it up so you can double-click the errors? mmm, both. TextPad lets me set a regular expression to interpret errors as file/line. When that is set correctly the double-clicking works. > >>Try >>C:\Python24\Lib\idlelib\idle -r C:\path\to\myprog.py > > > I tried this but it said it couldn't find idle.pyw (even though it is > there). The working directory must be wrong. Try calling Python directly with full paths: C:\Python24\pythonw C:\Python24\Lib\idlelib\idle.pyw -r C:\path\to\myprog.py Kent From pmartin at snakecard.com Sat Apr 22 16:55:07 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Sat, 22 Apr 2006 15:55:07 -0500 Subject: Can my python script return a value to the c program executing it? References: <1145646392.037236.105750@u72g2000cwu.googlegroups.com> Message-ID: Like this ? http://aspn.activestate.com/ASPN/Mail/Message/python-list/1304518 Philippe vduber6er wrote: > I have a C program that calls my python script by > > exec_pycode(code); > > code = "import CheckFasta\nCheckFasta.CheckFasta (\"sampledata.txt\", > %d)\n", PyNum); > > CheckFasta.py is my python script with a def CheckFasta in it that > returns a string. > > Is there a way for my C code to get the return value from CheckFasta? > > Example: > If CheckFasta returns "hello world" > > can I somehow do something like > > returnstring = exec_pycode(code); > > where returnstring will contain "hello world" after the line above? > > Thanks From jnair at ensim.com Wed Apr 26 02:11:48 2006 From: jnair at ensim.com (jnair at ensim.com) Date: 25 Apr 2006 23:11:48 -0700 Subject: how to browse using urllib2 and cookeilib the correct way In-Reply-To: References: <1146024468.154244.162510@t31g2000cwb.googlegroups.com> Message-ID: <1146031908.590996.306240@y43g2000cwc.googlegroups.com> ok , got it . Thanks From fabianosidler at gmail.com Sun Apr 30 08:02:17 2006 From: fabianosidler at gmail.com (Fabiano Sidler) Date: Sun, 30 Apr 2006 14:02:17 +0200 Subject: unable to resize mmap object Message-ID: <200604301402.17738.fabianosidler@gmail.com> Hi folks! I created an mmap object like so: --- snip --- from mmap import mmap,MAP_ANONYMOUS,MAP_PRIVATE fl = file('/dev/zero','rw') mm = mmap(fl.fileno(), 1, MAP_PRIVATE|MAP_ANONYMOUS) --- snap --- Now, when I try to resize mm to 10 byte --- snip --- mm.resize(10) --- snap --- I get an EnvironmentError:[Errno 22] Invalid argument. How can I implement a resizeable anonymous memory mapping? Thanks for your reply! F. Sidler From Serge.Orlov at gmail.com Sun Apr 30 15:06:33 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 30 Apr 2006 12:06:33 -0700 Subject: unable to resize mmap object In-Reply-To: References: Message-ID: <1146423993.105177.182420@v46g2000cwv.googlegroups.com> Fabiano Sidler wrote: > Hi folks! > > I created an mmap object like so: > --- snip --- > from mmap import mmap,MAP_ANONYMOUS,MAP_PRIVATE > fl = file('/dev/zero','rw') > mm = mmap(fl.fileno(), 1, MAP_PRIVATE|MAP_ANONYMOUS) > --- snap --- > > Now, when I try to resize mm to 10 byte > --- snip --- > mm.resize(10) > --- snap --- > I get an EnvironmentError:[Errno 22] Invalid argument. Just a guess: try a new size argument that is multiple of page size. From robert.h.boyd at gmail.com Mon Apr 10 17:00:13 2006 From: robert.h.boyd at gmail.com (Robert Boyd) Date: Mon, 10 Apr 2006 17:00:13 -0400 Subject: Calling Web Services from Python In-Reply-To: References: Message-ID: On 4/7/06, Ivan Zuzak wrote: [snip] > I need a package/tool that generates web service proxies that will do > all the low-level HTTP work. (Someting like the WSDL.EXE tool in .NET > Framework) The ZSI and SOAPy packages [1] that i found (should) have > those functionalities but either have a bug (SOAPy) or either do not > work for arbitrary web services (ZSI). I tried the ZSI wsdl2py script on > a wsdl of one of my services, and the script crashes. I suppose the wsdl > was "too hard" for the script to parse. I've successfully used wsdl2py for very complex WSDLs and gotten better results than with .Net's equivalent! Could you post the error you got? I don't know of other Python SOAP modules with WSDL support, sorry. Rob From brown at esteem.com Thu Apr 27 11:47:35 2006 From: brown at esteem.com (Tom Brown) Date: Thu, 27 Apr 2006 08:47:35 -0700 Subject: how do I make a class global? Message-ID: <200604270847.35428.brown@esteem.com> Hi, I thought it would be nifty to create a class that created other classes for me. The method below shows what I would like to do. The problem is that the class the method creates is local to the method. Is it possible to make the class visible in the global scope so I can import the module see the dynamically created classes? Or do I need to generate a source file and do a 'from tmp import *'? def new(self, eventType, param): self.value += 1 exec 'global %s; %s = %d' % (eventType, eventType, self.value) sl = [] sl.append('class %sEvent(QEvent):' % eventType) sl.append(' def __init__(self, %s):' % param) sl.append(' QEvent.__init__(self, %s)' % evenType) sl.append(' self.%s = %s' % (param, param)) source = '\n'.join(sl) co = compile(source, 'tmp.py', 'exec') exec co Then, to create another event, I would just have to add another line like this: e.new('ETestEvent', 'test') Thanks, Tom From lukasz.ciesnik at gmail.com Thu Apr 20 16:13:25 2006 From: lukasz.ciesnik at gmail.com (lukasz.ciesnik at gmail.com) Date: 20 Apr 2006 13:13:25 -0700 Subject: newbie OO question In-Reply-To: References: Message-ID: <1145564005.568848.256610@e56g2000cwe.googlegroups.com> Jeremy Winters napisal(a): > class SegmentValue: > def > __init__(self,seg=[0,0,0,0,0,0],value=0,description=""): > self.segment=seg > self.value=value > self.description=description > > #that's my class! note the default of a 6 item list > for the seg parameter... which is then bound(?) to the > segment attribute of the instance... > > now here's the session I just did > > >>> from SegmentValue import * > >>> a=SegmentValue([1,2,3,4,5,6],22,"segment a") > >>> b=SegmentValue() > >>> c=SegmentValue() > >>> b.segment[0]=1 > >>> b.segment > [1, 0, 0, 0, 0, 0] > >>> c.segment > [1, 0, 0, 0, 0, 0] > >>> a.segment > [1, 2, 3, 4, 5, 6] > > so... what I'm seeing here is that when I explicitly > set seg during instantiation... it creates a unique > sequence that can be manipulated without affecting > other instances... but if I instantiate using the > default... it seems to refer back to the default when > maniuplating the segment attribute. > > in a continuation of the session... > > >>> d=SegmentValue() > >>> d.segment > [1, 0, 0, 0, 0, 0] > > ...you'll note that any new instances now refer to the > *modified default sequence*. > > what is going on here? how do I instantiate without > explicitly defining a new sequence each time? or is > this even possible? > > thanks in advance, > jeremy > Read the doc: http://docs.python.org/tut/node6.html#SECTION006710000000000000000 Important warning: The default value is evaluated only once. From Kyler at news.Lairds.org Wed Apr 19 09:17:06 2006 From: Kyler at news.Lairds.org (Kyler Laird) Date: Wed, 19 Apr 2006 13:17:06 GMT Subject: mod_python web-dav management system References: Message-ID: Damjan writes: >Now I've been thinking that it might be pretty easy to implement a >authorization layer with mod_python (but living handling of the web-dav >protocol to apache)... So, has anyone already done something similar? Yup. I'm in the process. I'm using mod_python to do LDAP authentication of WebDAV requests. Now I just need to get a FUSE filesystem working and I should be able to cobble together a "simple" DAV server... It would be *so* much cleaner to have a total Python-based solution (that could run as root) so I periodically check on progress in this area. I have high hopes for Twisted's DAV server but I'm told it's not ready for use yet. In another thread I just learned about PanDAV http://ivoras.sharanet.org/projects/pandav.html but I haven't installed it yet. --kyler From jos at xos.nl Mon Apr 17 06:43:58 2006 From: jos at xos.nl (Jos Vos) Date: Mon, 17 Apr 2006 12:43:58 +0200 Subject: XML-RPC server via xinetd In-Reply-To: <44436FA2.1090709@sweetapp.com>; from brian@sweetapp.com on Mon, Apr 17, 2006 at 12:36:18PM +0200 References: <20060417122001.B22258@xos037.xos.nl> <44436FA2.1090709@sweetapp.com> Message-ID: <20060417124358.A22340@xos037.xos.nl> On Mon, Apr 17, 2006 at 12:36:18PM +0200, Brian Quinlan wrote: > I don't know exactly what your usage pattern is, but you might be able > to use SimpleXMLRPCDispatcher directly e.g. > > >>> s = SimpleXMLRPCDispatcher() > >>> s.register_function(pow) > >>> s._marshaled_dispatch(' ' -- X/OS Experts in Open Systems BV | Phone: +31 20 6938364 -- Amsterdam, The Netherlands | Fax: +31 20 6948204 From steve at rueb.com Fri Apr 14 22:32:56 2006 From: steve at rueb.com (Steve Bergman) Date: 14 Apr 2006 19:32:56 -0700 Subject: Help for a complete newbie References: <7xY%f.1245$kz3.903@twister.nyroc.rr.com> Message-ID: <1145068376.847188.78110@t31g2000cwb.googlegroups.com> The indentation is wrong. Python cares about indentation. print " " print "This \"autotp\" program will create raw bitmap test pattern images." print " " print "Please read the information below thoroughly:" print " " print "1. Graphic files MUST be TIFF images." print "2. Images MUST have been ripped though a Nuvera system as a Print and Save job" print "3. Images should already be named with the desired file name." print "4. The Lead Edge and file name should be identified in the image." print "5. The name includes the purpose for, resolution of, side, and paper size" print "6. Images should be rotated to print correctly from Service Diagnostics." print " " print "EXAMPLE: Bypass_BFM_Damage_1200x1200_Letter.tif" print " " # Get the decision if operator is ready ready = raw_input("Ready to proceed ? TYPE (y)es or (n)o: ") if ready == "y": print "You are Ready" else: print "Try again" From phpbird at gmail.com Wed Apr 12 22:56:05 2006 From: phpbird at gmail.com (Ju Hui) Date: 12 Apr 2006 19:56:05 -0700 Subject: I wanna use urllib2 to get a page with a socks 5 proxy, who can give me a sample code ? In-Reply-To: References: <1144593748.272792.133830@e56g2000cwe.googlegroups.com> Message-ID: <1144896965.213255.314660@u72g2000cwu.googlegroups.com> thanks a lot! From pramod at tumkur.com Wed Apr 26 11:02:11 2006 From: pramod at tumkur.com (Pramod TK) Date: Wed, 26 Apr 2006 20:32:11 +0530 Subject: Query regarding support for IPv6 in python Message-ID: Hello All, I have some queries related to python support for IPv6. Can you kindly clarify the doubts which I have - 1. Does python support IPv6? [128 bit IP addresses?] 2. Does it support setting of QoS flags? 3. Does it support tunneling of IPv6 on a IPv4 network? 4. If an IPv4 address is given, does it support this on a IPv6 network? If not can you kindly let me know, Are there any plans for supporting these features in future? For Example - In IPv4 we have gethostbyname() function, which is deprecated in IPv6. In IPv6, getaddrinfo() and new data structure like struct addrinfo is introduced. Is this new function getaddrinfo() of IPv6 is supported in Win32 Extensions for python. Thanks in Advance, Pramod TK From deets at nospam.web.de Thu Apr 6 09:31:43 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 06 Apr 2006 15:31:43 +0200 Subject: GUI issues in Python References: <1144328552.221998.230480@g10g2000cwb.googlegroups.com> Message-ID: <49kjiaFopo00U1@uni-berlin.de> diffuser78 at gmail.com wrote: > Hi, > > I want to create a GUI where a user can select drag and drop kind of > boxes, circles and make connections between them. > > This is basically for depicting states and dependencies. I am writing a > program where I let the user input states and dependencies in a certain > domain. Based on input given by user in the GUI, I grab it and run my > algorithm to generate the output. > > I am wondering if there is any library like that in Python, or if > anybody of you has done something similar in past, could you post some > pointers. tkinter. Amongst a bazillion others - but this is included, and the canvas-widget actually very useful for your purpose. Regards, From jbellis at gmail.com Mon Apr 3 16:21:23 2006 From: jbellis at gmail.com (Jonathan Ellis) Date: 3 Apr 2006 13:21:23 -0700 Subject: MOO meets Python References: Message-ID: <1144095683.430864.44450@v46g2000cwv.googlegroups.com> Aahz wrote: > http://playsh.org/ > http://sourceforge.net/projects/playsh Damn, I thought you meant MOO as in Master of Orion. -Jonathan From tjreedy at udel.edu Sun Apr 30 21:34:46 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 30 Apr 2006 21:34:46 -0400 Subject: ending a string with a backslash References: <445546c8$0$13341$c3e8da3@news.astraweb.com> Message-ID: "John Salerno" wrote in message news:445546c8$0$13341$c3e8da3 at news.astraweb.com... >I have this: > > subdomain = raw_input('Enter subdomain name: ') > > path = r'C:\Documents and Settings\John Salerno\My Documents\My > Webs\1and1\johnjsalerno.com\' + subdomain For any direct use of paths within Python (to open a file, change directory, etc), forward slashes work fine, avoiding backslash problems. tjr From ian at excess.org Sun Apr 9 17:57:18 2006 From: ian at excess.org (Ian Ward) Date: Sun, 09 Apr 2006 17:57:18 -0400 Subject: ANN: Speedometer 2.4 - bandwidth and download monitor Message-ID: <4439833E.2000908@excess.org> Announcing Speedometer 2.4 -------------------------- Speedometer home page: http://excess.org/speedometer/ Download: http://excess.org/speedometer/speedometer.py New in this release: ==================== - New -z option treats files that don't exist as zero length so speedometer will not wait for them to be created at startup. - Multiple file taps may now be used stacked vertically in the same column. About Speedometer ================= Speedometer is a console bandwidth and file download progress monitor with a logarithmic bandwidth display and a simple command-line interface. Speedometer requires Python 2.1 or later and Urwid 0.8.9 or later for full-console bar graph display. Urwid may be downloaded from: http://excess.org/urwid/ Speedometer is released under the GNU LGPL. From fredrik at pythonware.com Tue Apr 11 14:25:25 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 11 Apr 2006 20:25:25 +0200 Subject: list.clear() missing?!? References: <1144767680.583085.310160@v46g2000cwv.googlegroups.com> Message-ID: John Salerno wrote: > Steven Bethard wrote: > > > > lst[:] = [] > > lst = [] > > What's the difference here? L[:]= modifies the object in place, L=[] binds the variable to a new object. compare and contrast: >>> L = ["a", "b", "c"] >>> M = L >>> L ['a', 'b', 'c'] >>> M ['a', 'b', 'c'] >>> L is M True >>> L[:] = [] >>> L [] >>> M [] >>> L is M True >>> L = ["a", "b", "c"] >>> M = L >>> L ['a', 'b', 'c'] >>> M ['a', 'b', 'c'] >>> L = [] >>> L [] >>> M ['a', 'b', 'c'] >>> L is M False From aleaxit at yahoo.com Mon Apr 24 11:01:54 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 24 Apr 2006 08:01:54 -0700 Subject: MS VC++ Toolkit 2003, where? References: <1he8pss.1yk7ug81rv7pw2N%aleaxit@yahoo.com> <1145811839.042394.73260@t31g2000cwb.googlegroups.com> <1he8sbx.dqqp3q10n5thaN%aleaxit@yahoo.com> <1145849491.347970.112150@e56g2000cwe.googlegroups.com> <1he9m4m.9d8okx1x7mxeaN%aleaxit@yahoo.com> Message-ID: <1heag2b.1ry4glp14vg8xeN%aleaxit@yahoo.com> JW wrote: ... > > As suggested to me by David Rushby 10 hours ago, > > > > ... < huge URL snipped > ... > > Alas, somehow this URL was split in two, and all the kings horses and all > the kings men can't seem to put it back together again (at least in my > browser). Could someone post a tinyurl? http://tinyurl.com/gv8wr Alex From ldo at geek-central.gen.new_zealand Mon Apr 10 23:04:16 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 11 Apr 2006 15:04:16 +1200 Subject: Decorators, Identity functions and execution... References: <1144597938.664642.133100@v46g2000cwv.googlegroups.com> Message-ID: In article <1144597938.664642.133100 at v46g2000cwv.googlegroups.com>, "Carl Banks" wrote: >Always use spaces when posting, and use them in your code as well. >Spaces are the current recommended practice, and in the future tabs >might become illegal. I'd prefer tabs myself, but it's more important >to respect community standards than to stick to some silly preference >you have. Tab stops every 4 columns. What's silly about that? Any other definition is silly, or at best antiquated. From jparlar at cogeco.ca Sat Apr 8 19:57:07 2006 From: jparlar at cogeco.ca (Jay Parlar) Date: Sat, 8 Apr 2006 16:57:07 -0700 Subject: Python-list Digest, Vol 31, Issue 119 In-Reply-To: References: Message-ID: <0c715ef42d61b653a79307a35d4ac7fa@cogeco.ca> On Apr 8, 2006, at 1:40 PM, tomer.ha at gmail.com wrote: > > Hi there, > > I'm new to Python, but know other scripting and programming languages. > I > want to develop a script which will receive emails with attachments > from my POP3 account, perform certain actions on it and email it back > to someone else. > > However, I'm not familiar with any Python library which does it. Could > you a guide me to a relevant library which can handle emails? > > I haven't decided yet what scripting language I will use, so a nice > module for Python will probably make me choose it over Perl. :) > > Thanks in advance. :) Well, there's always the 'email' module, part of the standard library: http://docs.python.org/lib/module-email.html Jay P. From gh at ghaering.de Fri Apr 28 04:19:50 2006 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Fri, 28 Apr 2006 10:19:50 +0200 Subject: MS VC++ Toolkit 2003, where? In-Reply-To: References: <1he8pss.1yk7ug81rv7pw2N%aleaxit@yahoo.com> <1145811839.042394.73260@t31g2000cwb.googlegroups.com> <1he8sbx.dqqp3q10n5thaN%aleaxit@yahoo.com> <1145849491.347970.112150@e56g2000cwe.googlegroups.com> <1he9m4m.9d8okx1x7mxeaN%aleaxit@yahoo.com> <444C784F.3000502@v.loewis.de> <1heag4u.19dksfxrbe14wN%aleaxit@yahoo.com> <444D61F9.4040003@v.loewis.de> <1146163631.327928.79560@v46g2000cwv.googlegroups.com> Message-ID: <4451D026.2080008@ghaering.de> Brian Elmegaard wrote: > "sturlamolden" writes: > >> I believe MinGW can link .lib C libraries files from Visual Studio. But >> there are no .a for Python24.dll as far as I can tell. > > But afaik you don't need one. Actually, a libpython24.a file was added in Python 2.4.1. The original 2.4.0 release didn't include one. AFAIR recent MINGW releases don't need this file any longer: http://mail.python.org/pipermail/python-dev/2005-October/057693.html -- Gerhard From a.schmolck at gmail.com Sun Apr 23 10:10:30 2006 From: a.schmolck at gmail.com (Alexander Schmolck) Date: 23 Apr 2006 15:10:30 +0100 Subject: Calling Python from Matlab References: Message-ID: "Daniel Nogradi" writes: > > I am desperately looking for a way to call Python from Matlab. I have become > > used to Python's rich syntax and large number of libraries, and feel > > ridiculously clumsy being stuck with Matlab's rather restricted facilities > > for doing other things than standard mathematical work. > > > > Does anyone know of good techniques (or readily available software) for > > achieving a cross-language support between Python and Matlab? > > > > Carl > > Perhaps you will find this useful: > > http://claymore.engineer.gvsu.edu/~steriana/Python/pymat.html I'd recommend looking at instead (but then I'm the author). It's based on pymat but contains several critical bugfixes and a high-level interface from python to matlab (e.g. you can just do mlab.plot([1,2,3]) or x = mlab.sin(3)). I'll need to update a couple of things, but on the whole it appears quite stable -- people have succefully used it under windows, linux and os x. 'as From jdhunter at ace.bsd.uchicago.edu Mon Apr 17 09:54:56 2006 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Mon, 17 Apr 2006 08:54:56 -0500 Subject: Using Python To Create An Encrypted Container References: Message-ID: <87d5fgtihb.fsf@peds-pc311.bsd.uchicago.edu> >>>>> "Michael" == Michael Sperlle writes: Michael> Is it possible? Bestcrypt can supposedly be set up on Michael> linux, but it seems to need changes to the kernel before Michael> it can be installed, and I have no intention of going Michael> through whatever hell that would cause. Michael> If I could create a large file that could be encrypted, Michael> and maybe add files to it by appending them and putting Michael> in some kind of delimiter between files, maybe a homemade Michael> version of truecrypt could be constructed. One problem in using a large file which is encrypted is that a single byte error can destroy all your data (see DEDICATION below). I wrote a little python module called hashtar that works like tar, but encrypts every file independently in a flattened dir structure with filename hiding. It stores the file permissions, dir structure, and ownership in an encrypted header of each encrypted file after first padding some random data at the top to reduce the risk of known plaintext attacks. Here is some example usage > hashtar.py -cvf numeric.htar numeric Password: Confirm: numeric/__init__.py -> numeric.htar/1a/1a9f48d439144d1fa33b186fa49a6b63 numeric/contiguous_demo.py -> numeric.htar/8a/8a7757bf6f4a20e6904173f7c597eb45 numeric/diff_dmo.py -> numeric.htar/0c/0cea827761aef0ccfc55a869dd2aeb38 numeric/fileio.py -> numeric.htar/3e/3e50f59a1d2d87307c585212fb84be6a numeric/find -> numeric.htar/b1/b1070de08f4ea531f10abdc58cfe8edc ...snip > find numeric.htar|head numeric.htar numeric.htar/1a numeric.htar/1a/1a9f48d439144d1fa33b186fa49a6b63 numeric.htar/8a numeric.htar/8a/8a7757bf6f4a20e6904173f7c597eb45 numeric.htar/8a/8a4343ba60feda855fbaf8132e9b5a6b numeric.htar/8a/8a72457096828c8d509ece6520e49d0b numeric.htar/0c numeric.htar/0c/0cea827761aef0ccfc55a869dd2aeb38 numeric.htar/3e > hashtar.py -tvf numeric.htar Password: 131 numeric/__init__.py 594 numeric/contiguous_demo.py 26944 numeric/Quant.pyc 209 numeric/extensions/test/rpm_build.sh 230 numeric/diff_dmo.py 439 numeric/fileio.py It works across platforms (win32, OSX and linux tested), so files encrypted on one will decrypt on others. All the code lives in a single file (hashtar.py) included below. See also the WARNING below (hint -- I am not a cryptographer) #!/usr/bin/env python """ OVERVIEW hashtar: an encrypted archive utility designed for secure archiving to media vulnerable to corruption. Recursively encrypt the files and directories passed as arguments. Rather than preserving the directory structure, or archiving to a single file as in tar, the files are encrypted to a single dir and named with the hash of their relative path. The file information (filename, permission mode, uid, gid) is encrypted and stored in the header of the file itself, and can be used to restore the original file with dir structure from the archive file. For example, the command > hashtar.py -cvf tmp.htar finance/ prompts for a password and generates an encrypted recursive archive of the finance dir in the tmp.htar dir, with filenames mapped like finance/irs/98/f1040.pdf -> tmp.htar/e5/e5ed546c0bc0191d80d791bc2f73c890 finance/sale_house/notes -> tmp.htar/58/580e89bad7563ae76c295f75aecea030 finance/online/accounts.gz.mcr -> tmp.htar/bb/bbf12f06dc3fcee04067d40b9781f4a8 finance/phone/prepaid1242.doc -> tmp.htar/c1/c1fe52a9d8cbef55eff8840d379d972a The encrypted files are placed in subdirs based on the first two characters in their hash name because if too many files are placed in one dir, it may not be possible to pass all of them as command line arguments to the restore command. The entire finance dir structure can later be restored with > hashtar.py -xvf tmp.htar The advantage of this method of encrypted archiving, as opposed to archiving to a single tar file and encrypting it, is that this method is not sensitive to single byte corruption, which becomes important especially on externally stored archives, such as on CDR, or DVDR. Any individual file contains all the information needed to restore itself, with directory structure, permission bits, etc. So only the specific files that are corrupted on the media will be lost. The alternative strategy, encrypting all the files in place and then archiving to external media, doesn't suffer from single byte corruption but affords less privacy since the filenames, dir structure, and permission bits are available, and less security since a filename may indicate contents and thus expose the archive to a known plaintext attack. A match string allows you to only extract files matching a given pattern. Eg, to only extract pdf and xls files, do > hashtar.py -m pdf,xls -xvf tmp.htar Because the filenames are stored in the header, only a small portion of the file needs to be decrypted to determine the match, so this is quite fast. Data can be encrypted and decrypted across platforms (tested between linux and win32 and vice-versa) but of course some information may be lost, such as uid, gid for platforms that don't support it. USAGE: > hashtar.py [OPTIONS] files OPTIONS -h, --help Show help message and exit -fDIR, --arcdir=DIR Write hashed filenames to archive dir -pFILE, --passwdfile=FILE Get passwd from FILE, otherwise prompt -mPATTERN, --match=PATTERN Only extract files that match PATTERN. PATTERN is a comma separated list of strings, one of which must match the filename -u, --unlink Delete files after archiving them -c, --create Create archive dir -t, --tell Report information about files -x, --extract Extract files recursively from archive dir -v, --verbose Verbose listing of filenames to stdout WARNING: I think this software is suitable to protect your data from your sister, your boss, and even the nosy computer hacker next door, but not the NSA. REQUIREMENTS: python2.3 - python.org yawPyCrypto and Flatten - http://yawpycrypto.sourceforge.net/ pycrypto - http://www.amk.ca/python/code/crypto.html The python dependencies are very easy to install; just do the usual > python setup.py install PLATFORMS: Tested on linux and win32 AUTHOR: John D. Hunter LICENSE: same as python2.3 KNOWN BUGS: Ignores symbolic links DEDICATION: For Erik Curiel, who's life's work I lost when I volunteered to backup the only copy of his home dir on a CD containing a single encrypted gzipped tar file, which was subsequently corrupted. """ import sys, os, random, struct, csv, time, glob from md5 import md5 from optparse import OptionParser from cStringIO import StringIO from getpass import getpass #def getpass(arg): pass from yawPyCrypto.Cipher import DecryptCipher, EncryptCipher from yawPyCrypto.Cipher import ZipDecryptCipher, ZipEncryptCipher from yawPyCrypto.Constants import CIPHER_BLOWFISH, MODE_CBC version = 0.3 pathsep = os.path.join('.','')[1:] # is there a better way to get this? def encrypt_str(passwd, s, enc=None): """ Encrypt the string s using passwd and encryption cipher enc """ if enc is None: enc = ZipEncryptCipher(passwd, CIPHER_BLOWFISH, MODE_CBC) enc.feed(s) enc.finish() return enc.data def decrypt_str(passwd, s, dec=None): """ Decrypt the string s using passwd and encryption cipher enc """ if dec is None: dec = ZipDecryptCipher(passwd) dec.feed(s) dec.finish() return dec.data def ends_with_pathsep(fname): """ Return true if string fname ends in a path separator string """ head, tail = os.path.split(fname) return tail == '' junk = list('abcdefghijklmnopqrstuvwyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_- /\\.\n'*20) numJunk = 200 def info_to_str(info): """ info is a fname, mode, uid, gid tuple Return a string for storage in the encrypted archive outfile """ global junk # Here is the real info string sh = StringIO() writer = csv.writer(sh) writer.writerow(info) s = sh.getvalue() # because the info string will be fed thru zlib before encryption, # I'm prepending numJunk garbage characters at the beginning of # the key string to make it difficult for someone trying to do a # known plaintext attack on the key file given that the info # contains plain text that might be guessed and plain text that is # common between archive file (such as base path names). random.shuffle(junk) junkStr = ''.join(junk[:numJunk]) return junkStr + s def str_to_info(s): """ Takes string and returns (fname, mode, uid, gid) """ sh = StringIO(s[numJunk:]) reader = csv.reader(sh) for row in reader: fname,mode,uid,gid = row return fname, int(mode), int(uid), int(gid) def encode(infile, arcdir, passwd, unlink=0, verbose=0, endian='little'): """ Encrypt the file infile and hash it's filename to arcdir - infile: the input filename - arcdir is the dir that the files where the hashed filenames will be placed - passwd is the encryption passwd as string - unlink, if true, will try to remove the src file after archiving it """ if not os.path.exists(infile): print >> sys.stderr, '%s does not exist: skipping' % infile return if os.path.isdir(infile): # mark dirs with pathsep at the end if they don't have one head, tail = os.path.split(infile) if not ends_with_pathsep(infile): infile = os.path.join(infile, '') m = md5(infile) hd = m.hexdigest() tup = os.stat(infile) if pathsep=='/': storeName = infile else: storeName = '/'.join(infile.split(pathsep)) s = info_to_str( (storeName, tup.st_mode, tup.st_uid, tup.st_gid) ) s = encrypt_str(passwd, s) outdir = os.path.join(arcdir, hd[:2]) if not os.path.isdir(outdir): os.mkdir(outdir, 0700) outfile = os.path.join(outdir, hd) oh = file(outfile, 'wb') if endian=='little': fmt = '<' else: fmt = '>' oh.write(struct.pack(fmt+'fI', version, len(s))) oh.write(s) if verbose: print '%s -> %s' % (infile, outfile) if os.path.isdir(infile): return 1 # nothing more to do for dirs ih = file(infile, 'rb') enc = EncryptCipher(passwd, CIPHER_BLOWFISH, MODE_CBC) while 1: data = ih.read(1024) if len(data)==0: break enc.feed(data) oh.write(enc.data) enc.finish() oh.write(enc.data) ih.close() oh.close() if unlink: try: os.remove(infile) except OSError, msg: print >> sys.stderr, 'Could not remove', fname print >> sys.stderr, msg return 1 def decode(infile, passwd, unlink=0, verbose=0, match=None, endian='little'): """ Restore the original file system from the archive dir - keys is a list of file information tuples; see str_to_keys. - arcdir is the dir that the files with hashed filenames live - passwd is the decryption passwd as string - unlink, if true, will try to remove the archice file after restoring it """ ih = file(infile, 'rb') if endian=='little': fmt = '<' else: fmt = '>' thisVersion, lenHeader = struct.unpack(fmt+'fI', ih.read(8)) if lenHeader>2000: print '%s header size %d too large; aborting (try flipping endian)'%(infile, lenHeader) sys.exit() try: header = decrypt_str(passwd, ih.read(lenHeader)) except MemoryError, msg: print >>sys.stderr, 'Could not decode %s; skipping' % infile return 0 except ValueError, msg: print >>sys.stderr, 'Could not decode %s; bad passwd or file?' % infile print >>sys.stderr, '\t', msg return 0 fname, mode, uid, gid = str_to_info(header) if match is not None: for pattern in match.split(','): if fname.find(pattern)!=-1: break else: return 0 if verbose: print '%s -> %s' % (infile,fname) if ends_with_pathsep(fname): # it's a dir if not os.path.isdir(fname): os.makedirs(fname) os.chmod(fname, mode) try: os.chown(fname, uid, gid) except AttributeError, msg: pass except OSError, msg: pass # if coming from win32, uid,gid=0 return 1 # nothing more to do thedir, thename = os.path.split(fname) if not os.path.isdir(thedir) and len(thedir): os.makedirs(thedir) dec = DecryptCipher(passwd) oh = file(fname, 'wb') while 1: data = ih.read(1024) if len(data)==0: break dec.feed(data) oh.write(dec.data) dec.finish() oh.write(dec.data) ih.close() oh.close() os.chmod(fname, mode) try: os.chown(fname, uid, gid) except AttributeError: pass except OSError, msg: pass # if coming from win32, uid,gid=0 if unlink: try: os.remove(infile) except OSError, msg: print >> sys.stderr, 'Could not remove', infile def tell(infile, passwd, verbose=0, endian='little'): """ Report the information about infile """ if endian=='little': fmt = '<' else: fmt = '>' ih = file(infile, 'rb') thisVersion, lenHeader = struct.unpack(fmt+'fI', ih.read(8)) if lenHeader>2000: print '%s header size %d too large; aborting (try flipping endian)'%(infile, lenHeader) sys.exit() try: header = decrypt_str(passwd, ih.read(lenHeader)) except MemoryError, msg: print >>sys.stderr, 'Could not decode %s; skipping' % infile return 0 except ValueError, msg: print >>sys.stderr, 'Could not decode %s; bad passwd or file?' % infile print >>sys.stderr, '\t', msg return 0 size = os.path.getsize(infile)-lenHeader fname, mode, uid, gid = str_to_info(header) print '%d\t%s'%(size, fname) def getpass2(): """ Prompt for a passwd twice, returning the string only when they match """ p1 = getpass('Password: ') p2 = getpass('Confirm: ') if p1!=p2: print >> sys.stderr, '\nPasswords do not match. Try again.\n' return getpass2() else: return p1 def listFiles(root, patterns='*', recurse=1, return_folders=0): # from Parmar and Martelli in the Python Cookbook import os.path, fnmatch # Expand patterns from semicolon-separated string to list pattern_list = patterns.split(';') # Collect input and output arguments into one bunch class Bunch: def __init__(self, **kwds): self.__dict__.update(kwds) arg = Bunch(recurse=recurse, pattern_list=pattern_list, return_folders=return_folders, results=[]) def visit(arg, dirname, files): # Append to arg.results all relevant files (and perhaps folders) for name in files: fullname = os.path.normpath(os.path.join(dirname, name)) if arg.return_folders or os.path.isfile(fullname): for pattern in arg.pattern_list: if fnmatch.fnmatch(name, pattern): arg.results.append(fullname) break # Block recursion if recursion was disallowed if not arg.recurse: files[:]=[] os.path.walk(root, visit, arg) return arg.results def get_recursive_filelist(args): """ Recurs all the files and dirs in args ignoring symbolic links and return the files as a list of strings """ files = [] for arg in args: if os.path.isfile(arg): files.append(arg) continue if os.path.isdir(arg): newfiles = listFiles(arg, recurse=1, return_folders=1) files.extend(newfiles) return [f for f in files if not os.path.islink(f)] if __name__=='__main__': parser = OptionParser() parser.add_option("-f", "--arcdir", dest="arcdir", help="Write hashed filenames to archive dir", metavar="DIR", default=os.getcwd()) parser.add_option("-e", "--endian", dest="endian", help="big|little", default="little") parser.add_option("-p", "--passwdfile", dest="passwdfile", help="Get passwd from FILE, otherwise prompt", metavar="FILE", default=None) parser.add_option("-m", "--match", dest="match", help="Only extract files that match PATTERN. PATTERN is a comma separated list of strings, one of which must match the filename", metavar="PATTERN", default=None) parser.add_option("-u", "--unlink", action="store_true", dest="unlink", default=False, help="Delete files after archiving them") parser.add_option("-c", "--create", action="store_true", dest="create", default=False, help="Create archive dir") parser.add_option("-x", "--extract", action="store_true", dest="extract", default=False, help="Extract files recursively from archive dir") parser.add_option("-t", "--tell", action="store_true", dest="tell", default=False, help="Report information about file but do not extract") parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=False, help="Verbose listing of filenames to stdout") (options, args) = parser.parse_args() if options.create and options.extract: print >>sys.stderr, 'Cannot create and extract archive simultaneously!' sys.exit() if not( options.create or options.extract or options.tell): print >>sys.stderr, 'You must specify either -c or -x!' sys.exit() if os.path.exists(options.arcdir) and not os.path.isdir(options.arcdir): print '%s exists and is not a dir' % options.arcdir if not os.path.exists(options.arcdir): os.makedirs(options.arcdir) if options.passwdfile is not None: passwd = file(options.passwdfile, 'rb').read() else: if options.create: passwd = getpass2() else: passwd = getpass() if options.extract: if len(args)==0: args = [options.arcdir] files = get_recursive_filelist(args) for thisFile in files: head, tail = os.path.split(thisFile) if not os.path.isfile(thisFile): continue if not len(tail)==32: print >>sys.stderr, '%s does not look like a hashname; skipping' % thisFile continue decode(thisFile, passwd, unlink=options.unlink, verbose=options.verbose, match=options.match, endian=options.endian ) elif options.tell: if len(args)==0: args = [options.arcdir] files = get_recursive_filelist(args) for thisFile in files: head, tail = os.path.split(thisFile) if not os.path.isfile(thisFile): continue if not len(tail)==32: print >>sys.stderr, '%s does not look like a hashname; skipping' % thisFile continue tell(thisFile, passwd, verbose=options.verbose, endian=options.endian) else: if sys.platform=='win32': # do glob expansion manually expand = [] for arg in args: expand.extend(glob.glob(arg)) args = expand files = get_recursive_filelist(args) for thisFile in files: encode(thisFile, options.arcdir, passwd, unlink=options.unlink, verbose=options.verbose, endian=options.endian) From rogerb at rogerbinns.com Wed Apr 5 12:08:20 2006 From: rogerb at rogerbinns.com (Roger Binns) Date: Wed, 5 Apr 2006 09:08:20 -0700 Subject: Convertion of Unicode to ASCII NIGHTMARE References: <1144079830.734516.8390@z34g2000cwc.googlegroups.com><1144081137.137744.253790@i39g2000cwa.googlegroups.com><34b9g3-ku8.ln1@home.rogerbinns.com><1144150561.389856.302670@v46g2000cwv.googlegroups.com><2enbg3-kr8.ln1@home.rogerbinns.com> Message-ID: "Fredrik Lundh" wrote in message news:mailman.4114.1144239972.27775.python-list at python.org... > sounds like your understanding of Unicode and Python's Unicode system > is a bit unclear. Err, no. Relaying unicode data between two disparate C APIs requires being careful and thorough. That means paying attention to when conversions happen, byte ordering (compile time) and boms (run time) and when the API documentation isn't thorough, verifying the behaviour yourself. That requires a very clear understanding of Unicode in order to do the requisite test cases, as well as reading what the code does. Roger From michele.simionato at gmail.com Fri Apr 21 09:07:46 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 21 Apr 2006 06:07:46 -0700 Subject: what has python added to programming languages? (lets be esoteric, shall we ; ) In-Reply-To: References: Message-ID: <1145624866.896211.252160@g10g2000cwb.googlegroups.com> Wildemar Wildenburger wrote: > Over the time I've seen lots of remarks about python that read like "a > lot like lists in lisp" or "like the hashtable in java" or any other > form of "like in ". > > Are there any concepts that python has not borrowed, concepts that were > not even inspired by other languages? I'm just interested if it is > "merely" a best-of collection of language features or if there are > actually inventions that have not - or hardly - existed in programming > before python? > > wildemar 1. One of the strenght of Python is that it does not try to be particularly original, most of the times it just borrows the good features from other languages without borrowing the warts. 2. If you ask in a Lisp newsgroup, they will tell you that they invented everything that it is cool now (in any language) over 40 years ago. They are also mostly right ;) Michele Simionato From neil.fitzgerald at ic.ac.uk Fri Apr 14 12:58:59 2006 From: neil.fitzgerald at ic.ac.uk (neil.fitzgerald at ic.ac.uk) Date: 14 Apr 2006 09:58:59 -0700 Subject: Forms with multiple submit buttons vs 'form' objects with single 'submit' methods In-Reply-To: <7xbqv5c7ry.fsf@ruckus.brouhaha.com> References: <1144956412.286214.316800@u72g2000cwu.googlegroups.com> <7xbqv5c7ry.fsf@ruckus.brouhaha.com> Message-ID: <1145033939.778292.275860@z34g2000cwc.googlegroups.com> Paul Rubin wrote: > neil.fitzgerald at ic.ac.uk writes: > > Here's my question: Suppose a form has more than one submit button. > > Now the COM 'form' object has a 'submit' method that doesn't take any > > arguments, so how do I tell it which button I want to press? > > What difference does it make? Don't they all do the same thing? Not in this case, no. If you want to see an example of how the button you press might make a difference, go to www.google.com. What I'm dealing with, basically, is a form consisting of lots of tags, which is being used purely as a collection of links. However, this arrangement means that they don't appear as links in the document object's "links" collection. Now in the case of Google, the form contains a pair of 'items' corresponding to the two buttons, and each item has a click method, and so everything works out fine. However, in the page I'm trying to navigate, the form doesn't possess any 'items' whatsoever. Anyway, it's seeming more and more likely to me that the page was specifically designed to prevent anyone doing what I'm trying to do (which is not in any way nefarious, but if I succeeded then it would only take a small modification to make it very destructive indeed.) Hence, I'm giving up. Sorry for the waste of bandwidth. From samantha7395 at hotmail.com Tue Apr 4 15:44:21 2006 From: samantha7395 at hotmail.com (Samantha) Date: Tue, 4 Apr 2006 12:44:21 -0700 Subject: Help with display placement References: <0v-dnVDsAaY-F6_Z4p2dnA@adelphia.com> <1144163990.760020.312370@g10g2000cwb.googlegroups.com> <1144170334.755700.221220@u72g2000cwu.googlegroups.com> Message-ID: Thanks, think I have it now. S wrote in message news:1144170334.755700.221220 at u72g2000cwu.googlegroups.com... > Ok so I'm not to bright sometimes > > Well if you want this kinda control I suggest you go ahead and subclass > toplevel, but the simple answer before running > > root.mainloop() > > > make a call to > > root.geometry(geometryString) > > > > geoometrystring is in the format WxH+X+Y - you may hve to do some > screen calcs first to get the right numbers. ie "50x100+50+50" create > a 50pix by 100 pix window offset 50 from the top and 50 from the left. > > To my mind, better to subclass toplevel and set everything in there - > but's mostly stylistic preference for something this simple. > > And while I'm making suggestions ;) Try wxPython. I used tKinter for > about 3 months before tossing it in frustration when I wanted to do > somtheing "slick" , but I have a lot of fondness for some quick and > dirty UI's I did in tKinter a ways back. > From tjreedy at udel.edu Mon Apr 17 21:53:07 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 17 Apr 2006 21:53:07 -0400 Subject: A 'Box' Function References: <1145321497.261653.62130@g10g2000cwb.googlegroups.com> Message-ID: wrote in message news:1145321497.261653.62130 at g10g2000cwb.googlegroups.com... > The word-wrapping function I'm working with is I have never used this, but it might help you >>> import textwrap >>> dir(textwrap) ['TextWrapper', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__revision__', '_whitespace', 'dedent', 'fill', 're', 'string', 'wrap'] tjr From johnjsal at NOSPAMgmail.com Sun Apr 9 18:09:04 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sun, 09 Apr 2006 18:09:04 -0400 Subject: Best Python web-hosting? In-Reply-To: <1144605832.364688.305300@j33g2000cwa.googlegroups.com> References: <1144605832.364688.305300@j33g2000cwa.googlegroups.com> Message-ID: <4439870a$0$4206$c3e8da3@news.astraweb.com> walterbyrd wrote: > I don't need that much web space. I don't need Zope/Plone. > > But, I want a site that offers more than just CGI. And I would like > support for recent Python releases. > > Price is an issue, that's one reason I've been reluctant to use python > for web-sites, hosting seems to be more expensive than with php. > I was testing out http://www.devisland.net/ and it's pretty nice. They installed the latest versions of Python, mod_python and mysqldb at my request, and support was good. Only real problem is it's too expensive for the space you get (about $5/month for 100MB), but you said space wasn't much of an issue. From Serge.Orlov at gmail.com Sun Apr 16 06:26:21 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 16 Apr 2006 03:26:21 -0700 Subject: py2exe problem In-Reply-To: References: <1145134511.975204.232650@g10g2000cwb.googlegroups.com> Message-ID: <1145183181.942584.311190@g10g2000cwb.googlegroups.com> bwaha wrote: > Thanks for the suggestion, but I definitely have only one version installed. > In fact I uninstalled it and installed an earlier version (2.5.5.1) to see > if it was specifically wxPython related. No change. Then why don't you try to print what is passed to SetValue in the exe, just change windows = ['mpival3.py'] in setup.py with console = ['mpival3.py'] and add prints. From reply.in.the.newsgroup at my.address.is.invalid Mon Apr 24 15:12:36 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Mon, 24 Apr 2006 21:12:36 +0200 Subject: need a thread to keep a socket connection alive? References: <1145718638.526525.235090@i39g2000cwa.googlegroups.com> <1145885130.140370.166490@t31g2000cwb.googlegroups.com> <1145891966.658138.31310@i40g2000cwc.googlegroups.com> <1145900352.203424.105890@i40g2000cwc.googlegroups.com> Message-ID: nephish at xit.net: >i have discovered that the server will send a request for the heartbeat >ping if its almost timed out, so i use the length of the message to >determine what to do with it. > >msg = sockobj.recv(1024) > >if len(msg) == 158: > record the data >elif len(msg) == (34): # length of request for ping > ping the server Incorrect. There are no 'messages' with TCP, only bytes. -- Ren? Pijlman From struggleyb at gmail.com Tue Apr 11 12:01:20 2006 From: struggleyb at gmail.com (Bo Yang) Date: Wed, 12 Apr 2006 00:01:20 +0800 Subject: A question about the urllib2 ? Message-ID: <443BD2D0.4040708@gmail.com> Hi , Recently I use python's urllib2 write a small script to login our university gateway . Usually , I must login into the gateway in order to surf the web . So , every time I start my computer , it is my first thing to do that open a browser to login the gateway ! So , I decide to write such a script , sending some post information to the webserver directly to login automatic once the computer is on . And I write the code below : urllib2.urlopen(urllib2.Request(url="https://202.113.16.223/php/user_login.php", data="loginuser=0312889&password=o127me&domainid=1&refer=1& logintype= ?????")) In the five '#' above , I must submit some Chinese character , but the urllib2 complain for the non-ascii characters . What do you think this ? Any help will be appreciated very much , thanks in advance ! From SSchukat at dspace.de Fri Apr 28 10:12:44 2006 From: SSchukat at dspace.de (Stefan Schukat) Date: Fri, 28 Apr 2006 15:12:44 +0100 Subject: Get all attributes of a com object Message-ID: <1B3F2E002D9AD04BBC1A27B370F29EB9022DD5@exchange2003.dspace.de> > -----Original Message----- > From: python-list-bounces+sschukat=dspace.de at python.org > [mailto:python-list-bounces+sschukat=dspace.de at python.org] On > Behalf Of Tim Golden > Sent: Friday, April 28, 2006 11:45 AM > To: python-list at python.org > Subject: RE: Get all attributes of a com object > > [snip] > > The only thing is that you can't always build a proxy module. > I'm never quite sure why or why not. > You can only build a proxy module if you have the typelibrary information which not all programs provide, since it prohibits changes in the interface the easy way. E.g., MFC application will normally not provide a typelibrary but support dynamic dispatch. Stefan From rex.eastbourne at gmail.com Sun Apr 9 02:07:54 2006 From: rex.eastbourne at gmail.com (Rex Eastbourne) Date: 8 Apr 2006 23:07:54 -0700 Subject: Mysterious EOFError Message-ID: <1144562874.585483.91450@u72g2000cwu.googlegroups.com> Hi, I'm executing a python script as a cron job. When I run it myself from the command line it works, but when cron executes it I get an EOFError: File "/home/rex/cronscript.py", line 6, in ? level = int(raw_input("hello?")) EOFError: EOF when reading a line It's not the last line of the file. When I run it as root from the command line I don't get any errors. Any ideas? From steven.bethard at gmail.com Fri Apr 21 19:08:44 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 21 Apr 2006 17:08:44 -0600 Subject: Updated PEP 359: The make statement In-Reply-To: References: <_aydnYpYE_rjuNjZRVn-og@comcast.com> Message-ID: Tim Roberts wrote: > Steven Bethard wrote: > >> Steven Bethard wrote: >>> I've updated PEP 359 with a bunch of the recent suggestions. ... >> Guido has pronounced on this PEP: >> http://mail.python.org/pipermail/python-3000/2006-April/000936.html >> Consider it dead. =) > > I tried to follow the thread backwards and find out what proposed change in > the "class" construct would render "make" unnecessary, but I couldn't find > it. Can you summarize, Steven? The make statement was mostly syntactic sugar for:: class : __metaclass__ = So was technically unnecessary from the beginning. ;) Here's the one post where he presented a few reasons he didn't like it: http://mail.python.org/pipermail/python-3000/2006-April/000704.html He didn't say a whole lot else about it, but when he mentioned that he'd like the discussion to end, I offered to end it. ;) STeVe From rajesh1986 at gmail.com Fri Apr 14 17:01:37 2006 From: rajesh1986 at gmail.com (Rajesh Sathyamoorthy) Date: Sat, 15 Apr 2006 05:01:37 +0800 Subject: reading files in small chunks? In-Reply-To: <1360b7230604140129n49cc7da8n8b2c0308e84879cc@mail.gmail.com> References: <47a726d60604132245s32fc4d55r3279e8e4372d720a@mail.gmail.com> <1360b7230604140129n49cc7da8n8b2c0308e84879cc@mail.gmail.com> Message-ID: <47a726d60604141401h252497c3t61a44716c7444184@mail.gmail.com> Hi, What chunk sizes do you normally use in your code? Thank You. On 4/14/06, Amit Khemka wrote: > > On 4/14/06, Rajesh Sathyamoorthy wrote: > > Hi, > > > > I wanted to know why it is more efficient to read a file in smaller > chunks ( > > using file() or open() )? If this is not done, will this lead to errors > in > > the data read or just results in slower performance? > > > > Thank You. > > It has basically to do with disk seeks and cache+memory utilization. > and you can look around for the same for details on any of your fav > search engine. > > cheers, > amit. > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > > > -- > ---- > Amit Khemka -- onyomo.com > Home Page: www.cse.iitd.ernet.in/~csd00377 > Endless the world's turn, endless the sun's Spinning, Endless the quest; > I turn again, back to my own beginning, And here, find rest. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From me at privacy.net Tue Apr 18 21:49:19 2006 From: me at privacy.net (Dan Sommers) Date: Tue, 18 Apr 2006 21:49:19 -0400 Subject: Writing backwards compatible code - when? References: Message-ID: On Tue, 18 Apr 2006 13:40:11 -0600, "Bob Greschke" wrote: > Is there a list of all of the Python commands and modules that tell > when (what version) they were added to Python? I was hoping the new > Essential Reference would have it, but it doesn't. I thought it was more cohesive, but googling for python "what's new" turns up a collection of such documents in various places. Regards, Dan -- Dan Sommers "I wish people would die in alphabetical order." -- My wife, the genealogist From skip at pobox.com Fri Apr 7 11:02:45 2006 From: skip at pobox.com (skip at pobox.com) Date: Fri, 7 Apr 2006 10:02:45 -0500 Subject: pre-PEP: The create statement In-Reply-To: <1144396060.657364.7240@i39g2000cwa.googlegroups.com> References: <59Wdnbd8EazRCqnZnZ2dnUVZ_vudnZ2d@comcast.com> <1144331431.696334.248850@u72g2000cwu.googlegroups.com> <1144396060.657364.7240@i39g2000cwa.googlegroups.com> Message-ID: <17462.32533.218384.37304@montanaro.dyndns.org> Michele> I think looking at the occurrences in the standard library only Michele> is unfair. In addition, when considering the standard library you need to search the source repository, not just what's installed on your platform. I noticed in your earlier post that you pointed your count_names script (very handy, btw) at your /usr/lib/pythonN.M directory. Pointing it at the source repository picks up stuff in the platform-dependent sections as well as searching through other less-used code. Michele> I guess 'make' sounds too Lispy, this is why it is never used Michele> in Pythonland. It doesn't seem lispish to me. OTOH, "make" seems more utilitarian than "create". For instance, cooks make things while chefs create things. Perhaps "make" is better anyway. The proposed statement is essentially a namespace factory. I think of object factories as very utilitarian beasts. Skip From NethanO at SPdogdiniAM.com Thu Apr 20 17:51:38 2006 From: NethanO at SPdogdiniAM.com (EShames) Date: Thu, 20 Apr 2006 21:51:38 GMT Subject: Activating Batch Files from Python In-Reply-To: <1145417944.549477.198510@g10g2000cwb.googlegroups.com> References: <1145417944.549477.198510@g10g2000cwb.googlegroups.com> Message-ID: On 4/18/2006 11:39 PM, Jeff Groves wrote: > I'm writing a launcher that should do the following: > > 1. Activate a .bat file to set environmental variables. > 2. Start 3 programs, using said environmental variables as arguments. > > However, I can't get the environmental variables to stick because all > of Pythons' system start/open functions split off into their own little > subshells, therefore the .bat file doesn't affect the main shell. > > How can I use the .bat file to set environmental vars from Python? > Resource Kit has SETX, but better is SETENV by Vincent Fatica http://barnyard.syr.edu/~vefatica/ C:\_Utils>setenv /? SETENV syntax: To set or change the value of a variable: User environment: setenv -u name value (also /u) Machine environment: setenv -m name value (also /m) Default user environment: setenv -d name value (also /d) Volatile environment: setenv -v name value (also /v) To display a variable: setenv -u|-m|-d|-v name To delete a variable: setenv -u|-m|-d|-v name -delete (also /delete) To display an environment: setenv -u|-m|-d|-v Use double-quotes around values containing spaces. If a variable name or value is to CONTAIN a double-quote, escape that double-quote as \" Return codes: 0 = success 1 = variable not found 2 = access denied 3 = other error 4 = SETENV has shown this syntax message Requested output goes to STDOUT; help and error messages to STDERR. From felipe.lessa at gmail.com Tue Apr 4 20:01:14 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Tue, 04 Apr 2006 21:01:14 -0300 Subject: Python Decompilers? In-Reply-To: <1144194130.731253.170930@t31g2000cwb.googlegroups.com> References: <1144194130.731253.170930@t31g2000cwb.googlegroups.com> Message-ID: <1144195275.8660.0.camel@kenshin.CASA> Em Ter, 2006-04-04 ?s 16:42 -0700, flamesrock escreveu: > Hi, Hi > Are there any good decompilers for python? Yes > -Thanks You're welcome =) -- Felipe. From pratik.ganguly at gmail.com Thu Apr 20 05:20:01 2006 From: pratik.ganguly at gmail.com (prats) Date: 20 Apr 2006 02:20:01 -0700 Subject: help wanted regarding displaying Japanese characters in a GUI using QT and python In-Reply-To: <1145519024.125421.327360@t31g2000cwb.googlegroups.com> References: <1145454203.770652.79920@j33g2000cwa.googlegroups.com> <1145460813.222787.302360@z34g2000cwc.googlegroups.com> <1145505985.664590.39580@t31g2000cwb.googlegroups.com> <1145515929.799871.29550@z34g2000cwc.googlegroups.com> <1145519024.125421.327360@t31g2000cwb.googlegroups.com> Message-ID: <1145524801.104992.121800@e56g2000cwe.googlegroups.com> I think I could not make myself clear. I have a GUI written in Python and Qt and PyQt as the python wrappper fro QT. Now I have a string which is base64 encoded. This string contains both japanese and english charaters. I need to decode them and display them properly in the GUI ie. with both english and japanese characters. I need a way to display them. Qt doc says that QStrings are capable of displaying all characters. So I need a way to get a QString from the base64 encoded string. ~pratik From phpbird at gmail.com Mon Apr 3 11:47:51 2006 From: phpbird at gmail.com (JuHui) Date: 3 Apr 2006 08:47:51 -0700 Subject: can I get the index number in for x in y loop? In-Reply-To: <1144078792.350510.57870@i39g2000cwa.googlegroups.com> References: <1144078372.411795.21570@i39g2000cwa.googlegroups.com> <1144078792.350510.57870@i39g2000cwa.googlegroups.com> Message-ID: <1144079271.758144.92070@v46g2000cwv.googlegroups.com> which one has best performance? a:for i in range(0,len(a)) b:for x in a c:for x,y in enumerate(a) but, it seems I cann't get index number with b format..:( From bayerj at in.tum.de Tue Apr 18 02:56:55 2006 From: bayerj at in.tum.de (bayerj) Date: 17 Apr 2006 23:56:55 -0700 Subject: How do you guys print out a binary tree? In-Reply-To: References: Message-ID: <1145343415.809363.116280@i39g2000cwa.googlegroups.com> Hi, > 1 2 3 4 5 > 0 7 8 9 10 > 0 0 13 14 15 > 0 0 0 19 20 > 0 0 0 0 25 > Look at the triangle represented by the non-zero > integers. This triangle is a binary tree if we take 5 > as the root and walk down on both sides. Are you sure? Is 9 a child of 4 or 10? A binary tree can have up to 2^n - 1 nodes. A matrix can have up to n^2 values, in your case of a half-empty matrix about (n-1)^2. From aahz at pythoncraft.com Mon Apr 10 23:20:52 2006 From: aahz at pythoncraft.com (Aahz) Date: Mon, 10 Apr 2006 20:20:52 -0700 Subject: BayPIGgies: April 13, 7:30pm (IronPort) Message-ID: <20060411032052.GA2596@panix.com> The next meeting of BayPIGgies will be Thurs, April 13 at 7:30pm at IronPort. This meeting features JJ reviewing "Professional Software Development" with discussion and newbie questions afterward. BayPIGgies meetings alternate between IronPort (San Bruno, California) and Google (Mountain View, California). For more information and directions, see http://baypiggies.net/ Before the meeting, we sometimes meet at 6pm for dinner. Discussion of dinner plans is handled on the BayPIGgies mailing list. Advance notice: We have a speaker for May. We can use speakers for June/July. Please e-mail baypiggies at python.org if you want to suggest an agenda (or volunteer to give a presentation). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "LL YR VWL R BLNG T S" From walterbyrd at iname.com Tue Apr 11 10:11:18 2006 From: walterbyrd at iname.com (walterbyrd) Date: 11 Apr 2006 07:11:18 -0700 Subject: Best Python web-hosting? In-Reply-To: <443b15dd$0$11701$c3e8da3@news.astraweb.com> References: <1144605832.364688.305300@j33g2000cwa.googlegroups.com> <4439870a$0$4206$c3e8da3@news.astraweb.com> <1144710859.872630.297820@u72g2000cwu.googlegroups.com> <443b15dd$0$11701$c3e8da3@news.astraweb.com> Message-ID: <1144764678.709671.91210@u72g2000cwu.googlegroups.com> I emailed them, they say they have mod_python. From jparlar at cogeco.ca Fri Apr 14 15:54:52 2006 From: jparlar at cogeco.ca (Jay Parlar) Date: Fri, 14 Apr 2006 12:54:52 -0700 Subject: Passing a packed C structure to a c module In-Reply-To: References: <3OP%f.811$9c6.333@dukeread11> <443fcb63$0$3177$9b622d9e@news.freenet.de> Message-ID: <824ade1dbead98239d528ed7c714cfd0@cogeco.ca> On Apr 14, 2006, at 9:44 AM, Philippe Martin wrote: > Thanks, > > It's a pretty big structure: painfull to pass each item as a param. > > Regards, > > Philippe > Maybe this can do something for you? http://pyconstruct.sourceforge.net/ Jay P. From jelleferinga at gmail.com Fri Apr 21 09:31:13 2006 From: jelleferinga at gmail.com (jelle) Date: 21 Apr 2006 06:31:13 -0700 Subject: are docstrings for variables a bad idea? In-Reply-To: References: <1145615763.943050.170950@j33g2000cwa.googlegroups.com> Message-ID: <1145626273.873576.89930@t31g2000cwb.googlegroups.com> ---- class GeographicCoordinate: def __init__ (self, lat, long): self.lat = lat "Latitude in degrees (positive North), per WGS84" self.long = long "Longitude in degrees (positive West), per WGS84" ---- Thanks for your example Roy, that illustrates well what I'm after: self.lat = lat "ellipsoid reference: WGS84\nGRS 80 no longer supported" It does exactly what its intended to do: i had no clue what the World Geodetic System and would have asserted my input with a GRS80_2_WGS84 function Little notes to avoid major mistakes. class landClimateOrbiter(NASA): self.speed = self.unit * x Just imagine 'feet' would have popped up when typing self.unit From antroy at gmail.com Tue Apr 4 04:25:39 2006 From: antroy at gmail.com (Ant) Date: 4 Apr 2006 01:25:39 -0700 Subject: what's going on here? In-Reply-To: <4431eb28$0$17995$c3e8da3@news.astraweb.com> References: <4431eb28$0$17995$c3e8da3@news.astraweb.com> Message-ID: <1144139139.659001.176300@j33g2000cwa.googlegroups.com> You are along the right lines. Try printing out the content of each URL - one of the pages will match your expression, but has additional instructions... I think you are reaching the end of their false trail when you get None returned from the url. The set of pages themselves are the linked list - each contains a reference to the next element in the sequence. You don't need one to solve the problem, the problem *is* the linked list! An example of a linked list in Python is the following if you are interested: class Element (object): next = None def __init__(self, content): self.content = content class LinkedList (object): first = None last = None def add(self, item): elmnt = Element(item) if not self.first: self.first = elmnt if self.last: self.last.next = elmnt self.last = elmnt def __iter__(self): current = self.first while current: yield current.content current = current.next ll = LinkedList() for i in range(10): ll.add(i) for x in ll: print "Res: %s" % x From alisonken1 at gmail.com Thu Apr 20 16:40:32 2006 From: alisonken1 at gmail.com (alisonken1) Date: 20 Apr 2006 13:40:32 -0700 Subject: How should multiple (related) projects be arranged (structured) and configured so that they can share code, have a related package structure and enable proper unittesting, and ensuring no namespace collisions In-Reply-To: <4447ee60$0$5199$626a54ce@news.free.fr> References: <1145546785.268550.154240@e56g2000cwe.googlegroups.com> <1145563823.160038.257950@j33g2000cwa.googlegroups.com> <4447ee60$0$5199$626a54ce@news.free.fr> Message-ID: <1145565632.131816.146560@i40g2000cwc.googlegroups.com> I believe that Paddy was referencing his second point about keeping "production code" and "test code" clearly delimited, so was recommending that a version control system be used rather than the local disk structure required by python for building module packages. Although, I have found that symlinks work fine for delimiting file structure - ex.: $BASEDIR/ $TESTDIR/ $TESTDIR/ Using an example program that I wrote, the following directory structure snippet works for me (where 'bin' is a directory to shared modules of production code): -rw-r--r-- 1 ken users 509 2004-11-30 13:35 label.ini lrwxrwxrwx 1 ken users 9 2004-12-29 01:54 bin -> ../../bin/ drwxr-xr-x 3 ken users 72 2004-12-10 16:01 data/ drwxr-xr-x 2 ken users 80 2004-12-10 16:46 disp/ drwxr-xr-x 2 ken users 48 2004-12-10 16:01 etc/ drwxr-xr-x 2 ken users 80 2004-12-10 16:27 prn/ drwxr-xr-x 2 ken users 208 2004-12-10 16:14 test/ drwxr-xr-x 2 ken users 1208 2004-12-10 17:15 label.py From tomerfiliba at gmail.com Mon Apr 24 16:17:05 2006 From: tomerfiliba at gmail.com (gangesmaster) Date: 24 Apr 2006 13:17:05 -0700 Subject: threads and sys.exit() In-Reply-To: References: <1145897992.091952.326970@e56g2000cwe.googlegroups.com> Message-ID: <1145909825.231565.42250@j33g2000cwa.googlegroups.com> that's not a question of design. i just want a child-thread to kill the process. in a platform agnostic way. From skip at pobox.com Mon Apr 17 21:07:48 2006 From: skip at pobox.com (skip at pobox.com) Date: Mon, 17 Apr 2006 20:07:48 -0500 Subject: scanning through page and replacing all instances of 00:00:00.00 In-Reply-To: References: Message-ID: <17476.15332.903041.937401@montanaro.dyndns.org> Kun> assuming that my date column is 2, how would i parse out the date? No parsing required. Just get its date: d = record[2].date() The str() of a datetime.date object is a string in YYYY-MM-DD form. Kun> the example you gave is of you parsing out the current time, but Kun> how do you parse out a pre-specified time that is extracted via Kun> sql? i don't think something like dt.date() works because it Kun> doesn't work with a string? correct me if i'm wrong. I think MySQLdb automatically returns datetime objects when the column data type is date. Skip From johnjsal at NOSPAMgmail.com Sun Apr 30 18:59:58 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sun, 30 Apr 2006 18:59:58 -0400 Subject: setting file permissions on a web server In-Reply-To: References: <445449f6$0$9437$c3e8da3@news.astraweb.com> <4454f1e1$0$1963$c3e8da3@news.astraweb.com> Message-ID: <44554237$0$13323$c3e8da3@news.astraweb.com> Daniel Nogradi wrote: > This depends on your arrangements with your web server provider. > Perhaps you are allowed to ssh into that machine, perhaps not, you > need to ask your provider. In case you can use ssh, then you can log > in with putty (an ssh client for windows, grab it from here: > http://www.chiark.greenend.org.uk/~sgtatham/putty/) and you will have > a command line on the server so you can run chmod there. Turns out that my web hosting company provides ssh access on the next highest plan and up, but not mine. :) Oh well, I think I'll explore FileZilla a little more and see if there's more of an automated way to do it than just right-clicking each file (or even right-clicking multiple files at once, if possible). It shouldn't be too big of a deal anyway, but I'm always after more automated ways to do things...call me lazy! :) From chris.uppal at metagnostic.REMOVE-THIS.org Fri Apr 28 10:07:56 2006 From: chris.uppal at metagnostic.REMOVE-THIS.org (Chris Uppal) Date: Fri, 28 Apr 2006 15:07:56 +0100 Subject: (was Re: Xah's Edu Corner: Criticism vs Constructive Criticism) References: <1145992903.834316.198370@u72g2000cwu.googlegroups.com> <4GM3g.3084$TT.1768@twister.nyroc.rr.com> <1146231280.733609.143230@e56g2000cwe.googlegroups.com> Message-ID: <4452258e$0$655$bed64819@news.gradwell.net> Tagore Smith wrote: > It's much easier to use a killfile than to complain to an ISP, and I > think that that should be the preferred response to messages you don't > like. I'm inclined to agree. The problem is not Xah Lee (whom I have killfiled), but the people who insist on making my killfile useless by posting loads of follow-ups saying things amounting to "stop this insane gibberish". Every bloody time. Wake up, people ! You are not the victims, you are the problem. Shut up, /please/. (And yes, I do realise that I'm adding to the problem here, and indeed that I'm not following my own advice, nor heeding my own request.). -- chris From wildemar at freakmail.de Tue Apr 18 06:28:54 2006 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Tue, 18 Apr 2006 12:28:54 +0200 Subject: Why new Python 2.5 feature "class C()" return old-style class ? In-Reply-To: References: <1144752553.305591.88050@j33g2000cwa.googlegroups.com> <443bbdbe$0$15517$626a54ce@news.free.fr> <443c22d1$0$11341$636a55ce@news.free.fr> <443E4204.2020003@freakmail.de> Message-ID: <4444BF66.4050703@freakmail.de> Fredrik Lundh wrote: > why are you using an IDE that doesn't understand Python syntax ? > > > Because I don't like using a whole new editor for every new language I'm using (as you would not use a new hammer for each nail) and jedit just plain rocks. I guess it could be made to recognize class statements ... but its python mode works well enough, so I'll rather stick to that and create python magic. ok, on to the next useless post ... ;) wildemar From cvanarsdall at mvista.com Thu Apr 20 19:00:36 2006 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Thu, 20 Apr 2006 16:00:36 -0700 Subject: search a string In-Reply-To: <444810e2$0$14295$626a54ce@news.free.fr> References: <9583ed900604201423k5671242en7d4345e695ea7000@mail.gmail.com> <44480380$0$30095$636a55ce@news.free.fr> <444810e2$0$14295$626a54ce@news.free.fr> Message-ID: <44481294.7050901@mvista.com> Bruno Desthuilliers wrote: > Carl J. Van Arsdall a ?crit : > (snip) > > >> With a file object, to iterate through the lines in a file don't you >> have to use readlines()? >> > > Nope - no more, should I say. The file object is now an iterable. > file.readlines() try and read all the file and returns it as a list. > It's ok for small files, but can lead to problem with huge ones... using > the file as an iterator, you have a lazy read - just like you would with > the older file.readline() idiom: > Ah sweet, I didn't realize you could do that, thanks! > line = f.readline() > while line: > do_something_with(line) > line = f.readline() > > but with much less hassle : > > for line in f: > do_something_with(line) > > -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From nothingcanfulfill at gmail.com Mon Apr 10 05:16:24 2006 From: nothingcanfulfill at gmail.com (ncf) Date: 10 Apr 2006 02:16:24 -0700 Subject: GridBagSizer Message-ID: <1144660584.283396.205520@u72g2000cwu.googlegroups.com> Recently, I came across a presentation about wx.GridBagSizer while trying to look up more info to use it in an application, however, the presentation noted "Don't use GridBagSizer. Ever." Can anyone please explain to me why using GridBagSizer would be such a bad idea? Or is this only applicable when using XRC? Presentation URI: http://yergler.net/talks/desktopapps_uk/ Presentation Dated: 20APR05 Slide Number: 9 -- "Sanity and Cross-Platform XRC" -Ws From fredrik at pythonware.com Wed Apr 12 14:34:54 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 12 Apr 2006 20:34:54 +0200 Subject: just one more question about the python challenge References: <%2a%f.1965$No6.42797@news.tufts.edu> Message-ID: John Salerno wrote: > > At the second, don't rename the file, rename the URL. > > Do you mean rename the URL *aside from* the file name? no, the URL you got when you followed georg's instructions will give you some data that you need to manipulate before you can see what it is. to figure out how to manipulate it, study the *first* image carefully. what is the person on that page doing? From sam at nuevageorgia.com Tue Apr 4 19:55:52 2006 From: sam at nuevageorgia.com (SamFeltus) Date: 4 Apr 2006 16:55:52 -0700 Subject: Python Decompilers? In-Reply-To: <1144194130.731253.170930@t31g2000cwb.googlegroups.com> References: <1144194130.731253.170930@t31g2000cwb.googlegroups.com> Message-ID: <1144194952.880957.18970@e56g2000cwe.googlegroups.com> I prefer Emacs or TextWrangler From steven.bethard at gmail.com Fri Apr 28 17:03:46 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 28 Apr 2006 15:03:46 -0600 Subject: best way to determine sequence ordering? In-Reply-To: <70q4g.2006$No6.43783@news.tufts.edu> References: <70q4g.2006$No6.43783@news.tufts.edu> Message-ID: John Salerno wrote: > If I want to make a list of four items, e.g. L = ['C', 'A', 'D', 'B'], > and then figure out if a certain element precedes another element, what > would be the best way to do that? > > Looking at the built-in list functions, I thought I could do something > like: > > if L.index('A') < L.index('D'): > # do some stuff This is probably a pretty reasonable approach as long as you're not too worried about efficiency. It scans the list twice though, so if you start doing this with really big lists, it might be better to do something like: >>> L = ['C', 'A', 'D', 'B'] >>> positions = dict((item, i) for i, item in enumerate(L)) >>> positions {'A': 1, 'C': 0, 'B': 3, 'D': 2} >>> positions['A'] < positions['D'] True If you care about memory in addition to speed, you could do something like: >>> L = ['C', 'A', 'D', 'B'] >>> items_to_compare = ['A', 'D'] >>> positions = dict( ... (item, i) ... for i, item in enumerate(L) ... if item in items_to_compare ... ) >>> positions {'A': 1, 'D': 2} >>> positions['A'] < positions['D'] True STeVe From m2ids2005 at gmail.com Wed Apr 26 05:36:03 2006 From: m2ids2005 at gmail.com (Shine Anne) Date: Wed, 26 Apr 2006 15:06:03 +0530 Subject: logging problem Message-ID: <5a0288e70604260236u4c9ecfa9r6ba53d66eb831aec@mail.gmail.com> HI All, I am having an app that needs to display a lot of msgs. These msgs need to kept ina log. I have written it as : D EBUG =1 if DEBUG: import logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s', filename='x.log', filemode='w') def DBG (s): if DEBUG: logging.debug(s) Then whereever i need i tried calling DBG("xxxxx") but i am getting error as: Traceback (most recent call last): File "C:\Python24\lib\logging\__init__.py", line 712, in emit self.stream.write(fs % msg) ValueError: I/O operation on closed file Can anyone help me..i am new to python so plz help -- Regards, Shine Anne -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at rueb.com Sat Apr 15 09:17:11 2006 From: steve at rueb.com (Steve Bergman) Date: 15 Apr 2006 06:17:11 -0700 Subject: Help for a complete newbie References: <7xY%f.1245$kz3.903@twister.nyroc.rr.com> Message-ID: <1145107031.283066.172300@j33g2000cwa.googlegroups.com> You can also access this group through Google Groups: http://groups.google.com/group/comp.lang.python which has nice search features. I found O'Reilly's "Learning Python" to be helpful in combination with O'Reilly's "Python in a Nutshell". Learning python is a nice introduction to Python but is (intentionally) *far* from complete. Python In a Nutshell is a reference work. The two complement each other nicely. Both are a bit out of date. The current python version is 2.4. Learning Python covers 2.3. Nutshell covers up to 2.2. One of these days Alex will come out with a 2nd Edition of Nutshell and there will be much rejoicing. ;-) From rpdooling at gmail.com Wed Apr 19 16:00:08 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 19 Apr 2006 13:00:08 -0700 Subject: Official Python logo References: <1145470122.145225.53110@z34g2000cwc.googlegroups.com> Message-ID: <1145476808.537716.183230@t31g2000cwb.googlegroups.com> logos: http://www.fastmirrors.org/python/pub/beta.python.org/resources/design/logo/ rick From fredrik at pythonware.com Thu Apr 13 11:43:07 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 13 Apr 2006 17:43:07 +0200 Subject: trying to grasp OO : newbie Q? References: <1144937168.508799.67410@i40g2000cwc.googlegroups.com><1144938934.900062.219600@i40g2000cwc.googlegroups.com> <1144941250.517385.144590@u72g2000cwu.googlegroups.com> Message-ID: mitsura at skynet.be wrote: > It is starting to make much more sense. Most documentation I find about > OO is very academic you may find Jay Parlar's new python class tutorial helpful: http://parlar.infogami.com/pytut_classes_copy (this is a proposed addition/replacement for the class chapter in the current tutorial). From alexandre.fayolle at logilab.fr Tue Apr 25 02:22:13 2006 From: alexandre.fayolle at logilab.fr (Alexandre Fayolle) Date: Tue, 25 Apr 2006 06:22:13 +0000 (UTC) Subject: PyLint results? References: Message-ID: Others have answered most of your questions, I won't repeat the answers here, but only join the choir to stress that pylint needs tuning to your coding style. An obvious case is camelCaseMethodNames versus underscored_method_names, but there are also a lot of issues. The default pylint settings match Logilab's coding standards. The coding metrics were heavily inspired by Steve McConnell's Code Complete book, but the figures provided therein have been heavily downscaled to match for Python's expressivity (Code Complete deals mostly with C/C++/Java code). Le 21-04-2006, Michael nous disait: > 2) C: 0: Missing required attribute "__revision__" > What is this? Is that for CVS? I don't use CVS (we use SVN). I have not > seen any sample code which includes this tag yet. But if I include > __revision 1.0 somewhere in the code it will remove that warning? We generally have a __revision__ = '$Id$' statement at module top level, which gets replaced a check in time by CVS, which makes it easy to know who checked in the HEAD revision of the module. This behaviour can be emulated with subversion properties. > 5) R:547:readDiscreteData: Too many branches (28/12) > Python doesn't have the switch/case statements that C/C++ have. So I > could have a large block if/elif/else statements. > Is there any way to avoid that? > > 6) R:722:waitDiscretes: Too many local variables (38/15) > That's new to me. What is wrong with too many local variables? > Can anything be done to improve that besides having too many globals? For these two, I strongly recommend giving a look at Martin Fowler's Refactoring book (published by Addison Wesley). These are typical so called "code smells" which can be solved using for instance the "Extract Method" refactoring. Of course, it all depends on the kind of program you are working, and sometimes using intermediate variables helps understanding the code (by providing useful names, for instance). What pylint tells you is "there could be an issue here, you should check." -- Alexandre Fayolle LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org From steve at holdenweb.com Tue Apr 4 21:47:32 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 04 Apr 2006 21:47:32 -0400 Subject: The "Need for Speed" Sprint, Reykjavik, Iceland, May 21-28, 2006 Message-ID: <443321B4.5010204@holdenweb.com> EWT LLC and CCP h.f., having specific commercial interests in doing so, have decided to sponsor a sprint on the Python programming language with specific short- and medium-term acceleration goals. The sprint is also intended to stimulate broad consideration of the future of Python, and specifically to try and identify the most promising routes to improved performance. Selected members of the Python developer community will receive direct invitations, and their attendance will be sponsored, to try to ensure the most effective possible result. In the spirit of open source events the sprint is open to all. The venue is the Grand Hotel, Reykjavik, http://www.grand.is/. The following objectives are of interest to the sponsors. * Improving the decimal module by implementing portions in C * Investigate whether RPython offers sufficient speedup over the regular CPython interpreter to replace tailored C and C++ code in MMP gaming applications * Implement an ordered dictionary in both C and Python * Implement data-structure-specific algorithms, which rely heavily on certain data structures, as RPython * Adding an iterator interface (similar to re.finditer) to the struct module * Further refine the PyPy LLVM back end to improve general execution speeds * Offer the PyPy team a sprint venue to continue their development work on Python implementations written in Python * Create a string subtype that provides lazy slicing without copying Sprinters are, as always, free to choose the aspects of Python they choose to work on. Flights should be booked to and from Keflavik airport (KEF). There will be a mid-week ?let your hair down? social event to which all sprint participants are cordially invited. In order to ensure that sufficient meeting space is available, please notify Steve Holden of your intention to attend by emailing steve at holdenweb.com. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd www.holdenweb.com Love me, love my blog holdenweb.blogspot.com From g.horvath at gmx.at Wed Apr 12 01:30:06 2006 From: g.horvath at gmx.at (Gregor Horvath) Date: Wed, 12 Apr 2006 07:30:06 +0200 Subject: About classes and OOP in Python In-Reply-To: References: <1144678797.749000.155010@t31g2000cwb.googlegroups.com> <1144743716.408970.23840@z34g2000cwc.googlegroups.com> <00rn321nv3oqbjesmqpdl4p0s3tgdj7o2f@4ax.com> Message-ID: Steven D'Aprano schrieb: > I don't know of many other OO languages that didn't/don't have > inheritance, VB4 - VB6 -- Mit freundlichen Gr??en, Ing. Gregor Horvath, Industrieberatung & Softwareentwicklung http://www.gregor-horvath.com From jon+usenet at unequivocal.co.uk Mon Apr 3 22:41:51 2006 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: 4 Apr 2006 02:41:51 GMT Subject: overloading constructor in python? References: <1144092500.618489.204740@e56g2000cwe.googlegroups.com> <1144098577.732202.314090@t31g2000cwb.googlegroups.com> <1hd8g42.t78sge1tuys90N%aleaxit@yahoo.com> Message-ID: In article <1hd8g42.t78sge1tuys90N%aleaxit at yahoo.com>, Alex Martelli wrote: >> I guess in python we use two idioms to cover most of the uses of >> mulltiple constructors: > > ... and classmethods. OK, _three_ idioms. Oh, and factory functions. > Among the idioms we use are the following... Nobody expects the Spanglish inquisition... From just at xs4all.nl Thu Apr 6 14:00:13 2006 From: just at xs4all.nl (Just) Date: Thu, 06 Apr 2006 20:00:13 +0200 Subject: Quickie: converting r"\x2019" to int References: <4435501d$1_2@newspeer2.tds.net> Message-ID: In article <4435501d$1_2 at newspeer2.tds.net>, Kent Johnson wrote: > Robin Haswell wrote: > > Hey guys. This should just be a quickie: I can't figure out how to convert > > r"\x2019" to an int - could someone give me a hand please? > > Is this what you mean? > In [9]: int(r'\x2019'[2:], 16) > Out[9]: 8217 > > or maybe you meant this: > In [6]: ord(u'\u2019') > Out[6]: 8217 Or even: >>> import struct >>> struct.unpack("q", "\0\0"+ r'\x2019')[0] 101671307850041L >>> Who knows :) Just From osv at javad.com Tue Apr 11 02:10:41 2006 From: osv at javad.com (Sergei Organov) Date: Tue, 11 Apr 2006 10:10:41 +0400 Subject: Python 3.0 or Python 3000? References: <4439aba9$0$18019$c3e8da3@news.astraweb.com> Message-ID: Robert Kern writes: > Sergei Organov wrote: >> Dennis Lee Bieber writes: >> >>>On Mon, 10 Apr 2006 12:12:58 +0200, Benjamin Niemann >>>declaimed the following in comp.lang.python: [...] >> Anyway, it's unfair to speak of one of the most wonderful pieces of >> software ever written in such a tone. > > Judging tone through email is error prone. Please try not to imagine insults > where there are none. Yes, you are right, I'll try to refrain from that in the future. -- Sergei. From ldo at geek-central.gen.new_zealand Thu Apr 27 03:40:03 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 27 Apr 2006 19:40:03 +1200 Subject: OOP / language design question References: <1145961248.794496.80220@j33g2000cwa.googlegroups.com> <444e0e97$0$2052$626a54ce@news.free.fr> <1145969107.837185.212970@e56g2000cwe.googlegroups.com> Message-ID: In article , Duncan Booth wrote: >Carl Banks wrote: > >> You know, Python's __init__ has almost the same semantics as C++ >> constructors (they both initialize something that's already been >> allocated in memory, and neither can return a substitute object). > >There is a significant difference: imagine B is a base type and C a >subclass of B: > >When you create an object of type C in Python, while B.__init__ is >executing self is an object of type C (albeit without all the attributes >you expect on your C). > >In C++ when the B() constructor is executing the object is an object of >type B. It doesn't become a C object until the C() constructor is >executing. > >In other words, the object is constructed in Python before any __init__ is >called, but in C++ it isn't constructed until after all the base class >constructors have returned. But if "construction" is what a constructor does, then you're wrong. From dave.opstad at monotypeimaging.com Tue Apr 11 12:29:10 2006 From: dave.opstad at monotypeimaging.com (Dave Opstad) Date: Tue, 11 Apr 2006 09:29:10 -0700 Subject: Manipulating sets from the 2.4 C API? Message-ID: I just looked through the Python/C API reference for 2.4.3 and didn't see anything about using sets. I'd been expecting things like PySet_New, PySet_Check etc. If I want to handle sets should I just use a dictionary's keys and ignore the values, or is there some more explicit set support somewhere I'm not seeing? Thanks, Dave Opstad From johnjsal at NOSPAMgmail.com Wed Apr 19 11:50:01 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 19 Apr 2006 15:50:01 GMT Subject: Ironpython book? In-Reply-To: <1he18dm.e64uky1urr3n0N%aleaxit@yahoo.com> References: <1145329406.419299.12780@i40g2000cwc.googlegroups.com> <1he15xj.1dy2h0vzbebqmN%aleaxit@yahoo.com> <1he18dm.e64uky1urr3n0N%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Jim Hugunin. But, apparently, we're having communication problems. > Since I say that Python.NET is "a long-completed research project", what > contradition do you find between that and your opinion that "it [isn't] > being developed/used anymore"? Why should a research project, that was > finished years ago and to which (to the best of my knowledge) no > followup is planned, be "developed" any further? I was just saying what my thoughts were before you told me that it was a completed project. What I had thought was that work on it had stopped and it wasn't being used anymore, perhaps because IronPython was becoming the main .NET implementation to use. But it sounds like, from Fred's post, that work is still being done on it. My main point in asking was just that I hadn't heard as much about it as IronPython lately, and I was just curious what the community would think about two competing .NET implementations, since a big part of Python is having one main way to do everything (I think). From godoy at ieee.org Tue Apr 4 07:38:38 2006 From: godoy at ieee.org (Jorge Godoy) Date: Tue, 04 Apr 2006 08:38:38 -0300 Subject: Best way to create a copy of a list References: <1144130464.918371.143160@u72g2000cwu.googlegroups.com> <1144134473.327848.307040@g10g2000cwb.googlegroups.com> Message-ID: <87irppy3i9.fsf@ieee.org> "Frank Millman" writes: > Interesting. My results are opposite. I got the same here (cPython 2.4.1): godoy at jupiter ~ % python -mtimeit -s "data=[range(100)]*100; row = []" "row[:] = data[23]" 1000000 loops, best of 3: 1.15 usec per loop godoy at jupiter ~ % python -mtimeit -s "data=[range(100)]*100" "row = data[23][:]" 100000 loops, best of 3: 1.42 usec per loop godoy at jupiter ~ % python -mtimeit -s "data=[range(100)]*100" "row = list(data[23])" 100000 loops, best of 3: 1.93 usec per loop godoy at jupiter ~ % > If they are all equivalent from a functional point of view, I lean > towards the second version. I agree with Rune that the third one is > nicer to read, but somehow the [:] syntax makes it a bit more obvious > what is going on. I prefer the third option for readability. It makes it clear that I'll get a *new* list with the 23rd row of data. Just think: how would you get the 1st column of the 23rd row? >>> a = [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6]] >>> a [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6]] >>> a[1] [2, 3] >>> a[1][1] 3 >>> a[1][:] [2, 3] >>> Someone might think that the "[:]" means "all columns" and the syntax to be equivalent to "data[23]". -- Jorge Godoy "Quidquid latine dictum sit, altum sonatur." - Qualquer coisa dita em latim soa profundo. - Anything said in Latin sounds smart. From onurb at xiludom.gro Tue Apr 11 10:18:06 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 11 Apr 2006 16:18:06 +0200 Subject: unboundlocalerror with cgi module In-Reply-To: <1282490.JcRWy2CgMu@teancum> References: <1282490.JcRWy2CgMu@teancum> Message-ID: <443bbae9$0$7706$636a55ce@news.free.fr> David Bear wrote: > I'm attempting to use the cgi module with code like this: > > import cgi > fo = cgi.FieldStorage() > # form field names are in the form if 'name:part' > keys = fo.keys() > for i in keys: > try: > item,value=i.split(':') > except NameError, UnboundLocalError: > print "exception..." > item,value=(None,None) > return(item,value) > > However, the except block does not seem to catch the exception Which one ?-) > and an > unboundlocalerror is thrown anyway. What am I missing? Err... 1/ the correct try/except syntax is: try: whatever_that_may_raise() except (ExceptionClass1, ExceptionClassN): handle_the_exception() What you code would actually do (if it raised a NameError, which will not be the case, cf next point) is to *bind* the exception object to the name 'UnboundLocalError'. 2/ the line: item,value=i.split(':') *won't* raise NameError nor UnboundLocalError 3/ if fo.keys() returns a non-empty list, your code (that I assume is the body of a function) will return the result of the split() for the *last* item in the list (after having uselessly split'ed each and every key...) 4/ else (ie : fo.keys() returns an empty list), *then* you'll get an UnboundLocalError (once again, assuming this code is the body of a function - but else you'd get a SyntaxError, since the return statement is not allowed outside a function body), *but* this exception will be raised when the 'return' statement is executed - not in the loop. A corrected version of your code could be: def extract_last_key(field_storage): # form field names are in the form if 'name:part' keys = field_storage.keys() if keys: return keys[-1].split(':', 1) else: return (None, None) import cgi fo = cgi.FieldStorage() name, part = extract_last_key(fo) I doubt this is actually what you *really* want, but this is at least what your code effectively try to do. FWIW, trying things at random until it seems to work is the worst way to program (some call this 'programming by accident'). -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From reply.in.the.newsgroup at my.address.is.invalid Wed Apr 19 04:04:26 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Wed, 19 Apr 2006 10:04:26 +0200 Subject: Missing interfaces in Python... References: <1145306373.781129.305840@z34g2000cwc.googlegroups.com> <1145430546.625634.194710@g10g2000cwb.googlegroups.com> Message-ID: <7lrb429tg5c6dt1bt99d1131cafuulvqap@4ax.com> Kay Schluehr: >You won't find many deep class hierarchies and extensive frameworks. Zope comes to mind. >This has the advantage that a classification you have done once at >the beginning of your project in the design phase is not considered >to be carved in stone. Zope 3 comes to mind. From johnjsal at NOSPAMgmail.com Thu Apr 6 10:05:23 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 06 Apr 2006 14:05:23 GMT Subject: python411 podcast -- problem with the 'modules' podcast? Message-ID: Not sure if you guys follow along with the podcast, but if you do, has anyone else had problems listening to the Modules podcast? On my iPod, it stops at 8 minutes, and in iTunes it stretches out across the full 17-19 minutes, but the contents are still just the first 8 minutes (meaning that what you hear at minute 1 might be the same if you skip ahead to minute 3, for example). From adam.l.m at gmail.com Wed Apr 26 01:15:55 2006 From: adam.l.m at gmail.com (Adam Mullins) Date: Wed, 26 Apr 2006 01:15:55 -0400 Subject: Passing Exceptions Across Threads Message-ID: <1146028555.18789.11.camel@localhost.localdomain> Hello, I'm writing a physics simulator back-end with a built-in, threaded server that for the moment is quite simple. I've faced a few problems in writing this code, however, as it's the first time I've played with threading. For the moment, everything works decently, but I need (or rather, want) a method for passing caught exceptions in sub-threads to the main thread to be raised there. Although this solution isn't the only one, I feel it will be the most elegant (the thread/class will be called inside the main module within a try/except structure, which makes the program a bit more modular, in my opinion, and cleaner). Here is my code so far: http://rafb.net/paste/results/UESOWB24.html You can see near the top where I clumsily tried to a hack a function into threading._MainThread, in the hopes that if it were called from a sub-thread it would execute in the main thread. This is seemingly not so. Many thanks for any help. From bayerj at in.tum.de Tue Apr 18 03:00:52 2006 From: bayerj at in.tum.de (bayerj) Date: 18 Apr 2006 00:00:52 -0700 Subject: How do you guys print out a binary tree? In-Reply-To: <1145343415.809363.116280@i39g2000cwa.googlegroups.com> References: <1145343415.809363.116280@i39g2000cwa.googlegroups.com> Message-ID: <1145343652.314376.284980@e56g2000cwe.googlegroups.com> A half-empty matrix will of course have (n+1)* n * 1/2 elements. From kent at kentsjohnson.com Sat Apr 1 06:54:00 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Sat, 01 Apr 2006 06:54:00 -0500 Subject: Python 2.5 licensing: stop this change In-Reply-To: <1143886079.435254.118110@t31g2000cwb.googlegroups.com> References: <1143881699.232542.224960@j33g2000cwa.googlegroups.com> <442e4dc6$0$62914$dbd49001@news.euronet.nl> <1143886079.435254.118110@t31g2000cwb.googlegroups.com> Message-ID: <442e6491_3@newspeer2.tds.net> bearophileHUGS at lycos.com wrote: > Aww, but I liked the idea of copying Perl 6 REs, and porting python to > the toy CPU :-) I think if PSF is going to support porting of Python to "toy" CPUs then the Digi-Comp should be the first target. This will breathe new life into these toys which for years have been relegated to the backs of closets and dusty attics. Having a modern programming language available will bring them out of the dark ages of counters and logic tables and make them useful for such purposes as web servers and biological research. And for the developers or others who need to target this platform, it is again in production. http://paperforest.blogspot.com/2006/02/digi-comp-1.html Kent From pecoraREMOVE at THISanvil.nrl.navy.mil Tue Apr 25 18:26:51 2006 From: pecoraREMOVE at THISanvil.nrl.navy.mil (Lou Pecora) Date: Tue, 25 Apr 2006 18:26:51 -0400 Subject: Plotting package? References: Message-ID: In article , "Andrew Koenig" wrote: > This may be a foolish question, but what's the most straightforward way to > plot a bunch of data in Python? > > That is, I want to write a program that does some number crunching, and then > I want to change some parameters and watch how the changes affect the > results. I could produce a file to hand to gnuplot, but that's a bit of a > pain; so I'm wondering if there is a widely used package to which I can give > my x-y pairs and have it produce a graph for me with axes, scaling, etc. I second all other recommendations on matplotlib. -- Lou Pecora (my views are my own) REMOVE THIS to email me. From frank at chagford.com Tue Apr 11 01:42:24 2006 From: frank at chagford.com (Frank Millman) Date: 10 Apr 2006 22:42:24 -0700 Subject: Programming Tutorial for absolute beginners In-Reply-To: References: <1144439148.751062.16590@t31g2000cwb.googlegroups.com> <1144512142.324056.281660@g10g2000cwb.googlegroups.com> <1144572585.147756.144240@i40g2000cwc.googlegroups.com> Message-ID: <1144734144.708314.119330@v46g2000cwv.googlegroups.com> Marc 'BlackJack' Rintsch wrote: > In <1144572585.147756.144240 at i40g2000cwc.googlegroups.com>, Frank Millman > wrote: > > > Then you can mention that, if they just want the integer portion, they > > can use int(3/2). I think that most people with the slightest > > understanding of basic arithmetic will relate to this without a > > problem. > > Or instead of converting the `float` back to an `int`, they can use > integer division: ``3 // 2`` > I had thought of that. The reason I did not suggest it is that, as I understand it, this tutorial is not about how to learn Python, it is about teaching programming to the absolute beginner. I imagine (hope I am not making invalid assumptions here) that Python was chosen as a base because it is easy and intuitive to learn, and in most cases it is. It just happens that division is one area where it is a bit awkward. The // syntax is specific to Python. I don't think you are helping the absolute beginner by forcing them to understand what is going on here. On the other hand, int(x) is a basic mathematical concept (extract the portion to the left of the decimal point) that is shared by several languages and is fairly easy to understand. My 2c (I am up to 4c now) Frank From olanglois at quazal.com Tue Apr 11 14:20:58 2006 From: olanglois at quazal.com (Olivier Langlois) Date: Tue, 11 Apr 2006 14:20:58 -0400 Subject: Memory limit to dict? Message-ID: <400BDC416E2A0042AA35DF3919BB8A5123A0EE@mail.mtl.proksim.com> That is a good observation! Considering that hash tables to have good performance need to have a fill rate of 70% or lower means that if you try to fit 3.6 GB of data into a dict, your memory requirement will be much higher than 3.6GB. BTW, this brings a new question. How does Python controls dictionnaries fill rate, hash collisions and tables rehashes? > > I don't have the answer to your question and I'll make a new one: isn't > the overhead (performance and memory) of creating dicts too large to be > used in this scale? > > I'm just speculating, but I *think* that using lists and objects may be > better. > > My 2 cents, > > -- > Felipe. > > -- > http://mail.python.org/mailman/listinfo/python-list From aahz at pythoncraft.com Sun Apr 16 11:46:30 2006 From: aahz at pythoncraft.com (Aahz) Date: 16 Apr 2006 08:46:30 -0700 Subject: Python certification/training References: <1145193231.657614.275950@v46g2000cwv.googlegroups.com> Message-ID: In article <1145193231.657614.275950 at v46g2000cwv.googlegroups.com>, wrote: > >Are there any certifications that are available for developers learning >Python? Where? > >I'm specifically looking for distance/on-line courses or certifications >but welcome any information available. Question is, what do you want it for? There is currently no certificate generally recognized by the Python community. If you're simply looking for Python training, there are several options; if you want recognition, your best option is to make code available to the community. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "LL YR VWL R BLNG T S" From aleaxit at yahoo.com Wed Apr 5 23:14:23 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 5 Apr 2006 20:14:23 -0700 Subject: using range() in for loops References: <443324dc$0$11257$c3e8da3@news.astraweb.com> <1144212600.591743.293570@j33g2000cwa.googlegroups.com> Message-ID: <1hdc81l.sy05xf1phrf3qN%aleaxit@yahoo.com> Georg Brandl wrote: > Steven D'Aprano wrote: > > On Wed, 05 Apr 2006 16:15:12 +0200, Georg Brandl wrote: > > > >> sushant.sirsikar at gmail.com wrote: > >>> hi John, > >>> Python doesn't provide for loop like C / C++ but using Range() or > >>> Xrange() you can achive all the functionalities of the C for loop. > >> > >> Not quite. > > > > Care to explain what the differences are, or shall we guess? > > C's for is much more powerful. > > for(a; b; c) { d } translates to > > a > while b > d > c > > which can't be replaced by a simple > > for i in range(...) No, but it can be easily replaced by: # factoring out the loopstructure... def gotcha(): a while b: yield c # ...from the loopbody for i in gotcha(): d or several variations thereof. In C++, I almost half-heartedly replace most of Python's generators' power with C++'s templated iterators, but when I program in C I find myself really straightjacketed these days in NOT being able to pull out the "loopstructure" as I can in Python (and, about halfway, in C++). Alex From daniel.dittmar at sap.corp Thu Apr 6 11:23:08 2006 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Thu, 06 Apr 2006 17:23:08 +0200 Subject: GUI issues in Python In-Reply-To: <1144335401.607337.172140@j33g2000cwa.googlegroups.com> References: <1144328552.221998.230480@g10g2000cwb.googlegroups.com> <1144335401.607337.172140@j33g2000cwa.googlegroups.com> Message-ID: diffuser78 at gmail.com wrote: > Thanks Daniel, I really think that this should be the solution to my > problem. > > A quick Question...is wxPython Operating System dependent or it can be > used with anu OS like Linux, Windows and Mac ? > see http://www.wxpython.org/download.php#binaries Linux and Win32 have been supported for a while. And the screenshot in my first reply was from Mac OS X, so OGL seems to be supported there too. The wxPython demo application has an OGL example, so you can check that pretty quickly. Daniel From mike.klaas at gmail.com Thu Apr 6 00:24:45 2006 From: mike.klaas at gmail.com (Klaas) Date: 5 Apr 2006 21:24:45 -0700 Subject: Best way to have a for-loop index? In-Reply-To: References: <1141950744.482666.4430@j33g2000cwa.googlegroups.com> Message-ID: <1144297485.066490.300350@v46g2000cwv.googlegroups.com> roy spewed: > The real question is *why* do you want the index? > > If you're trying to iterate through list indicies, you're probably trying > to write C, C++, Fortran, Java, etc in Python. Could we stop the stupid continual beratement of people validly asking about enumerate()? Yes, we want to discourage: for i in xrange(len(seq)): seq[i] but in this case, and many other cases, that is clearly not the question being posed. enumerate is one of the most useful built-ins and a love the way it reads in code. Stop the index-hate. -Mike From shkelley at gmail.com Wed Apr 19 10:20:07 2006 From: shkelley at gmail.com (Shawn Kelley) Date: 19 Apr 2006 07:20:07 -0700 Subject: items in an array References: <1145455441.531332.295700@e56g2000cwe.googlegroups.com> Message-ID: <1145456407.631111.161040@u72g2000cwu.googlegroups.com> Hi All - Thanks to everyone for their input. The repsonses provided are exactly what I was looking for! Regards - Shawn From jpellerin at gmail.com Sun Apr 30 20:00:07 2006 From: jpellerin at gmail.com (jpellerin+nose@gmail.com) Date: 30 Apr 2006 17:00:07 -0700 Subject: ANN: nose 0.9.0a1 Message-ID: <1146440898.118981.9570@v46g2000cwv.googlegroups.com> I'm pleased to announce the 0.9.0a1 release of nose, a test runner that brings py.test convenience to unittest, without resorting to (too much) magic. nose 0.9 includes a host of new features, as well as numerous backwards-incompatible changes to interfaces and implementation. For this reason, I'm releasing it first as an alpha version. Thanks to the many folks who have contributed patches and ideas and made bug reports for the development version of 0.9, especially Mika Eloranta, Jay Parlar, Kevin Dangoor, Scot Doyle and Philip J. Eby. Here's a quick rundown of what's new in 0.9.0a1. - Plugins The most important new feature is support for plugins using setuptools entrypoints. nose plugins can select and load tests (like the builtin doctest plugin), reject tests (like the builtin attrib plugin, contributed by Mika Eloranta, that allows users to select tests by attribute), watch and report on tests (like the builtin coverage and profiler plugins), completely replace test result output (like the html result plugin in the examples directory) or any combination of the above. Writing plugins is simple: subclass nose.plugins.Plugin and implement any of the methods in nose.plugins.IPluginInterface. - Better compatibility with unittest Test loading has been consolidated into a test loader class that is drop-in compatible with unittest.TestLoader. Likewise test result output, including output capture, assert introspection, and support for skipped and deprecated tests, in nose.result.TextTestResult. If you want those features and not the rest of nose, you can use just those classes. nose.main() has also been rewritten to have the same signature as unittest.main(). - Better command line interface Command line test selection is more intuitive and powerful, enabling easy and correct running of single tests while ensuring that fixtures (setup and teardown) are correctly executed at all levels. No more -f -m or -o options; now simply specify the tests to run: nosetests this/file.py that.module Tests may be specified down to the callable: nosetests this/file.py:TestClass that.module:this_test nosetests that.module:TestClass.test_method There are also new options for dropping into pdb on errors or failures, and stopping the test run on the first error or failure (thanks to Kevin Dangoor for the idea). - More! Helpful test decorators and functions in nose.tools. Support for generators in test classes. Better import path handling -- that you can shut off! Detailed verbose logging using the logging package. And more... For more information, installation instructions, etc, see: http://somethingaboutorange.com/mrl/projects/nose/ From aleaxit at yahoo.com Mon Apr 3 23:15:21 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 3 Apr 2006 19:15:21 -0800 Subject: MOO meets Python References: <1144095683.430864.44450@v46g2000cwv.googlegroups.com> Message-ID: <1hd8g01.1gtn9zxq78uojN%aleaxit@yahoo.com> Jonathan Ellis wrote: > Aahz wrote: > > http://playsh.org/ > > http://sourceforge.net/projects/playsh > > Damn, I thought you meant MOO as in Master of Orion. Naah, "Stars!", now *that* was a worthy game! Alex From duncan.booth at invalid.invalid Tue Apr 11 04:06:14 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 11 Apr 2006 08:06:14 GMT Subject: [Off topic] Re: Backing Up VMWare References: <1144727766.603611.226070@i40g2000cwc.googlegroups.com> <443b5dda$0$7236$79c14f64@nan-newsreader-06.noos.net> Message-ID: Franck Pommereau wrote: >> Hello - has anyone written a Python script to backup VMWare servers? >> If so, I'd appreciate any pointers as to how to go about doing so. > > Nothing to do with Python, but... Under Linux, VMware disks are > mountable using the script vmware-mount.pl, see: > > http://www.vmware.com/support/reference/linux/loopback_linux.html > and for windows users DiskMount (http://www.vmware.com/download/ws/) does a similar job (but you cannot mount a suspended machine so you would have to shut it down first). I guess though you want something which runs inside the virtual machine to backup just the files which have changed to a networked drive on the host machine or a CD/DVD drive? From wrongbad at gmail.com Mon Apr 17 17:40:58 2006 From: wrongbad at gmail.com (I V) Date: 17 Apr 2006 14:40:58 -0700 Subject: Missing interfaces in Python... In-Reply-To: <1145306373.781129.305840@z34g2000cwc.googlegroups.com> References: <1145306373.781129.305840@z34g2000cwc.googlegroups.com> Message-ID: <1145310058.584301.76320@g10g2000cwb.googlegroups.com> redefined.horizons at gmail.com wrote: > I see that Python is missing "interfaces". The concept of an interface > is a key to good programming design in Java, but I've read that they > aren't really necessary in Python. I am wondering what technique I can > use in Python to get the same benefits to a program design that I would > get with interfaces in Java. To use interfaces in python, just what you would do in Java, except don't use interfaces. To expand on that slightly Zen answer, think about why you use interfaces in Java. The interface declaration tells the compiler that your object implements a specific set of functions, or that your function expects an object that implements these functions. Then, at run time, the actual type of the object is used to decide what function to call. However, python doesn't to any type checking at compile time, so it just uses the dynamic type of the object to decide what function to call. > How would I approach this problem in Python? I think I would use an > abstract class instead of an interface for IFixable, since Python > supports multiple inheritance, but I'm not sure this is correct. Concretely: class Car: def fix(self): print "Your car is ready, sir" class Bus: def fix(self): print "Your bus is ready, sir" class Mechanic: def repair(self, customer, vehicle): vehicle.fix() customer.bill() class Customer: def bill(self): print "Ouch, that was expensive" me = Customer() my_bus = Bus() my_car = Car() m = Mechanic() m.repair(me, my_bus) m.repair(me, my_car) Which gives the output: Your bus is ready, sir Ouch, that was expensive Your car is ready, sir Ouch, that was expensive If you try and repair something that can't be fixed: m.repair(me, me) you get: Traceback (most recent call last): File "test.py", line 30, in ? m.repair(me, me) File "test.py", line 14, in repair vehicle.fix() AttributeError: Customer instance has no attribute 'fix' Obviously, you don't want this to happen when people use your program. Java would check this at compile time, but as python doesn't, you can write a unit test to check that the object's you want to implement the relevant functions really do. def is_fixable(obj): try: obj.fix except AttributeError: return False return True assert is_fixable(Car()) assert is_fixable(Bus()) assert not is_fixable(Customer()) assert not is_fixable(Mechanic()) From do_not_use_this_email at hotmail.com Wed Apr 19 15:28:57 2006 From: do_not_use_this_email at hotmail.com (rx) Date: Wed, 19 Apr 2006 21:28:57 +0200 Subject: multiline comments References: <1381517.XiSu08VAzt@jupiter.g2ctech> <1164308.fsspVXKdt2@jupiter.g2ctech> <44467cb4$0$4820$ba624c82@nntp02.dk.telia.net> <1296658.ifSUO08S9I@jupiter.g2ctech> <44468977$0$12401$ba624c82@nntp02.dk.telia.net> <1783712.Nhl0uzysWq@jupiter.g2ctech> Message-ID: <44468f7b$0$12399$ba624c82@nntp02.dk.telia.net> "Jorge Godoy" wrote in message news:1783712.Nhl0uzysWq at jupiter.g2ctech... > rx wrote: > >> I don't understand the problem - why should comments (and I hope you >> believe there should be a one line comment at least) be restricted to one >> line. It doesn't work that way for if, while, for. > > It is the minimum case that can solve a problem commenting one line -- or > part of it as in "print '3' # print the number 3" -- or commenting > multiple > lines. It is also easier to deal with since you don't have to end your > comment all the time. > > For "if", "while", "for", etc. you have ":" and the indentation. You > don't > have an "endif", "endwhile", "endfor" (so, why having an "end comment"?). > > -- > Jorge Godoy > There no reason why a multiple line comment couldn't be indented (then the indentation is the end of comment in some sense), but I don't find that logical - after all its my comment and I don't want python to tell me how to indent it. From kent at kentsjohnson.com Wed Apr 19 08:34:19 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Wed, 19 Apr 2006 08:34:19 -0400 Subject: http request with cookie sending In-Reply-To: <1145396274.746861.40330@i39g2000cwa.googlegroups.com> References: <1145396274.746861.40330@i39g2000cwa.googlegroups.com> Message-ID: <44462e31$1_1@newspeer2.tds.net> itay_k wrote: > Hi, > > I want to send a cookie on some http request (with urllib2), > so I created a Cookie but I cant associate it with CookieJar object. You have to use a cookielib.Cookie, not Cookie.SimpleCookie(): import cookielib, urllib2 cj = cookielib.CookieJar() cookie = cookielib.Cookie(...your cookie data here...) cj.set_cookie(cookie) opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) data = urllib2.urlopen(...).read() Kent From __peter__ at web.de Mon Apr 17 04:18:56 2006 From: __peter__ at web.de (Peter Otten) Date: Mon, 17 Apr 2006 10:18:56 +0200 Subject: __getattribute__ and __slots__ References: <1145006114.333157.129760@t31g2000cwb.googlegroups.com> Message-ID: pascal.parent at free.fr wrote: Python has both __getattribute__() and __getattr__(). While __getattribute__() will always be called if you ask for an attribute __getattr__() serves only as fallback if the attribute if not found by other means. > I try to define a (new-style) class who: > - have a __slots__ defined to be strict attributes, __slots__ is a performance/memory optimization. Using __slots__ to introduce bondage & discipline through the backdoor is against Python's spirit. > - return None if the attribute is 'ok' but not set, or raise a 'normal' > error if the attribute isn't in __slots__. The approach you have chosen is a very ineffective one. Why don't you just set the attribute to a default value in the initializer? > This code runs, but is it the good way? I don't think so... > class test(object): > __slots__ = ['id'] > def __getattr__(self, attr): > if not attr in self.__slots__: raise AttributeError > try: > return self.attr The line above does not do what you think it does. It just calls test_instance.__getattr__("attr"), and since "attr" is not in __slots__ it raises an AttributeError. > except: > return None You should get the same effect with >>> class T(object): ... __slots__ = ["id"] ... def __getattr__(self, name): ... if name not in self.__slots__: ... raise AttributeError ... return 42 # for better visibility ... >>> t = T() >>> t.id 42 >>> t.whatever Traceback (most recent call last): File "", line 1, in ? File "", line 5, in __getattr__ AttributeError >>> t.id = "something else" >>> t.id 'something else' >>> t.whatever = "something else" Traceback (most recent call last): File "", line 1, in ? AttributeError: 'T' object has no attribute 'whatever' Peter From dstcruz at gmail.com Fri Apr 21 01:32:09 2006 From: dstcruz at gmail.com (Daniel Santa Cruz) Date: 20 Apr 2006 22:32:09 -0700 Subject: Strategy Design Pattern Message-ID: <1145597529.217734.25600@g10g2000cwb.googlegroups.com> Hello all, I've been trying to go over my OO Patterns book, and I decided to try to implement them in Python this time around. I figured this would help me learn the language better. Well, I've gotten stuck with my first go at OO patterns with Python. I guess it goes without say that some of the stuff that are taken for granted in most of the books (ie. Interfaces, Abstract classes) don't really apply to Python per say, but the idea behind the patterns can be extracted out still. In the specific case of the Strategy pattern, I think the goal is to abstract out of the class an algorithm that can then be reused by some of the inherited classes. This way we don't repeat ourselves. Maybe I got this all wrong... I'm at a loss at how I can do this with Python, any pointers would be more than welcomed! To aid commenters... we can use the example used in "Head First Design Patterns". I've implemented this simple patter in Java and .NET... now in python. I can't draw UML here, so I'll try to pseudo talk what the example has: Abstract Base Class: Duck + FlyBehavior _fly + swim() + fly() -> calls _fly.fly() Interface: FlyBehavior + fly() Concrete Interface FlyHigh (implements FlyBehavior): + fly() Concrete Class Duck1 (Inherits Duck): + Constructor: _fly = new FlyHigh() Daniel. From jimlewis at miclog.com Sun Apr 16 07:53:31 2006 From: jimlewis at miclog.com (Jim Lewis) Date: 16 Apr 2006 04:53:31 -0700 Subject: String pattern matching References: <1143888648.234963.326000@j33g2000cwa.googlegroups.com> <443159e6$1_1@newspeer2.tds.net> Message-ID: <1145188411.127183.319700@j33g2000cwa.googlegroups.com> >You can do this with a regular expression... I tried the plain RE approach and found it no faster than my direct-coded version. Anyone have any ideas on how to code this problem elegantly without RE? My code is long and cumbersome - 200 lines! Speed is my primary concern but low LOC would be nice of course. The sezman approach above seems a bit complex. From Serge.Orlov at gmail.com Wed Apr 5 22:57:06 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 5 Apr 2006 19:57:06 -0700 Subject: =?iso-8859-1?q?Re:_urllib.urlencode_wrongly_encoding_=B1_character?= References: <1144287250.071811.296390@i39g2000cwa.googlegroups.com> Message-ID: <1144292226.017425.97420@i40g2000cwc.googlegroups.com> sleytr at gmail.com wrote: > Hi, I'm trying to make a gui for a web service. Site using ? > character in value of some fields. But I can't encode this character > properly. > > > >>> data = {'key':'?'} > >>> urllib.urlencode(data) > 'key=%C2%B1' > > but it should be only %B1 not %C2%B1. It should be %C2%B1, because de-facto urls are encoded as utf-8. I've just tried entering ? into four input field: firefox 1.5 search toolbar, www.google.com search in firefox 1.5, google toolbar in IE 6, www.google.com search in IE 6. Everywhere ? is encoded as %C2%B1. In older browsers YMMV. > where is this %C2 coming from? Your console must be utf-8. >>> u'?'.encode('utf-8') '\xc2\xb1' From sperlle at yahoo.com Tue Apr 4 21:03:10 2006 From: sperlle at yahoo.com (Michael Sperlle) Date: 5 Apr 2006 01:03:10 -0000 Subject: how to comment lot of lines in python References: <1143760897.940841.285300@i39g2000cwa.googlegroups.com> <1144194320.725889.228140@u72g2000cwu.googlegroups.com> Message-ID: <00A7FOGZ38812.3771990741@reece.net.au> What's wrong with using three sets of double-quotes? I do it with kwrite and it works like a charm. From danb_83 at yahoo.com Sun Apr 23 21:48:55 2006 From: danb_83 at yahoo.com (Dan Bishop) Date: 23 Apr 2006 18:48:55 -0700 Subject: bug in modulus? References: <1145807918.069455.241510@i40g2000cwc.googlegroups.com> <1145824389.832245.62600@t31g2000cwb.googlegroups.com> Message-ID: <1145843335.589624.184590@v46g2000cwv.googlegroups.com> jantod at gmail.com wrote: > Hmmm. I understand. I'd suggest that someone just drop a link from the > Library reference manual as the divmod entry over there seems to > contradict it. > > """ > divmod(a, b) > > Take two (non complex) numbers as arguments and return a pair of > numbers consisting of their quotient and remainder when using long > division. With mixed operand types, the rules for binary arithmetic > operators apply. For plain and long integers, the result is the same as > (a / b, a % b). For floating point numbers the result is (q, a % b), > where q is usually math.floor(a / b) but may be 1 less than that. In > any case q * b + a % b is very close to a, if a % b is non-zero it has > the same sign as b, and 0 <= abs(a % b) < abs(b). > """ > > But maybe I'm reading it wrong. In any case what I wanted was simply a > way to extract the angle from a complex number where the angle is > between 0 and 2*pi. I think I'll just take the modulus twice. If you absolutely insist on having the angle be less than 2*pi, you could always do something like: theta = min(theta, pi*2 - 2**(-50)) From mhoward736 at gmail.com Fri Apr 28 01:05:10 2006 From: mhoward736 at gmail.com (Mike Howard) Date: 27 Apr 2006 22:05:10 -0700 Subject: Help needed on COM issue In-Reply-To: References: Message-ID: <1146200710.275316.145680@v46g2000cwv.googlegroups.com> Thanks for the suggestions. I tried the tuple to list to tuple method with no success Its not a .Value issue either. In order to keep going I've left this code as vb for the moment From nobody at 127.0.0.1 Fri Apr 21 17:23:16 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Fri, 21 Apr 2006 21:23:16 GMT Subject: Jython: exec a string In-Reply-To: <1145652831.034969.204230@j33g2000cwa.googlegroups.com> References: <1145650854.705377.270060@v46g2000cwv.googlegroups.com> <1145652831.034969.204230@j33g2000cwa.googlegroups.com> Message-ID: <83c2g.70526$Jd.51613@newssvr25.news.prodigy.net> iirc java doesn't like multiple classes in a single file (not counting anonymous or inner classes). sounds like jython may have the same restriction... abcd wrote: > the error i get when i run the exec is, "java.lang.ClassFormatError"... > > thanks > From rupole at hotmail.com Wed Apr 19 14:23:07 2006 From: rupole at hotmail.com (Roger Upole) Date: Wed, 19 Apr 2006 14:23:07 -0400 Subject: pywin32 : scheduled weakup from standby/hiberate ? References: Message-ID: <1145470819_51227@sp6iad.superfeed.net> ."robert" wrote in message news:e230eo$k8u$1 at ulysses.news.tiscali.de... > On Windows the task scheduler tool can program (the BIOS?) to weak up the machine from standby/hibernate at certain > pre-configured times. Can this be done directly through the (py)win32 API? > > robert Pywin32 has a taskscheduler module that can be used to create a scheduled task to wake up your system. The TASK_FLAG_SYSTEM_REQUIRED flag corresponds to the "Wake the system to run this task" option in the UI. hth Roger ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= East/West-Coast Server Farms - Total Privacy via Encryption =--- From arv.nntp at gmail.com Thu Apr 20 18:53:56 2006 From: arv.nntp at gmail.com (Alexis Roda) Date: Fri, 21 Apr 2006 00:53:56 +0200 Subject: Confused about properties, descriptors, and attributes... In-Reply-To: <1145562065.423388.9410@v46g2000cwv.googlegroups.com> References: <1145562065.423388.9410@v46g2000cwv.googlegroups.com> Message-ID: redefined.horizons at gmail.com escribi?: > I've been reading about Python Classes, and I'm a little confused about > how Python stores the state of an object. I was hoping for some help. > > I realize that you can't create an empty place holder for a member > variable of a Python object. It has to be given a value when defined, > or set within a method. I don't understand what do you mean with "empty place holder". Some pre-allocated-and-uninitialized memory to hold the attribute value (ala C++ o java)? Maybe slots? >>> class Foo(object) : ... __slots__ = ['foo'] ... >>> f=Foo() >>> dir(f) ['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__slots__', '__str__', 'foo'] >>> f.foo Traceback (most recent call last): File "", line 1, in ? AttributeError: foo >>> f.foo = 3 >>> dir(f) ['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__slots__', '__str__', 'foo'] >>> f.foo 3 > But what is the difference between an Attribute of a Class, a > Descriptor in a Class, and a Property in a Class? I don't know what the formal definitions are. Probably "attribute" refers to anything that can be obtained by way of getattr(). According to this "definition" an attribute does not require to be stored in the instance, it can be calculated or obtained from somewhere else. >>> class SimpleExample : ... def __getattr__(self, name) : ... if name=='attr' : ... return 0 ... raise AttributeError(name) ... >>> s = SimpleExample() >>> s.attr 0 >>> s.bar Traceback (most recent call last): File "", line 1, in ? File "", line 5, in __getattr__ AttributeError: bar descriptors are a mechanism/protocol for attribute access. It's intended to solve some problems of the original __getattr__() protocol. A property is a specialized type of descriptor which allows customization of attribute's access methods. > If I had a Monster Class, and I wanted to give each Monster a member > variable called ScaryFactor, how would I define it? If you're asking when to use plain attributes, descriptors or properties the answer is that it depends on what you want/need: * if you store monsters in a database and the ScaryFactor attribute is computed by some complex and expensive database lookup I'll go for some kind of lazy descriptor/property * if you want to be able to control/limit what can be done with an attribute may be a property is enough. This includes things like make the attribute read only etc. * if you don't have special requirements a plain attribute would be probably simpler and faster > Does a Property > simply provide methods that access an Attribute? not exactly, it allows you to assign/define the methods that will be used to access the attribute, but you still access to the attribute in the usual "dot-way". For further info take a look at: http://www.python.org/doc/newstyle/ HTH From bblais at bryant.edu Mon Apr 3 14:27:49 2006 From: bblais at bryant.edu (Brian Blais) Date: Mon, 03 Apr 2006 14:27:49 -0400 Subject: Vacuum World version 1e-6alpha ;) released Message-ID: <44316925.2010601@bryant.edu> Hello, I am just learning Python, and my first somewhat significant project is now available at http://web.bryant.edu/~bblais/python/vac.tgz What is it? Vacuum World is a simple simulation environment used to introduce some concepts in Artificial Intelligence (Norvig, 2002), but can also be used as a simple introduction to a programming language. In this case, of course, it is in Python. You write python scripts to control a vacuum cleaner in a simulated room of dirt and furniture, trying to vacuum up as much dirt and get back home to turn off. I've used wax to make a nice gui for running the simulator. A sample agent might look like: Forward() if IsDirt(): Vacuum() Off() Some Questions: As I was making this, I had a number of issues. I invite anyone who cares to look at the code to give me feedback about anything from GUI development, to code organization, or anything else. I have a few questions right off the bat: 1) how is code like this usually distributed? Does one make a setup.py to install it somewhere, and are there certain files that should be in the distribution that I don't have? Should it include a windows binary from py2exe too? 2) I had some problems getting the center panel to fit right. I'd like to have it so that when I resize the board, that the window grows and shrinks to the right size, down to a minimum size (so I can still see the menus). I could do this, using the Fit() method, but I found at the smaller sizes the individual images in the panel started to have large (and growing) spaces between them. I'd rather the whole board be centered in the panel. I tried every combination of Pack() and Fit() and expand=... and align=... , but couldn't get it to work. 3) what sorts of documentation are standard for this? is there a standard way of formatting docstrings (and am I thinking correctly that docstrings are just the quoted strings right after a function declaration?)? I'm sure that I will have more, but answers to these questions will get me a long way. Let me know what you think! Please be gentle, because this is really my first somewhat significant python project, so there is probably some cruft from my Matlab and C experience (stray semi-colons here and there, etc.) thanks, Brian Blais -- ----------------- bblais at bryant.edu http://web.bryant.edu/~bblais From enterr at gmail.com Wed Apr 19 01:41:51 2006 From: enterr at gmail.com (Atanas Banov) Date: 18 Apr 2006 22:41:51 -0700 Subject: multiline comments In-Reply-To: References: Message-ID: <1145425311.771598.140970@i40g2000cwc.googlegroups.com> Edward Elliott wrote: > At the risk of flogging a dead horse, I'm wondering why Python doesn't have > any multiline comments. One can abuse triple-quotes for that purpose, but > that's obviously not what it's for and doesn't nest properly. ... > Saying coders shouldn't use multiline comments to disable code misses the > point. Coders will comment out code regardless of the existence of > multiline comemnts. There has to be a better argument for leaving them out. i beg to differ: you'd be surprised how much effect can little inconveniences have. want to comment block of code? use tripple-quotes. does not nest? ahhh, maybe it's time to get rid of that block you commented out a month ago "just in case the new code doesnt work". that gives you incentive to tidy up. don't be a code slob... don't leave a mess forever ;-) From pascal.parent at free.fr Fri Apr 14 05:15:14 2006 From: pascal.parent at free.fr (pascal.parent at free.fr) Date: 14 Apr 2006 02:15:14 -0700 Subject: __getattribute__ and __slots__ Message-ID: <1145006114.333157.129760@t31g2000cwb.googlegroups.com> Hi, I try to define a (new-style) class who: - have a __slots__ defined to be strict attributes, - return None if the attribute is 'ok' but not set, or raise a 'normal' error if the attribute isn't in __slots__. This code runs, but is it the good way? Thanks. class test(object): __slots__ = ['id'] def __getattr__(self, attr): if not attr in self.__slots__: raise AttributeError try: return self.attr except: return None From do_not_use_this_email at hotmail.com Wed Apr 19 13:41:39 2006 From: do_not_use_this_email at hotmail.com (rx) Date: Wed, 19 Apr 2006 19:41:39 +0200 Subject: multiline comments References: <1145425311.771598.140970@i40g2000cwc.googlegroups.com> Message-ID: <44467656$0$9301$ba624c82@nntp02.dk.telia.net> "Edward Elliott" wrote in message news:URk1g.72511$dW3.48789 at newssvr21.news.prodigy.com... > Ben Finney wrote: >> Indeed. Using revision control means never needing to comment out >> blocks of code. > > Typing (* and *) on a few line will always be quicker, easier, and less > confusing than any rcs diffs/restores. Once you delete the code you can > no longer see it or add pieces back in without retrieving it from an > external store. I'm not saying nested comments solve every problem, just > that there exists a certain (perhaps small) class of problems they solve > particularly well. > > Personally, I rarely leave code commented out beyond a single coding > session. But my particular coding habits aren't relevant here. Well I perfectly agree, and why make a dependence on external tools (IDE/CVS) if you can build it into the language with no conflicts by using some strange ascii combinations. I'm sure something like: a() (# b() c() #) d() would be fine. From cfriedalek at gmail.com Wed Apr 19 02:02:10 2006 From: cfriedalek at gmail.com (cfriedalek at gmail.com) Date: 18 Apr 2006 23:02:10 -0700 Subject: win32com Excel bug? Message-ID: <1145426529.989164.212450@g10g2000cwb.googlegroups.com> I'm driving Excel from python, largely successfully. Now I'm trying to add errorbars to XY scatter plots. Keep getting a com_error. Can't track down the problem. I modified a simple example to duplicate the problem. Thanks to Mathieu Fenniak http://www.stompstompstomp.com/weblog/entries/67/ for the code. The traceback is shown below. You can see that the Excel chart series has a method called ErrorBar. But when I try to use it with any or all of its allowed arguments, it fails. The traceback goes into the guts of win32com but I don't really have a clue at that point. (Happy to learn something new though). The relevant Excel VBA language doc is here. http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbaxl11/html/xlmthErrorBar1_HV03076818.asp Hope someone can help. Losing hair .... fast! In [16]: %run test.py --Return-- > c:\python23\lib\pdb.py(992)set_trace()->None -> Pdb().set_trace() (Pdb) c There's a method waiting --------------------------------------------------------------------------- pywintypes.com_error Traceback (most recent call last) c:\temp\mpival\test.py 79 80 # A simple example: ---> 81 plot( (1,2,3,4,5), (6,7,8,9,10) ) 82 83 # Some more data: c:\temp\mpival\test.py in plot(x, y, xAxisLog, yAxisLog) 35 if series.ErrorBar: 36 print "There's a method waiting" ---> 37 series.ErrorBar(Direction = constants.xlY) 38 39 C:\Python23\lib\site-packages\win32com\gen_py\00020813-0000-0000-C000-0000000000 46x0x1x4.py in ErrorBar(self, Direction, Include, Type, Amount, MinusValues) 22722 , MinusValues=defaultNamedOptArg): 22723 return self._ApplyTypes_(152, 1, (12, 0), ((3, 1), (3, 1 ), (3, 1), (12, 17), (12, 17)), 'ErrorBar', None,Direction > 22724 , Include, Type, Amount, MinusValues) 22725 22726 def Paste(self): C:\Python23\lib\site-packages\win32com\client\__init__.py in _ApplyTypes_(self, dispid, wFlags, retType, argTypes, user, resultCLSID, *args) 444 def _ApplyTypes_(self, dispid, wFlags, retType, argTypes, user, 445 resultCLSID, *args): --> 446 return self._get_good_object_( 447 self._oleobj_.InvokeTypes( 448 dispid, 0, wFlags, retType, argTypes, *arg s), com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', 'ErrorBar method of Series class failed', 'C:\\Program Files (x86)\\Microsoft Office\\Off ice10\\1033\\xlmain10.chm', 0, -2146827284), None) WARNING: Failure executing file: From godoy at ieee.org Tue Apr 18 13:42:38 2006 From: godoy at ieee.org (Jorge Godoy) Date: Tue, 18 Apr 2006 14:42:38 -0300 Subject: 2.5 excitement (was Re: Java Developer Exploring Python) References: <1145290449.735642.120860@i40g2000cwc.googlegroups.com> <1145292795.565277.288760@v46g2000cwv.googlegroups.com> <1hdyb46.1yllkst1o2asjlN%aleaxit@yahoo.com> Message-ID: <1204021.LzRF60KP7e@jupiter.g2ctech> Aahz wrote: > In article , > Roy Smith wrote: >>Indeed, I think the inclusion of ctypes is far and away the most exciting >>thing in 2.5. > > Really? More than pysqlite? To me much more. After all, why would I need pysqlite if I use PostgreSQL? ;-) /me remembering the old days of Clipper Summer '87, when he'd use DBFs all over... ;-) -- Jorge Godoy "Quidquid latine dictum sit, altum sonatur." - Qualquer coisa dita em latim soa profundo. - Anything said in Latin sounds smart. From deets at nospam.web.de Fri Apr 14 14:33:50 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 14 Apr 2006 20:33:50 +0200 Subject: skip item in list "for loop" In-Reply-To: <1145038171.945758.256600@j33g2000cwa.googlegroups.com> References: <1145038171.945758.256600@j33g2000cwa.googlegroups.com> Message-ID: <4aa88dFs6u2cU1@uni-berlin.de> Jacob Rael schrieb: > I am new to python and I love it. I am hacking a file. I want to not > print a line if it contains the word 'pmos4_highv'. I also don't want > to print the next line. The following code works but it "smells bad" > and just doesn't look right. I was reading about generators. If I was > using one, I could do a .next() after the match and get rid of the > flags. Any suggestions how I can improve this? A generator certainly would be handy: def read_lines(inFile): fg = iter(inFile) for line in fg: if "pmos4_highv" in line: fg.next() else: yield line lines = """a b c d pmos4_highv no no! e f g""".split("\n") for line in read_lines(lines): print line Diez From python.list at tim.thechases.com Wed Apr 12 15:47:35 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 12 Apr 2006 14:47:35 -0500 Subject: Regular Expressions In-Reply-To: <9583ed900604121205o5da84b0crd2ae671c0b6a4395@mail.gmail.com> References: <9583ed900604121205o5da84b0crd2ae671c0b6a4395@mail.gmail.com> Message-ID: <443D5957.7070801@tim.thechases.com> > I am trying to grab the following string out of a text file using regular > expression (re module): While I'm all for using regexps when they're needed, are you sure you need the overhead of regexps? f = open("foo.txt", "r") for line in f.readlines(): # if '"DcaVer"=dword:' in line: if line.startswith('"DcaVer"=dword:'): value = int(line.split(":", 1)[-1], 16) print value f.close() If you absolutely must use a regexp, import re f = open("foo", "r") r = re.compile(r'"DcaVer"=dword:([0-9a-fA-F]{7})') for line in f.readlines(): m = r.match(line) if m: value = int(m.group(1), 16) print value f.close() should do the trick for you. This assumes that each string of hex digits has seven characters. Adjust accordingly. -tim From DavidRushby at gmail.com Wed Apr 5 21:20:26 2006 From: DavidRushby at gmail.com (David Rushby) Date: 5 Apr 2006 18:20:26 -0700 Subject: kinterbas and Python References: <1144169752.389326@anc-srv.fastnet.it> Message-ID: <1144286425.983622.311530@j33g2000cwa.googlegroups.com> Balin wrote: > Hi all, > I have some problem with packege kinterbas for Firebird db connection > this is my code: > > import kinterbasdb > > class ConnessioneDB: > def initialize(self): > kinterbasdb.init(concurrency_level=1) > con = kinterbasdb.connect(host='192.168.1.20', > database='/home/db/TEST.FDB', user='SYSDBA', password='masterkey) <--- E If that's the actual code you're using, presumably you're getting an error message like: SyntaxError: EOL while scanning single-quoted string because there's no closing quote after 'masterkey. If that's not the actual code, could you post the actual code, the actual error message, along with the versions of Python, Firebird, KInterbasDB, and your operating system? From cesugden at gmail.com Thu Apr 27 19:50:48 2006 From: cesugden at gmail.com (Chris) Date: 27 Apr 2006 16:50:48 -0700 Subject: Converstion Message-ID: <1146181848.615239.281200@j33g2000cwa.googlegroups.com> In a program I'm writing I have a problem where a bit of text sent over a network arrives at my server. If the person who sent the text made a mistake typing the word and pressed backspace the backspace code is included in the word for example hello is hel\x08lo. The \x08 is the backspace key. How do I convert this string to a normal string (without the \x08). If I print it to screen it appears normal, "hello" but if I store it in a list it appears as hel\x08lo. From pythor at gmail.com Tue Apr 4 15:15:39 2006 From: pythor at gmail.com (Pythor) Date: 4 Apr 2006 12:15:39 -0700 Subject: how do you use pickle? References: <1144167350.837406.172430@i39g2000cwa.googlegroups.com> <1144169459.630621.240510@i40g2000cwc.googlegroups.com> <1144170857.069178.115440@i39g2000cwa.googlegroups.com> Message-ID: <1144178139.765305.191440@e56g2000cwe.googlegroups.com> John Salerno wrote: > John Salerno wrote: > > Pythor wrote: > > > >> Whis is why I said carefully ;) I missed it several times myself when > >> I was working on the challenge. > > > > Ok, frustration has set in again. I see the file name in the source > > code, but am I meant to actually access a file, or just use the name > > itself? I also had to look up what 'banner' meant in Unix, which wasn't > > a very fun thing to have to do for a Python puzzle. > > Ah, I should have known we weren't done with URL manipulation yet. Now I > just need to figure out what to do with this source code. Incidentally, there's a forum specifically for posting an receiving hints on the challenges here: http://www.pythonchallenge.com/forums/viewforum.php?f=1 Not that I mind helping. ;) From ag at mirada-solutions.com Mon Apr 10 11:38:47 2006 From: ag at mirada-solutions.com (Alexandre Guimond) Date: 10 Apr 2006 08:38:47 -0700 Subject: python interpreter widget for Tkinter? Message-ID: <1144683527.705418.240140@z34g2000cwc.googlegroups.com> Hi i was wondering if there already existed a simple python interpreter widget for tkinter? Basically, i would like to be able to lauch a python interpreter in a seperate window from my tkinter app for debugging purposes. I would assume that this would be possible using idlelib, but i can't figure out how. Does anyone know how to do this? thx for any help alex From david at boddie.org.uk Tue Apr 11 12:23:26 2006 From: david at boddie.org.uk (David Boddie) Date: 11 Apr 2006 09:23:26 -0700 Subject: Removing an item from a QListView in PyQt References: <1144769597.763389.67500@j33g2000cwa.googlegroups.com> Message-ID: <1144772606.340377.290120@i40g2000cwc.googlegroups.com> Svenn Bjerkem wrote: > In a dialog I have a QListView called referenceList. Entries are added > and deleted from this list with buttons addButton and removeButton > connected with sockets: [...] > def removeReferenceSlot(self): > print "selected has address %s" % (self.referenceList.selectedItem()) > self.referenceList.removeChild(self.referenceList.selectedItem()) > ---- > Adding Items by pressing the addButton works fine. I then select one of > the list elements and press the removeButton. This is the output I get. > > selected has address > Traceback (most recent call last): > File "./idea_input.py", line 20, in removeReferenceSlot > self.referenceList.removeChild(self.referenceList.selectedItem()) > TypeError: argument 1 of QScrollView.removeChild() has an invalid type That's because removeChild() is a QScrollView method. You can call this method because QListView inherits it from QScrollView, but it's not the method you're looking for. > I see that I have an address of a QListViewItem, but I am not able to > delete it. What am I obviously doing wrong here? You need to call your QListView instance's takeItem() method with the item you want to remove as the argument. Hope this helps, David From tgrav at mac.com Tue Apr 25 15:44:06 2006 From: tgrav at mac.com (Tommy Grav) Date: Tue, 25 Apr 2006 15:44:06 -0400 Subject: pCFITSIO problems In-Reply-To: <1145965796.432891.274310@i39g2000cwa.googlegroups.com> References: <1145965796.432891.274310@i39g2000cwa.googlegroups.com> Message-ID: I am trying to install pCFITSIO on my Mac (Mac OS X.4. Numarray is already installed and imports fine in python (ActivePhyton v2.4.2), but when I try to build pCFITSIO it fails in finding a number of .h files for numarray. > [tgravi] Desktop/pCFITSIO-0.99.3 ->python setup.py build > running build > running build_py > running build_ext > building 'pcfitsio' extension > gcc -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno- > fused-madd -fPIC -fno-common -dynamic -DNDEBUG -g -O3 -Wall - > Wstrict-prototypes -I/usr/local/cfitsio/include/ -I/Library/ > Frameworks/Python.framework/Versions/2.4/include/python2.4 -c > pcfitsio_wrap.c -o build/temp.darwin-8.6.0-Power_Macintosh-2.4/ > pcfitsio_wrap.o > In file included from /Library/Frameworks/Python.framework/Versions/ > 2.4/include/python2.4/Python.h:55, > from pcfitsio_wrap.c:50: > /Library/Frameworks/Python.framework/Versions/2.4/include/python2.4/ > pyport.h:396: warning: 'struct winsize' declared inside parameter list > /Library/Frameworks/Python.framework/Versions/2.4/include/python2.4/ > pyport.h:397: warning: 'struct winsize' declared inside parameter list > In file included from pcfitsio_wrap.c:566: > fitsio.h:2:34: error: numarray/arrayobject.h: No such file or > directory But it does not seem like numarray left any files like this on the system. Anyone run into this problem as well and know of a fix? Or is there another fits extension out there? Cheers Tommy tgrav at mac.com http://homepage.mac.com/tgrav/ "Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius -- and a lot of courage -- to move in the opposite direction" -- Albert Einstein -------------- next part -------------- An HTML attachment was scrubbed... URL: From vivainio at gmail.com Tue Apr 11 12:55:44 2006 From: vivainio at gmail.com (Ville Vainio) Date: 11 Apr 2006 09:55:44 -0700 Subject: list.clear() missing?!? References: <1144767680.583085.310160@v46g2000cwv.googlegroups.com> Message-ID: <1144774544.177184.171080@u72g2000cwu.googlegroups.com> Steven Bethard wrote: > If you feel really strongly about this though, you might consider > writing up a PEP. It's been contentious enough that there's not much > chance of getting a change without one. No strong feelings here, and I'm sure greater minds than me have already hashed this over sufficiently. It's just that, when I have an object, and am wondering how I can clear it, I tend to look what methods it has first and go to google looking for "idioms" second. Perhaps "clear" method could be added that raises PedagogicException("Use del lst[:], stupid!")? *ducks* From nephish at xit.net Sat Apr 22 18:46:59 2006 From: nephish at xit.net (nephish at xit.net) Date: 22 Apr 2006 15:46:59 -0700 Subject: need a thread to keep a socket connection alive? In-Reply-To: <1llk425397ed7qj6jr0tk915pd1crpbprq@4ax.com> References: <1145718638.526525.235090@i39g2000cwa.googlegroups.com> <1llk425397ed7qj6jr0tk915pd1crpbprq@4ax.com> Message-ID: <1145746019.929704.60690@e56g2000cwe.googlegroups.com> thanks for the info, i will likely use the first link you posted with the async module just to get it going, but i want to learn more about twisted for later. there is even an O'Reilly book on it i see. thanks for the tips, sk From nogradi at gmail.com Mon Apr 3 18:09:35 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Tue, 4 Apr 2006 00:09:35 +0200 Subject: [ANN] markup.py - 1.2 - an HTML/XML generator Message-ID: <5f56302b0604031509r51af902dh2e908561bbf78d44@mail.gmail.com> A new release of markup.py is available at the sourceforge project page: http://sourceforge.net/projects/markup/ Markup.py is a set of classes that attempts to make it easier to generate HTML/XML from a Python program in an intuitive, light-weight, customizable and pythonic way. Full documentation and examples are available at http://markup.sourceforge.net A quick example: # example for markup.py import markup items = ( "Item one", "Item two", "Item three", "Item four" ) paras = ( "This was a fantastic list.", "And now for something completely different." ) images = ( "thumb1.jpg", "thumb2.jpg", "more.jpg", "more2.jpg" ) page = markup.page( ) page.init( title="My title", css=( 'one.css', 'two.css' ), header="Something at the top", footer="The bitter end." ) page.ul.open( klass='mylist' ) page.li( items, klass='myitem' ) page.ul.close( ) page.p( paras ) page.img( src=images, width=100, height=80, alt="Thumbnails" ) print page # end of example The above code would produce My title Something at the top
  • Item one
  • Item two
  • Item three
  • Item four

This was a fantastic list.

And now for something completely different.

Thumbnails Thumbnails Thumbnails Thumbnails The bitter end. From deets at nospam.web.de Mon Apr 24 13:15:19 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 24 Apr 2006 19:15:19 +0200 Subject: threads and sys.exit() References: <1145897992.091952.326970@e56g2000cwe.googlegroups.com> Message-ID: <4b4fdaFv61niU1@uni-berlin.de> gangesmaster wrote: > calling sys.exit() from a thread does nothing... the thread dies, but > the interpreter remains. i guess the interpreter just catches and > ignore the SystemExit exception... > > does anybody know of a way to overcome this limitation? Use Thread.setDaemon(True) on your threads. diez From rpdooling at gmail.com Sun Apr 16 13:44:35 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 16 Apr 2006 10:44:35 -0700 Subject: keyboard command to break out of infinite loop? References: <1145174364.436843.26660@e56g2000cwe.googlegroups.com> <1145189296.491399.83350@i40g2000cwc.googlegroups.com> Message-ID: <1145209475.375824.8560@e56g2000cwe.googlegroups.com> Thank you, both. I'll put in on a sticky! rick From me+python at modelnine.org Fri Apr 21 08:02:42 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Fri, 21 Apr 2006 14:02:42 +0200 Subject: ANN: Pyrr 0.1 - Lexer and LR(1)-Parser Generator for Python Message-ID: <200604211402.42751.me+python@modelnine.org> Hi list! Not long ago I was looking for an easy to use, but powerful parser and lexer generating tool for Python, and to my dismay, I found quite a number of Python projects implementing an (LA)LR(1) parser generator, but none of them seemed quite finished, or even pythonic. As I required a parser generator for Python for one of my work projects, I set out to write (yet another one), and currently am at (release-)version 0.1 for Pyrr.ltk and ptk. An example for Pyrr.ltk and ptk usage implementing a (very) simple calculator: <<< # -*- coding: iso-8859-15 -*- from ltk import LexerBase, IgnoreMatch from ptk import ParserBase from operator import add, sub, mul, div class NumLexer(LexerBase): def number(self,value): """number -> r/[0-9]+/""" return float(value) def ws(self,*args): """ws -> r/\\s+/""" raise IgnoreMatch def ops(self,op): """addop -> /+/ -> /-/ mulop -> /*/ -> r/\\//""" return op class NumParser(ParserBase): """/mulop/: left /addop/: left""" __start__ = "term" def term(self,value1,op,value2): """term -> term /addop/ term -> term /mulop/ term""" return {"+":add,"-":sub,"*":mul,"/":div}[op](value1,value2) def value(self,value): """term -> /number/""" return value print NumParser.parse(NumLexer.tokenize("3 + 4 - 123 / 23")) <<< Grammar rules and lexemes are specified in docstrings, where lines not matching a definition of a rule or lexeme are ignored. The resulting lexer and parser class is, thus, very much self-documenting, which was one of my biggest goals for the project. I'm currently in the process of writing documentation for both packages (and especially documenting the extensions to BNF-grammars that Pyrr.ptk allows, such as your usual RE-operators ?, *, + and {x,y}, and forward arguments, and documenting the stateful lexer support that Pyrr.ltk implements), but I thought that I'd release early and often, so that people interested in this project might have a look at it now to input suggestions and extensions that they'd like me to add to make this a fully featured Python parser generating toolkit which might be offered as a Python package. Anyway, the sources can be downloaded (via subversion) from: http://svn.modelnine.org/svn/Pyrr/trunk where I'll check in the documentation that I've written so far and a Python distutils distribution over the weekend, and make sure that I don't check in brocken code from now on. And, Pyrr.* is Python 2.4 only at the moment, and I have no plans to make it backwards-compatible, but if you're interested in backporting it, feel free to mail me patches. --- Heiko. From stormandstress at gmail.com Sat Apr 8 23:10:37 2006 From: stormandstress at gmail.com (stormandstress at gmail.com) Date: 8 Apr 2006 20:10:37 -0700 Subject: Curses and Character Handling In-Reply-To: <1144551633.071194.33920@z34g2000cwc.googlegroups.com> References: <1144550778.549805.19820@v46g2000cwv.googlegroups.com> <1144551633.071194.33920@z34g2000cwc.googlegroups.com> Message-ID: <1144552237.704354.306250@t31g2000cwb.googlegroups.com> Thank you very much. From cygnus at cprogrammer.org Mon Apr 17 17:05:41 2006 From: cygnus at cprogrammer.org (Jonathan Daugherty) Date: Mon, 17 Apr 2006 14:05:41 -0700 Subject: Missing interfaces in Python... In-Reply-To: References: <1145306373.781129.305840@z34g2000cwc.googlegroups.com> Message-ID: <20060417210541.GV7561@vulcan.cprogrammer.org> # In Python, you would simply call the functions you need. No need to # make things that rigidly defined. Except when you need to handle exceptions when those methods don't exist. I think interfaces can definitely be useful. -- Jonathan Daugherty http://www.parsed.org From steven.bethard at gmail.com Sat Apr 29 20:37:20 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 29 Apr 2006 18:37:20 -0600 Subject: best way to determine sequence ordering? In-Reply-To: <70q4g.2006$No6.43783@news.tufts.edu> References: <70q4g.2006$No6.43783@news.tufts.edu> Message-ID: <2eqdnbgOAqcjm8nZnZ2dnUVZ_umdnZ2d@comcast.com> John Salerno wrote: > If I want to make a list of four items, e.g. L = ['C', 'A', 'D', 'B'], > and then figure out if a certain element precedes another element, what > would be the best way to do that? > > Looking at the built-in list functions, I thought I could do something > like: > > if L.index('A') < L.index('D'): > # do some stuff Ok, since, as happens some times, the discussion here has gotten extremely sidetracked from the original question, as a public service ;) I thought I'd give a brief summary of the options discussed and when they might be useful: * The original:: if L.index('A') < L.index('D'): # do some stuff If you're doing exactly one comparison, this is probably your best bet in most cases as .index() is coded in C. It's clear, concise and correct. * Justin Azoff's before():: def before(lst, a, b): for x in lst: if x == a: return True if x == b: return False if before(L, 'A', 'D'): # do some stuff You might gain a bit from this version if one of the elements you're looking for appears early in the list. It only iterates through the list once, but performs two comparisons each time, so you'll only gain from it if you comparisons aren't too costly (e.g. you're comparing single character strings). * building a dict of indicies:: positions = dict((item, i) for i, item in enumerate(L)) if positions['A'] < positions['D']: # do some stuff You'll only get a gain from this version if you need to do several comparisons instead of just one. And most importantly, as Edward Elliot put it: Remember kids: 1. Numbers can show anything 2. Know your data set 3. Premature optimizations are evil HTH, STeVe From mtobis at gmail.com Fri Apr 21 18:46:40 2006 From: mtobis at gmail.com (Michael Tobis) Date: 21 Apr 2006 15:46:40 -0700 Subject: proposed Python logo In-Reply-To: <124i8176of81331@corp.supernews.com> References: <1145585399.871299.31900@t31g2000cwb.googlegroups.com> <1145628079.749480.191190@g10g2000cwb.googlegroups.com> <124hqel51rur33b@corp.supernews.com> <1145640106.269556.276060@u72g2000cwu.googlegroups.com> <124i8176of81331@corp.supernews.com> Message-ID: <1145659600.115550.270520@e56g2000cwe.googlegroups.com> A more Monty sort of Python logo would be fine with me. A flying sheep perhaps? An exploding penguin? A giant hedgehog? A dog license with the word "dog" crossed out and "cat" written in crayon? A great big book on how to put your budgie down? This http://www.informatik.uni-trier.de/~roth/bilder/mpfc/GUMBY3.JPG chap? I'm not sure that conveys the intended gravitas to the corporate community, though. mt From gene.tani at gmail.com Tue Apr 4 13:21:56 2006 From: gene.tani at gmail.com (gene tani) Date: 4 Apr 2006 10:21:56 -0700 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Apr 4) In-Reply-To: References: Message-ID: <1144171316.283001.151290@i39g2000cwa.googlegroups.com> Peter Otten wrote: > The old Python "To-Do List" now lives principally in a > SourceForge reincarnation. > http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse > http://python.sourceforge.net/peps/pep-0042.html > Thanks, very nice summary. One thing, the peps moved: http://www.python.org/dev/peps/pep-0042/ From nobody at 127.0.0.1 Sun Apr 23 18:56:49 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Sun, 23 Apr 2006 22:56:49 GMT Subject: getattr from local scope In-Reply-To: <1he96ru.12l8tuv1tphnddN%aleaxit@yahoo.com> References: <1145827050.347326.84980@t31g2000cwb.googlegroups.com> <1he96ru.12l8tuv1tphnddN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > sys.modules[__name__].__dict__ may be more handily accessed by the > built-in function globals(). Well there you go. Glad it's not that awkward. From amorgan at xenon.Stanford.EDU Wed Apr 5 19:24:18 2006 From: amorgan at xenon.Stanford.EDU (Alan Morgan) Date: Wed, 5 Apr 2006 16:24:18 -0700 (PDT) Subject: efficiency of range() and xrange() in for loops References: Message-ID: In article , Georg Brandl wrote: >Alan Morgan wrote: >> In article , >> Giovanni Bajo wrote: >>>Steve R. Hastings wrote: >>> >>>>> in Python 2.X, range is defined to return a list. if you start >>>>> returning something else, you'll break stuff. >>>> >>>> Perhaps I'm mistaken here, but I don't see how this optimization could >>>> possibly break anything. >>> >>>Because you assume that the only use-case of range() is within a for-loop. >>>range() is a builtin function that can be used in any Python expression. For >>>instance: >>> >>>RED, GREEN, BLUE, WHITE, BLACK = range(5) >> >> Hmmm, this worked fine when I used xrange as well. Am I missing something? >> Obviously there *are* differences, viz: > >Just _look_ at the objects: > >>>> range(5) >[0, 1, 2, 3, 4] >>>> xrange(5) >xrange(5) >>>> Yes, I was well aware of this. I noted a difference in my original post. I was just pointing out that the example given didn't, in fact, behave differently for range() and xrange() even though range() and xrange() *are* different. >range is giving you a real list, while xrange is giving you an xrange object. >Have you tried to slice an xrange object? Or using .append on it? No, I hadn't. I presume these could all be defined. Alan -- Defendit numerus From DailyLama at gmail.com Mon Apr 3 07:06:28 2006 From: DailyLama at gmail.com (Daily Lama) Date: 3 Apr 2006 04:06:28 -0700 Subject: beautiful GUI Message-ID: <1144062388.699313.138160@j33g2000cwa.googlegroups.com> Hello, is there a way to create nice good-looking Form for Windows; I mean not the windows-style form, but something cute, like mac os forms with their coloured red-yellow-green buttons From greg.kujawa at gmail.com Tue Apr 11 10:19:51 2006 From: greg.kujawa at gmail.com (gregarican) Date: 11 Apr 2006 07:19:51 -0700 Subject: how relevant is C today? References: <44381ee4$0$4209$c3e8da3@news.astraweb.com> <44382711.10403@v.loewis.de> <44393fbe$0$19226$c3e8da3@news.astraweb.com> <44398651$0$4206$c3e8da3@news.astraweb.com> <1144632983.039143.203330@u72g2000cwu.googlegroups.com> <443a4e8a$0$21013$626a54ce@news.free.fr> <443b9b91$0$27077$626a54ce@news.free.fr> Message-ID: <1144765191.225146.130140@u72g2000cwu.googlegroups.com> bruno wrote: > Err... > And ? It's the snide, curt replies such as your recent ones in this thread that reinforce the generalization that the Python community can be rude. From invalidemail at aerojockey.com Sun Apr 9 21:06:03 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 9 Apr 2006 18:06:03 -0700 Subject: Decorators, Identity functions and execution... In-Reply-To: References: <1144597938.664642.133100@v46g2000cwv.googlegroups.com> Message-ID: <1144631163.723351.143610@i39g2000cwa.googlegroups.com> Steven D'Aprano wrote: > On Sun, 09 Apr 2006 08:52:18 -0700, Carl Banks wrote: > > > it's more important > > to respect community standards than to stick to some silly preference > > you have. > > What happens when the community standard is a silly preference? I object > to the suggestion that "community standards" (that is, a standard not even > designed by a committee, merely evolved by a mob) is necessarily worthy of > respect. It is worthy of respect because it's such a stupid thing to even have a preference for; consistency with the community is by far the strongest argument one could make for or against tabs. Carl Banks From reply.in.the.newsgroup at my.address.is.invalid Tue Apr 25 07:15:58 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Tue, 25 Apr 2006 13:15:58 +0200 Subject: OOP / language design question References: <1145961248.794496.80220@j33g2000cwa.googlegroups.com> <1145963311.348482.15080@i40g2000cwc.googlegroups.com> Message-ID: <961s4295r5gf1hj4op9e3jhm53e8fc0i02@4ax.com> cctv.star at gmail.com: >I think I'll need some shift in thinking after C++. +1 qotw -- Ren? Pijlman From roy at panix.com Mon Apr 17 17:51:41 2006 From: roy at panix.com (Roy Smith) Date: 17 Apr 2006 17:51:41 -0400 Subject: Missing interfaces in Python... References: <1145306373.781129.305840@z34g2000cwc.googlegroups.com> Message-ID: wrote: > I see that Python is missing "interfaces". The concept of an interface > is a key to good programming design in Java, but I've read that they > aren't really necessary in Python. I am wondering what technique I can > use in Python to get the same benefits to a program design that I would > get with interfaces in Java. Python is a very dynamic language. Java is a very static language. What that means is that in Java (like C++), you do a lot of error checking at compile time. That's what interfaces are all about. In Python, you do almost no error checking (beyond basic language syntax) at compile time, and do everything at run time. For the most part, this means wrapping things in try blocks and catching exceptions. >For example, if I want to have a program with a Car object, and a Bus >object. I want both of these objects to present a common group of >methods that can be used by Mechanic objects, but slightly different >methods that can be used by Driver objects. > >In Java I would accomplish this by defining an IFixable interface that >would be implemented by both the Car and Bus objects. Mechanic objects >would work with any object implementing this interface. > >How would I approach this problem in Python? I think I would use an >abstract class instead of an interface for IFixable, since Python >supports multiple inheritance, but I'm not sure this is correct. Well, let's say your IFixable interface in Java would have included changeTire(), rechargeBattery(), and adjustBrakes() methods. In Python, I'd just go ahead and implement those methods for both Car and Bus classes. All Java's interface mechanism does for you is provide some compile-time checking that those methods are implemented. In Python, you would just call those methods when appropriate, and catch any NameError exception that would happen if it turns out there is no such method. Consider that in Python, an object can have methods added to it after it is created. It's entirely possible that the Car class has no changeTire() method, but one would be added to each Car instance sometime before the first place it might be called. Consider something like: if self.owner.hasRoadsideAssistance(): self.changeTire = callForHelp elif self.owner.canFixThings: self.changeTire = getHandsDirty Now, calling myCar.changeTire() could end up calling callForHelp(), or calling getHandsDirty(), or throwing NameError is no way exists to get the tire fixed. Maybe that's what makes sense in your application. From kyoguan at gmail.com Thu Apr 27 06:07:42 2006 From: kyoguan at gmail.com (kyo guan) Date: Thu, 27 Apr 2006 18:07:42 +0800 Subject: how to free the big list memory Message-ID: <004f01c669e2$6f307590$350aa8c0@kyom> Python version 2.4.3 >>> l=range(50*1024*100) after this code, you can see the python nearly using about 80MB. then I do this >>> del l after this, the python still using more then 60MB, Why the python don't free my memory? Is there any way to force the python free my memory? Thanks. Kyo. From ldo at geek-central.gen.new_zealand Tue Apr 11 03:07:19 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 11 Apr 2006 19:07:19 +1200 Subject: waiting for file lock? References: <1144725394.174399.4030@j33g2000cwa.googlegroups.com> Message-ID: In article <1144725394.174399.4030 at j33g2000cwa.googlegroups.com>, s99999999s2003 at yahoo.com wrote: >i need to go into a directory to grab some files and do some >processing. >The thing is, i need to wait till the process that generates the files >in that directory to finish >before i can grab the files. eg if file A is being generated and has >not finished, my python script will not go into the directory. >how can i check that file A has actually finished? I wrote a similar system that watches for new files arriving in an "uploads" directory, whether copied there via FTP or using a GUI desktop script. My heuristic was to only process files whose last-modified date/time was at least 5 minutes in the past. My assumption was that it was unlikely that 5 minutes would go by between more information being added to a file. From raims at dot.com Sun Apr 16 20:25:48 2006 From: raims at dot.com (Lawrence Oluyede) Date: Mon, 17 Apr 2006 02:25:48 +0200 Subject: Should I learn Python instead? References: <1145048531.915798.97060@v46g2000cwv.googlegroups.com> Message-ID: <87k69pavzn.fsf@voodoo.myself> "fyleow" writes: > I'm a student/hobbyist programmer interested in creating a web project. I'm a student too and I've done a little Python web related stuff long ago. > It's nothing too complicated, I would like to get data from an RSS > feed and store that into a database. I want my website to get the > information from the database and display parts of it depending on the > criteria I set. That's a really easy thing to do. You're lucky because thanks to Mark Pilgrim we have one of the best RSS/Atom parsing libraries out there: http://feedparser.org/ It's quite simple: 1 - you parse the feed 2 - you take the data 3 - you display them in your html page with one of the python frameworks available. > I just finished an OO programming class in Java and I thought it would > be a good idea to do this in C# since ASP.NET makes web applications > easier than using Java (that's what I've heard anyway). It's quite right. ASP.NET is easier than JSP and J2EE stuff but Python is better to me :) > I thought it > would be easy to pick up since the language syntax is very similar but > I'm getting overwhelmed by the massive class library. MSDN docs are > very good and thorough but the language just seems a little unwieldy > and too verbose. Yeah they like in that way. A 40000+ class library and gigatons of documents. All is verbose in their static world: documents, books, languages :( > This is how to access an RSS feed and create an XML document to > manipulate it. I know the author of the RSS.NET library and I used it in the past, it can save you some machinery. But why get a bad language with a good library instead of a wonderful library and a very good language :) ? > Is Python easier than C#? IMHO yes. > Can > someone show how to access an XML document on the web and have it ready > to be manipulated for comparison? Any other advice for a newbie? Start with the examples on the feedparser homepage. Then choose a framework (Turbogears? CherryPy?) and then it's a matter of _minutes_ to have a HTML page filled with your data. -- Lawrence - http://www.oluyede.org/blog "Nothing is more dangerous than an idea if it's the only one you have" - E. A. Chartier From adam.deprince at gmail.com Mon Apr 3 10:11:44 2006 From: adam.deprince at gmail.com (Adam DePrince) Date: Mon, 03 Apr 2006 10:11:44 -0400 Subject: Difference between 'is' and '==' In-Reply-To: References: <1143459098.385264.139560@g10g2000cwb.googlegroups.com> <4427d287$0$38669$edfadb0f@dread12.news.tele.dk> Message-ID: <1144073505.3136.30.camel@localhost.localdomain> On Mon, 2006-03-27 at 17:17 -0500, Terry Reedy wrote: > "Clemens Hepper" wrote in message > news:e08qgg$nt$1 at news2.open-news-network.org... > > > It's strange: python seem to cache constants from 0 to 99: > > The Python specification allows but does not require such behind-the-scenes > implementation optimization hacks. As released, CPython 2.4 caches -5 to > 99, I believe. In 2.5, the upper limit was increased to 256. The limits > are in a pair of #define statements in the int object source file. Anyone > who compiles from source can adjust as desired (though the corresponding > test will fail unless also adjusted ;-). > > I think the visibility of this implementation detail from Python code is an > example of a leaky abstraction. For more, see > http://www.joelonsoftware.com/articles/LeakyAbstractions.html I disagree wholeheartedly with this. == and is are two very different operators that have very different meaning. It just happens that the logical operation (a is b ) -> (a == b ) is always True. There is no abstraction going on here; a==b is not an abstract version of a is b. They are different operations. a == b tests if the values of objects at a and b are equal. a and b point be the same darn object, or they might be different objects, but the question we are asking is if they have the same value. The is operator is different, you use it if you are interested in introspecting the language. Some people have noticed that 1 + 1 is 2 will return True and 1 + 100 is 101 returns False. This isn't a "leaky abstraction" unless you wrongly consider is to be an analogy for ==. Python has certain optimizations ... small strings and numbers are "interned," that is canonical copies are maintained and efforts to create fresh objects result in the old cached copies being returned, albeit with higher reference counts. This saves memory and time; time because for any intern-able objects the truth of the first test is a realistic possibility. if a is b: return True if hash( a ) != hash( b ) return False ... Now do proper equality testing. ... As for "joelonsoftware's" leaky abstraction article, I respectfully disagree. His leaky abstractions are merely inappropriate analogies. TCP is perfectly reliable with respect to its definition of reliability. As for wipers abstracting away the rain ... Well over a decade ago I recall walking to lunch with my supervisor, a truly masterful C programmer. We worked in Manhattan, a land where two way streets are the exception. When crossing each street he would look the wrong way, look the correct way and then stare the wrong way again. Upon noticing my inquisitorial expression, he answered "A good programmer always looks both ways when crossing a one way street." I'm uncertain that a quip about abstracting away the rain would have prompted the same adjective "masterful" now 10+ years in the future. - Adam DePrince From mitsura at skynet.be Thu Apr 13 11:14:10 2006 From: mitsura at skynet.be (mitsura at skynet.be) Date: 13 Apr 2006 08:14:10 -0700 Subject: trying to grasp OO : newbie Q? In-Reply-To: References: <1144937168.508799.67410@i40g2000cwc.googlegroups.com> <1144938934.900062.219600@i40g2000cwc.googlegroups.com> Message-ID: <1144941250.517385.144590@u72g2000cwu.googlegroups.com> Thanks guys, It is starting to make much more sense. Most documentation I find about OO is very academic From anton.vredegoor at gmail.com Fri Apr 28 09:17:30 2006 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Fri, 28 Apr 2006 15:17:30 +0200 Subject: not quite 1252 In-Reply-To: <1146228498.056632.168360@j73g2000cwa.googlegroups.com> References: <444f5e6b$1@usenet.zapto.org> <444f8781@usenet.zapto.org> <44507F68.7080804@lexicon.net> <4450e193$1@usenet.zapto.org> <1146228498.056632.168360@j73g2000cwa.googlegroups.com> Message-ID: <445214a1$1@usenet.zapto.org> Serge Orlov wrote: > Anton Vredegoor wrote: >> In fact there are a lot of printable things that haven't got a text >> attribute, for example some items with tag (xxxx)s. > > In my sample file I see , is that you're talking > about? Since my file is small I can say for sure this tag represents > two space characters. Or for example in firefox: in Amsterdam So, probably yes. If it doesn't have a text attribrute if you iterate over it using OOopy for example: o = OOoPy (infile = fname) c = o.read ('content.xml') for x in c.getiterator(): if x.text: Then we know for sure you have recreated my other problem. Anton From aleaxit at yahoo.com Thu Apr 13 21:05:11 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 13 Apr 2006 18:05:11 -0700 Subject: Kross - Start of a Unified Scripting Approach References: <1144866431.999725.293670@v46g2000cwv.googlegroups.com> Message-ID: <1hdqj4h.1ixp24v1dqm4wrN%aleaxit@yahoo.com> RM wrote: > This is from the new KOffice Announcement. > > http://www.koffice.org/announcements/announce-1.5.php > > '''This version of KOffice features a start of a unified scripting > solution called Kross. Kross provides cross-language support for > scripting (thus its name) and at present supports Python and Ruby. > > Kross is easy to include into programs previously lacking scripting > abilities, and is included in this version as a technology preview. So > far, only Krita and Kexi are improved by means of the Kross engine.We > would also like to point out that the API might change in the future > and expect Kross to be fully integrated into KOffice version 2.0.''' > > Interesting isn't it? An absolutely exellent idea. Most of the potential issues are with the details (that's where the devil is, right?-)... can't check it out right now (vacationing in the Grand Canyon, very occasional net access), but I plan to do so when I'm back home next week! Alex From zweistein at gmail.com Sun Apr 16 04:58:09 2006 From: zweistein at gmail.com (zweistein) Date: 16 Apr 2006 01:58:09 -0700 Subject: keyboard command to break out of infinite loop? References: <1145174364.436843.26660@e56g2000cwe.googlegroups.com> Message-ID: <1145177889.600793.146390@i39g2000cwa.googlegroups.com> Try CTRL + C. If it doesn't work, CTRL + Pause/Break should also work (if you're running it from the CLI). HTH From dananrg at yahoo.com Wed Apr 5 07:39:21 2006 From: dananrg at yahoo.com (dananrg at yahoo.com) Date: 5 Apr 2006 04:39:21 -0700 Subject: Filters like old skool Jive, Fudd, Valspeak... Text transformation in Python Message-ID: <1144237161.700762.75630@e56g2000cwe.googlegroups.com> I would like to learn how to roll my own filter ala early 90's filters like Jive, Fudd, Kraut, Moron, etc, that take text as an input, and re-writes the text adding general hilarity of various linguistic flavor (depending on the filter). I always loved running my philosophy papers, or anything that sounded "too dang serious" through filters. Gave me a new perspective on my own writing. Running the screenplay of the Empire Strikes Back through the Kraut filter, particularly the scene where Vader reveals Skywalker's true lineage, is amusing. No offense to good Germans everywhere. I'm sure someone could write a good "American" filter than would be a gag on American obsession with success and work, being happy 100% of the time, etc. Anyway, I'd like to see an old skool filter written in Python so I can write my own filters. There's an old prof of mine so, erm, linguistically unique, that I absolutely must write a Prof X filter to share with old college buds. I need to encapsulate / generate a model of the Prof's speech patterns for posterity and "educational purposes only" - ok, for entertainment. A fun way to learn more about Python and text processing. Any good "generators" written in Python? I'd like to roll me one of these as well; e.g. execute the program and it will create a few paragraphs of text in the jargon of a discipline, subdiscipline, subculture, etc. Anyone know what I'm talking about? Thanks. From ralf at tecont.de Wed Apr 5 14:30:54 2006 From: ralf at tecont.de (Ralf Muschall) Date: Wed, 05 Apr 2006 20:30:54 +0200 Subject: "The World's Most Maintainable Programming Language" In-Reply-To: References: <44331897$0$12009$c3e8da3@news.astraweb.com> Message-ID: Mirco Wahab wrote: > Perl, named after Pearl Biggar (Larry Wall?s fianc?e), His wife was Gloria since at least 1979, perl was published in 1987. This seems to be an insider joke (he wanted to call the language "Gloria" first, then "pearl", then "perl"). > set a high standard for naming techniques. So we should rename Python into Cottonmouth to get more attention. Ralf From kent at kentsjohnson.com Thu Apr 20 17:40:59 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Thu, 20 Apr 2006 17:40:59 -0400 Subject: send cookie on request with urllib2 In-Reply-To: <1145539129.322307.77220@z34g2000cwc.googlegroups.com> References: <1145539129.322307.77220@z34g2000cwc.googlegroups.com> Message-ID: <4447ffcb$1_2@newspeer2.tds.net> itay_k wrote: > Hi, > > I dont understand why this is so complicated, just to add one line of > cookie header on the GET request. > > This is my unworking code: > import time > import Cookie > import cookielib, urllib2 > > c= cookielib.Cookie(1,"Name","Tom", 80,False, "itay", False, False, > "d:\\asddd",False, False,time.time()+1000,False,None,None,None) ^^^^ path is the server path to which the cookie applies. Try '/'. Kent From tomer.ha at gmail.com Sun Apr 9 12:36:40 2006 From: tomer.ha at gmail.com (tomer.ha at gmail.com) Date: 9 Apr 2006 09:36:40 -0700 Subject: Receiving emails with attachments In-Reply-To: <1144529985.082549.318710@z34g2000cwc.googlegroups.com> References: <1144527860.805632.181890@i39g2000cwa.googlegroups.com> <1144529985.082549.318710@z34g2000cwc.googlegroups.com> Message-ID: <1144600600.775834.91830@u72g2000cwu.googlegroups.com> Gerard, I tried to run your code but my interpreter couldn't locate the maildocument module. Is it included in Python standart library or should I install it from other place? Thanks, Tomer From duncan.booth at invalid.invalid Tue Apr 25 13:24:02 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 25 Apr 2006 17:24:02 GMT Subject: OOP / language design question References: <1145961248.794496.80220@j33g2000cwa.googlegroups.com> <1145963311.348482.15080@i40g2000cwc.googlegroups.com> <444e0dec$0$27071$626a54ce@news.free.fr> <444e38e9$0$29686$636a55ce@news.free.fr> Message-ID: bruno at modulix wrote: > class Base(object): > def __init__(self, arg1): > self.attr1 = arg1 > self.dothis() > > def dothis(self): > return self.attr1 > > class Derived(Base): > def __init__(self, arg1, arg2=0): > self.attr2 = arg2 > Base.__init__(self, arg1) > > def dothis(self): > return self.attr1 + self.attr2 > > (snip) > >> Perhaps if the base __init__ calls an overridden >> method, but at that point it sounds to me like something wants >> refactoring. > > Why so ? This is a well-known pattern (template method). I don't see > what's wrong with it. Apart from the fact that you can delete the method 'dothis' from both classes with no effect on the code? Actually, this is quite an interesting example becaue it wouldn't work in C++: if you tried the same trick the call to dothis from the base constructor (even assuming it is virtual) would actually call Base.dothis. I think you have demonstrated that you can do some things in Python which you simply cannot do in static languages like C++: assigning to derived attributes before calling a base initialiser, and calling a virtual method from a base initialiser. I'm not arguing about that. What I don't have though is an example of code where doing this would actually be a good thing. What I think I'm trying to get at is that I believe that most situations where someone actually tries to do something in the base initialiser which requires calling a virtual method are probably also cases where the initialiser is doing too much: i.e. separating the construction/initialisation from actually doing something is usually a good idea. From flamesrock at gmail.com Thu Apr 6 15:29:36 2006 From: flamesrock at gmail.com (flamesrock) Date: 6 Apr 2006 12:29:36 -0700 Subject: XMLRPCLIB appears to be broken? In-Reply-To: References: <1144299571.452329.310640@j33g2000cwa.googlegroups.com> <1144347696.011868.268990@e56g2000cwe.googlegroups.com> Message-ID: <1144351776.514543.82290@z34g2000cwc.googlegroups.com> Ughhh I feel like such an idiot :( Thanks for clearing that up it works now. From brian at rkspeed-rugby.dk Tue Apr 25 02:32:32 2006 From: brian at rkspeed-rugby.dk (Brian Elmegaard) Date: Tue, 25 Apr 2006 08:32:32 +0200 Subject: MinGW and Python References: <1145861223.509630.247350@y43g2000cwc.googlegroups.com> <444C79D7.4060007@v.loewis.de> Message-ID: Robert Kern writes: > the gcc project is to provide a portable compiler, not one that > generates the best code for any given platform. And in that goal, it > succeeds remarkably well. Will a python program be slower on the same machine running windows compared to linux? What I don't understand is that it is not possible to distribute a python compiled with gcc for windows. The main reason I saw in this thread is that python uses mfc. So python requires api access, I guess. Once I asked about distutils here. The answer was that I had access to the source so I could just extend it. After messing around I found I couldn't because I don't have msvc. -- Brian (remove the sport for mail) http://www.et.web.mek.dtu.dk/Staff/be/be.html http://www.rugbyklubben-speed.dk From kent at kentsjohnson.com Wed Apr 12 06:40:33 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Wed, 12 Apr 2006 06:40:33 -0400 Subject: Unicode, command-line and idle In-Reply-To: <1144768769.790903.5330@j33g2000cwa.googlegroups.com> References: <1144321375.901932.161330@v46g2000cwv.googlegroups.com> <1144333536.440072.13830@i40g2000cwc.googlegroups.com> <44359427.6080805@v.loewis.de> <1144391227.670210.221930@e56g2000cwe.googlegroups.com> <44363234_2@newspeer2.tds.net> <1144768769.790903.5330@j33g2000cwa.googlegroups.com> Message-ID: <443cd3a3_3@newspeer2.tds.net> a.serrano at vielca.com wrote: > Hello again, I've investigated a little bit and this is what I found: > > If I run IDLE and type > >>>> import sys >>>> sys.stdin.encoding > > I get > > 'cp1252' > > But if I have a whatever.py file (it can even be a blank file), I edit > it with IDLE, I press F5 (Run Module) and then type: > >>>> import sys >>>> sys.stdin.encoding > > I get > > Traceback (most recent call last): > File "", line 1, in ? > sys.stdin.encoding > AttributeError: PyShell instance has no attribute 'encoding' > > So when I have the following code in a file: > > # -*- coding: cp1252 -*- > import sys > text1 = u'espa?a' > text2 = unicode(raw_input(), sys.stdin.encoding) > if text1 == text2: > print 'same' > else: > print 'not same' > > and I press F5 (Run Module) I get: > > Traceback (most recent call last): > File "C:\test.py", line 4, in ? > text2 = unicode(raw_input(), sys.stdin.encoding) > AttributeError: PyShell instance has no attribute 'encoding' > > This same code works if I just double-click it (run it in the windows > console) instead of using IDLE. > > I'm using Python 2.4.3 and IDLE 1.1.3. FWIW all of the above give me 'cp1252', not AttributeError, and the type of sys.stdin on my system is idlelib.rpc.RPCProxy, not PyShell. Python 2.4.3 and IDLE 1.1.3 on Win2k Kent From rrr at ronadam.com Sat Apr 1 19:39:58 2006 From: rrr at ronadam.com (Ron Adam) Date: Sat, 01 Apr 2006 18:39:58 -0600 Subject: any() and all() on empty list? In-Reply-To: References: <7x3bh1x0ym.fsf@ruckus.brouhaha.com> <42qWf.18211$uX5.7574@tornado.texas.rr.com> <7xzmj9u1di.fsf@ruckus.brouhaha.com> <85tWf.2748$Aa1.1605@dukeread05> <7xy7ytmtk2.fsf@ruckus.brouhaha.com> <7xpsk2f8ab.fsf@ruckus.brouhaha.com> Message-ID: <56FXf.20765$VE.19215@dukeread05> Steve R. Hastings wrote: > Here is a function called "tally()". It reduces a list to a dictionary > of counts, with one key for each value from the list. The value for > each key is the count of how many times it appeared in the list. > > > def tally(seq, d=None): > if d == None: > d = {} > > for x in seq: > if x in d: > d[x] += 1 > else: > d[x] = 1 > return d > > > This neatly replaces truecount(), and you can use it for other things as > well. if True in talley(S): do_somthing() Works for me... ;-) Cheers, Ron From k.r.fry at durham.ac.uk Mon Apr 3 09:23:37 2006 From: k.r.fry at durham.ac.uk (k r fry) Date: Mon, 03 Apr 2006 14:23:37 +0100 Subject: Oserror: [Errno 20] In-Reply-To: <12328a1o4lp3i64@corp.supernews.com> References: <12328a1o4lp3i64@corp.supernews.com> Message-ID: Thank you very much! *embarassed*. :-) Ben Thul wrote: > I think that if you go back and look at the original reply, he spelled > it "isdir"...;) > > --Ben > k r fry wrote: > >> Again, I apologise. Not knowing much about Python means that I don't >> know what needs to be provided. I meant it doesn't work in the same >> way that "istdir" didn't work. >> >> Here is what I have coded: >> >> for subdir in os.path.istdir(DATADIR): #loop through list >> of strings >> >> file=FITS.Read(DATADIR+'/'+subdir+'/flux.fits') #opens >> flux.fits file and reads >> >> summation=open(DATADIR+'/'+subdir+'/flux.dat','w') #opens the >> summation results file for writing to >> >> spotbyspot=open(DATADIR+'/'+subdir+'/spotflux.dat','w') #opens the >> spot-by-spot file for writing to >> >> output='' >> print'\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n'+sys.argv[1]+' >> '+subdir+'\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n' >> >> And here is what I get when I try to run it: >> >> Traceback (most recent call last): >> File "katiescint.py", line 153, in ? >> for subdir in os.path.istdir(DATADIR): #loop through >> list of strings >> AttributeError: 'module' object has no attribute 'istdir' >> >> Here is trying with listdir: >> >> for subdir in os.path.listdir(DATADIR): #loop through >> list of strings >> >> and here is what I get: >> >> Traceback (most recent call last): >> File "katiescint.py", line 153, in ? >> for subdir in os.path.listdir(DATADIR): #loop through >> list of strings >> AttributeError: 'module' object has no attribute 'listdir' >> >> >> >> >> Sybren Stuvel wrote: >> >>> k r fry enlightened us with: >>> >>>> I did think maybe it was meant to be "listdir" instead of "istdir", >>>> but that doesn't work either. >>> >>> >>> >>> >>> And again you don't tell us in what way it doesn't work. >>> >>> Think about what you post from our point of view. Then re-read it, and >>> think about it again. Only if you're sure that we'll be able to fully >>> understand it, hit the 'send' button. That will save us a lot of >>> guessting and asking, and will also get you your answer a lot faster. >>> >>> Sybren From aleaxit at yahoo.com Thu Apr 20 10:31:46 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 20 Apr 2006 07:31:46 -0700 Subject: How protect proprietary Python code? (bytecode obfuscation?, what better?) References: <1145293384.791678.14450@v46g2000cwv.googlegroups.com> <4444c777$0$9453$626a54ce@news.free.fr> <1145450399.254863.234380@i40g2000cwc.googlegroups.com> <44466dd9$0$20865$636a55ce@news.free.fr> <1145541967.959650.305600@z34g2000cwc.googlegroups.com> Message-ID: <1he30cu.1akaa40fe3fwpN%aleaxit@yahoo.com> Ben Sizer wrote: > bruno at modulix wrote: > > Let's rephrase it: > > "do you really think that native code is harder *enough* to > > reverse-engineer ?" > > I don't know. In terms of copy protection, popular off-the-shelf > software is going to get cracked whether it's written in Python or x86 > ASM, that much is true. But in terms of perhaps protecting innovative > algorithms from competitors, or something similar, compilation into > native code does a great job of hiding your work. Not a perfect job, > but a good enough job. If they're truly worth protecting, they're worth reverse engineering. Remember, the competition includes excellent programmers working in countries where $10 an hour's salary is luxury and IP law enforcements non-existent, so the cost to reveng is not as high as you might think. > I know some people talk a lot about using web services to keep the > proprietary data behind a secure server, but there is a large number of Ah yes, that would be me;-). Except that I don't limit my advice to proprietary DATA -- it also applies to CODE worth keeping secret. > applications where this is not practical - eg. image/audio processing, > computer games, artificial intelligence, or several other applications > with heavy real-time or cpu-intensive requirements, or embedded systems > that don't have web access. Fewer and fewer systems "intrinsically lack" net access. For example, good (costly) computer games more and more need net access to be played in the best way (multiplayer etc). "CPU intensive" is a weird reason to want to avoid keeping in a well protected environment any code that's really worth money -- if it IS worth that much you're no doubt charging enough for it to afford supplying the CPU power to your customers (whatever your business model, say pay-per-use or subscription levels with different maxima, etc etc). > > Perhaps the inclusion of ctypes will make it more practical to migrate > any sensitive code into native code libraries. Naah, ctypes shines when you access *pre-existing* dynamic libraries; if you're building those libraries yourself, it makes more sense to make them immediately usable from Python, e.g. via Pyrex, or SWIG, or SIP, or the C API, etc, etc. And if your secrets are truly valuable, none of those will really help keep them safe. If your secrets are worth diddlysquat, and the only reason to "protect" them is (e.g.) to keep some PHB happy (relying on the fact that he or she has no clue as to reality anyway), then go ahead -- use a Caesar cypher (as a just-arrested Mafia "capo di tutti i capi" appears to have done -- Italian police easily broke it, enabling it to arrest several other mafiosi!), or native code, or any other ineffectual approach. But if your wallet (or jailtime;-) is really on the line, do realize that they ARE ineffectual. Alex From Avizoa at gmail.com Wed Apr 26 12:08:29 2006 From: Avizoa at gmail.com (Avizoa at gmail.com) Date: 26 Apr 2006 09:08:29 -0700 Subject: Events in Python? In-Reply-To: <1146065995.016939.187440@i40g2000cwc.googlegroups.com> References: <1146065995.016939.187440@i40g2000cwc.googlegroups.com> Message-ID: <1146067709.553957.303650@t31g2000cwb.googlegroups.com> redefined.horizons at gmail.com wrote: > Here is another non-pythonic question from the Java Developer. (I beg > for forgiveness...) > > Does Python have a mechanism for events/event-driven programming? > > I'm not necessarily talking about just GUIs either, I'm interested in > using events for other parts of an application as well. > > If there isn't some sort of event mechanism built into Python, where > might I find some information about implementing one? > > Thanks, > > Scott Huey Technically this is a question more of perception than capability. All programming languages are event driven. Calling a function is an event, for instance. What I suspect you mean is an event management system, which is what OO state machines are all about. If you actually mean something akin in function to GUI event systems, you're really talking about message passing. In the case of message passing you just need to build a simple event manager class that echoes a message to all subscribed listening objects. In python that message can be a function, object, arguments, text, etc. This is easily done without threading, in case you're worried about that. The function of the event manager that is used for the purpose of initiating events can simply call a particular method of all subscribing objects held in a list. Simple as can be :) ~Brendan Kohler From eoinrogers at gmail.com Sat Apr 8 11:45:48 2006 From: eoinrogers at gmail.com (Byte) Date: 8 Apr 2006 08:45:48 -0700 Subject: Working with decimal points In-Reply-To: References: <1144509666.471858.55160@v46g2000cwv.googlegroups.com> Message-ID: <1144511148.491439.68340@i39g2000cwa.googlegroups.com> Fredrik Lundh's way works: thank a million! From flexx at jerasoft.net Sun Apr 2 08:54:10 2006 From: flexx at jerasoft.net (Flexx) Date: Sun, 02 Apr 2006 15:54:10 +0300 Subject: Exception handling....dumb question? In-Reply-To: References: <1143849093.457940.294150@g10g2000cwb.googlegroups.com> Message-ID: <1143982411.571726@isa.mirotel.net> Ben Finney writes: > You should catch *specific* exceptions that you know you can deal with at that point in the code. > > import logging > try: > foo = 12 / 0 > except ZeroDivisionError, e: > print "You *knew* this was going to happen: '%s'" % e > logging.error(str(e)) > > This allows all other exceptions to propogate back through the call > stack. import sys, logging try: foo = 12/0 except: e = str(sys.exc_value) print "You *knew* this was going to happen: '%s'" % (e) logging.error(e) From f.petri at steinbichler.de Sun Apr 9 17:48:57 2006 From: f.petri at steinbichler.de (blackno666) Date: 9 Apr 2006 14:48:57 -0700 Subject: Problems with current value of wx.SpinCtrl and EVT_SPIN In-Reply-To: References: <1144608437.075278.188350@j33g2000cwa.googlegroups.com> Message-ID: <1144619337.758695.142210@v46g2000cwv.googlegroups.com> Yes, it "works". However buggy. When the slider is set to 0 and the up button is pressed in the SpinCtrl, the value in the SpinCtrl will be 1, but the slider will not move. There's also a discrepancy between the value displayed in the SpinCtrl and the value output by print self.spin.GetValue(). When playing with this code I also noticed that I was not able change the behaviour of the up and down buttons. I expected that if I modify OnSpin in the following way: def OnSpin(self, event): pass That pressing the spin buttons would have no effect. However, the value is still increased or decreased.... From notme at bogus.example.com Tue Apr 25 21:16:46 2006 From: notme at bogus.example.com (Dean) Date: 26 Apr 2006 01:16:46 GMT Subject: Building a Dynamic Library (libpython.so) for Python 2.4.3 Final Message-ID: <6ABE4DBF-4B1F-4351-8B38-1EC3817C3913%notme@bogus.example.com> I've been trying to make python a dynamic library. I downloaded Python 2.4.3 Final from the Python web site and I cannot get it to create the library. I've tried using the directive: --enable-shared and --enable-shared=yes and both of them had the same effect of creating a bunch of parts of the python interpreter in .so format but not in creating a single libpython2.4.so.X.Y file. I could probably hack something together using ar but I would prefer to do it "correctly" by setting some options. I'm compiling under OpenBSD 3.5. Thanks for any advice. From reply.in.the.newsgroup at my.address.is.invalid Wed Apr 5 06:45:44 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Wed, 05 Apr 2006 12:45:44 +0200 Subject: HTMLParser fragility References: Message-ID: Lawrence D'Oliveiro: >I've been using HTMLParser to scrape Web sites. The trouble with this >is, there's a lot of malformed HTML out there. Real browsers have to be >written to cope gracefully with this, but HTMLParser does not. There are two solutions to this: 1. Tidy the source before parsing it. http://www.egenix.com/files/python/mxTidy.html 2. Use something more foregiving, like BeautifulSoup. http://www.crummy.com/software/BeautifulSoup/ -- Ren? Pijlman From siona at chiark.greenend.org.uk Thu Apr 6 09:27:12 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 06 Apr 2006 14:27:12 +0100 (BST) Subject: shelve and ".bak .dat .dir" files References: <443502c0$0$29101$5fc30a8@news.tiscali.it> Message-ID: Michele Petrazzo wrote: >I'm trying a script on a debian 3.1 that has problems on shelve library. >The same script work well on a fedora 2 and I don't know why it create >this problem on debian: > [ ... ] >Now I see that shelve create not my file, but three files that has the >name that I want (/tmp/myfile) and also the extensions: .bak .dat .dir This is a documented behaviour of shelve: http://docs.python.org/lib/module-shelve.html and note "an extension may be added to the filename and more than one file may be created". I guess this depends on what dbm shelve is built on the documentation implies it goes through anydbm. I'm not seeing this behaviour on my Debian 3.1 (and I fail to understand why it is a problem). -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From williams.jasonscott at gmail.com Mon Apr 24 16:22:59 2006 From: williams.jasonscott at gmail.com (williams.jasonscott at gmail.com) Date: 24 Apr 2006 13:22:59 -0700 Subject: C API - tp_getattro and tp_methods Message-ID: <1145910179.468987.266850@u72g2000cwu.googlegroups.com> Hi, I'm using a tp_getattro function to call into a C library and get values the the lib keeps track of. This works: >>> o = obj.Obj() >>> o.var 'value' Thats great but I also want to expose some instance methods and I'm having trouble. But when I set tp_methods nothing shows up? If I unset tp_getattro I can use my methods. I'm not understanding the relationship between the two, tp_methods and tp_getattro. Could someone point me in the right direction? thanks~ From see_signature_for_reply-to at ccrl-nece.de Fri Apr 7 08:13:18 2006 From: see_signature_for_reply-to at ccrl-nece.de (Joachim Worringen) Date: Fri, 07 Apr 2006 14:13:18 +0200 Subject: performance degradation when looping through lists Message-ID: <4436575e$0$11070$9b4e6d93@newsread4.arcor-online.net> I need to process large lists (in my real application, this is to parse the content of a file). I noticed that the performance to access the individual list elements degrades over runtime. This can be reproduced easily using this code: import time N=100000 p=10000 A=[] for i in range(N): A.append(str(i)) j = 0 t = time.clock() for i in range(len(A)): j += int(A[i]) if i % p == 0: t = time.clock() - t print t (the string conversion only servers to increase the duration of each iteration; you can observer the same effect with ints, too). When running this, I get output like this: 0.0 0.37 0.03 0.4 0.06 0.43 0.09 0.46 0.13 0.49 I use Python 2.3.4 (#1, Sep 3 2004, 12:08:45) [GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-110)] on linux2 I wonder why 1. The execution times alternate between "fast" and "slow" (I observe the same effect in my much more complex application) 2. The execution times increase steadily, from "0" to 0.13 for the "fast" phases, and from 0.37 to 0.49 for the slow phases. Within my application, the effect is more drastical as the following numbers show (the processing time per line is roughly the same for each line!): at line 10000 (32258 lines/s) at line 20000 (478 lines/s) at line 30000 (21276 lines/s) at line 40000 (475 lines/s) at line 50000 (15873 lines/s) at line 60000 (471 lines/s) at line 70000 (12658 lines/s) at line 80000 (468 lines/s) at line 90000 (10638 lines/s) at line 100000 (464 lines/s) at line 110000 (9090 lines/s) at line 120000 (461 lines/s) at line 130000 (7936 lines/s) at line 140000 (457 lines/s) at line 150000 (7042 lines/s) at line 160000 (454 lines/s) at line 170000 (6369 lines/s) at line 180000 (451 lines/s) at line 190000 (5780 lines/s) at line 200000 (448 lines/s) at line 210000 (4854 lines/s) at line 220000 (444 lines/s) at line 230000 (4504 lines/s) at line 240000 (441 lines/s) at line 250000 (4201 lines/s) at line 260000 (438 lines/s) at line 270000 (3952 lines/s) at line 280000 (435 lines/s) at line 290000 (3717 lines/s) at line 300000 (432 lines/s) at line 310000 (3508 lines/s) at line 320000 (429 lines/s) at line 330000 (3322 lines/s) at line 340000 (426 lines/s) at line 350000 (3154 lines/s) at line 360000 (423 lines/s) at line 370000 (3003 lines/s) at line 380000 (421 lines/s) at line 390000 (2873 lines/s) Any ideas why this is like this, and what I could do about it? It really makes may application non-scalable as the lines/s go down even further. -- Joachim - reply to joachim at domain ccrl-nece dot de Opinion expressed is personal and does not constitute an opinion or statement of NEC Laboratories. From phddas at yahoo.com Sun Apr 30 20:10:08 2006 From: phddas at yahoo.com (Gary Wessle) Date: 01 May 2006 10:10:08 +1000 Subject: file open "no such file" Message-ID: <87vesqip0f.fsf@localhost.localdomain> I am getting this error when I try to run the code below **************** f = open("~/m", "r") print f.read() **************** **************** :~$ python python/my.py Traceback (most recent call last): File "python/my.py", line 1, in ? f = open("~/m", "r") IOError: [Errno 2] No such file or directory: '~/m' **************** but I have the "m" file in my home/username/ thank you From iddw at hotmail.com Wed Apr 12 09:50:59 2006 From: iddw at hotmail.com (Dave Hansen) Date: Wed, 12 Apr 2006 08:50:59 -0500 Subject: Decorators, Identity functions and execution... References: <1144597938.664642.133100@v46g2000cwv.googlegroups.com> <1144742379.824131.299990@t31g2000cwb.googlegroups.com> Message-ID: On Wed, 12 Apr 2006 17:19:25 +1200 in comp.lang.python, Lawrence D'Oliveiro wrote: >In article , > "Terry Reedy" wrote: > >>"Sybren Stuvel" wrote in >> > I don't care about how people see my tabs. I use one tab for every >>> indent level, so no matter how you set your tab width, my code will >>> look consistent. >> >>Unless they view with tab_width = 0, as with some news readers. > >I have my newsreader set to use a proportional font, so the point is >moot. Even in a proportional font, spaces all have the same width. Though not as wide as a fixed font... Regards, -=Dave -- Change is inevitable, progress is not. From qlng2000 at gmail.com Fri Apr 7 12:43:56 2006 From: qlng2000 at gmail.com (beta) Date: 7 Apr 2006 09:43:56 -0700 Subject: binding - python In-Reply-To: References: <1144284193.604084.141910@i40g2000cwc.googlegroups.com> <1144366764.240620.46310@i39g2000cwa.googlegroups.com> Message-ID: <1144428236.383180.127380@g10g2000cwb.googlegroups.com> Hi John, It works. Thank you veyr much. Cheers, Q From usenet at ionlists.co.uk Sun Apr 30 16:30:09 2006 From: usenet at ionlists.co.uk (John Kirkland) Date: Sun, 30 Apr 2006 21:30:09 +0100 Subject: basic python programing References: <1146376141.767029.17850@j73g2000cwa.googlegroups.com> <1146383327.664894.279250@v46g2000cwv.googlegroups.com> Message-ID: <44551e50$0$651$bed64819@news.gradwell.net> On 30 Apr 2006 00:48:47 -0700, Ravi Teja wrote: > How To Ask Questions The Smart Way > http://www.catb.org/~esr/faqs/smart-questions.html Damn, that's one of the best respones ever. :) WTG. Oh, and I'm not being sarcastic. That's a truly useful set of ideals. It's now joined my short and distinguished bookmark list. :) -- John Kirkland From steven.bethard at gmail.com Fri Apr 28 23:47:59 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 28 Apr 2006 21:47:59 -0600 Subject: python-dev Summary for 2006-03-01 through 2006-03-15 Message-ID: python-dev Summary for 2006-03-01 through 2006-03-15 ++++++++++++++++++++++++++++++++++++++++++++++++++++ .. contents:: [The HTML version of this Summary is available at http://www.python.org/dev/summary/2006-03-01_2006-03-15] ============= Announcements ============= ----------------------- Webstats for python.org ----------------------- Thomas Wouters set up webalizer on dinsdale.python.org and added webstats for all subsites of python.org: * http://www.python.org/webstats/ * http://beta.python.org/webstats/ * http://bugs.python.org/webstats/ * http://planet.python.org/webstats/ * http://docs.python.org/webstats/ * http://svn.python.org/webstats/ Check 'em out if you're interested! Contributing thread: - `Webstats for www.python.org et al. `__ [SJB] --------------------------- Python 2.5 release schedule --------------------------- The first releases scheduled for Python 2.5 are quickly approaching. Check `PEP 356`_ for details, but the first alpha is due on April 1st. .. _PEP 356: http://www.python.org/doc/peps/pep-0356/ Contributing thread: - `2.5 release schedule? `__ [SJB] ----------- Py3K branch ----------- Guido has begun work on Py3K, starting a new branch to rip out some stuff like string exceptions and classic classes. He's trying to get a "feel" for what Python 3.0 will look like, hopefully before his keynote in OSCON. Contributing thread: - `Py3k branch - please stay out :-) `__ [SJB] ------------------------------------------- Deprecated modules going away in Python 2.5 ------------------------------------------- A number of deprecated modules will be removed in Python 2.5, including: * reconvert.py * regex (regexmodule.c) * regex_syntax.py * regsub.py and a variety of things from lib-old. These modules have been deprecated for a while now, and will be pulled in the next Python release. Contributing thread: - `Deprecated modules going away in 2.5 `__ [SJB] ========= Summaries ========= ------------------------------- Maintaining ctypes in SVN trunk ------------------------------- Thomas Heller put ctypes into the Python SVN repository, and with the help of perky, Neal Norwitz and Thomas Wouters, updated it to take advantage of the new ssize_t feature. The "official" ctypes development will remain in its Sourceforge repository at least for a while since this makes it easy to test ctypes on the SF compile farm. Contributing threads: - `ctypes is in SVN now. `__ - `Developing/patching ctypes (was: Re: integrating ctypes into python) `__ - `Developing/patching ctypes `__ [SJB] ----------------- Windows buildbots ----------------- Josiah Carlson had been working on getting a buildbot slave running on a Windows box, but eventually gave up due to crashes caused by VS.NET. Tim Peters fought his way through the setup with a XP box, posting `his lessons`_ to the wiki, and Trent Mick managed to follow a similar route and setup a Win2K buildbot slave. Thanks to all who suffered through the config -- Windows buildbot coverage looks pretty good now! .. _his lessons: http://wiki.python.org/moin/BuildbotOnWindows Contributing threads: - `Another Windows buildbot slave `__ - `Still looking for volunteer to run Windows buildbot `__ [SJB] ----------------------------------- Python 3.0: itr.next() or next(itr) ----------------------------------- The end of last fortnight's defaultdict thread turned to discussing the fate of the iterator protocol's .next() method in Python 3.0. Greg Ewing argued that renaming .next() to .__next__() and introducing a builtin function next() would be more consistent with the other magic methods and also more future-proof, since the next() function could be modified if the protocol method needed to change. Raymond Hettinger was very strongly against this proposal, suggesting that trading a Python-level attribute lookup for a Python-level global lookup plus a C-level slot lookup was not a good tradeoff. The discussion then spread out to other protocol method/function pairs -- e.g. len() and __len__() -- and Oleg Broytmann suggested that they could all be replaced with methods, thus saving a lookup and clearing out the builtin namespace. Neil Schemenauer and Michael Chermside argued against such a change, saying that the double-underscore pattern allows new special methods to be introduced without worrying about breaking user code, and that using functions for protocols forces developers to use the same names when the protocols are involved, while using methods could allow some developers to choose different names than others. Guido indicated that he'd like to do some usability studies to determine whether methods or functions were more intuitive for the various protocols. Contributing threads: - `defaultdict and on_missing() `__ - `iterator API in Py3.0 `__ - `iterator API in Py3. `__ - `.len() instead of __len__() (was: iterator API in Py3.0) `__ - `x.len() instead of len(x) in Py3.0 `__ - `.len() instead of __len__() (was: iterator API inPy3.0) `__ - `.len() instead of __len__() in Py3.0 `__ [SJB] --------------------------- Python 3.0: base64 encoding --------------------------- This fortnight continued discussion from the last as to whether the base64 encoding should produce unicode or bytes objects. The encoding is specified in `RFC 2045`_ as "designed to represent arbitrary sequences of octets" using "a 65-character subset of US-ASCII". Traditionally, base64 "encoding" goes from bytes to characters, and base64 "decoding" goes from characters to bytes. But this is the inverse of the usual unicode meanings, where "encoding" goes from characters to bytes, and where "decoding" goes from bytes to characters. Thus some people felt that the recent proposal to have only bytes.decode(), which would produce unicode, and unicode.encode(), which would produce bytes, would be a major problem for encodings like base64 which used the opposite terminology. A variety of proposals ensued, including putting .encode() and .decode() on both bytes and strings, having encode() and decode() builtins, and various ways of putting encoding and decoding into the unicode and bytes constructors or classmethods. No clear solution could be agreed upon at the time. .. _RFC 2045: http://www.ietf.org/rfc/rfc2045.txt Contributing thread: - `bytes.from_hex() `__ [SJB] ----------------------------- Coverity scans of Python code ----------------------------- Ben Chelf of Coverity presented scan.coverity.com, which provides the results of some static source code analysis looking for a variety of code defects in a variety of open source projects, including Python. Full access to the reports is limited to core developers, but Neal Norwitz explained a bit what had been made available. The types of problems reported in Python include unintialized variables, resource leak, negative return values, using a NULL pointer, dead code, use after free and some other similar conditions. The reports provide information about what condition is violated and where, and according to Neal have been high quality and accurate, though of course there were some false positives. Generally, developers seemed quite happy with the reports, and a number of bugs have subsequently been fixed. Contributing threads: - `Coverity Open Source Defect Scan of Python `__ - `About "Coverity Study Ranks LAMP Code Quality" `__ - `Coverity report `__ [SJB] ------------------------------- Speeding up lookups of builtins ------------------------------- Steven Elliott was looking into reducing the cost of looking up Python builtins. Two PEPs (`PEP 280`_ and `PEP 329`_) had already been proposed for similar purposes, but Steven felt these were biting off too much at once as they tried to optimize all global attribute lookups instead of just those of builtins. His proposal would replace the global-builtin lookup chain with an array that indexed the builtins. A fast check for builtin shadowing would be performed before using a builtin; if no shadowing existed, the builtin would simply be extracted from the array, and if shadowing was present, the longer lookup sequence would be followed. Guido indicated that he would like to be able to assume that builtins are not shadowed in Python 3.0, but made no comment on the particular implementation strategy suggested. Steven Elliott promised a PEP, though it was not yet available at the time of this summary. .. _PEP 280: http://www.python.org/doc/peps/pep-0280/ .. _PEP 329: http://www.python.org/doc/peps/pep-0329/ Contributing thread: - `Making builtins more efficient `__ [SJB] ------------------------------------------------- Requiring parentheses for conditional expressions ------------------------------------------------- Upon seeing a recent checkin using conditional expressions, Jim Jewett suggested that parentheses should be required around all conditional expressions for the sake of readability. The usual syntax debate ensued, and in the end it looked like the most likely result was that `PEP 8`_ would be updated to suggest parentheses around the "test" part of the conditional expression if it contained any internal whitespace. .. _PEP 8: http://www.python.org/doc/peps/pep-0008/ Contributing threads: - `conditional expressions - add parens? `__ - `(no subject) `__ [SJB] ----------------------------- Exposing a global thread lock ----------------------------- Raymond Hettinger suggested exposing the global interpreter lock to allow code to temporarily suspend all thread switching. Guido was strongly against the idea as it was not portable to Jython or IronPython and it was likely to cause deadlocks. However, there was some support for it, and others indicated that the only way it could cause deadlocks is if locks were acquired within the sections where thread switching was disabled, and that even these could be avoided by having locks raise an exception if acquired in such a section. However, Michael Chermside explained that supporting such a thing in Jython and IronPython would really be impossible, and suggested that the functionality be made available in an extension module instead. Raymond Hettinger then suggested modifying sys.setcheckinterval() to allow thread switching to be stopped, but Martin v. L??wis explained that even disabling this "release the GIL from time to time" setting would not disable thread switching as, for example, the file_write call inside a PRINT_* opcode releases the GIL around fwrite regardless. Contributing thread: - `Threading idea -- exposing a global thread lock `__ [SJB] ----------------------------- Making quit and exit callable ----------------------------- Ian Bicking resuscitated a previous proposal to make ``quit`` and ``exit`` callable objects with informative __repr__ messages like ``license`` and ``help`` already have. Georg Brandl submitted a patch that makes ``quit`` and ``exit`` essentially synonymous with ``sys.exit`` but with better __repr__ messages. The patch was accepted and should appear in Python 2.5. Contributing thread: - `quit() on the prompt `__ [SJB] --------------------- Python 3.0: Using C++ --------------------- Fredrik Lundh suggested that in Python 3.0 it might be useful to switch to C++ instead of C for Python's implementation. This would allow some additional type checking, some more reliable reference counting with local variable destructors and smart pointers, and "native" exception handling. However, it would likely make linking and writing extension modules more difficult as C++ does not interoperate with others as happily as C does. Stephen J. Turnbull suggested that it might also be worth considering following the route of XEmacs -- all code must compile without warnings under both C and C++. No final decision was made, but for the moment it looks like Python will stick with the status quo. Contributing thread: - `C++ for CPython 3? (Re: str.count is slow) `__ [SJB] ---------------------- A @decorator decorator ---------------------- Georg Brandl presented a `patch providing a ``decorator`` decorator`_ that would transfer a function's __name__, __doc__ and __dict__ attributes to the wrapped function. Initially, he had placed it in a new ``decorator`` module, but a number of folks suggested that this module and the ``functional`` module -- which currently only contains partial() -- should be merged into a ``functools`` module. At the time of this summary, the patch had not been applied. .. _patch providing a ``decorator`` decorator: http://bugs.python.org/1448297 Contributing thread: - `decorator module patch `__ [SJB] ----------------------- Expanding the use of as ----------------------- Georg Brandl proposed that since ``as`` is finally becoming a keyword, other statements might allow ``as`` to be used for binding a name like the ``import`` and ``with`` statements do now. Generally people thought that using ``as`` to name the ``while`` or ``if`` conditions was not really that useful, especially since the parallel to ``with`` statements was pretty weak -- ``with`` statements bind the result of the context manager's __enter__() call, not the context manager itself. Contributing thread: - `"as" mania `__ [SJB] ------------------------------ Relative imports in the stdlib ------------------------------ Guido made a checkin using the new `relative import feature`_ in a few places. Because using relative imports can cause custom __import__'s to break (because they don't take the new optional fifth argument), Guido backed out the changes, and updated `PEP 8`_ to indicate that absolute imports were to be preferred over relative imports whenever possible. .. _relative import feature: http://www.python.org/doc/peps/pep-0328/ Contributing threads: - `Using relative imports in std lib packages ([Python-checkins] r43033 - in python/trunk/Lib: distutils/sysconfig.py encodings/__init__.py) `__ - `[Python-checkins] r43033 - in python/trunk/Lib: distutils/sysconfig.py encodings/__init__.py `__ [SJB] ------------------------------------ Making staticmethod objects callable ------------------------------------ Nicolas Fleury suggested that staticmethod objects should be made callable so that code like:: class A(object): @staticmethod def foo(): pass bar = foo() would work instead of compaining that staticmethod objects are not callable. Generally, people seemed to feel that most uses of staticmethods were better expressed as module-level functions anyway, and so catering to odd uses of staticmethods was not something Python needed to do. Contributing thread: - `Making staticmethod objects callable? `__ [SJB] ---------------------------------- Adding a uuid module to the stdlib ---------------------------------- Fredrik Lundh suggested `adding Ka-Ping Yee's uuid module`_ to the standard library. Most people were agreeable to the idea, but with other uuid implementations around, there was some discussion about the details. Phillip J. Eby suggested something more along the lines of `PEAK's uuid module`_, but no final decisions were made. .. _adding Ka-Ping Yee's uuid module: http://bugs.python.org/1368955 .. _PEAK's uuid module: http://svn.eby-sarna.com/PEAK/src/peak/util/uuid.py?view=markup Contributing thread: - `how about adding ping's uuid module to the standard lib ? `__ [SJB] ------------------------------- A dict that takes key= callable ------------------------------- Neil Schemenauer suggested providing dict variants in the collections module that would use the ids of the objects instead of the objects themselves. Guido suggested that it would likely be more useful to design a dict variant that took a key= argument like list.sort() does, and apply that key function to all keys in the dict. That would make implementing Neil's id-dict almost trivial and support a variety of other use-cases, like case-insensitive dicts. People seemed quite supportive of the proposal, but no patch was available at the time of this summary. Contributing thread: - `collections.idset and collections.iddict? `__ [SJB] ---------------------------- Bug in __future__ processing ---------------------------- Martin Maly found `Guido's previously encountered bug`_ that Python 2.2 through 2.4 allows some assignment statements before the ``__future__`` import. Tim Peters correctly channeled Guido that this was a bug and would be fixed in Python 2.5. .. _Guido's previously encountered bug: http://mail.python.org/pipermail/python-dev/2006-January/060247.html Contributing thread: - `Bug in from __future__ processing? `__ [SJB] ----------------------- Cleaning up string code ----------------------- Chris Perkins noted that ``str.count()`` is substantially slower than ``unicode.count()``. Ben Cartwright and others indicated that the source for these functions showed clearly that the unicode version had been better optimized. Fredrik Lundh and Armin Rigo both mentioned cleaning up the string code to avoid some of the duplication and potentially to merge the str and unicode implementations together. At the time of this summary, it didn't seem that any progress towards this goal had yet been made. Contributing thread: - `str.count is slow `__ - `str.count is slow `__ [SJB] --------------------------------------------- Freeing Python-allocated memory to the system --------------------------------------------- Tim Peters spent his PyCon time working on `a patch by Evan Jones`_, originally `discussed in January`_. The patch enables Python to free memory back to the operating system so that code like:: x = [] for i in xrange(1000000): x.append([]) del x[:] does not continue to consume massive memory after the del statement. Tim gave python-devvers some time to review the patch for any speed or other issues, and then committed it. .. _a patch by Evan Jones: http://bugs.python.org/1123430 .. _discussed in January: http://mail.python.org/pipermail/python-dev/2005-January/051255.html Contributing thread: - `Arena-freeing obmalloc ready for testing `__ [SJB] ------------------------------------------ Modifying the context manager __exit__ API ------------------------------------------ After thinking things over, Guido decided that the context manager ``__exit__`` method should be required to return True if it wants to suppress an exception. This addressed the main concerns about the previous API, that if ``__exit__`` methods were required to reraise exceptions, a lot of ``__exit__`` methods might end up with easily-missed bugs. Contributing thread: - `__exit__ API? `__ [SJB] ------------------------------- Python 3.0: default comparisons ------------------------------- In Python 3.0, Guido plans to ditch the default ``< <= > >=`` comparisons currently provided, and only provide ``== !=`` where by default all objects compare as unequal. Contributing thread: - `Keep default comparisons - or add a second set? `__ [SJB] ================ Deferred Threads ================ - `[Python-checkins] r43041 - python/trunk/Modules/_ctypes/cfield.c `__ ================== Previous Summaries ================== - `Proposal: defaultdict `__ =============== Skipped Threads =============== - `New test failure on Windows `__ - `.py and .txt files missing svn:eol-style in trunk `__ - `Using and binding relative names (was Re: PEP forBetter Control of Nested Lexical Scopes) `__ - `Stateful codecs [Was: str object going in Py3K] `__ - `bytes thoughts `__ - `wiki as scratchpad `__ - `test_compiler failure `__ - `DRAFT: python-dev Summary for 2006-01-16 through 2005-01-31 `__ - `Weekly Python Patch/Bug Summary `__ - `When will regex really go away? `__ - `ref leak w/except hooks `__ - `Faster list comprehensions `__ - `PEP 357 `__ - `Lib/test/test_compiler.py fails `__ - `FrOSCon 2006 - Call for {Papers|Projects} `__ - `Outdated Python Info on www.unicode.org (fwd) `__ - `My buildbot host upgraded to OSX 10.4 `__ - `Slightly OT: Replying to posts `__ - `New Future Keywords `__ - `[Python-checkins] Python Regression Test Failures refleak (1) `__ - `[Python-checkins] Python humor `__ - `Two gcmodule patches `__ - `Scientific Survey: Working Conditions in Open Source Projects `__ - `_bsddb.c ownership `__ - `str(Exception) changed, is that intended? `__ - `Long-time shy failure in test_socket_ssl `__ - `mail.python.org disruption `__ - `Bug Day? `__ - `Generated code in test_ast.py `__ - `fixing log messages `__ - `[Python-checkins] r42929 - python/trunk/Tools/scripts/svneol.py `__ - `unicodedata.c no longer compiles on Windows `__ - `multidict API `__ - `Google ads on python.org? `__ - `libbzip2 version? `__ - `PythonCore\CurrentVersion `__ - `Strange behavior in Python 2.5a0 (trunk) --- possible error in AST? `__ - `Why are so many built-in types inheritable? `__ - `checkin r43015 `__ - `Topic suggestions from the PyCon feedback `__ - `Another threading idea `__ - `Octal literals `__ - `[Python-checkins] r43022 - in python/trunk: Modules/xxmodule.c Objects/object.c `__ - `[Python-checkins] Python Regression Test Failuresrefleak (1) `__ - `[Python-checkins] r43028 - python/trunk/Modules/_ctypes/cfield.c `__ - `PEP 338 implemented in SVN `__ ======== Epilogue ======== This is a summary of traffic on the `python-dev mailing list`_ from March 01, 2006 through March 15, 2006. It is intended to inform the wider Python community of on-going developments on the list on a semi-monthly basis. An archive_ of previous summaries is available online. An `RSS feed`_ of the titles of the summaries is available. You can also watch comp.lang.python or comp.lang.python.announce for new summaries (or through their email gateways of python-list or python-announce, respectively, as found at http://mail.python.org). This python-dev summary is the 15th written by the python-dev summary pair of Steve Bethard and Tony Meyer (some day we'll really catch up). To contact us, please send email: - Steve Bethard (steven.bethard at gmail.com) - Tony Meyer (tony.meyer at gmail.com) Do *not* post to comp.lang.python if you wish to reach us. The `Python Software Foundation`_ is the non-profit organization that holds the intellectual property for Python. It also tries to advance the development and use of Python. If you find the python-dev Summary helpful please consider making a donation. You can make a donation at http://python.org/psf/donations.html . Every cent counts so even a small donation with a credit card, check, or by PayPal helps. -------------------- Commenting on Topics -------------------- To comment on anything mentioned here, just post to `comp.lang.python`_ (or email python-list at python.org which is a gateway to the newsgroup) with a subject line mentioning what you are discussing. All python-dev members are interested in seeing ideas discussed by the community, so don't hesitate to take a stance on something. And if all of this really interests you then get involved and join `python-dev`_! ------------------------- How to Read the Summaries ------------------------- That this summary is written using reStructuredText_. Any unfamiliar punctuation is probably markup for reST_ (otherwise it is probably regular expression syntax or a typo :); you can safely ignore it. We do suggest learning reST, though; it's simple and is accepted for `PEP markup`_ and can be turned into many different formats like HTML and LaTeX. Unfortunately, even though reST is standardized, the wonders of programs that like to reformat text do not allow us to guarantee you will be able to run the text version of this summary through Docutils_ as-is unless it is from the `original text file`_. .. _python-dev: http://www.python.org/dev/ .. _SourceForge: http://sourceforge.net/tracker/?group_id=5470 .. _python-dev mailing list: http://mail.python.org/mailman/listinfo/python-dev .. _c.l.py: .. _comp.lang.python: http://groups.google.com/groups?q=comp.lang.python .. _PEP Markup: http://www.python.org/peps/pep-0012.html .. _Docutils: http://docutils.sf.net/ .. _reST: .. _reStructuredText: http://docutils.sf.net/rst.html .. _PSF: .. _Python Software Foundation: http://python.org/psf/ .. _original text file: http://www.python.org/dev/summary/2006-03-01_2006-03-15.rst .. _archive: http://www.python.org/dev/summary/ .. _RSS feed: http://www.python.org/dev/summary/channews.rdf From frank at chagford.com Fri Apr 7 05:29:47 2006 From: frank at chagford.com (Frank Millman) Date: 7 Apr 2006 02:29:47 -0700 Subject: Quickie: converting r"\x2019" to int In-Reply-To: References: <4435501d$1_2@newspeer2.tds.net> Message-ID: <1144402187.703404.132530@v46g2000cwv.googlegroups.com> Robin Haswell wrote: > > rob at aranea:~$ python > Python 2.4.2 (#2, Sep 30 2005, 21:19:01) > [GCC 4.0.2 20050808 (prerelease) (Ubuntu 4.0.1-4ubuntu8)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> int("\x2019") > 19 > >>> > > Something like that. Except with: > > >>> int(r"\x2019") > Traceback (most recent call last): > File "", line 1, in ? > ValueError: invalid literal for int(): \x2019 > >>> > > > :-) > > -Rob I decided to use this as a learning exercise for myself. This is what I figured out. All quotes are paraphrased from the docs. "\xhh in a string substitutes the character with the hex value hh. Unlike in Standard C, at most two hex digits are accepted." \x20 is equal to a space. Therefore '\x2019' is equal to ' 19'. "int(x) converts a string or number to a plain integer. If the argument is a string, it must contain a possibly signed decimal number representable as a Python integer, possibly embedded in whitespace." Therefore int(' 19') is equal to 19. "When an 'r' prefix is present, a character following a backslash is included in the string without change, and all backslashes are left in the string". Therefore r'\x2019' is left unchanged, and cannot be converted to an int. Rob, this explains *why* you are getting the above error. It does not explain how to achieve your objective, as you have not specified what it is. If you give more information, one of the resident gurus may be able to assist you. Frank Millman From fredrik at pythonware.com Sun Apr 2 10:19:00 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 2 Apr 2006 16:19:00 +0200 Subject: why doesn't is work?a script to backup a directory References: <1143859031.679813.94400@i40g2000cwc.googlegroups.com><1143893556.309560.53090@u72g2000cwu.googlegroups.com><1143894302.551308.98710@u72g2000cwu.googlegroups.com> Message-ID: I wrote: > > WindowsError: [Errno 3] : 'O:/eb/mb/S/*.*' > > shutil.rmtree() expects a directory name, not a file pattern. if you leave > out the "*.*" part at the end, it should do what you want. postscript: typically enough, I stumbled upon the same error message myself, a day later. looks like it's Windows that adds the "*.*" thing to the path, all by itself. however, on my machine, I get a bit more information: WindowsError: [Errno 3] The system cannot find the path specified: 'directory/*.*' From petergoffin at hotmail.com Mon Apr 24 10:27:58 2006 From: petergoffin at hotmail.com (PeterG) Date: 24 Apr 2006 07:27:58 -0700 Subject: Twisted/wxPython Problem... Message-ID: <1145888878.330009.154320@u72g2000cwu.googlegroups.com> Hi, I am relatively new to Python, and am learning it as part of a university module... Im currently undertaking a project to create an IM server and IM gui client. I have a very basic server, and a basic gui client. I can get my client to connect to my server, but cant get it to disconnect or send messages to the server. I am getting the following error when I click on the 'Disconnect' button - AttributeError: 'NoneType' object has no attribute 'loseConnection' I have attached the code for both the server and the client below this. I am using the Twisted and wxPython packages, and as previously stated am fairly new to Python so would appreciate any help anyone can offer. Thanks, Peter server.py ------------ from twisted.internet import reactor from twisted.internet.protocol import Factory from twisted.protocols.basic import LineReceiver factory = Factory() #this is a list factory.transports = [] #this is a dictionary userNicknames = {} class SimpleLogger(LineReceiver): def connectionMade(self): self.factory.transports.append(self.transport) userNicknames[self.transport.client] = '' #write to the client self.transport.write("Welcome to Chris & Pete's chat server!\r\n") self.transport.write("Please enter your nickname:\r\n") #prints on the server screen print 'got connection from', self.transport.client def connectionLost(self, reason): who = str(userNicknames.get(self.transport.client)) + ' Disconnected' + '\r\n' print who userNicknames[self.transport.client] = '' for transport in self.factory.transports: transport.write(who) def lineReceived(self, line): #if the users nickname in the dictionary (userNicknames) is blank, create a #value in the dictionary with the line just received. #if the user already has a nickname then it must be a message they are writing. #So instead print out the message if userNicknames.get(self.transport.client) == '': #if the username is already in the dictionary someone is #already using it so ask for another one. if line in userNicknames.values(): self.transport.write('That nickname is already in use, please use another:') else: userNicknames[self.transport.client] = line #print userNicknames.items() message = userNicknames.get(self.transport.client) + ' has joined\r\n' for transport in self.factory.transports: transport.write(message) else: message = userNicknames.get(self.transport.client) + ': ' + line + '\r\n' for transport in self.factory.transports: transport.write(message) factory.protocol = SimpleLogger reactor.listenTCP(1234, factory) reactor.run() client.py ---------- from wxPython.wx import * import wx from twisted.internet import wxreactor wxreactor.install() from twisted.internet import reactor from twisted.internet.protocol import Protocol, ClientCreator class imApp(wxApp, Protocol): def buildMe(self): frame = wx.Frame(None, title="IM Client", size=(800, 550)) bkg = wx.Panel(frame) global ipAdd global portNo global messages global newMsg ipAddLab = wx.StaticText(bkg, -1, 'IP Address: ') ipAdd = wx.TextCtrl(bkg) ipAdd.SetToolTipString('Please enter the server IP address here.') spacer1 = wx.StaticText(bkg, -1, ' ') portNoLab = wx.StaticText(bkg, -1, 'Port No: ') portNo = wx.TextCtrl(bkg) portNo.SetToolTipString('Please enter the port number the server is using here.') spacer2 = wx.StaticText(bkg, -1, ' ') connectButton = wx.Button(bkg, label='Connect') connectButton.SetToolTipString('Click this button to connect to the server.') connectButton.Bind(wx.EVT_BUTTON, self.connectMe) disconnectButton = wx.Button(bkg, label='Disconnect') disconnectButton.SetToolTipString('Click this button to disconnect from the server.') disconnectButton.Bind(wx.EVT_BUTTON, self.disconnectMe) messages = wx.TextCtrl(bkg, style=(wx.TE_MULTILINE | wx.HSCROLL)) newMsg = wx.TextCtrl(bkg) sendButton = wx.Button(bkg, label='Send') sendButton.SetToolTipString('Click this button to send a message to the server.') sendButton.Bind(wx.EVT_BUTTON, self.sendMe) hbox1 = wx.BoxSizer() hbox1.Add(ipAddLab, proportion=0, flag=wx.EXPAND) hbox1.Add(ipAdd, proportion=0, flag=wx.EXPAND) hbox1.Add(spacer1, proportion=0, flag=wx.EXPAND) hbox1.Add(portNoLab, proportion=0, flag=wx.EXPAND) hbox1.Add(portNo, proportion=0, flag=wx.EXPAND) hbox1.Add(spacer2, proportion=0, flag=wx.EXPAND) hbox1.Add(connectButton, proportion=0, flag=wx.LEFT, border=5) hbox1.Add(disconnectButton, proportion=0, flag=wx.LEFT, border=5) hbox2 = wx.BoxSizer() hbox2.Add(newMsg, proportion=1, flag=wx.EXPAND | wx.LEFT | wx.LEFT | wx.LEFT, border=5) hbox2.Add(sendButton, proportion=0, flag=wx.LEFT, border=5) vbox = wx.BoxSizer(wx.VERTICAL) vbox.Add(hbox1, proportion=0, flag=wx.EXPAND | wx.ALL, border=5) vbox.Add(messages, proportion=1, flag=wx.EXPAND | wx.LEFT | wx.LEFT | wx.LEFT, border=5) vbox.Add(hbox2, proportion=1, flag=wx.EXPAND | wx.ALL, border=5) bkg.SetSizer(vbox) ipAdd.WriteText('localhost') portNo.WriteText('1234') frame.Show(true) return true def sendMe(self, e): msg = newMsg.GetValue() + '\n' messages.WriteText(msg) newMsg.SetValue('') def disconnectMe(self, e): messages.WriteText('Disconnecting from server...\n') self.transport.loseConnection() def connectMe(self, e): messages.WriteText('Connecting to server...\n') c = ClientCreator(reactor, imApp) ip = str(ipAdd.GetValue()) port = int(portNo.GetValue()) c.connectTCP(ip, port) def mainProg(): app = imApp(0) app.buildMe() reactor.registerWxApp(app) reactor.run() if __name__ == '__main__': mainProg() From brennan162 at sbcglobal.net Tue Apr 4 19:42:09 2006 From: brennan162 at sbcglobal.net (fxe) Date: Tue, 4 Apr 2006 16:42:09 -0700 (PDT) Subject: tkinter canvas In-Reply-To: <1144193602.772.18.camel@cornell> References: <3753823.post@talk.nabble.com> <1144193602.772.18.camel@cornell> Message-ID: <3755397.post@talk.nabble.com> Hi John , thanks a million for the info.Looking at your solution I am sure this would work. After struggling with this for the past few hours I found another way just before reading your post. Its as simple as : canvas.create_line(x1,y1,x2,y2,fill='#000000',state=DISABLED) Thanks again, Tom -- View this message in context: http://www.nabble.com/tkinter-canvas-t1395807.html#a3755397 Sent from the Python - python-list forum at Nabble.com. From cfajohnson at gmail.com Wed Apr 12 15:59:05 2006 From: cfajohnson at gmail.com (Chris F.A. Johnson) Date: Wed, 12 Apr 2006 15:59:05 -0400 Subject: symbolic links, aliases, cls clear References: <1143672131.167324.36920@i39g2000cwa.googlegroups.com> <1144844223.094969.82870@t31g2000cwb.googlegroups.com> <87r7430x2t.fld@apaflo.com> <4a53skFr812lU1@individual.net> Message-ID: <9p20h3-sfc.ln1@xword.teksavvy.com> On 2006-04-12, jpd wrote: > Begin > On 2006-04-12, Chris F.A. Johnson wrote: >> These days, the ISO-6429 standard (almost the same as the older >> ANSI x3.64) is so close to universal that I don't bother writing >> for anything else any more. > > Oh, wonderful. ``All the world's a vax^W^WISO-6429 compatible'' all over > again. > >> If the need arises, I'll do it, but it will be simple to do, and >> much faster (both in coding and script execution) than trying to >> accommodate all terminals from the start. > > Yes, why use a perfectly good abstraction when you can hardcode stuff. If it were perfectly good, there would be no question; however, it's not. >> I still have a system which does not have tput. > > And that justifies everything else. Of course. If I want to write portable scripts, then yes, it does. -- Chris F.A. Johnson, author | Shell Scripting Recipes: | My code in this post, if any, A Problem-Solution Approach | is released under the 2005, Apress | GNU General Public Licence From forward at seznam.cz Sat Apr 1 09:07:52 2006 From: forward at seznam.cz (forward at seznam.cz) Date: 1 Apr 2006 06:07:52 -0800 Subject: String pattern matching In-Reply-To: <1143888648.234963.326000@j33g2000cwa.googlegroups.com> References: <1143888648.234963.326000@j33g2000cwa.googlegroups.com> Message-ID: <1143900472.857612.72840@z34g2000cwc.googlegroups.com> Firstly sort variable expressions by its length xy = 'abca' xyz = 'abcaaab' vxw = 'eeabcac' Expand all expressions by its values except itself xy = 'abca' 'abca' z = 'abcaaab' vxw = 'eeabcac' Cut all left and right matches xy = 'abca' z = 'aab' vxw = 'eeabcac' Repeat until you can. z = 'aab' xy = 'abca' vxw = 'eeabcac' Get first variable expression intersection - variables: x is longest intersection of xy and vxw - value : 'abca' starting at position 2 of vxw (longest intersection of 'abca' and 'eeabcac') 'a' starting at position 5 of vxw Then try matching: x='abca' (at position 2 of vxw) x='abc' (at position 2 of vxw) x='ab' (at position 2 of vxw) x='a' (at position 2 of vxw) x='a' (at position 5 of vxw) x='' (at position arbitrary position of vxw) and calculate the others. Repeat all step until you can. In your example, there are 13 results. x='abca' y='' z='aab' v='ee' w='c' x='abc' y='a' z='aab' v='ee' w='ac' x='ab' y='ca' z='aab' v='ee' w='cac' x='a' y='bca' z='aab' v='ee' w='bcac' x='a' y='bca' z='aab' v='eeabc' w='c' x='' y='abca' z='aab' v='' w='' x='' y='abca' z='aab' v='e' w='eabcac' x='' y='abca' z='aab' v='ee' w='abcac' x='' y='abca' z='aab' v='eea' w='bcac' x='' y='abca' z='aab' v='eeab' w='cac' x='' y='abca' z='aab' v='eeabc' w='ac' x='' y='abca' z='aab' v='eeabca' w='c' x='' y='abca' z='aab' v='eeabcac' w='' with the same original expressions xy = 'abca' xyz = 'abcaaab' vxw = 'eeabcac' Note that maximum matching is best matching in some kind of problems. Cutting off empty values, you can get 4 results: x='abc' y='a' z='aab' v='ee' w='ac' x='ab' y='ca' z='aab' v='ee' w='cac' x='a' y='bca' z='aab' v='ee' w='bcac' x='a' y='bca' z='aab' v='eeabc' w='c' From tjreedy at udel.edu Sat Apr 1 18:53:02 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 1 Apr 2006 18:53:02 -0500 Subject: Identifying filled circles in a scanned image References: <20060330231044.66670.qmail@web34203.mail.mud.yahoo.com> <87fykxhsm2.fsf@pobox.com> Message-ID: "> Douglas Douglas writes: > >> Hi everybody. >> >> I have a paper form that I scan into an image. My user fills some >> circles in >> this paper form using black ink. Every form has ten rows with five >> circles each >> and the user fills only one circle for each row. >> >> I was wondering if I could use the Python Imaging Library to process >> these >> forms. I know the Image class is really powerful, but I can't think of a >> way of >> how to locate wich circle was filled. I though about this problem once but never had occasion to do anything concrete. The key is to have some landmarks on the paper form that the analysis program can find. One can then convert between printed image coordinates and scanned image coordinates. This corrects for both variations in image placement on the sheet and sheet placement on the scanner. Terry Jan Reedy From peter at engcorp.com Fri Apr 7 16:23:16 2006 From: peter at engcorp.com (Peter Hansen) Date: Fri, 07 Apr 2006 16:23:16 -0400 Subject: GUI Treeview In-Reply-To: References: Message-ID: Arne wrote: > Hello ! > > I am looking for a widget with the following properties: > - showing the tree file structure/ directory structure > - next to each file should be a checkbox > - the tree should only show certain files (i. e. only for the looked in > user) For which GUI framework? (e.g. Tkinter, wxPython, etc...) -Peter From cginboston at hotmail.com Sun Apr 9 12:21:41 2006 From: cginboston at hotmail.com (Chance Ginger) Date: Sun, 09 Apr 2006 16:21:41 GMT Subject: Decorators, Identity functions and execution... References: <1144597938.664642.133100@v46g2000cwv.googlegroups.com> Message-ID: First, thanks for the tip of 'tabs'. I keep forgetting Outlook has some interesting rules about displaying text. Thanks for the comment about happening at load time. That resolved the problem (in my thinking)! I don't believe I have an issue at all... Peace, CG. On Sun, 09 Apr 2006 08:52:18 -0700, Carl Banks wrote: > > Chance Ginger wrote: >> On Sun, 09 Apr 2006 09:51:18 +0200, Fredrik Lundh wrote: >> >> > Chance Ginger" wrote: >> > >> >> If I define a decorator like: >> >> >> >> def t(x) : >> >> def I(x) : return x >> >> return I >> > >> > ... you get a syntax error. >> > >> >> It isn't a syntax error...I tried it before I posted. In fact >> def t(x) : >> def I(x) : return x >> return I >> >> is correct. > > You've made the unfortunate mistake of indenting it with tabs, which do > not show up on some newsreaders. I see the tabs in Google; people > using Microsoft Outlook do not. > > Always use spaces when posting, and use them in your code as well. > Spaces are the current recommended practice, and in the future tabs > might become illegal. I'd prefer tabs myself, but it's more important > to respect community standards than to stick to some silly preference > you have. > > >> Decorators are a way to add "syntactic" sugar to Python, >> extending it in ways that make it useful for tools. What >> I am trying to do is lessen the impact on the time used >> in executing Python code when I use some forms of decorators. > > One suggestion. Have you run the script, determined it's too slow, and > are trying to optimize? If not (and it doesn't sound like you are), I > suggest that it's too soon to worry about whether this decorator has > any overhead. You may end up doing a lot of work optimizing that will > ultimately have very little benefit. > > Having said that, this decorator will not affect calling overhead at > all. The decorator is applied when the module is loaded, not when the > decorated function is called. > > > Carl Banks From jon+usenet at unequivocal.co.uk Mon Apr 3 10:58:13 2006 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: 3 Apr 2006 14:58:13 GMT Subject: Difference between 'is' and '==' References: <1143459098.385264.139560@g10g2000cwb.googlegroups.com> Message-ID: In article , Roy Smith wrote: > This may even be useful. What if you were trying to emulate SQL's > NULL? NULL compares false to anything, even itself. Strictly speaking, comparing NULL to anything gives NULL, not False. From johnjsal at NOSPAMgmail.com Fri Apr 28 14:05:37 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 28 Apr 2006 18:05:37 GMT Subject: best way to determine sequence ordering? In-Reply-To: <1146246356.220444.55460@g10g2000cwb.googlegroups.com> References: <70q4g.2006$No6.43783@news.tufts.edu> <1146246356.220444.55460@g10g2000cwb.googlegroups.com> Message-ID: gry at ll.mit.edu wrote: > index is about the best you can do with the structure you're using. > If you made the "items" instances of a class, then you could define a > __cmp__ member, which would let you do: > > a=Item('A') > b=Item('B') > if a > The Item class could use any of various means to maintain order > information. If there are not too many values, it could have a > dictionary storing an integer for the order: > > class Item(object): > def __init__(self, value): > self.val=value > self.order = dict(c=0, a=1, d=2, b=3) > def __cmp__(self, other): > return cmp(self.order[self.val], self.order[other.val]) > > If you don't care about performance, or you find it clearer, just use: > self.order = ['C', 'A', 'D', 'B'] > and > def __cmp__(self, other): > return cmp(self.order.index(self.value), > self.order.index(other.value)) > > > -- George Young > Thanks. As I progressed with my little project, I was beginning to wonder about making a class, so your suggestions might be helpful if I convert it to that. From fredrik at pythonware.com Mon Apr 24 08:39:20 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 24 Apr 2006 14:39:20 +0200 Subject: need a thread to keep a socket connection alive? References: <1145718638.526525.235090@i39g2000cwa.googlegroups.com> Message-ID: Roy Smith wrote: > If you want to read fixed-length messages (as you appear to be trying to do > with your recv(158)), you need to build a buffering layer which reads from > the socket into a buffer and then doles out messages to a higher layer from > that buffer. > This is not a trivial problem. By the time you're done with it, you will > have learned a lot about how to communicate over a network. however, creating a buffered layer for reading is a trivial problem: just call makefile on the socket object, and use the resulting object as a file handle: >>> s = socket.socket() >>> s.connect(("www.python.org", 80)) >>> s.send("GET / HTTP/1.0\n\n") 16 >>> f = s.makefile() >>> f.readline() 'HTTP/1.1 200 OK\r\n' >>> f.readline() 'Date: Mon, 24 Apr 2006 12:37:46 GMT\r\n' >>> f.read(10) 'Server: Ap' >>> f.read(10) 'ache/2.0.5' >>> f.readline() '4 (Debian GNU/Linux) DAV/2 SVN/1.1.4 mod_python/3.1.3 ... >>> f.readline() 'Last-Modified: Mon, 24 Apr 2006 04:52:53 GMT\r\n' etc. From sjmachin at lexicon.net Thu Apr 20 22:46:38 2006 From: sjmachin at lexicon.net (John Machin) Date: Fri, 21 Apr 2006 12:46:38 +1000 Subject: tail a file (win) In-Reply-To: References: Message-ID: <444847a7$1@news.eftel.com> On 21/04/2006 11:24 AM, Ryan Ginstrom wrote: >> Behalf Of david brochu jr >> I wrote a script to monitor ping activity and output it to a >> log file. I am using windows and want to have another script >> constantly check the latest entry to see if Request timed out >> is seen. Is there a way to "tail" a file much like I would in >> Unix so I can just see the latest entry and move from there? > > The method I would use that is not RAM/CPU intensive would be to create a > memory-mapped file, take the size of the file, and increment your pointer to > file_length - tail_size. > > The Windows API functions to look at are: > CreateFile > CreateFileMapping > MapViewOfFile > > I'm sorry, but I'm not a ctypes guru so can't tell you how you would > accomplish this in python. (The C(++) code is fairly straightforward, > however). This possibly could be done without using the Windows API, just by using the mmap module and otherwise standard Python file functionality. However if the need would be met by a tail.exe, consider not re-inventing the wheel: http://en.wikipedia.org/wiki/GnuWin32 From nuffnough at gmail.com Sun Apr 30 11:25:20 2006 From: nuffnough at gmail.com (nuffnough at gmail.com) Date: 30 Apr 2006 08:25:20 -0700 Subject: Can I collapse a Panel in wxPython? Message-ID: <1146410720.541919.54910@j33g2000cwa.googlegroups.com> Hi. I have a gui with one frame and 5 panels. The second panel will only be required in some cases, so I am wondering if there is some way I can only create this panel in the circumstances where it is required, confirmed by a simple len(list) > 1 If it is possible, I am wondering how I might go about it.... I am not sure where to put an if statement as there are many different referrals to panel_2 Letting me know or just pointing me to an example of such a thing would be fabulous. TIA From codecraig at gmail.com Fri Apr 28 08:11:21 2006 From: codecraig at gmail.com (abcd) Date: 28 Apr 2006 05:11:21 -0700 Subject: Add file to zip, or replace file in zip Message-ID: <1146226281.040805.252450@j33g2000cwa.googlegroups.com> I have a script which zips up a directory, once it does with that (before it closes the zip file) I want to replace a file that was added to the zip, say "Foo.txt". So I tried this... [code] z = zipfile.ZipFile("blah.zip", "w") # zip the directory #... z.writestr("c:\\path\\to\\current\\foo_txt_file\\Foo.txt", "some new data") z.close() All this does is add a new Foo.txt file in the zip alongside the existing one....any suggestions? Thanks From walterbyrd at iname.com Sun Apr 9 14:03:52 2006 From: walterbyrd at iname.com (walterbyrd) Date: 9 Apr 2006 11:03:52 -0700 Subject: Best Python web-hosting? Message-ID: <1144605832.364688.305300@j33g2000cwa.googlegroups.com> I don't need that much web space. I don't need Zope/Plone. But, I want a site that offers more than just CGI. And I would like support for recent Python releases. Price is an issue, that's one reason I've been reluctant to use python for web-sites, hosting seems to be more expensive than with php. From nobody at 127.0.0.1 Wed Apr 26 14:09:15 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 26 Apr 2006 18:09:15 GMT Subject: A defense for bracket-less code References: Message-ID: Dave Hansen wrote: > Not really. It was mostly a lead-in to that last sentence. Problems > like this couldn't happen in Python. So it's an opportunity to get a > giggle at the expense of programmers using a language that gives you > enough rope to shoot yourself in the foot... Which can be entirely avoided by making the braces mandatory rather than optional. This is one thing perl got right: while (foo); # parse error while (foo) next; # parse error while (foo) { next; } # ok while (foo) { } # ok And if you compile C++ without a lint checker, well, you're playing with fire. :) From fuzzyman at gmail.com Fri Apr 7 18:07:03 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 7 Apr 2006 15:07:03 -0700 Subject: ANN: ConfigObj 4.3.0 Message-ID: <1144447623.503072.3760@i40g2000cwc.googlegroups.com> `ConfigObj 4.3.0 `_ is now released. This has several bugfixes, as well as *several* major feature enhancements. You can download it from : `ConfigObj-4.3.0.zip 244Kb `_ .. raw:: html {title;What is ConfigObj ?} **ConfigObj** is a simple but powerful config file reader and writer: an *ini file round tripper*. Its main feature is that it is very easy to use, with a straightforward programmer's interface and a simple syntax for config files. It has lots of other features though : * Nested sections (subsections), to any level * List values * Multiple line values * String interpolation (substitution) * Integrated with a powerful validation system - including automatic type checking/conversion - repeated sections - and allowing default values * All comments in the file are preserved * The order of keys/sections is preserved * No external dependencies * Full Unicode support * A powerful ``unrepr`` mode for storing basic datatypes .. raw:: html {title;What's New ?} Moved the tests and the CHANGELOG (etc) into a separate file. This has reduced the size of ``configobj.py`` by about 40%. Added the ``unrepr`` mode to reading and writing config files. Thanks to Kevin Dangoor for this suggestion. Empty values are now valid syntax. They are read as an empty string ``''``. (``key =``, or ``key = # comment``.) ``validate`` now honours the order of the configspec. Added the ``copy`` mode to validate. Thanks to Louis Cordier for this suggestion. Fixed bug where files written on windows could be given ``'\r\r\n'`` line terminators. Fixed bug where last occurring comment line could be interpreted as the final comment if the last line isn't terminated. Fixed bug where nested list values would be flattened when ``write`` is called. Now sub-lists have a string representation written instead. Deprecated ``encode`` and ``decode`` methods instead. You can now pass in a ConfigObj instance as a configspec (remember to read the configspec file using ``list_values=False``). From aahz at pythoncraft.com Sun Apr 16 13:25:05 2006 From: aahz at pythoncraft.com (Aahz) Date: 16 Apr 2006 10:25:05 -0700 Subject: Python certification/training References: <1145193231.657614.275950@v46g2000cwv.googlegroups.com> <1145205741.731529.84530@u72g2000cwu.googlegroups.com> Message-ID: In article <1145205741.731529.84530 at u72g2000cwu.googlegroups.com>, wrote: > >I asked about training/certification because its proved to be a good >way for me to learn in the past. > >My aim is not to gain recognition but more to measure my understanding >- a sort of benchmark. I have been so far unable to find any courses >offering training in my country that would not bankrupt me (I live in >South Africa). Then may I suggest that you subscribe to the tutor list? That will give you a good place to ask questions; as you learn Python, answering other people's questions will give you a good way to hone your own knowledge. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "LL YR VWL R BLNG T S" From chief7 at netvision.net.il Sun Apr 16 12:36:06 2006 From: chief7 at netvision.net.il (internetDotComs.com) Date: Sun, 16 Apr 2006 18:36:06 +0200 Subject: for sale: internetDotComs.com Message-ID: domain for sale: internetdotcoms.com http://www.afternic.com/name.php?id=11866440 From Serge.Orlov at gmail.com Sat Apr 15 17:05:26 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 15 Apr 2006 14:05:26 -0700 Subject: Announce: Construct's wiki! In-Reply-To: References: <1144958936.581310.256830@v46g2000cwv.googlegroups.com> Message-ID: <1145135126.069723.160800@z34g2000cwc.googlegroups.com> skip at pobox.com wrote: > tomer> so now we have one place where people can share inventory > tomer> constructs, questions-and-answers, patches, documentation and > tomer> more. enjoy. > > I've never seen Construct before, but when you say "parser" I think of > parsing programming languages. The couple of examples on the Construct wiki > look more like what I'd use the struct module for. Kind of. Except that struct module does not scale and is less readable. You can say struct is not pythonic, construct is. IMHO construct is a good candidate for stdlib Serge. From Aiwass333 at gmail.com Thu Apr 27 17:21:54 2006 From: Aiwass333 at gmail.com (RunLevelZero) Date: 27 Apr 2006 14:21:54 -0700 Subject: Regular Expression help In-Reply-To: <1146172456.106195.243160@j33g2000cwa.googlegroups.com> References: <1146162048.903980.281290@y43g2000cwc.googlegroups.com> <1146172456.106195.243160@j33g2000cwa.googlegroups.com> Message-ID: <1146172914.383277.259940@u72g2000cwu.googlegroups.com> I considered that but what I need is simple and I don't want to use another library for something so simple but thank you. Plus I don't understand them all that well :) From sushant.sirsikar at gmail.com Fri Apr 7 02:19:29 2006 From: sushant.sirsikar at gmail.com (sushant.sirsikar at gmail.com) Date: 6 Apr 2006 23:19:29 -0700 Subject: good style guides for python-style documentation ? In-Reply-To: References: Message-ID: <1144390769.404217.200620@u72g2000cwu.googlegroups.com> Fredrik Lundh wrote: > (reposted from doc-sig, which seems to be mostly dead > these days). > > over at the pytut wiki, "carndt" asked: > > Are there any guidelines about conventions concerning > punctuation, text styles and language style (e.g. how > to address the reader)? > > any suggestions from this list ? > > Hi You can read the document given in link: Documenting Python http://docs.python.org/dev/doc/style-guide.html Bye From g.brandl-nospam at gmx.net Tue Apr 11 07:09:54 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Tue, 11 Apr 2006 13:09:54 +0200 Subject: Why new Python 2.5 feature "class C()" return old-style class ? In-Reply-To: <1144752553.305591.88050@j33g2000cwa.googlegroups.com> References: <1144752553.305591.88050@j33g2000cwa.googlegroups.com> Message-ID: looping wrote: > For Python developers around. > >>From Python 2.5 doc: > The list of base classes in a class definition can now be empty. As an > example, this is now legal: > class C(): > pass > > nice but why this syntax return old-style class, same as "class C:", > and not the new style "class C(object):" ? > Old-style class are somewhat deprecated and could be almost always be > replaced by new-style class, so this syntax could be a nice shortcut to > create them. > > Am I wrong or is there something that I've missed ? class C(): is meant to be synonymous with class C: and therefore cannot create a new-style class. Georg From pruebauno at latinmail.com Thu Apr 6 12:09:39 2006 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: 6 Apr 2006 09:09:39 -0700 Subject: "definitive" source on advanced python? References: <1144040231.239622.159630@j33g2000cwa.googlegroups.com> Message-ID: <1144339779.112572.55170@v46g2000cwv.googlegroups.com> vdrab wrote: > Hi all, > > Is there some sort of coherent source (dead tree format, maybe?) on > some of the more advanced features > of python (decorators, metaclasses, etc)? I'm sort of looking for a If you just want a good book in feature description I recomend Python in a Nutshell. It will explain everything you ever did (or didn't) want to know without much fuzz. It will not have a long list of when you should use them. For the later the Python Cookbook is probably more appropiate. It is the book with the most amount and kind of advanced stuff IMHO. The printed version is much better than the online because it not only contains the examples but explains how they work. The problem is that the cookbook is organized by problem domain and not by implementation technique. To learn techniques you have to read it like the Bible: you read the stories and try to deduce what it tells you about Python. From josecarlos.balderas at gmail.com Wed Apr 5 04:56:26 2006 From: josecarlos.balderas at gmail.com (Jose Carlos Balderas Alberico) Date: Wed, 5 Apr 2006 10:56:26 +0200 Subject: Problem connecting Python with PostgreSQL Message-ID: Hello. I have a problem connecting to a PostgreSQL database and I don't know where the problem lays. A bit of background: I installed the psycopg module yesterday (it was a bit of a pain to do it since I installed the wrong version and it didn't work). I got to install it in the end anyway. I have a database hosted in a server (let's call it xxx.yy.com). I need to access that database from another computer. I have configured the PostgreSQL server right (except something I'll explain later), and added the right line to the pg_hba.conf file. After trying to connect to the server using the connect() function in the psycopg module, I get the following error message after a few seconds: "psycopg.OperationalError: could not connect to server: Connection timed out Is the server running on host xxx.yy.com and accepting TCP/IP connections on port 5432?" Following the error's suggestion, I went to check the Postgresql.conf file, and realized the "tcpip_socket = true" line was commented. I uncommented the line, and after restarting the server, it crashed, so I commented the line again. I thought that was the source of the problem, but when I checked my netstat, realized that the postgresql server was listening on port 5432... Don't ask me why, since the line "tcpip_socket = true" was commented. But why does the server crash when I try to set tcpip_socket to true? Anyway, I'm now out of possible solutions. Maybe the source of the error lays in a different place. I really need help on this. Has anyone ever gotten the same error message before, or is familiar with it? If you need more information about the error, I'll be glad to share it with you. Thank you very much for your attention. Jose Carlos. -------------- next part -------------- An HTML attachment was scrubbed... URL: From Andreas.Ames at comergo.com Fri Apr 28 05:54:35 2006 From: Andreas.Ames at comergo.com (Ames Andreas) Date: Fri, 28 Apr 2006 11:54:35 +0200 Subject: MinGW and Python Message-ID: <552B6B925278EF478EA8887D7F9E5AC3814E44@tndefr-ws00024.tenovis.corp.lan> > -----Original Message----- > From: python-list-bounces+andreas.ames=comergo.com at python.org > [mailto:python-list-bounces+andreas.ames=comergo.com at python.or > g] On Behalf Of Ross Ridge > Sent: Thursday, April 27, 2006 8:53 PM > Subject: Re: MinGW and Python > > > No one is working on removing MinGW's depency on MSVCRT.DLL. There is certainly work underway to ease the use of msvcrXX in mingw built binaries. It's already possible to do it today with some tweaking, but I seem to remember that this was already mentioned in this thread. For example: http://sourceforge.net/mailarchive/message.php?msg_id=7374474 I don't think it is a technical problem that prevents a mingw-python from being distributed, I rather see (in no particular order): 1) psychological issues: 'convenient IDE', 'better debugger' 2) legal issues: redistribution of msvcrXX 3) 'economical' issues: no one seems to be willing to reliably support a mingw-python No. 2 could be a show-stopper. There remains one technical issue that isn't a killer but would be inconvenient, IMHO: Can pywin32 be made working with a mingw-python (I'm quite sure it can't be made building on it)? I'd appreciate any datapoints about that ... cheers, aa -- Andreas Ames | Programmer | Comergo GmbH | Voice: +49 69 7505 3213 | ames AT avaya . com From rob at digital-crocus.com Thu Apr 6 13:28:28 2006 From: rob at digital-crocus.com (Robin Haswell) Date: Thu, 06 Apr 2006 18:28:28 +0100 Subject: Cleaning the current environment after a fork References: <49k9u6Fp6as8U1@uni-berlin.de> Message-ID: On Thu, 06 Apr 2006 12:47:25 +0200, Diez B. Roggisch wrote: > And even if that wasn't the case: I think as long as you don't run into > memory-troubles, don't do it. Its complex, flaky and thus an unnecessary > source of failure. Yeah that sounds fair enough. Actually I ran in to threading problems so I sorted out a way of transferring my data Thanks -Rob > > Diez From mensanator at aol.com Sat Apr 8 23:51:36 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 8 Apr 2006 20:51:36 -0700 Subject: programming puzzles? In-Reply-To: <7xpsjrwhm6.fsf@ruckus.brouhaha.com> References: <44381f2f$0$4209$c3e8da3@news.astraweb.com> <1144532090.213069.191600@i39g2000cwa.googlegroups.com> <4438428e$0$11362$c3e8da3@news.astraweb.com> <1144543413.421821.132730@e56g2000cwe.googlegroups.com> <7xpsjrwhm6.fsf@ruckus.brouhaha.com> Message-ID: <1144554696.748228.12310@g10g2000cwb.googlegroups.com> Paul Rubin wrote: > "Michael Tobis" writes: > > The first piece of code that I ever voluntarily wrote was intended to > > solve this puzzle: > > > > Assign the number 2 to 'a', 3 to 'b' ... 27 to 'z'. To each word assign > > the value of the product of its characters. Find the English (or > > language of your choice) word whose product is closest to a million (or > > number of your choice). > > Hey, that was a contest in Games Magazine in the 1980's. A co-worker > and I used a PDP-10 BASIC program to search for numbers near 1 million > with no prime factors higher than 27. The factorizations of those > numbers told us which letters to try to use, and after a while of > fooling around rearranging letters on a whiteboard, we came up with > "curvy", a very recognizable word that multiplies out to 999,856. > > That's the closest number to 1 million (other than 1 million itself) > which doesn't have any prime factors that are too large. We convinced > ourselves that there was no word that multiplied to exactly 1 million, > so we felt we were likely to win the contest. However, somebody > apparently with a computerized word list won with "ixodid". It was > fun to remember this. The trouble with word lists is when you run across something you don't recognize, like "ixodid", you can't tell if it's a word or an acronym or an abbreviation. Being in the environmental remediation business, I thought "dioxid" (which I assume is related to "dioxin") to be more plausible as a word. And it would seem that Games no longer has contests that simply find words, they add a twist to prevent those like me from having an advantage. See I still used my word list database to find valid words to use in my contest entries, but entries are judged, not simply scored. From nobody at 127.0.0.1 Thu Apr 20 14:28:25 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Thu, 20 Apr 2006 18:28:25 GMT Subject: perspective on ruby In-Reply-To: <1145555339.316764.123210@i39g2000cwa.googlegroups.com> References: <1145555339.316764.123210@i39g2000cwa.googlegroups.com> Message-ID: RK wrote: > I just don't get it. The scripted object-oriented clean programming > language is done. Nothing's ever done except LISP. There's always room for experimentation and improvement. > I'm more than willing to supprt RoR if it's being sold as the popular > alternative to .NET programming, which it is in some CS curriculum > (where Java being thrown out). Switching to Java for CS was a tremendous blunder. Students need to understand low-level resource management. They need to learn to think in more than 1 programming paradigm that shoehorns everything into objects (ok, java has generics now. if you squint really hard. sort of). One course in C++ doesn't cut it, the curriculum should either use different languages fitted to each task or emphasize a single language with broad abilities (picking the best programming model for each task). Java is piss-poor for most undergraduate classes (I've taught several). C++ isn't perfect but it is pretty good, warts and all (some warts make good learning experiences). Note that I'm talking about teaching languages. Outside the classroom my choices would be completely different. Sorry, I don't know anything about Ruby on Rails. :) The fact that even numeric literals are objects make me suspicious of Ruby as a general-purpose language though. From felipe.lessa at gmail.com Sun Apr 9 18:51:53 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Sun, 09 Apr 2006 19:51:53 -0300 Subject: Decorators, Identity functions and execution... In-Reply-To: <1144597938.664642.133100@v46g2000cwv.googlegroups.com> References: <1144597938.664642.133100@v46g2000cwv.googlegroups.com> Message-ID: <1144623113.5621.8.camel@kenshin.CASA> Em Dom, 2006-04-09 ?s 08:52 -0700, Carl Banks escreveu: > You've made the unfortunate mistake of indenting it with tabs, which > do > not show up on some newsreaders. I see the tabs in Google; people > using Microsoft Outlook do not. He does not need to know that some poor designed newsreaders mess up with tabs at will. Python supports tab indentation and it's not forbidden to use it (if it was, support for it in the Python codebase would have been removed long time ago). I don't like to code with tab-indents, I use 4 spaces, but I don't press space four times each time I need to indent something, I just press Tab and the editor does the clunky part for me. The problem is that most (if not all) mail programs/newsreaders don't convert tabs to spaces, they don't even keep the indentation of the last line, so nobody has the obligation of opening its IDE or hitting dozens of times the space key just to post a message to the list. -- Felipe. From gh at ghaering.de Sat Apr 29 10:34:39 2006 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sat, 29 Apr 2006 16:34:39 +0200 Subject: Recommendations for a PostgreSQL db adapter, please? In-Reply-To: <44536B34.8080800@optushome.com.au> References: <44535ED7.4010007@ghaering.de> <44536B34.8080800@optushome.com.au> Message-ID: <4453797F.8020803@ghaering.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Tim Churches wrote: > Gerhard H?ring wrote: >>[...] Considering pyPgSQL, psycopg1, PyGreSQL and psycopg2 - psycopg2 is a good >>choice. > > Hmmm, Gerhard, you are listed as one of two developers for pyPgSQL on > SourceForge ( http://sourceforge.net/projects/pypgsql/ ). The fact that > you are recommending a different DB adaptor project suggests a degree of > disengagement with pyPgSQL. It's not that I'd now say that pyPgSQL is bad software, but as you say it didn't see a lot of maintenance the last two years, and AFAIK this won't change anytime soon. With the last release, it was pretty much feature complete, and Billy G. Allie and me were talking about a rewrite of many parts in C for increased performance, and for taking advantage of the new PostgreSQL API. I told him that I was unfortunately too busy with other things to contribute significantly to pyPgSQL. I see myself more as a helper for pyPgSQL nowadays. > Is Billy G. Allie still interested in pyPgSQL, or is it now completely > unloved? AFAIK he is still interested and committing fixes to the current codebase now and then and working on the rewrite. I don't know, however, if there's a plan for the long overdue maintenance release to the last release from 2003. > If so, then perhaps some new maintainers can be found for it [...] I'll just cc Billy so he can comment :-) > - several projects rely on pyPgSQL, > including ours ( http://sourceforge.net/projects/netepi/ ) - for which > we currently need to provide our own pyPgSQL tarball rolled from CVS > plus some of our own minor but important patches - which were submitted > for consideration but have not (AFAIK) been checked into the pyPgSQL > CVS. The latest tarball for pyPgSQl available from the pyPgSQL > SourceForge pages is dated 2003. > > No criticism is intended in any of the foregoing observations - it is > inevitable that people move on to new projects (such as pySQLite), but > it would be a shame if pyPgSQL just rotted, because it has several > things in its favour, such as some unit tests (which were conspicuously > absent from any of the alternatives when we evaluated them in 2003 - > perhaps they have been added by now). Overall we have found pyPgSQL to > be very reliable. - -- Gerhard -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.1 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFEU3l/dIO4ozGCH14RAm7uAJ9AE5TnPvDL6Ic0z6Cf+QSSlkWnRwCgirdy TQnyqOyWMGX2KbGE+gFKIZU= =cTbz -----END PGP SIGNATURE----- From jjl at pobox.com Wed Apr 26 16:56:18 2006 From: jjl at pobox.com (John J. Lee) Date: 26 Apr 2006 20:56:18 +0000 Subject: how to browse using urllib2 and cookeilib the correct way References: <1146026633.580456.98590@t31g2000cwb.googlegroups.com> Message-ID: <871wvknjil.fsf@pobox.com> jnair at ensim.com writes: [...] > 1) >>>import urllib2,urllib,cookielib > 2) >>>cj = cookielib.CookieJar() > 3) >>>opener = urllib2.build_opener( urllib2.HTTPCookieProcessor(cj)) > 4) >>>data = urllib.urlencode ( { "username" : "user" , > "password" :"****" } ) > 5) >>>fp = opener.open( > "https://rhn.redhat.com/rhn/LoginSubmit.do",data ) > 6) >>>fp.url .url is not a public interface. Use .geturl() . > 'https://rhn.redhat.com/rhn/ReLogin.do?url_bounce=/network/index.pxt' > 7) >>>fp = opener.open( > "https://rhn.redhat.com/rhn/LoginSubmit.do",data ) > 8) >>>fp.url > 'https://rhn.redhat.com/network/index.pxt' Dunno. Perhaps because a Refresh is used to handle the login? twill is based on mechanize, which handles Refresh headers. John From sturlamolden at yahoo.no Tue Apr 25 08:14:47 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 25 Apr 2006 05:14:47 -0700 Subject: MinGW and Python In-Reply-To: <444C79D7.4060007@v.loewis.de> References: <1145861223.509630.247350@y43g2000cwc.googlegroups.com> <444C79D7.4060007@v.loewis.de> Message-ID: <1145967287.536182.311970@g10g2000cwb.googlegroups.com> Martin v. L?wis wrote: > - there is no build process available to do that In MSYS: $ ./configure --prefix=/c/mingw $ make $ make install This should be obvious to any with Unix experience. MinGW actually distribute precompiled Python binaries as well (in MSYS-DTK). > - people building extensions to Python must be able to do so with > Microsoft C++, since some of these extensions are written using MFC. MinGW can compile MFC. Download Windows Platform SDK and you get the MFC source. > - developing Python itself in Visual Studio is quite convenient; in > particular, the debugger works "better" than gdb. Eclipse is an excellent IDE that works with MinGW. From detlev at die-offenbachs.de Sun Apr 30 10:31:59 2006 From: detlev at die-offenbachs.de (Detlev Offenbach) Date: Sun, 30 Apr 2006 16:31:59 +0200 Subject: ANN: eric3 3.9.0 released Message-ID: Hi, this is to inform you of the release of eric3 3.9.0. This version includes support for Qt4 and PyQt4. It will be the last major release in the eric3 line of development. From now on the development effort will concentrate on eric4, the PyQt4 variant of the IDE. As usual the release is available via http://www.die-offenbachs.de/detlev/eric3.html Eric3 is a Python and Ruby IDE with all batteries included. Regards, Detlev -- Detlev Offenbach detlev at die-offenbachs.de From rpdooling at gmail.com Thu Apr 20 23:51:22 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 20 Apr 2006 20:51:22 -0700 Subject: Looking for a programming resource for newbees In-Reply-To: <1145581209.588428.249770@v46g2000cwv.googlegroups.com> References: <1145581209.588428.249770@v46g2000cwv.googlegroups.com> Message-ID: <1145591482.642760.182850@j33g2000cwa.googlegroups.com> Steve, Try this. http://www.freenetpages.co.uk/hp/alan.gauld/ If you were at the Python.org site, and clicked on "Getting started," the first sentence says, "Are you completely new to programming?" That's you, right? ;) http://wiki.python.org/moin/BeginnersGuide/NonProgrammers After you learn a little bit, if you really want "case studies" then move on to the Python Cookbook, but that is pretty advanced coding. A newer book called Beginning Python http://www.amazon.com/exec/obidos/asin/0201748843/inscape20/ comes at it with a brief intro and then gets right into actual projects, but I don't think the writing is as well done as say, Chris Fehily's Python Quickstart Guide. http://www.amazon.com/exec/obidos/asin/0201748843/inscape20/ but caution here because it is 2001, a little long in tooth but snappy writing and gobs of examples. rick From sw at wordtech-software.com Tue Apr 4 14:03:04 2006 From: sw at wordtech-software.com (Kevin Walzer) Date: Tue, 04 Apr 2006 14:03:04 -0400 Subject: [wxPython-users] Re: ANNOUNCE: wxPython 2.6.3.2 In-Reply-To: References: Message-ID: <4432B4D8.4000404@wordtech-software.com> Robin Dunn wrote: > > Announcing > ---------- > > The 2.6.3.2 release of wxPython is now available for download at > http://wxpython.org/download.php. This is a mostly bug fix release > and takes care of several "unfortunate features" discovered in the > 2.6.3.0 release made last week. A summary of changes is listed below > and at http://wxpython.org/recentchanges.php. > > > What is wxPython? > ----------------- > > wxPython is a GUI toolkit for the Python programming language. It > allows Python programmers to create programs with a robust, highly > functional graphical user interface, simply and easily. It is > implemented as a Python extension module that wraps the GUI components > of the popular wxWidgets cross platform library, which is written in > C++. > > wxPython is a cross-platform toolkit. This means that the same program > will usually run on multiple platforms without modifications. > Currently supported platforms are 32-bit Microsoft Windows, most Linux > or other Unix-like systems using GTK2, and Mac OS X 10.2+, in most > cases the native widgets are used on each platform. > > > Changes in 2.6.3.2 > ------------------ > > Fixed reference leak in wx.gizmos.TreeListCtrl.GetSelections. > > wxMSW: Fixed sizing issue with wx.Choice and wx.ComboBox. This change > was implemented by reverting a prior fix for a different problem > (continuous painting/resizing when a combobox is used as a widget in a > wx.html.HtmlWindow) so a method to fix both problems is still being > investigated. > > wxGTK: Fixed potential buffer overrun when pasting from the > clipboard. > > Fixed problem in wx.lib.splitter when used on 64-bit platforms. Used > the current length of the list for specifying an append instead of > sys.maxint. > > wxMSW: Support added for XP themed owner drawn buttons and bitmap > buttons. For example, if you change the foreground color of a button > it will now be drawn with the XP themed style rather than an ugly > generic button style. > > XRCed: Fix for Copy/Paste objects with international characters. > > Fixed the equality and inequality operators for some of the basic > data types (wx.Point, wx.Size, wx.Colour, etc.) to no longer raise a > TypeError if the compared object is not compatible, but to just return > a boolean as expected. For example:: > > wx.Colour(64,0,64) == 123 ==> False > > wxMSW: Fixed (again) sizing/positioning issues of calling Realize on > a wx.ToolBar that is not manaaged directly by a frame and that is > already shown. > > wxMSW: Fixed wx.Choice/wx.ComboBox so they send events when a new item > is selected only with the keyboard. > > > Is the new build of wxPython-Mac a universal binary? -- Kevin Walzer iReveal: File Search Tool http://www.wordtech-software.com --------------------------------------------------------------------- To unsubscribe, e-mail: wxPython-users-unsubscribe at lists.wxwidgets.org For additional commands, e-mail: wxPython-users-help at lists.wxwidgets.org From panos.laganakos at gmail.com Thu Apr 27 20:28:40 2006 From: panos.laganakos at gmail.com (Panos Laganakos) Date: 27 Apr 2006 17:28:40 -0700 Subject: OOP techniques in Python In-Reply-To: References: <1146158190.320947.108480@t31g2000cwb.googlegroups.com> <3%84g.4111$B42.3689@dukeread05> Message-ID: <1146184120.203917.81000@u72g2000cwu.googlegroups.com> Thanks for all the useful answers :) Alot of stuff to take into consideration/chew on. I come up with similar drawbacks now and then, 'cause some OOP techniques can be made in Python relatively simpler or plainly different (still simpler though). Though I am hesitant on how to act on certain occasations, as I was with this one, luckily I can get to post here and hear all these cool comments/opinions. :D From johnjsal at NOSPAMgmail.com Fri Apr 21 16:07:02 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 21 Apr 2006 20:07:02 GMT Subject: Thanks from the Java Developer In-Reply-To: <4448b412$1_2@newspeer2.tds.net> References: <1145474995.143893.31760@z34g2000cwc.googlegroups.com> <1145568613.146056.135230@u72g2000cwu.googlegroups.com> <1he434n.vosf551izis2eN%aleaxit@yahoo.com> <4448b412$1_2@newspeer2.tds.net> Message-ID: Kent Johnson wrote: >> At least in the Bay Area, the jobmarket for Python programmers is wild, >> right now -- firms such as Google, Pixar, BitTorrent, IronPort, etc, >> etc, all hungry for Pythonistas -- BayPIGgies mailing list bitching over >> too many job-offer posts, and the nuisance of all those recruiters >> haunting our monthly meetings and how much time they take, ...!!! > > Hmm...eagerly awaiting this phenomenon to reach the Boston area. Hey, I was just thinking the same thing! Of course, what I'm *really* waiting for is the "looking for people who like to *think* they are Python developers but aren't really" trend to hit Boston. :) From jparlar at cogeco.ca Wed Apr 19 10:53:45 2006 From: jparlar at cogeco.ca (Jay Parlar) Date: Wed, 19 Apr 2006 07:53:45 -0700 Subject: 2.5 excitement In-Reply-To: <1he09pm.1txy84o1mprpfjN%aleaxit@yahoo.com> References: <1145290449.735642.120860@i40g2000cwc.googlegroups.com> <1145292795.565277.288760@v46g2000cwv.googlegroups.com> <1hdyb46.1yllkst1o2asjlN%aleaxit@yahoo.com> <1204021.LzRF60KP7e@jupiter.g2ctech> <1he09pm.1txy84o1mprpfjN%aleaxit@yahoo.com> Message-ID: <5281d6d9bf0f4079511e398ebdae51e0@cogeco.ca> On Apr 18, 2006, at 9:06 PM, Alex Martelli wrote: > > Funny timing coincidence: your 1st draft of Python for Dummies going in > now, my 2nd edition of Python in a Nutshell just went to production, > AND > Wesley Chun's 2nd ed is also being finished this week. Three > Baypiggies > (or whatever we'll have to call ourselves) all finishing Python books > (be they new, or 2nd eds) all within one week of Easter -- what's the > chances of THAT?-) > > Wesley Chun is doing a second edition of Core Python? Oh wow! That's the book I learned Python with oh so long ago(between 1.5.2 and the mysterious 1.6). I told people for a long time that Core was the best book with which to learn Python, but I stopped doing that as it's too out of date now. Glad to see Ruby isn't the only language getting a bunch of new good books. Jay P. From Aiwass333 at gmail.com Fri Apr 7 14:19:11 2006 From: Aiwass333 at gmail.com (RunLevelZero) Date: 7 Apr 2006 11:19:11 -0700 Subject: wxPython Question In-Reply-To: <1144425953.491348.37130@t31g2000cwb.googlegroups.com> References: <1144419812.960133.224010@t31g2000cwb.googlegroups.com> <1144422098.382628.42440@i40g2000cwc.googlegroups.com> <1144425953.491348.37130@t31g2000cwb.googlegroups.com> Message-ID: <1144433951.083177.156550@z34g2000cwc.googlegroups.com> Well you will need to download the " docs demos and tools " and that contains a windows help file that is easily searchable. If you run Linux there is a Gnome tool to run the help file in Linux if you so wish. From continium at gmail.com Tue Apr 18 22:22:40 2006 From: continium at gmail.com (continium at gmail.com) Date: 18 Apr 2006 19:22:40 -0700 Subject: Quick Problem References: <1145412306.686740.266110@j33g2000cwa.googlegroups.com> Message-ID: <1145413360.292591.272040@u72g2000cwu.googlegroups.com> Thank you. That worked perfectly, I understand why it was not working before because the variables were assigned within the function definition only. And replying to John Machin, admin is the name of the account I created on windows. The default administrator account in XP is called simply 'administrator' which is the account one would use in safe mode. From amk at amk.ca Fri Apr 21 14:02:30 2006 From: amk at amk.ca (A.M. Kuchling) Date: Fri, 21 Apr 2006 13:02:30 -0500 Subject: proposed Python logo References: <1145615455.477800.74730@i39g2000cwa.googlegroups.com> <1145636272.363143.208410@i40g2000cwc.googlegroups.com> Message-ID: On 21 Apr 2006 09:17:52 -0700, BartlebyScrivener wrote: >>> I'd like some variation of used as a logo. > That has real potential, but I bet it's trademarked. It's taken from a Renaissance painting (http://witcombe.sbc.edu/davincicode/bronzino-allegory.html -- NSFW, if your workplace is dumb), so the foot itself shouldn't be trademarked; its use alongside the word "Python" might conceivably be. --amk From pmartin at snakecard.com Thu Apr 27 16:36:36 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Thu, 27 Apr 2006 15:36:36 -0500 Subject: OOP techniques in Python References: <1146158190.320947.108480@t31g2000cwb.googlegroups.com> <3%84g.4111$B42.3689@dukeread05> Message-ID: Edward Elliott wrote: > Philippe Martin wrote: > '' > > On the other hand, foo.__doc__ and foo.__name__ work fine. > > (I was going to quote your post but my reader interprets everything after > the two dashes as your sig and ignores it. And I won't bother to fix it.) I'm not sure I understand what you mean ... I did get a strange new message from my email client and disabled the signature. From rpdooling at gmail.com Mon Apr 17 23:50:08 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 17 Apr 2006 20:50:08 -0700 Subject: Ironpython book? In-Reply-To: <1145329406.419299.12780@i40g2000cwc.googlegroups.com> References: <1145329406.419299.12780@i40g2000cwc.googlegroups.com> Message-ID: <1145332208.428363.199440@v46g2000cwv.googlegroups.com> I'll let somebody jump in and say, "You're crazy!" But it seems to me the interest in IronPython on this list is pretty subdued. Maybe because most people are running on Linux or Macs? Here's a thread http://groups.google.com/group/comp.lang.python/browse_thread/thread/2762f6dfc5f72651/ I would like to see more discussion of it. Even if it means discussion about why people are skeptical or otherwise in wait-and-see mode. Being an XP user, I would love to see more about it. rick From floyd at apaflo.com Wed Apr 12 08:58:50 2006 From: floyd at apaflo.com (Floyd L. Davidson) Date: Wed, 12 Apr 2006 04:58:50 -0800 Subject: symbolic links, aliases, cls clear References: <1143672131.167324.36920@i39g2000cwa.googlegroups.com> <1144844223.094969.82870@t31g2000cwb.googlegroups.com> Message-ID: <87r7430x2t.fld@apaflo.com> af.dingo at gmail.com wrote: >If I may recommend an alternative, > >print "\033[H\033[J" > >the ansi sequence to clear the screen. Or so you would hope (however, that is *not* what you have listed!). Unfortunately, it is poor practice to hard code such sequences. Instead the proper sequence should be obtained from the appropriate database (TERMINFO or TERMCAP), and the easy way to do that is, tput clear -- Floyd L. Davidson Ukpeagvik (Barrow, Alaska) floyd at apaflo.com From onurb at xiludom.gro Fri Apr 28 06:36:47 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 28 Apr 2006 12:36:47 +0200 Subject: append function problem? In-Reply-To: <1146196184.408569.197960@i40g2000cwc.googlegroups.com> References: <1146196184.408569.197960@i40g2000cwc.googlegroups.com> Message-ID: <4451f095$0$12849$626a54ce@news.free.fr> randomtalk at gmail.com wrote: > hello, recently i tried to use list.append() function in seemingly > logical ways, What seems logical and how it really works may not be the same... As a general rule, for builtin types, destructive methods returns None. I personnaly find it a wart, but what, it's the BDFL's choice. (snip) > I'm not sure why seed1 and the function doesn't recognize the list.. because list.append() modifys the list in place and returns None. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From robert.kern at gmail.com Wed Apr 5 23:30:14 2006 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 05 Apr 2006 22:30:14 -0500 Subject: python on Mac In-Reply-To: References: <1144284073.446005.53950@t31g2000cwb.googlegroups.com> Message-ID: James Stroud wrote: > Thomas Nelson wrote: > >>I just purchased a new macbook (os 10.4.6), and I'm trying to install >>python 2.4 on it. I downloaded and ran the two installers recommended >>at http://www.python.org/download/mac/. Now I have IDLE, which runs >>2.4.1, but typing "python" at a terminal still opens 2.3.5, because it >>points to /usr/bin/python. Is there a way to run python 2.4 without >>idle? If I want to do a unix style script, something like >>#!/usr/bin/python >>print "hello world" >>what can I put on the first line that will cause python 2.4 to >>interpret my code? >> >>Thanks a lot. >>THN > > The python in /usr/bin is a link (to a link). You can do this: > > sudo rm /usr/bin/python > sudo ln -s \ > /System/Library/Frameworks/Python.framework/Versions/2.4/bin/python \ > /usr/bin/python No, for the love of all that is holy, don't do that! OS X depends on stuff in /usr/bin/. Don't pull the carpet out from under your OS! The python executables from the Python 2.4 installer are installed to /usr/local/bin/. I believe that the Universal binary that Alex linked to takes care of adjusting the PATH environment variable such that this is exposed. -- Robert Kern robert.kern at gmail.com "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From shay at shay-riggs.fsnet.co.uk Sat Apr 8 05:38:07 2006 From: shay at shay-riggs.fsnet.co.uk (SR) Date: 8 Apr 2006 02:38:07 -0700 Subject: How can I reduce the number of queries to my PostgreSQL database? Message-ID: <1144489087.794505.277930@v46g2000cwv.googlegroups.com> As a starter project for learning Python/PostgreSQL, I am building a Books database that stores information on the books on my bookshelf. Say I have three tables. Table "books" contains rows for book_id, title, subtitle, ISBN. Table "authors" contains rows for author_id, author surname, author first names, biographical notes. Table "bookauthors" contains two rows: book_id, author_id. The bookauthors table links the books and authors tables. Scenario: I have a python script which creates web page listing all books in the database, and all authors for each book. My python script does essentially three things: 1. retrieve a list of all book_ids and book_titles. 2. for each book_id, query the bookauthors table and retrieve all author names for that book_id. 3. display it all out as an html table on a web page. The script works fine, if a little slow. I think that's because if I have 50 books in my database, my script performs 51 database queries (1 for all book names; then 1 for each book). A colleague of mine suggested that I could get away with two queries, 1 to read the book ids and titles, and 1 to read the bookauthors table to pull in *all* relations, and then do all the work in Python. I think I know where he's coming from, but I don't know where to begin. Any clues? Is there a specific name for this technique? From wojciech_mula at poczta.null.onet.pl.invalid Sat Apr 22 16:38:15 2006 From: wojciech_mula at poczta.null.onet.pl.invalid (Wojciech =?iso-8859-2?Q?Mu=B3a?=) Date: Sat, 22 Apr 2006 20:38:15 +0000 (UTC) Subject: list example References: <1145737240.221433.176160@i40g2000cwc.googlegroups.com> Message-ID: PAolo wrote: > any comment, suggestion? Is there something not elegant? Try this: even = range(10)[0::2] odd = range(10)[1::2] From gaz082 at gmail.com Fri Apr 21 13:37:32 2006 From: gaz082 at gmail.com (Gaz) Date: 21 Apr 2006 10:37:32 -0700 Subject: Pythonesque interface. In-Reply-To: <1145640417.247970.116480@v46g2000cwv.googlegroups.com> References: <1145639147.524042.260220@z34g2000cwc.googlegroups.com> <4asil8FuicdvU1@uni-berlin.de> <1145640417.247970.116480@v46g2000cwv.googlegroups.com> Message-ID: <1145641052.645436.255950@g10g2000cwb.googlegroups.com> Michael Tobis ha escrito: > www.pygame.org > > Yes but he obviously wants this to be delivered to the browser. (Also > the site is broken today... ) > > This comes up a lot, but I don't think there's an answer to it as yet. > > mt Yeah, i want it playable on a browser. From steve at hastings.org Wed Apr 5 18:02:33 2006 From: steve at hastings.org (Steve R. Hastings) Date: Wed, 05 Apr 2006 15:02:33 -0700 Subject: efficiency of range() and xrange() in for loops References: Message-ID: On Wed, 05 Apr 2006 22:24:24 +0200, Fredrik Lundh wrote: >> If Python actually allocates the list, then clearly we should all use >> "for i in xrange". > > clearly we should all? speak for yourself. I apologize for my pithy turn of phrase. Clearly what I should have written was: "If Python actually allocates the list, then clearly 'for i in xrange' would be desirable in cases where memory allocation might possibly be a problem; of course if you have lots of memory, or you are only looping a small number of times, go ahead and use range() because why not." I deeply apologize for inadvertently trying to tell you how to write a for loop. I hope the offense isn't unforgivable. I apologise for the fault in the newsgroup posting. Those responsible have been sacked. > the difference isn't very > large, xrange is actually slower in some python versions, and you'll > need the integer objects sooner or later anyway... Actually, for many uses of "for i in (range|xrange)", you only need the value of i, and you aren't doing anything with the integer object. You might not even be looking at the value of i: start_time = time.time() for i in xrange(10**6): run_some_function() stop_time = time.time() secs = (stop_time - start_time) / 10**6 print "run_some_function() took on average, %f seconds." % secs In the above, clearly we should all use xrange()... oops, I meant, if you want to, you could use xrange() instead of allocating a list of a million integers and then doing nothing with the list itself and then deallocating the list of a million integers. I apologise again for the fault in the newsgroup posting. Those responsible for sacking the people who have just been sacked have been sacked. >> If Python doesn't currently optimize this case, is there any chance >> this optimization could be added? > > in Python 2.X, range is defined to return a list. if you start > returning something else, you'll break stuff. Perhaps I'm mistaken here, but I don't see how this optimization could possibly break anything. range() makes a list, and for consumes it, and the list isn't seen anywhere else. If the Python compiler took this: for i in range(10**6): pass and produced code equivalent to this: for i in iter(range(10**6)) pass How would this break stuff? -- Steve R. Hastings "Vita est" steve at hastings.org http://www.blarg.net/~steveha From mandelin at cs.berkeley.edu Mon Apr 3 16:31:13 2006 From: mandelin at cs.berkeley.edu (Dave Mandelin) Date: 3 Apr 2006 13:31:13 -0700 Subject: Registration Code References: Message-ID: <1144096273.915268.90360@v46g2000cwv.googlegroups.com> Ken Seehart wrote: > Math wrote: > > Hello, > I encypted the bytecode of a few important functions with a key based on > information required from the user. Without the key, these functions > can't be decrypted. This is somewhat more secure than just testing the > key with an "if" statement since the latter could easily be bypassed by > a hacker. That's a really good idea. I have a couple more questions, if you don't mind: I am going to distribute an app using py2exe. Is it reasonably easy to apply this technique to bytecode stored inside the library.zip file, or should I just include the encrypted Python files as separate files? Second, I hear that in general it is very difficult to make a time-limited demo, because the code has to be all there, so all a cracker has to do is bypass the "if". It seems that even this method won't work for that. Do you know of any way to make time limiting secure? Thanks. -- Want to play tabletop RPGs online? Check out RPZen: http://koboldsoft.com From grflanagan at yahoo.co.uk Sat Apr 22 04:17:35 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 22 Apr 2006 01:17:35 -0700 Subject: Generate a sequence of random numbers that sum up to 1? In-Reply-To: References: Message-ID: <1145693855.407215.102720@j33g2000cwa.googlegroups.com> Anthony Liu wrote: > I am at my wit's end. > > I want to generate a certain number of random numbers. > This is easy, I can repeatedly do uniform(0, 1) for > example. > > But, I want the random numbers just generated sum up > to 1 . > > I am not sure how to do this. Any idea? Thanks. > -------------------------------------------------------------- import random def partition(start=0,stop=1,eps=5): d = stop - start vals = [ start + d * random.random() for _ in range(2*eps) ] vals = [start] + vals + [stop] vals.sort() return vals P = partition() intervals = [ P[i:i+2] for i in range(len(P)-1) ] deltas = [ x[1] - x[0] for x in intervals ] print deltas print sum(deltas) --------------------------------------------------------------- Gerard From peter at engcorp.com Wed Apr 12 08:56:28 2006 From: peter at engcorp.com (Peter Hansen) Date: Wed, 12 Apr 2006 08:56:28 -0400 Subject: example of logging w/ user-defined keywords? In-Reply-To: <1144845969.595683.185750@i40g2000cwc.googlegroups.com> References: <1144845969.595683.185750@i40g2000cwc.googlegroups.com> Message-ID: Chris Curvey wrote: > Several things that I've read lead me to think this is possible, but I > can't figure out how to do it. I have some information (a "job > number") that I would like logged on every log message, just like the > time or the severity. > > I saw some mail threads that suggested that there was an easy way to do > this, but I havent' found any examples. Is there a simple way to do > this, or do I need to write my own logger subclass? class MyClass: def __init__(self, name, job): self.logger = logging.getLogger(name) self.job = job def log(self, msg): self.logger.debug('#%d: %s' % (self.job, msg) Then just call self.log('foo') whenever you want to log something. If this isn't sufficient please describe what requirements you have that it doesn't meet. (Subclassing Logger is certainly a simple way to do it though... in that case you would just pass the job number to the subclass when you construct it and it could do something like that above. -Peter From jbamsterdam at gmail.com Mon Apr 17 10:32:06 2006 From: jbamsterdam at gmail.com (Jonathan Amsterdam) Date: 17 Apr 2006 07:32:06 -0700 Subject: Queue can result in nested monitor deadlock Message-ID: <1145284326.177062.230120@v46g2000cwv.googlegroups.com> I think there's a slight design flaw in the Queue class that makes it hard to avoid nested monitor deadlock. The problem is that the mutex used by the Queue is not easy to change. You can then easily get yourself into the following situation (nested monitor deadlock): Say we have a class that contains a Queue and some other things. The class's internals are protected by a mutex M. Initially the Queue is empty. The only access to the queue is through this class. Thread 1 locks M, then calls Queue.get(). It blocks. At this point the Queue's mutex is released, but M is still held. Thread 2 tries to put something in the Queue by calling the enclosing class's methods, but it blocks on M. Deadlock. The solution would be to expose the Queue's mutex via a constructor argument and/or method, so that, to take the above example, one could create M and give it to the Queue as its mutex. Of course this is doable now, as the code below demonstrates. But it should be documented and exposed. As I'm new to the Python community, I'm not sure that this is the right forum for this suggestion. Is it the sort of thing one would put on the SourceForge bug list? Advice appreciated. "Fixed" Queue class: class LQueue(Queue.Queue): """ Fixes a problem with the standard Queue implementation: you can't use your own mutex, so you are subject to nested monitor deadlock. This version lets you pass in your own lock. """ def __init__(self, maxsize=0, lock=None): "Optionally takes a lock (threading.Lock or threading.RLock) to use for the queue's lock." Queue.Queue.__init__(self, maxsize) if lock: self.mutex = lock # Re-create the condition objects with the new mutex. self.not_empty = threading.Condition(self.mutex) self.not_full = threading.Condition(self.mutex) From no_spam at tilanus.com Fri Apr 28 04:03:09 2006 From: no_spam at tilanus.com (Winfried Tilanus) Date: Fri, 28 Apr 2006 10:03:09 +0200 Subject: can i set up a mysql db connection as a class ? In-Reply-To: References: <1146183359.932904.298760@g10g2000cwb.googlegroups.com> <1146199764.328276.241320@j33g2000cwa.googlegroups.com> <4451b394$0$31649$e4fe514c@news.xs4all.nl> Message-ID: <4451cc3e$0$31649$e4fe514c@news.xs4all.nl> On 04/28/2006 08:35 AM, *binarystar* wrote: Looking better at the """ Humble Database Connection Class """: if I am not mistaken, it seems to mix up connections and cursors. MySQLdb has a thread safety level of '1', meaning: "Threads may share the module, but not connections". So you have to give each thread an own connection. Beside of that I would prefer not to share the cursor object, although it should not really matter. The following should work and make the cursors private to the Execute function (untested): class DB_Connector(object): """ Humble Database Connection Class """ def __init__(self, host="localhost", user="MyUser", passwd="MyPassword", **other_db_arguments): self.host = host self.user = user self.passwd = passwd # Unpack Other Database Arguments Here self.CreateConnection() def CreateConnection(self): self.connection = MySQLdb.connect(self.host, self.user, self.passwd) def DestroyConnection(self): self.connection.close() def Execute(self, sql_statement): cursor = self.connection.cursor() cursor.execute(sql_statement) result = cursor.fetchall() cursor.close() return result > I suppose that is possible because you are calling the one instance of a > cursor object ... maybe you have to create a copy of the cursor object, > rather than passing a reference to the one object? or set up the > db_connection objects inside each of the threads? .. > > Winfried Tilanus wrote: >> On 04/28/2006 07:54 AM, *binarystar* wrote: >> >> Just wondering: is there any risk of two threads accessing the Execute >> function at the same time and getting something like this on the same >> cursor object: >> >> thread_1: self.cursor.Execute( sql_statement ) >> thread_2: self.cursor.Execute( sql_statement ) >> thread_1: return self.cursor.FetchAll() >> thread_2: return self.cursor.FetchAll() >> >> In that case the queries would seriously be messed up. My intuition says >> this would need some locking or a 'cursor-pool'. >> >> best wishes, >> >> Winfried >> >> >>> your on the right track ... create something like this ( hope the >>> formatting doesn't go to hay wire ) >>> >>> class DB_Connector(object): >>> >>> """ Humble Database Connection Class """ >>> def __init__(self, host="localhost", >>> user="MyUser",passwd="MyPassword", **other_db_arguments): >>> self.host = host >>> self.user = user >>> self.passwd = passwd >>> # Unpack Other Database Arguments Here >>> self.CreateConnection() >>> def CreateConnection( self ): >>> self.cursor = MySQLdb.connect(self.host, self.user, >>> self.passwd) >>> def DestroyConnection( self ): >>> self.cursor.close() >>> def Execute( self, sql_statement ): >>> self.cursor.Execute( sql_statement ) >>> return self.cursor.FetchAll() >>> Then when you run your program create an instance of the object >>> >>> db_connection = DB_Connector( 'localhost', 'administrator', >>> 'betelgeuse99', auto_commit=1, other_keyword_arg="yes" ) >>> >>> now when you pass the db_connection instance to other classes, a copy >>> will be made automagically >>> >>> thread_1_instance = ThreadingClass( db_connection ) >>> thread_2_instance = ThreadingClass( db_connection ) >>> thread_3_instance = ThreadingClass( db_connection ) >>> >>> should work .. >>> I hope this is useful From nogradi at gmail.com Tue Apr 18 04:41:50 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Tue, 18 Apr 2006 10:41:50 +0200 Subject: How protect proprietary Python code? (bytecode obfuscation?, what better?) In-Reply-To: <1145300492.623527.300740@e56g2000cwe.googlegroups.com> References: <1145293384.791678.14450@v46g2000cwv.googlegroups.com> <1145300492.623527.300740@e56g2000cwe.googlegroups.com> Message-ID: <5f56302b0604180141j70130fc0y29cc4d1f0a478478@mail.gmail.com> > #include > > char code[] = "print 'hello moshe'"; > > void main(...) > { > Py_ExecString(code); > } I don't get this, with python 2.4 there is no function called Py_ExecString in any of the header files. I found something that might do the job PyRun_SimpleString( ) in pythonrun.h, but couldn't get it to work either. So what is really the way to execute python code in a string from a C program? From kay.schluehr at gmx.net Wed Apr 19 03:09:06 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 19 Apr 2006 00:09:06 -0700 Subject: Missing interfaces in Python... In-Reply-To: <1145306373.781129.305840@z34g2000cwc.googlegroups.com> References: <1145306373.781129.305840@z34g2000cwc.googlegroups.com> Message-ID: <1145430546.625634.194710@g10g2000cwb.googlegroups.com> redefined.horizons at gmail.com wrote: > I'm coming from a Java background, so please don't stone me... > > I see that Python is missing "interfaces". The concept of an interface > is a key to good programming design in Java, but I've read that they > aren't really necessary in Python. I am wondering what technique I can > use in Python to get the same benefits to a program design that I would > get with interfaces in Java. > > For example, if I want to have a program with a Car object, and a Bus > object. I want both of these objects to present a common group of > methods that can be used by Mechanic objects, but slightly different > methods that can be used by Driver objects. > > In Java I would accomplish this by defining an IFixable interface that > would be implemented by both the Car and Bus objects. Mechanic objects > would work with any object implementing this interface. > > How would I approach this problem in Python? I think I would use an > abstract class instead of an interface for IFixable, since Python > supports multiple inheritance, but I'm not sure this is correct. > > Thanks for any suggestions. > > Scott Huey The answer is called "duck typing" or "structural typing". Any two classes that implement a set of methods with pairwise equal signatures can be considered as "presenting a group of methods". You do not have to create a special construct and assign it to classes ( e.g. via an "implements" directive ) in order to make it work. That's because you are not enforced to know the type of an object at compile time. Car and Bus classes may be selected from two completely different libraries without any common convention but it is still possible ( though not very likely without any adaption ) that they work together and show sound behaviour ( you have to prove at least certain behavioural properties using unit tests ). "Duck typing" is also the reason why coupling of an interface with an implementation is not harmfull in Python. You won't find many deep class hierarchies and extensive frameworks. This has the advantage that a classification you have done once at the beginning of your project in the design phase is not considered to be carved in stone. In Java/C#/C++ you can achieve many of the same effects of using "generic" or "templates" but if you are not start coding with them from the very beginning you loose many of their benfits. In Python this is a non-issue. From daniel.dittmar at sap.corp Wed Apr 5 06:46:07 2006 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Wed, 05 Apr 2006 12:46:07 +0200 Subject: HTMLParser fragility In-Reply-To: References: Message-ID: Lawrence D'Oliveiro wrote: > I've been using HTMLParser to scrape Web sites. The trouble with this > is, there's a lot of malformed HTML out there. Real browsers have to be > written to cope gracefully with this, but HTMLParser does not. Not only > does it raise an exception, but the parser object then gets into a > confused state after that so you cannot continue using it. > > The way I'm currently working around this is to do a dummy pre-parsing > run with a dummy (non-subclassed) HTMLParser object. Every time I hit > HTMLParseError, I note the line number in a set of lines to skip, then > create a new HTMLParser object and restart the scan from the beginning, > skipping all the lines I've noted so far. Only when I get to the end > without further errors do I do the proper parse with all my appropriate > actions. You could try HTMLTidy (http://www.egenix.com/files/python/mxTidy.html) as a first step to get well formed HTML. Daniel From blais at furius.ca Sat Apr 15 12:08:06 2006 From: blais at furius.ca (Martin Blais) Date: Sat, 15 Apr 2006 12:08:06 -0400 Subject: The whitespaceless frontend In-Reply-To: <4440C721.8000006@cs.teiath.gr> References: <4440C721.8000006@cs.teiath.gr> Message-ID: <8393fff0604150908y544e16a4ma1de65eaa5ad6192@mail.gmail.com> On 4/15/06, Stelios Xanthakis wrote: > It had to happen :) Did it? > http://pyvm32.infogami.com/EPL > > Seriously, this is not so much about the whitespace as for the > new features, which might interest people who are thinking about > new features. More specifically, "methods" and the "$" operator > are really great and seem to solve the problem with having to > type "self." all the time. The new syntax has been tested in Exactly what is the problem with having to type self all the time? From rolf.wester at ilt.fraunhofer.de Fri Apr 28 04:58:49 2006 From: rolf.wester at ilt.fraunhofer.de (Rolf Wester) Date: Fri, 28 Apr 2006 10:58:49 +0200 Subject: Strange constructor behaviour (or not?) Message-ID: <4451d948$1@news.fhg.de> Hi, when defining: class A: def __init__(self, l=[]): self.l = l a = A() a.l.append(1111) b = A() print a.l I get the output [1111] instead of an empty list. I guess it's because the default value in the constructor is constructed once and whenever the constructor is called without l being specified. My work around is: class A: def __init__(self, l=None): if l == None: self.l = [] else: self.l = l Is there a way to take the first definition but force the constructor to create a new empty list every time it is called? Thanks in advance Rolf Wester From sjmachin at lexicon.net Thu Apr 20 07:13:01 2006 From: sjmachin at lexicon.net (John Machin) Date: Thu, 20 Apr 2006 21:13:01 +1000 Subject: help wanted regarding displaying Japanese characters in a GUI using QT and python In-Reply-To: <1145528149.531579.5990@j33g2000cwa.googlegroups.com> References: <1145454203.770652.79920@j33g2000cwa.googlegroups.com> <1145460813.222787.302360@z34g2000cwc.googlegroups.com> <1145505985.664590.39580@t31g2000cwb.googlegroups.com> <1145515929.799871.29550@z34g2000cwc.googlegroups.com> <1145519024.125421.327360@t31g2000cwb.googlegroups.com> <1145528149.531579.5990@j33g2000cwa.googlegroups.com> Message-ID: <44476CBD.5080100@lexicon.net> On 20/04/2006 8:15 PM, prats wrote: > sorry I did not correctly read your point. I works fine. Thanks for > your help. > I have one more query. It was said that the text I was supposed to show > was written using "ISO-2022-JP" charset. Where more than one encoding is in use for a language, some people just guess. I've seen this with ASCII/EBCDIC and GB[K]/Big5. > But It didn't when I decoded > it using that charset. But it worked fine with the "shift-jis" > encoding. Is it the default charset used by python i.e. I mean to say > bytes would be by default "shift-jis"? That may be Ruby's default, although I doubt it. Python was originally written in Old High Dutch, but PEP 0.0001 did away with the ij ligature so that Python could be expressed in ASCII, which has been the default encoding ever since. From brandon.mcginty at gmail.com Thu Apr 6 00:23:48 2006 From: brandon.mcginty at gmail.com (brandon.mcginty at gmail.com) Date: Wed, 5 Apr 2006 21:23:48 -0700 Subject: Python and microsoft outlook-using com, can I interact with msoutlook? In-Reply-To: Message-ID: <010501c65931$e85b3980$6400a8c0@D1FWTS61> Thanks to the 2 people who've replied; it's been a little harder than I thought to use outlook, but I'll get the hang of it, and I sincerely thank you both. THX, Brandon McGinty ---------- Feel free to contact me for technical support, or just to chat; I always have time to talk and help, and an open ear. Email:Brandon.mcginty at gmail.com Skype:brandon.mcginty Msn:brandon_mcginty at hotmail.com Aim:brandonmcginty (Not currently available.) Cell:4802025790 (Weekends and nights only, please.) "Kindness is a language that the deaf can hear and the blind can see." Mark Twain > -----Original Message----- > From: > python-list-bounces+brandon.mcginty=gmail.com at python.org > [mailto:python-list-bounces+brandon.mcginty=gmail.com at python.o > rg] On Behalf Of Daniel Dittmar > Sent: Tuesday, April 04, 2006 1:23 AM > To: python-list at python.org > Subject: Re: Python and microsoft outlook-using com,can I > interact with msoutlook? > > > brandon.mcginty at gmail.com wrote: > > Hi All, > > I know that Microsoft Exchange has a com interface, CDO, > but I can't seem to > > find one for Microsoft outlook. > > does anyone have code snippets for using msoutlook and python, or > > suggestions? > > You can use CDO to manage your Inbox, send mail etc. > > The following functions navigate to a certain folder and parse every > message text for a certain regular expression: > > def spamstat (): > s = Dispatch ("Mapi.Session") > s.Logon ("Default Outlook Profile") > junk = findJunk (s) > rex = re.compile ('The ([0-9]+) emails listed below') > for msg in junk.Messages: > text = msg.Text > match = rex.search (text) > if match: > date = parseDate (msg.TimeSent) > print (date, int (match.group (1))) > > def findJunk (s): > inbox = s.Inbox > for folder in s.Inbox.Folders: > if folder.Name == 'Junk': > return folder > > > See the Spambayes Outlook plugin > (http://spambayes.sourceforge.net/) for > a complex example. > > Daniel > -- > http://mail.python.org/mailman/listinfo/python-list > > -- > No virus found in this incoming message. > Checked by AVG Free Edition. > Version: 7.1.385 / Virus Database: 268.3.5/301 - Release > Date: 4/4/2006 > > -- No virus found in this outgoing message. Checked by AVG Free Edition. Version: 7.1.385 / Virus Database: 268.3.5/301 - Release Date: 4/4/2006 From f.braennstroem at gmx.de Fri Apr 7 14:12:54 2006 From: f.braennstroem at gmx.de (Fabian Braennstroem) Date: Fri, 7 Apr 2006 20:12:54 +0200 Subject: best way to install python modules on linux Message-ID: Hi, I am pretty new to python and will use it mainly in combination with scientific packages. I am running ubuntu breezy right now and see that some packages are out of date. Do you have any suggestion, how I can get/keep the latest python modules (e.g. scipy, numpy,...) on my ubuntu system? I.e. does there exist any script/program, which downloads and installs automatically the latest stable releases of selected modules? It would be nice, if the program can remove the installed modules, too!? Or would it be easier to stick to apt/deb and create own packages ... Greetings! Fabian From fredrik at pythonware.com Tue Apr 25 08:57:02 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 25 Apr 2006 14:57:02 +0200 Subject: python application ideas. References: <1145957229.395662.99610@t31g2000cwb.googlegroups.com> Message-ID: "momolulu" wrote: > That's really the right thing I want to know , I am a Python newbie > ,and learn to know that python is very strong ability in large scale > application , as a beginner , what is the first useful and meaningful > widget can we create through Python ? What makes you think that the first "useful and meaningful widget" is the same thing for everyone ? The first thing I built as a Python beginner was a high-volume fault-tolerant distributed image production system for heterogenous environments. The most recent thing I built is a small script that takes an infogami comment and reposts it as an article. What kind of applications and systems do you usually work on ? From bayerj at in.tum.de Sun Apr 2 15:05:49 2006 From: bayerj at in.tum.de (bayerj) Date: 2 Apr 2006 12:05:49 -0700 Subject: print() in Python 3000 return value? In-Reply-To: References: <1143997643.857261.186430@i40g2000cwc.googlegroups.com> <44300797$0$28451$9b622d9e@news.freenet.de> <1143999680.091690.253340@g10g2000cwb.googlegroups.com> Message-ID: <1144004749.150519.284270@i39g2000cwa.googlegroups.com> Expressions like >>> 2 + 2 return None, too. I am not certain, but as far as I know this has some major design reasons. Thus I am certain, that print() will return None also. From _karlo_ at _mosor.net_ Thu Apr 13 20:57:18 2006 From: _karlo_ at _mosor.net_ (Karlo Lozovina) Date: Fri, 14 Apr 2006 00:57:18 +0000 (UTC) Subject: print without newline "halts" program execution Message-ID: Consider this short script: --- from time import time, sleep st = time() print 'Start: %f, ' % st, sleep(10) sp = time() print 'Stop: %f, Duration: %f' % (sp, (st - sp)) --- On my environment (Linux, py24), when run, Python first waits 10s, and then produces the entire output. How, can I make it print first part ('Start: %f, '), then wait 10s, and then append (WITHOUT NEWLINE) that second print statement? I'm writting a script with lot of output which has to go on the same line, but I don't want to wait for it to end to see output, I just want it to print parts as it's finished with them. Using sys.stdout.write() produces the same behavior, so what can I do? Thanks a lot in advance. -- _______ Karlo Lozovina - Mosor | | |.-----.-----. web: http://www.mosor.net || ICQ#: 10667163 | || _ | _ | Parce mihi domine quia Dalmata sum. |__|_|__||_____|_____| From floyd at apaflo.com Wed Apr 12 09:17:36 2006 From: floyd at apaflo.com (Floyd L. Davidson) Date: Wed, 12 Apr 2006 05:17:36 -0800 Subject: symbolic links, aliases, cls clear References: <1143672131.167324.36920@i39g2000cwa.googlegroups.com> Message-ID: <87mzer0w7j.fld@apaflo.com> "mp" wrote: >i have a python program which attempts to call 'cls' but fails: > >sh: line 1: cls: command not found Hmmmmm... (I don't program in Python, so precisely what is happening isn't something I'm sure about). But, note how that line starts with "sh:"! That indicates it is /bin/sh which is reporting an inability to find a "cls" command. It suggests that Python (like most other programming languages) calls shell scripts using /bin/sh as the default shell. The problem is that unix has no command named "cls". >i tried creating an alias from cls to clear in .profile, .cshrc, and >/etc/profile, but none of these options seem to work. In /etc/profile and ~/.profile you will cause an alias to be defined *for* *interactive* *login* *shells*. But not for non-interactive non-login shells, which is what you are invoking with Python. The reason is because aliases are not inherited by sub-shells, and only interactive login shells read those two files. Hence your alias is never defined in the subshell your program executes. >my conclusion is that a python program that is executing does not use >the shell (because it does not recognize shell aliases). is this >correct? No. >should i use a symbolic link? if so, where should i place it? No. >what is the difference between aliases and symbolic links? Aliases are a mechanism used by a shell to define a command name that executes a series of commands. A symbolic link is a directory entry that de-references another directory entry, so that either entry points to the same actual file. >if i execute a command like 'clear' to clear the screen, where does the >shell look to find the command 'clear'? It looks in locations specified by the PATH variable. By default that will be a minimal list defined by the login program, but it might be significantly added to in the /etc/profile or other shell init scripts. The question you need to answer first is what happens if your Python program tries to execute /clear/ rather than /cls/. If that works, then your PATH variable is set correctly. If it doesn't work, verify that there is in fact a program named /clear/ that can be run from a shell command line. Then figure out how to set an appropriate PATH variable for your Python program. Note that if /clear/ does work, but you want this script to use /cls/ so that it is portable to some silly OS where a /cls/ exists... You can define a shell function (which will be inherited by sub-shells) to look like this, function cls () { clear; } And place it where ever is appropriate (/etc/profile is one place). >i'm using os x. I don't know anything about it... :-) -- Floyd L. Davidson Ukpeagvik (Barrow, Alaska) floyd at apaflo.com From rrr at ronadam.com Thu Apr 6 03:40:16 2006 From: rrr at ronadam.com (Ron Adam) Date: Thu, 06 Apr 2006 02:40:16 -0500 Subject: Python Module for Determining CPU Freq. and Memory? In-Reply-To: <4434b3c9@news.bezeqint.net> References: <4434b3c9@news.bezeqint.net> Message-ID: <9E3Zf.24081$VE.3360@dukeread05> efrat wrote: > Hello, > > I'd like to determine at runtime the computer's CPU frequency and memory. > > Is there a module for these types of queries? platform.platform returns > the computer's CPU name and type, but not its frequency; nor does it > report how much memory the computer has. In the python help(), I > searched for moudles cpu, but non were found. > (Please note: I'm interested in hardware stuff, like how much memory the > machine has; not how much free memory is available.) > > Many Thanks, > > Efrat For looking at memory on windows you might be able to make improvements to this class I wrote. I was going to add memget() methods for getting individual items, but it wasn't as useful as I was hoping it would be in checking my python memory use. For that I need info on individual tasks, but this might be better for your use. Cheers, Ron from ctypes import * from ctypes.wintypes import DWORD SIZE_T = c_ulong class MemStat(Structure): _fields_ = [ ("dwLength", DWORD), ("dwMemoryLength", DWORD), ("dwTotalPhys", SIZE_T), ("dwAvailPhys", SIZE_T), ("dwTotalPageFile", SIZE_T), ("dwAvailPageFile", SIZE_T), ("dwTotalVirtual", SIZE_T), ("dwAvailVirtualPhys", SIZE_T) ] def update(self): windll.kernel32.GlobalMemoryStatus(byref(self)) def show(self): self.update() result = [] for field_name, field_type in self._fields_: result.append("%s, %s\n" \ % (field_name, getattr(self, field_name))) return ''.join(result) memstat = MemStat() if __name__ == '__main__': print memstat.show() From bdesth.quelquechose at free.quelquepart.fr Thu Apr 20 21:33:13 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 21 Apr 2006 03:33:13 +0200 Subject: accessing a classes code In-Reply-To: <4446ce05@news.eftel.com> References: <444666af$0$12280$626a54ce@news.free.fr> <4446788a$0$31457$626a54ce@news.free.fr> <1145480053.936364.187470@e56g2000cwe.googlegroups.com> <4446ce05@news.eftel.com> Message-ID: <44480805$0$2638$636a55ce@news.free.fr> John Machin a ?crit : > On 20/04/2006 6:54 AM, bruno de chez modulix en face wrote: > >>> It turns out that what I want to do can be done using the inspect >>> module which has methods for getsourcecode among other things. >> >> >> I never said that what you wanted to do was impossible (nor even >> difficult, and FWIW, there are simpler alternatives than using inspect >> - using a templating system like empy comes to mind...). I only suggest >> that there are possibly far better solutions, that you seem to dismiss >> for some unknown reason... >> > > I'm with bruno -- IMHO, the OP's "solution" seems Byzantine, bizarre, ... > > Suggestion: the initial investigator gadget writes out the discovered > parameters into a case-specific config file, whose name is later passed > as an arg to the [only one] class's __init__ method() Suggestion: the investigator gadget is imported and called at the top-level of the modules containing the classes, that can then access the needed values. Then it's always possible to implement any caching mechanism in the investigator itself. import investigator platform_params = investigator.investigate() class MyObj(object): def __init__(self): self.attr1 = platform_params.attr1 self.attr2 = platform_params.attr2 (...) self.attrN = platform_params.attrN myMethod = platform_params.myMethod def otherMethod(self, arg): return platform_params.otherMethod(self, args) From yichao.zhang at gmail.com Thu Apr 27 11:02:53 2006 From: yichao.zhang at gmail.com (yichao.zhang) Date: 27 Apr 2006 08:02:53 -0700 Subject: =?utf-8?q?writing_some_lines_after_reading_goes_wrong_on_windows=EF=BC=9F?= Message-ID: <1146150173.947811.269820@y43g2000cwc.googlegroups.com> Hi all I can not write anything if I have read something. the code as: Python 2.4.3 (#69, Apr 11 2006, 15:32:42) [MSC v.1310 32 bit (Intel)] on win32 IDLE 1.1.3 >>> a=open('d:\\a','r+') >>> a >>> a.read() '11\n22\n33\n' >>> a.seek(0) >>> a.read(1) '1' >>> a.write("a") >>> a.seek(0) >>> a.read() '11\n22\n33\n' # it fails to write after reading >>> a.seek(0) >>> a.write("a") >>> a.seek(0) >>> a.read() 'a1\n22\n33\n' # it writes fine at the beginning of the file >>> it fails to write "a". but on my debian box, it works fine. the code on debian as: Python 2.3.5 (#2, Sep 4 2005, 22:01:42) [GCC 3.3.5 (Debian 1:3.3.5-13)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a=open('/a','r+') >>> a >>> a.read() '11\n22\n33\n' >>> a.seek(0) >>> a.read(1) '1' >>> a.write("a") >>> a.seek(0) >>> a.read() '1a\n22\n33\n' >>> What's wrong here? is this a bug on windows platform. From robert.kern at gmail.com Mon Apr 24 19:56:06 2006 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 24 Apr 2006 18:56:06 -0500 Subject: MS VC++ Toolkit 2003, where? In-Reply-To: <444D61F9.4040003@v.loewis.de> References: <1he8pss.1yk7ug81rv7pw2N%aleaxit@yahoo.com> <1145811839.042394.73260@t31g2000cwb.googlegroups.com> <1he8sbx.dqqp3q10n5thaN%aleaxit@yahoo.com> <1145849491.347970.112150@e56g2000cwe.googlegroups.com> <1he9m4m.9d8okx1x7mxeaN%aleaxit@yahoo.com> <444C784F.3000502@v.loewis.de> <1heag4u.19dksfxrbe14wN%aleaxit@yahoo.com> <444D61F9.4040003@v.loewis.de> Message-ID: Martin v. L?wis wrote: > Robert Kern wrote: > >>Oh, that's right, you need an import library for Python24.dll . > > That shouldn't be a problem: that library is included with Python. For mingw, too? I.e. a .a not a .lib? -- Robert Kern robert.kern at gmail.com "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From felipe.lessa at gmail.com Tue Apr 11 14:12:41 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Tue, 11 Apr 2006 15:12:41 -0300 Subject: Memory limit to dict? In-Reply-To: <4a289fFr0sufU1@uni-berlin.de> References: <4a289fFr0sufU1@uni-berlin.de> Message-ID: <1144779161.11151.16.camel@kenshin.CASA> Em Ter, 2006-04-11 ?s 19:45 +0200, Peter Beattie escreveu: > I was wondering whether certain data structures in Python, e.g. dict, > might have limits as to the amount of memory they're allowed to take up. > Is there any documentation on that? > > Why am I asking? I'm reading 3.6 GB worth of BLAST output files into a > nested dictionary structure (dict within dict ...). Looks something like > this: > > { GenomeID: > { ProteinID: > { GenomeID: > { ProteinID, Score, PercentValue, EValue } } } } I don't have the answer to your question and I'll make a new one: isn't the overhead (performance and memory) of creating dicts too large to be used in this scale? I'm just speculating, but I *think* that using lists and objects may be better. My 2 cents, -- Felipe. From jweida at gmail.com Thu Apr 13 09:42:04 2006 From: jweida at gmail.com (Jerry) Date: 13 Apr 2006 06:42:04 -0700 Subject: just one more question about the python challenge References: Message-ID: <1144935724.150276.275760@i40g2000cwc.googlegroups.com> This one threw me for a loop as well. I looked at that gfx file for a whole day before I finally understood what was in it. I only knew to separate it into five piles because of the hint forums though. I guess I'm not intuitive enough. :) I too did this challenge without PIL. Just remember that all files are just bytes of data. Hopefully, that idea with the rest of the hints will help you along. On a side note, level 13 was really fun. No images at all (whew!) and I got to learn something about Python AND the other technology used. As for level 14.... back to images. I really didn't like this level and it was the first time that I needed to find a solution. Yes, I cheated on this level. I'm not proud of it. But as it turns out, my solution was correct, but I was going in the wrong direction. I figured as much from the hints in the forum, but when I reversed my algorithm, it still ended up wrong. I didn't realize that there were four directions you could use to build the image. I had only accounted for two and both were not right. *sigh* On to level 15. From wilk-ml at flibuste.net Fri Apr 7 03:44:39 2006 From: wilk-ml at flibuste.net (William Dode) Date: Fri, 7 Apr 2006 07:44:39 +0000 (UTC) Subject: subprocess freeze with rsync on windows Message-ID: Hi, I try to call rsync (with ssh) with subprocess but _some times_ it freeze without traceback, without any reason. My code look like that : def sh(self,cmd): log.debug("S cmd: " + " ".join(cmd)) p = Popen(cmd, stdout = PIPE, stderr = PIPE) stdout, stderr = p.communicate() if stdout: log.debug("S ret: %s" % stdout) if stderr: log.error("S err: %s" % stderr) return p.returncode When it freeze i need to kill the ms-dos console by hand. I've no problem on linux with the same script. thanks the complet script (doing rsync and cp -al on the remote side) is available freely here : http://flibuste.net/libre/snapy (but documentation is in french) -- William Dod? - http://flibuste.net From Bulkan at gmail.com Mon Apr 10 20:56:30 2006 From: Bulkan at gmail.com (placid) Date: 10 Apr 2006 17:56:30 -0700 Subject: import help Message-ID: <1144716990.314306.79950@v46g2000cwv.googlegroups.com> Hi all, I have the following class code for a Node for a Linked List, (saved in node.py) class Node : def __init__(self,element): self.element = element self.next = None then i have another module called LinkedList.py, with following code import sys import node def main(): print "Does nothin ATM, as it doesnt work" main() the problem im having is that im getting NameError exception when i run LinkedList.py "global name 'Node' is not defined" Does anyone know what the problem is here? Thanks in advance From tagore at tagoresmith.com Sat Apr 29 00:43:29 2006 From: tagore at tagoresmith.com (Tagore Smith) Date: 28 Apr 2006 21:43:29 -0700 Subject: (was Re: Xah's Edu Corner: Criticism vs Constructive Criticism) In-Reply-To: References: <1145992903.834316.198370@u72g2000cwu.googlegroups.com> <4GM3g.3084$TT.1768@twister.nyroc.rr.com> <1146231280.733609.143230@e56g2000cwe.googlegroups.com> <1146276319.504694.218970@v46g2000cwv.googlegroups.com> Message-ID: <1146285809.127897.24070@j33g2000cwa.googlegroups.com> John Bokma wrote: > "Tagore Smith" wrote: > > > Your emails to his ISP > > are far more wasteful- you are using up very scarce resources > > dedicated to dealing with real abuse. > > According to his hosting provider dreamhost: > > I have warned this user that excessive offtopic cross-posting is not > allowed, and explained that if he doesn't quit he risks losing his > account. If you (or anyone else) notice this in the future, please do not > hesitate to submit another report. > Precisely: you have wasted the time of someone who might otherwise have spent that time dealing with real abuse. You got the standard email sent out to placate people like you. That was my point. Try sending mail to abuse at (any of my) desmesne(s). You won't get a response- in fact, no-one will read your mail. We just don't have the resources to deal with the easily offended. Too bad- we wouldn't mind handling real abuse, though it is unlikely given our selective set of users. I'm not sure that Xah's post was offtopic, and I am not sure how to determine that objectively. I am sure that it was excessively crossposted. I also know that Xah was posting to Usenet a long time before you, and that he will still be posting to Usenet long after you have given up in disgust, no matter who you complain to. > Reread it a few times, it might educate you (note the *cross-posting* and > the *submit another report*) I think I've mentioned the crossposting in every message I have posted on this thread, and that I don't approve of crossposting. I'm not sure that you are in a position to educate me, and that you suggest that you are is, frankly, obnoxious. I've been civil so far. > (Rest of your misinterpretation snipped). You can snip the important part, but that won't make the point go away. I happen to have been working in this industry for a long time. I have a lot of friends working at, and running, various enterprises. Some of those enterprises handle a lot of the internet's traffic, measured by packets at least. If I were really ethically impaired I could easily mess up internet access for a "list of people I don't like". A call from a backbone provider is not as ignorable as a random email to abuse at whateverlittleISP.com. But I am not ethically impaired (or at least not ethically impaired in that way). Every young sysadmin learns a simple thing: "you have disproportionate power, don't abuse it". Sometimes you have to read people's mail, to diagnose a problem. If they are into weird bondage stuff you avert your eyes, and you _never_ tell anyone (though I think you are allowed to look at them funny at the company picnic). If they are into child porn you call the cops, I think (the ethics are fuzzy here, but this is my conclusion). Crossposting is bad, unless it serves a specific purpose- Xah's post obviously doesn't. I dont like people reporting on Usenet posters to their ISPs, but... I can't really complain about that. Crossposting is not good, without a really good justification. But you are complaining about the content of his posts, and harassing his ISP based on that. That's not just bad, it is wicked. You can quote whatever you want from their emails, but I won't change my mind on this subject- Xah shouldn't crosspost, but otherwise he should be allowed to post. Would you like a Usenet campaign started to disrupt your internet access? You would be angry if that were done, and justifiably. From phpbird at gmail.com Wed Apr 5 23:13:08 2006 From: phpbird at gmail.com (Ju Hui) Date: 5 Apr 2006 20:13:08 -0700 Subject: Installing Python 2.4 on RedHat In-Reply-To: <1144292966.511167.84410@t31g2000cwb.googlegroups.com> References: <1144292966.511167.84410@t31g2000cwb.googlegroups.com> Message-ID: <1144293188.534499.131080@i39g2000cwa.googlegroups.com> install new version on differente location. use ln -s to use new python. From felipe.lessa at gmail.com Sat Apr 22 21:30:33 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Sat, 22 Apr 2006 22:30:33 -0300 Subject: Performance of Python 2.3 and 2.4 In-Reply-To: References: Message-ID: <1145755833.15325.15.camel@kenshin.CASA> Em Dom, 2006-04-23 ?s 00:20 +0200, Michal Kwiatkowski escreveu: > Hi! > > I was just wondering... Probably there is another factor involved: $ python2.3 Python 2.3.5 (#2, Mar 6 2006, 10:12:24) [GCC 4.0.3 20060304 (prerelease) (Debian 4.0.2-10)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import timeit >>> timeit.Timer('2**100000000').timeit(1) 4.6463479995727539 >>> timeit.Timer('112233445566778899 * 112233445566778899').timeit() 0.44853687286376953 $ python2.4 Python 2.4.3 (#2, Mar 30 2006, 21:52:26) [GCC 4.0.3 (Debian 4.0.3-1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import timeit >>> timeit.Timer('2**100000000').timeit(1) 4.9987671375274658 >>> timeit.Timer('112233445566778899 * 112233445566778899').timeit() 0.36968302726745605 -- Felipe. From a.schmolck at gmail.com Tue Apr 4 06:30:41 2006 From: a.schmolck at gmail.com (Alexander Schmolck) Date: 04 Apr 2006 11:30:41 +0100 Subject: Dice probability problem References: Message-ID: Tomi Lindberg writes: > I'm trying to find a way to calculate a distribution of outcomes with any > combination of dice. I have the basics done, but I'm a bit unsure how to > continue. My main concern is how to make this accept any number of dice, > without having to write a new list comprehension for each case? You need to think about the right way to break the problem down into some operation that can be repeated one fewer times than there are dice (if you just have a single dice, nothing needs to be done) and then repeat it. An obvious candidate is adding a single dice to the sums computed so far: def addDice(sums, dice): return [x+y for x in dice for y in sums] If you have less than 1 dice the answer is # len(pool) == 1 pool[0] After that, each time you add a dice you need to call addDice on the sum computed for all the previous dice and the new dice: # len(pool) == 2 addDice(resultFor1, pool[1]) addDice(pool[0], pool[1]) then # len(pool) == 3 addDice(resultFor2, pool[2]) addDice(addDice(resultFor1, pool[1]), pool[2]) addDice(addDice(pool[0], pool[1]), pool[2]) finally you get # len(pool) == n addDice(addDice(addDice(..., pool[n-3]), pool[n-2]) pool[n-1]) OK, so how do we get the repetition? Conveniently the pattern f(...f(f(x[0],x[1]),x[2])...,x[n-1]) or equivalently, if we write the infix operator * for f: x[0]*x[1]*...*x[n-1], can just be written as reduce(f, x) in python. So we get: reduce(addDice, pool) == reduce(lambda sums, dice: [x+y for x in dice for y in sums], pool) You should presumably also try writing this out as a single function, without using reduce (but recognizing the (left) reduction pattern is useful, even if you don't use python's reduce). 'as From diffuser78 at gmail.com Fri Apr 7 11:58:20 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 7 Apr 2006 08:58:20 -0700 Subject: performance degradation when looping through lists In-Reply-To: <60aipyz97wtt.1i1lxw1yj3rop.dlg@40tude.net> References: <4436575e$0$11070$9b4e6d93@newsread4.arcor-online.net> <60aipyz97wtt.1i1lxw1yj3rop.dlg@40tude.net> Message-ID: <1144425500.378931.295490@i40g2000cwc.googlegroups.com> Hi, I wrote a program some days back and I was using lists heavily for performing operations such as pop, remove, append. My list size was around 1024x3 and there were around 20 different objects like this. What I want to ask you is that my program also degraded over a period of time. I cannot post the code as its lot of code. But I want to ask a question why List degrade. What other alternative for lists is a faster measure. Eveyr help is greatly appreciated, From cvanarsdall at mvista.com Tue Apr 18 15:49:46 2006 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Tue, 18 Apr 2006 12:49:46 -0700 Subject: Java Developer Exploring Python In-Reply-To: References: <1145290449.735642.120860@i40g2000cwc.googlegroups.com> Message-ID: <444542DA.6020803@mvista.com> Jarek Zgoda wrote: > redefined.horizons at gmail.com napisa?(a): > > >> Is Python actively developed and supported on Linux? Would it be a >> viable option for cross-platform application development? >> > > Yeas and yeas. Yeas. (That's how we pronounce "yes" here, in Poland, > East Europe). > > >> Can anyone recommend an open source IDE for Python that runs on Linux? >> My favorite IDE: vi > > Komodo. But in most cases you don't need any IDE, just good text editor > would make it go. Like Kate, jEdit or similar. > -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From brochu121 at gmail.com Wed Apr 12 15:05:56 2006 From: brochu121 at gmail.com (david brochu jr) Date: Wed, 12 Apr 2006 15:05:56 -0400 Subject: Regular Expressions Message-ID: <9583ed900604121205o5da84b0crd2ae671c0b6a4395@mail.gmail.com> Hi, I am trying to grab the following string out of a text file using regular expression (re module): "DcaVer"=dword:00000640 What I need to do with that string is trim down " "DcaVer"=dword:" and convert the remaining number from hex to dec. I have been trying to figure this out for a while..I am fairly new so please any help would be greatly appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Fri Apr 21 19:29:54 2006 From: sjmachin at lexicon.net (John Machin) Date: Sat, 22 Apr 2006 09:29:54 +1000 Subject: Powerful Command line parsers In-Reply-To: <1145641993.281898.34110@i40g2000cwc.googlegroups.com> References: <1145641993.281898.34110@i40g2000cwc.googlegroups.com> Message-ID: <44496AF2.6010602@lexicon.net> On 22/04/2006 4:15 AM, PyPK wrote: > Is there a Command line parser in python that can: > 1. resolve conflicts > 2. specify something like requires > 3. and smart "... that can ... and smart" does not compute. > > for ex: > python test.py --a --b --c --d I'm used to seeing --fubar and -f; what does --f mean? > > Case 1: > If 'a' is an option 'b' or 'c' cannot be specified. > > Case 2: > atleast one option should be specified > > Case 3: > IF 'a' and 'c' are given then 'd' has to be given > > or many such cases. > > I was wondering as this is a very common problem there if there is a > module that could do these things . > 'optparse' is not this smart I guess. Modules are neither dumb nor smart. The author of optparse is IMHO smart; it does just about what it ought to do. To meet your specifications, the module would need to incorporate a mini-language: if a and (b or c): nasty("blah 1") if not (a or b or c or d): nasty("blah 2") if a and c and not d: nasty("blah 3") Again IMHO, it would be an enormous waste of effort to implement such a mini-language inside a command-line parser, when the call to the parser can be followed by whatever conditions and actions you like, written in Python. From apgwoz at gmail.com Wed Apr 5 18:51:25 2006 From: apgwoz at gmail.com (Andrew Gwozdziewycz) Date: Wed, 5 Apr 2006 18:51:25 -0400 Subject: Counting all permutations of a substring In-Reply-To: <1144271242.858677.124490@t31g2000cwb.googlegroups.com> References: <1144271242.858677.124490@t31g2000cwb.googlegroups.com> Message-ID: On Apr 5, 2006, at 5:07 PM, Chris Lasher wrote: > Hi all, > How can one count all the permutations of a substring in a string? For > a more concrete example, let's say > targetstr = 'AAA' > and > probestr = 'AA' > > I want to consider how many times one can count probestr ('AA') in > targetstr ('AAA'). The value in this example is, obviously, 2: you can > match the first and second A's as 'AA' and also the second and third > A's as 'AA'. Compiling a regular expression of the probestr and > doing a > findall(targetstr) will not work because the RE stops on the first > combination of 'AA' that it finds (the first and second A's of the > targetstr). The regular expression re.compile(r'A{2,}'} will not work, > either; it simply consumes all three A's as one match. The string > method count('AA') acts similarly to the findall of the 'AA' RE, > returning 1, as it only matches the first and second A's. > > Any suggestions on how to get at that 2nd pair of A's and count it? > Humbly, I'm a bit stumped. Any help would be appreciated. I don't think you're describing a permutation. A permutation of a string 'ABC' would be 'CBA', or 'BCA'. You're describing something like the number of proper substrings of a given value, and the easiest way to do that is to just check to see if the probestring starts a string at the current index of the string... def count_proper_substrings_equal_to(target, probe): i = 0 count = 0 while i < len(target): if target[i:].startswith(probe): count = count + 1 i = i + 1 return i And of course there's a more 'pythonic' way to do it, but this would be a generalized algorithm suitable for most languages. --- Andrew Gwozdziewycz apgwoz at gmail.com http://ihadagreatview.org http://and.rovir.us From tim at pollenation.net Fri Apr 21 16:09:17 2006 From: tim at pollenation.net (Tim Parkin) Date: Fri, 21 Apr 2006 21:09:17 +0100 Subject: proposed Python logo In-Reply-To: <1145639208.569365.135440@i40g2000cwc.googlegroups.com> References: <1145585399.871299.31900@t31g2000cwb.googlegroups.com> <1145615455.477800.74730@i39g2000cwa.googlegroups.com> <1145639208.569365.135440@i40g2000cwc.googlegroups.com> Message-ID: <44493BED.1020102@pollenation.net> Michael Tobis wrote: > > That said, and conceding that the first impression is positive, I don't > see how it represents Python. More to the point, the longer I look at > it the less I like it, and I would NOT wear it on a T-shirt. > over 25 people disagree with you so far and thats without any advertising whatsoever (and it's an older version of the logo) because you can get T-Shirts from cafepress.com/pydotorg and any profits go to the psf. I'll add the new logo over the weekend. > >>The + formation is positive enough, and it has a yin-yang >>feel to it which to me conjures up the image of balance, not >>divisiveness. > > Both the cross and the yin-yang have religious associations, which will > be positive for some and negative for others but will certainly be > unrepresentative of what Python is. This would be a great logo for > Taoist Christians, if such a group exists. > > How is Python about "balance"? It is about abstraction, composition, > the whole greater than the parts, yes, but there's nothing there that > really draws on duality. So the whole two-ness of the thing is one of > the parts that disturbs me. > They're freindly snakes at a tadpole fancy dress competition having a 'cuddle'. Where do you think Python eggs come from... Tim Parkin p.s. the logo is actually based on mayan representations of snakes which very often represent only the head and perhaps a short length of tail. The structure of the snake representations the natural coiling/nesting of a snake as seen side on.. The following image shows a similar representation (we have a snake house nearby which makes it easier to observe behaviour) http://www.xcalak.info/images/florafauna/fer_de_lance_l.jpg The mesoamerican calendar also represents snake heads in a similar manner. http://en.wikipedia.org/wiki/Tzolkin The abstraction of the snake design used in mayan culture seemed non-denominational enough to only raise contrived objections. The shapes used (cross/spiral/yin-yang) are also primitive enough that there will always be connotations that can be derived. http://www.alovelyworld.com/webhon/gimage/hdu011.jpg http://www.khoahoc.com.vn/photos/Image/2005/11/16/maya-snake.jpg http://www.xcalak.info/images/florafauna/fer_de_lance_l.jpg The two headed snake was also an influence on the design http://www-personal.umich.edu/~bjayatil/British%20Museum%20&%20London/slides/17-aztec_snake.html which is also a common 'meme' in many continents, including africa http://www.sfu.ca/archaeology/museum/ndi/cam5.jpg And I'd like to see you tell a civil war soldier that it looks like his trousers are held up by a two headed tadpole http://www.civilwarrelics.com/museum/graphics/Frame25a.JPG If you look carefully at the logo, you will also see an indian symbol of peace.. (I'll leave this one alone as it can also mean something else). From kruhftREMOVE at gmail.com Tue Apr 11 14:10:03 2006 From: kruhftREMOVE at gmail.com (Burton Samograd) Date: 11 Apr 2006 12:10:03 -0600 Subject: Memory limit to dict? References: <4a289fFr0sufU1@uni-berlin.de> Message-ID: <873bgkouf8.fsf@gmail.com> Peter Beattie writes: > I've no idea how far the Windows task manager's resource monitor can be > trusted -- probably not as far as I could throw a heavy-set St Bernard > --, but it seems to stop roughly when that monitor records a swap file > size of 2.2 GB. Not being a windows expert at all, but I would assume with 32 bit windows each process in the system can have an address space of ~2 gigs. In linux the process address space is split in half, bottom 2 gigs for OS mappings, top for the process, so it looks like you might just be hitting the maximum allowed address space mapping. You should partition your data into hierarchial modules and let python do the swapping for you...although you have 16 gigs (I have to put a holy crap after that!) you will always run into process limits, at least until true 64 bit os's are in vouge. -- burton samograd kruhft .at. gmail kruhft.blogspot.com www.myspace.com/kruhft metashell.blogspot.com From kevin.bell at slcgov.com Tue Apr 25 13:02:07 2006 From: kevin.bell at slcgov.com (Bell, Kevin) Date: Tue, 25 Apr 2006 11:02:07 -0600 Subject: search an entire website given the homepage URL Message-ID: <2387F0EED10A4545A840B231BBAAC7226082CA@slcimail1.slcgov.com> I know I can use urllib2 to get at a website given urllib2.urlopen(url) but I'm unsure how to then go through all pages that are linked to it, but still in the domain. If I want to search through the entire python website give the homepage, how would I go about it? I don't reinvent the wheel if someones already written a module for parsing out the links and drilling through them! TIA KEV From jaywgraves at gmail.com Mon Apr 10 17:02:19 2006 From: jaywgraves at gmail.com (jay graves) Date: 10 Apr 2006 14:02:19 -0700 Subject: Python Shell window In-Reply-To: <1144702713.136121.186230@e56g2000cwe.googlegroups.com> References: <1144693672.676045.193680@i40g2000cwc.googlegroups.com> <1144702713.136121.186230@e56g2000cwe.googlegroups.com> Message-ID: <1144702939.080649.140480@i39g2000cwa.googlegroups.com> > find the errand CMD prompt and move it. errand -> errant From bucodi at yahoo.fr.invalid Fri Apr 28 12:58:10 2006 From: bucodi at yahoo.fr.invalid (Rony Steelandt) Date: Fri, 28 Apr 2006 18:58:10 +0200 Subject: wxPython, wxcombobox opening Message-ID: Hi, Does somebody knows a way to automaticely open the list part of a wxCombobox when it gets the focus ? tia, Rony From greg.kujawa at gmail.com Sun Apr 2 21:04:49 2006 From: greg.kujawa at gmail.com (gregarican) Date: 2 Apr 2006 18:04:49 -0700 Subject: Is pwm Python MegaWidgets viable? References: <499rh1Fnh7voU1@individual.net> <1143983854.954254.221080@i40g2000cwc.googlegroups.com> <44306C31.1020007@redlinepy.com> Message-ID: <1144026289.428369.116570@i40g2000cwc.googlegroups.com> Paul Watson wrote: > Many thanks for your reply. I was setting out to make use of the > Manning book by Grayson. Perhaps I should just use online tutorial and > such for learning plain-old tk first. However, I have heard good things > about the book. Just trying to use what was already at hand. Here's the online tutorial that provides a basic introduction to Tkinter --> http://www.pythonware.com/library/tkinter/introduction/. I found it handy. I had used Tk implementations in other languages such as Ruby so I had already become familiar with the overall Tk toolkit, but nevertheless the online Tkinter tutorial was refreshing. Wasn't aware of the Manning book but it sounds like a great resource as well! From steve at REMOVETHIScyber.com.au Wed Apr 12 10:18:08 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Thu, 13 Apr 2006 00:18:08 +1000 Subject: random.sample with long int items References: <1144848541.805554.122180@u72g2000cwu.googlegroups.com> <7xd5fmucw2.fsf@ruckus.brouhaha.com> Message-ID: On Wed, 12 Apr 2006 06:44:29 -0700, Paul Rubin wrote: > "jordi" writes: >> I need the random.sample functionality where the population grows up to >> long int items. Do you know how could I get this same functionality in >> another way? thanks in advance. > > Nothing stops you: > > >>> from random import sample > >>> a = [n**25 for n in range(6)] > >>> a > [0, 1, 33554432, 847288609443L, 1125899906842624L, 298023223876953125L] > >>> sample(a,2) > [1125899906842624L, 298023223876953125L] No, I think he means the size of the list is big enough to need a long int. Something like xrange(10**10) or even bigger. >>> random.sample(xrange(10*10), 10) [96, 45, 90, 52, 57, 72, 94, 73, 79, 97] >>> random.sample(xrange(10**10), 10) Traceback (most recent call last): File "", line 1, in ? OverflowError: long int too large to convert to int -- Steven. From gdamjan at gmail.com Mon Apr 10 15:57:01 2006 From: gdamjan at gmail.com (Damjan) Date: 10 Apr 2006 12:57:01 -0700 Subject: Is there a Python MVC that works just as well with just CGI, or FCGI? In-Reply-To: <1144687427.086586.16400@i40g2000cwc.googlegroups.com> References: <1144687427.086586.16400@i40g2000cwc.googlegroups.com> Message-ID: <1144699021.932171.241120@j33g2000cwa.googlegroups.com> TurboGears? www.turbogears.com From f.petri at steinbichler.de Sun Apr 9 14:47:17 2006 From: f.petri at steinbichler.de (blackno666) Date: 9 Apr 2006 11:47:17 -0700 Subject: Problems with current value of wx.SpinCtrl and EVT_SPIN Message-ID: <1144608437.075278.188350@j33g2000cwa.googlegroups.com> Hello, I am new to Python/wxPython and am experiencing first problems. I have a dialog which includes a SpinCtrl and a Slider. I want the Slider to affect the SpinCtrl and vice versa (http://wiki.wxpython.org/index.cgi/ChallengeDemos#Part1). The code I wrote does, however, not work correctly. The event EVT_SPIN is never handled (even though I wrote a handler), and in the handler of EVT_SCROLL_CHANGED I do not obtain the modified value, but the value before the control has changed. Any feedback would be greatly appreciated. To clarify my problem, here's the code (Python2.4, wxPython 2.6) : import wx class AppFrame(wx.Frame): def OnSpinGeneral(self, event): b = wx.MessageBox("never reached") def OnSpin(self, event): # I tried to use Skip so that the changing of the value would take place before # I invoke GetValue(), however this has no effect event.Skip() print self.spin.GetValue() self.slider.SetValue(self.spin.GetValue()) def OnScrollChanged(self, event): self.spin.SetValue(self.slider.GetValue()) def __init__(self): wx.Frame.__init__( self, None, -1, "", #size=FRAME_SIZE, style=wx.DEFAULT_FRAME_STYLE ) self.sizer = wx.BoxSizer( wx.VERTICAL ) self.spin = wx.SpinCtrl(self, min = 0, max = 50) self.slider = wx.Slider(self, 1, 6, 0, 50) self.sizer.Add(self.spin) self.sizer.Add(self.slider) self.Bind(wx.EVT_SCROLL_CHANGED, self.OnScrollChanged, self.slider) self.Bind(wx.EVT_SPIN_UP, self.OnSpin, self.spin) self.Bind(wx.EVT_SPIN_DOWN, self.OnSpin, self.spin) self.Bind(wx.EVT_SPIN, self.OnSpinGeneral, self.spin) self.SetSizer(self.sizer) self.SetAutoLayout(1) self.Show(1) app = wx.PySimpleApp() frame = AppFrame() app.MainLoop() From ygao2004 at gmail.com Sat Apr 8 04:17:53 2006 From: ygao2004 at gmail.com (ygao) Date: 8 Apr 2006 01:17:53 -0700 Subject: unicode wrap unicode object? In-Reply-To: References: <1144452777.460885.131450@t31g2000cwb.googlegroups.com> Message-ID: <1144484273.207956.285400@i39g2000cwa.googlegroups.com> sorry,my poor english. I got a solution from others. I must use utf-8 for chinese. >>> import sys >>> reload(sys) >>> sys.setdefaultencoding("utf-8") >>> s='\xe9\xab\x98' #this uff-8 string >>> ss=U'\xe9\xab\x98' >>> ss1=ss.encode('unicode_escape').decode('string_escape') >>> s1=s.decode('unicode_escape') >>> s1==ss True >>> ss1==s True >>> From eurleif at ecritters.biz Wed Apr 26 16:13:48 2006 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Wed, 26 Apr 2006 16:13:48 -0400 Subject: modifying iterator value. In-Reply-To: References: Message-ID: <444fd475$0$3683$4d3efbfe@news.sover.net> chun ping wang wrote: > i want to modify an iterator value. > > for x in someList > x = 1 for index, value in enumerate(someList): someList[index] = 1 From brochu121 at gmail.com Thu Apr 20 09:12:18 2006 From: brochu121 at gmail.com (david brochu jr) Date: Thu, 20 Apr 2006 09:12:18 -0400 Subject: Tail a file Message-ID: <9583ed900604200612p44506504o3e573153253b5a9c@mail.gmail.com> Hello, I wrote a script to monitor ping activity and output it to a log file. I am using windows and want to have another script constantly check the latest entry to see if Request timed out is seen. Is there a way to "tail" a file much like I would in Unix so I can just see the latest entry and move from there? -------------- next part -------------- An HTML attachment was scrubbed... URL: From jpahullo at gmail.com Wed Apr 12 09:29:01 2006 From: jpahullo at gmail.com (jordi) Date: 12 Apr 2006 06:29:01 -0700 Subject: random.sample with long int items Message-ID: <1144848541.805554.122180@u72g2000cwu.googlegroups.com> I need the random.sample functionality where the population grows up to long int items. Do you know how could I get this same functionality in another way? thanks in advance. Jordi From http Thu Apr 13 08:05:44 2006 From: http (Paul Rubin) Date: 13 Apr 2006 05:05:44 -0700 Subject: New Karrigel page in Wikipedia References: <1144867025.095969.92870@e56g2000cwe.googlegroups.com> <1144915559.734587.131140@e56g2000cwe.googlegroups.com> <1144918850.680444.198980@g10g2000cwb.googlegroups.com> <7x1ww1lro6.fsf@ruckus.brouhaha.com> <1144927845.046176.69420@t31g2000cwb.googlegroups.com> Message-ID: <7xodz5r887.fsf@ruckus.brouhaha.com> "Pierre Quentel" writes: > Ok, thanks for the information. I have rewritten the page in a more > neutral way and removed the tutorial-like part, I'll put in in wikibooks I don't know if you really want to put the tutorial in wikibooks, since there's already documentation on karrigell.com. The idea of wikibooks is to develop books on the wiki. That's maybe a reasonable way to create new documentation, but in this case it would mean you have two parallel documents being developed separately. From __peter__ at web.de Fri Apr 7 10:12:07 2006 From: __peter__ at web.de (Peter Otten) Date: Fri, 07 Apr 2006 16:12:07 +0200 Subject: how convert "\\xd6\\xd0\\xb9\\xfa" into "\xd6\xd0\xb9\xfa" References: <1144417534.363639.90270@u72g2000cwu.googlegroups.com> Message-ID: ygao wrote: > in python > dd = "\\xd6\\xd0\\xb9\\xfa" > d = "\xd6\xd0\xb9\xfa" > but how to convert one to other ? >>> "\\xd6\\xd0\\xb9\\xfa".decode("string-escape") '\xd6\xd0\xb9\xfa' >>> "\xd6\xd0\xb9\xfa".encode("string-escape") '\\xd6\\xd0\\xb9\\xfa' Peter From nogradi at gmail.com Thu Apr 13 16:59:52 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Thu, 13 Apr 2006 22:59:52 +0200 Subject: namespace issue Message-ID: <5f56302b0604131359o1fc83de8m9a12b96812cd0b4c@mail.gmail.com> I would like to give the same name to a keyword argument of a class method as the name of a function, with the function and the class living in the same namespace and the class method using the aforementioned function. So far I've been unsuccesfully trying to go along these lines: def great_name( x ): return x.upper( ) class myclass: def mymethod( self, great_name=False ): if great_name: return great_name( 'something' ) else: return 'something' This would fail, because in the namespace of mymethod great_name is a local variable and is not a callable. So I tried to modify the class like this: class myclass: def mymethod( self, great_name=False ): great_name_ = great_name del great_name if great_name_: return great_name( 'something' ) else: return 'something' in the hope of the del statement only removing the local variable util but still remembering the great_name function from outside, but this didn't work either. So my question is if it was possible to do this at all? The reason for giving the same name is a usability issue of my module, I would like both the keyword argument and the function to be visible by the user and the name I would like to give them describes very well what they are doing. That is also the reason why I don't want to hide the great_name function in the class as a method. From aahz at pythoncraft.com Mon Apr 17 16:03:14 2006 From: aahz at pythoncraft.com (Aahz) Date: 17 Apr 2006 13:03:14 -0700 Subject: Why new Python 2.5 feature "class C()" return old-style class ? References: <1144752553.305591.88050@j33g2000cwa.googlegroups.com> <1hdwol0.luxoeathwi1cN%aleaxit@yahoo.com> Message-ID: In article <1hdwol0.luxoeathwi1cN%aleaxit at yahoo.com>, Alex Martelli wrote: >Aahz wrote: >> >> Method resolution order is the primary up-front difference, but >> introspective code can also have problems. > >The crucial difference between the old-style classes and the new ones >is about how Python lookups special methods. Right. Thanks! I don't actually use new-style classes much myself, so I forgot about that one. (And I needed it for the draft that's due today...) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "LL YR VWL R BLNG T S" From just at xs4all.nl Wed Apr 12 12:36:17 2006 From: just at xs4all.nl (Just) Date: Wed, 12 Apr 2006 18:36:17 +0200 Subject: just one more question about the python challenge References: Message-ID: In article , John Salerno wrote: > Georg Brandl wrote: > > John Salerno wrote: > >> Georg Brandl wrote: > >> > >>> Have you found the file? You'll have to distribute that file bytewise > >>> in 5 "piles". > >> No, I haven't figured out anything for this puzzle. It seems I might > >> have to change the filename of the image to something else, but I don't > >> know what. But even after I find the image, I won't know what to do from > >> there. I don't know what it means to distribute a file bytewise, but if > >> I knew exactly which modules/functions to use, I'd be more than happy > >> reading up on them myself. I just hate not knowing where to go to begin > >> with (even though I know I probably won't know enough about images to > >> use the right module properly either, but I can try). > > > > If you give me the URL of that level, maybe I'll recall what to do. > > > > Georg > > http://www.pythonchallenge.com/pc/****/**** > > If you're prompted, the name and password are '****' and '****'. Erm, it's not nice to post complete solutions in a public forum. Just From siona at chiark.greenend.org.uk Tue Apr 11 06:14:13 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 11 Apr 2006 11:14:13 +0100 (BST) Subject: Characters contain themselves? References: <1144689833.966377.270490@u72g2000cwu.googlegroups.com> Message-ID: Graham Fawcett wrote: >You could always use an "is-proper-subset-of" function, which is closer >to the intent of your algorithm. Using Jamitzky's very clever infix >recipe [1], you can even write it as an infix operator: > >#Jamitzky's infix-operator class, abbreviated >class Infix: > [ ... ] > ># define our is-proper-subset operator... >ips = Infix(lambda a, b: (a is not b) and (a in b)) > >>>> print 'a' |ips| 'a' >False >>>> print 'a' |ips| 'abc' >True Unfortunately: >>> print 'abc' |ips| 'abc' False >>> print 'a'+'bc' |ips| 'abc' True Which might not be what you want. On the other hand, it's a simple fix: >>> ips = Infix(lambda a, b: (a != b) and (a in b)) >>> print 'a' |ips| 'abc' True >>> print 'a'+'bc' |ips| 'abc' False >[1] http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/384122 -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From grahamd at dscpl.com.au Tue Apr 11 06:57:47 2006 From: grahamd at dscpl.com.au (grahamd at dscpl.com.au) Date: 11 Apr 2006 03:57:47 -0700 Subject: minidom + wxPython woes References: <1144448449.586601.293480@v46g2000cwv.googlegroups.com> <1144477016.011818.70290@e56g2000cwe.googlegroups.com> <1144503992.283231.305290@i40g2000cwc.googlegroups.com> <1144519390.080682.247970@e56g2000cwe.googlegroups.com> Message-ID: <1144753067.607004.49170@e56g2000cwe.googlegroups.com> Paul Boddie wrote: > Frank Millman wrote: > > Fredrik Lundh wrote: > > > > > > no, it's not a bug in the pyexpat module -- the problem is that > > > wxPython uses it's own incompatible version of the expat library, > > > and loads it in a way that causes problems for any library that's > > > tries to use its own statically linked version. > > [...] > > > Firstly, it seems from various posts to the tracker item that the same > > problem has been reported with pygtk, Qt, and VTK. > > There used to be issues with Expat, PyXML and mod_python which may be > vaguely related to this, mostly because there was some usage of Expat > within some Apache component which conflicted with PyXML's Expat > configuration. FYI, the incompatibility issues that arise with pyexpat in mod_python are well documented at: http://www.dscpl.com.au/articles/modpython-006.html Graham From bj_666 at gmx.net Mon Apr 10 18:47:47 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Tue, 11 Apr 2006 00:47:47 +0200 Subject: Programming Tutorial for absolute beginners References: <1144439148.751062.16590@t31g2000cwb.googlegroups.com> <1144512142.324056.281660@g10g2000cwb.googlegroups.com> <1144572585.147756.144240@i40g2000cwc.googlegroups.com> Message-ID: In <1144572585.147756.144240 at i40g2000cwc.googlegroups.com>, Frank Millman wrote: > Why not think to the future, and do it like this. Instruct the reader > to enter 'from __future__ import division'. You do not have to explain > the details, just say that this is the way division will work in the > future, and this statement will eventually not be required. > > Then your example will show that 3/2 = 1.5, which is what they would > expect. > > Then you can mention that, if they just want the integer portion, they > can use int(3/2). I think that most people with the slightest > understanding of basic arithmetic will relate to this without a > problem. Or instead of converting the `float` back to an `int`, they can use integer division: ``3 // 2`` Ciao, Marc 'BlackJack' Rintsch From cfriedl at bigpond.net.au Sun Apr 23 04:22:06 2006 From: cfriedl at bigpond.net.au (bwaha) Date: Sun, 23 Apr 2006 08:22:06 GMT Subject: Recommended IDE for creating GUI? References: <124idf0362d75dd@corp.supernews.com> Message-ID: "Marty Christion" wrote in message news:124idf0362d75dd at corp.supernews.com... > What are some good free or inexpensive (<$50) IDE's for learning how to > program and create GUI's for Python? I'm pretty good with the simple > programming aspect of the language, but I'm a little mystified by the world > of GUI's, and the options available in python. > > I've been using python on and off for about 12 months and WxPython for about 5 months. I've found the following combination works well together: SPE - Stani's Python Editor http://stani.be/python/spe/blog/ WXGlade - bundled with SPE WinPDB - debugger bundled with in SPE that works with GUIs WxPython - python bindings to WxWidgets library (fantastic demos that get you up and running quickly) http://www.wxpython.org/ Ipython - interactive python shell http://ipython.scipy.org/ hth bwaha From floris.vannee at gmail.com Fri Apr 7 12:58:19 2006 From: floris.vannee at gmail.com (floris.vannee at gmail.com) Date: 7 Apr 2006 09:58:19 -0700 Subject: win32com Message-ID: <1144429099.614139.139750@z34g2000cwc.googlegroups.com> Hi, Is it possible to create a com server in python and then access that server using VB .NET, for example using the following code. A very basic com server i found in a tutorial about win32com: class HelloWorld: _reg_clsid_ = "{7CC9F362-486D-11D1-BB48-0000E838A65F}" _reg_desc_ = "Python Test COM Server" _reg_progid_ = "Python.TestServer" # Next line assumes file is "testcomserver.py" _reg_class_spec_ = "testcomserver.HelloWorld" _public_methods_ = ['Hello'] _public_attrs_ = ['softspace', 'noCalls'] _readonly_attrs_ = ['noCalls'] def __init__(self): self.softspace = 1 self.noCalls = 0 def Hello(self, who): self.noCalls = self.noCalls + 1 # insert "softspace" number of spaces return "Hello" + " " * self.softspace + who if __name__=='__main__': import win32com.server.register win32com.server.register.UseCommandLine(HelloWorld) When I run it it says: '>>> Registered: Python.TestServer ' But how can I access that server now from VB .NET (if it's possible). Or do I need to use very different python code? (I wasnt sure where to put this, in vb or python section, sorry if its in the wrong section) Thanks in advance, Floris van Nee From godoy at ieee.org Wed Apr 19 07:40:57 2006 From: godoy at ieee.org (Jorge Godoy) Date: Wed, 19 Apr 2006 08:40:57 -0300 Subject: multiline comments References: Message-ID: <1381517.XiSu08VAzt@jupiter.g2ctech> Edward Elliott wrote: > Sure they can be abused. So can a thousand other language features. My > point is you can't teach good coding through syntax, and trying to causes > more problems than it solves. I like the phrase: there are some languages that incentivates bad practices in programming; there is Python that doesn't. Some rigid syntax indeed makes you think one way -- and that's one of Python's motto, isn't it? "There's one right way to do it" -- but that will make your code more understandable and readable in the future. > I would argue the current system is in fact slightly worse, because people > will comment out code chunks anyway (either lots of #s or triple-quotes) > and are less likely to remove them when it's more work. But either way, > social pressure is infinitely more effective at cleaning up code than > comment syntax. Is it harder to remove "n" lines of code commented out with "#" than "n" lines of multiline commented code? How? The same question goes for triple quoted code. -- Jorge Godoy "Quidquid latine dictum sit, altum sonatur." - Qualquer coisa dita em latim soa profundo. - Anything said in Latin sounds smart. From sturlamolden at yahoo.no Tue Apr 25 16:24:09 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 25 Apr 2006 13:24:09 -0700 Subject: MinGW and Python In-Reply-To: References: <1145861223.509630.247350@y43g2000cwc.googlegroups.com> <444C79D7.4060007@v.loewis.de> <444DC62B.7000702@v.loewis.de> <1145985979.369429.114040@i39g2000cwa.googlegroups.com> Message-ID: <1145996649.514911.99880@g10g2000cwb.googlegroups.com> Edward Elliott wrote: > Couldn't you compile the msvc-python code under gcc/mingw? Yes I could, but I cannot compile the code under msvc for comparison. I only have MinGW. If build the mingw binary then someone else has to build the msvc binary for comparison. Then we could do pybenches on the same computer. Uh .. I actually think it could be an EULA violation to publish mingw vs. msvc benchmarks without permission from Microsoft. I don't want to part of anything illegal or have M$ lawyers breathing down my back. If we are going to do this, then we must do it properly and get the permissions we need. From bignose+hates-spam at benfinney.id.au Wed Apr 5 18:38:12 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 06 Apr 2006 08:38:12 +1000 Subject: Unicode question : turn =?utf-8?q?=22Jos=C3=A9=22_into_u=22Jos=C3=A9=22?= References: <41A1CBC76FDECC42B67946519C6677A9036C6020@pippin.int.etrials.com> Message-ID: <878xqjveay.fsf@benfinney.id.au> "Ian Sparks" writes: > This is probably stupid and/or misguided but supposing I'm passed a > byte-string value that I want to be unicode, this is what I do. I'm > sure I'm missing something very important. Perhaps you need to read one of the good Python Unicode tutorials, such as: > Short version : > > >>> s = "Jos?" #Start with non-unicode string In what encoding? Once you step outside the ASCII character set, you *must* be explicit about the encoding used for the text. Because there is no sure way to infer it, Python refuses to guess. If you're going to include literal non-ASCII characters in the code (which is the simplest and most readable way), you must also tell Python what encoding to use when it reads the source file. > >>> unicoded = eval("u'%s'" % "Jos?") Once you know the encoding, you can simply say:: >>> str_encoding = "iso-8859-1" >>> str = "Jos?" >>> unicode_str = str.decode(str_encoding) (Note that I didn't type this using the iso-8859-1 encoding, so it's likely to be wrong in that respect; you'll need to change it to match your situation.) -- \ "To me, boxing is like a ballet, except there's no music, no | `\ choreography, and the dancers hit each other." -- Jack Handey | _o__) | Ben Finney From grflanagan at yahoo.co.uk Wed Apr 19 07:19:03 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 19 Apr 2006 04:19:03 -0700 Subject: scanning for numerals / letters References: Message-ID: <1145445543.376618.326670@j33g2000cwa.googlegroups.com> Kun wrote: > I have the following if statement that checks if a form is empty: > > if form.has_key("date") and form["date"].value != "": > date=form['date'].value > > else: > print "ERROR: No date entered!" > raise Exception > > I would also like to add another if statement checking if 'date' has any > letters (a-z) in it, and if so, would like to say that "you have to > enter a date with numbers". I am not sure how to alter my current if > statement to do that check so any assistance would be appreciated. > Having just attempted a 'string_to_date' function I can see the wisdom of having separate 'day', 'month' and 'year' input fields on the client. If you can't or won't provide separate fields then I suppose you have to inform users as to what you accept as valid input, eg. 'ddmmyy', or 'month/day/year'. Here's some code which assumes that you are providing appropriate formatting hints: import time import datetime DDMMYY = ['%d %m %Y', '%d %m %y', '%d/%m/%Y', '%d/%m/%y', '%d-%m-%Y', '%d-%m-%y' ] def yearmonthday(datestring, fmts=DDMMYY): ymd = tuple() for f in fmts: try: ymd = time.strptime( datestring, f ) break except ValueError: continue if not ymd: raise ValueError return ymd[0], ymd[1], ymd[2] def is_valid_date(datestring, fmts=DDMMYY): try: yearmonthday(datestring, fmts) return True except ValueError: return False def string_to_date(datestring, fmts=DDMMYY): return datetime.date( *yearmonthday(datestring, fmts) ) assert string_to_date( '1/2/01', DDMMYY) == datetime.date(2001,2,1) assert string_to_date( '1 2 01', DDMMYY) == datetime.date(2001,2,1) assert string_to_date( '01/02/01', DDMMYY) == datetime.date(2001,2,1) assert string_to_date( '1/02/2001', DDMMYY) == datetime.date(2001,2,1) assert string_to_date( '29/02/2008', DDMMYY) == datetime.date(2008,2,29) assert string_to_date( '01/2/99', DDMMYY) == datetime.date(1999,2,1) for d in [ '', '32/1/01', '01/13/01', '29/2/07', '1/2', 'abcdef' ]: assert not is_valid_date(d, DDMMYY) Gerard From wrongbad at gmail.com Fri Apr 28 18:08:19 2006 From: wrongbad at gmail.com (I V) Date: Fri, 28 Apr 2006 15:08:19 -0700 Subject: best way to determine sequence ordering? References: <70q4g.2006$No6.43783@news.tufts.edu> <1146259620.636600.119710@u72g2000cwu.googlegroups.com> Message-ID: On Fri, 28 Apr 2006 14:27:00 -0700, nikie wrote: > Steven Bethard wrote: > >> >>> L = ['C', 'A', 'D', 'B'] >> >>> positions = dict((item, i) for i, item in enumerate(L)) Do you need the generator expression here? dict(enumerate(L)) should be equivalent, no? > Isn't this bound to be less efficient? I mean, inserting the items into > a dict is probably O(n log n), which is definitely worse than O(n) for > searching the list twice. And, of course, it would yield different > results if 'A' or 'D' are in the list more than once. Although presumably the dict method might be quicker if you were comparing the positions a large number of times. Incidentally, does python have a built-in to do a binary search on a sorted list? Obviously it's not too tricky to write one, but it would be nice if there was one implemented in C. From sturlamolden at yahoo.no Tue Apr 25 08:34:56 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 25 Apr 2006 05:34:56 -0700 Subject: MinGW and Python In-Reply-To: References: <1145861223.509630.247350@y43g2000cwc.googlegroups.com> <444C79D7.4060007@v.loewis.de> Message-ID: <1145968496.649214.100040@i40g2000cwc.googlegroups.com> Robert Kern wrote: > Dunno. Depends on the machine. Depends on the program. Depends on how the > interpreter and any extension modules and underlying libraries were built. > Depends on which Linux and which Windows. > > I'm sorry, but your question is a non sequitur. I don't understand its relevance > to this thread. The relevance: Python is built with GCC on Linux. Do you or do you not see a performance hit on Linux? MinGW is GCC. Will you get a performance hit when building Python with MinGW? From john at castleamber.com Fri Apr 28 22:37:13 2006 From: john at castleamber.com (John Bokma) Date: 29 Apr 2006 02:37:13 GMT Subject: (was Re: Xah's Edu Corner: Criticism vs Constructive Criticism) References: <1145992903.834316.198370@u72g2000cwu.googlegroups.com> <4GM3g.3084$TT.1768@twister.nyroc.rr.com> <1146231280.733609.143230@e56g2000cwe.googlegroups.com> <1146276319.504694.218970@v46g2000cwv.googlegroups.com> Message-ID: "Tagore Smith" wrote: > Your emails to his ISP > are far more wasteful- you are using up very scarce resources > dedicated to dealing with real abuse. According to his hosting provider dreamhost: I have warned this user that excessive offtopic cross-posting is not allowed, and explained that if he doesn't quit he risks losing his account. If you (or anyone else) notice this in the future, please do not hesitate to submit another report. Reread it a few times, it might educate you (note the *cross-posting* and the *submit another report*) > The only thing really wrong with Xah's post is that it was crossposted > to several groups. But your objection seems to be less about the > crossposting, and more about the content. Your mistaken. I have reported it as excessive crossposting. (Rest of your misinterpretation snipped). -- John MexIT: http://johnbokma.com/mexit/ personal page: http://johnbokma.com/ Experienced programmer available: http://castleamber.com/ Happy Customers: http://castleamber.com/testimonials.html From evelyne0510 at gmail.com Thu Apr 20 14:31:23 2006 From: evelyne0510 at gmail.com (evelyne0510 at gmail.com) Date: 20 Apr 2006 11:31:23 -0700 Subject: How can I call a python method from the XML-RPC client in Java? Message-ID: <1145557883.584164.97830@t31g2000cwb.googlegroups.com> Hi all, I have created a XML-RPC model (with server and client) written in Java. I want to call the methods in another XML-RPC model written in Python. I know that in Java, I can use like "xmlrpc_client.excute("handler_name.method", param)" to call the methods in my xml-rpc server written in java. But how can I call the methods in Python? I cannot creat a handler in my Python XML-RPC server..... Is there anyone able to help me? I would be very appreciate! Thanks! Evelyne From sybrenUSE at YOURthirdtower.com.imagination Thu Apr 20 08:34:54 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Thu, 20 Apr 2006 14:34:54 +0200 Subject: PYTHONPATH References: <1145535721.138411.145790@z34g2000cwc.googlegroups.com> Message-ID: sushant.sirsikar at gmail.com enlightened us with: > I am using Linux env.I set the PYTHONPATH using > > import sys > sys.path.append(----) > > But we i close python and start again i is not showing my new entry in > PYTHONPATH. > Can anyone help me to make my path persistant? Add the following to /etc/profile: export PYTHONPATH="..." Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From luismgz at gmail.com Fri Apr 14 17:45:45 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 14 Apr 2006 14:45:45 -0700 Subject: Should I learn Python instead? In-Reply-To: <1145048531.915798.97060@v46g2000cwv.googlegroups.com> References: <1145048531.915798.97060@v46g2000cwv.googlegroups.com> Message-ID: <1145051145.175465.92410@g10g2000cwb.googlegroups.com> First of all, let me tell you that you can now write apps for .NET with Python. There's a python implementation for the .NET framework called Ironpython (in beta 5 now). Regarding XML, I can't tell you much but in general, python is much easier, cleaner, concise and intuitive than all the other alternatives you mention. Being a dynamic language, you can achieve more with less lines of code. Easy tasks are easier with python, and complex tasks can look simple with too. I also think that Python is an excellent first language to learn. Learn it, get used to think as a programmer, learn the basics (functions classes, oop.) and then, when you're reasonably comfortable, you'll be ready to pick any other language (or you'll be happy enough to know that you don't need to learn any other one). From Bulkan at gmail.com Sun Apr 23 21:59:19 2006 From: Bulkan at gmail.com (placid) Date: 23 Apr 2006 18:59:19 -0700 Subject: MySQLdb Message-ID: <1145843959.890656.218710@i40g2000cwc.googlegroups.com> Hi all, Does anyone have binary for MySQLdb (python 2.4.3, MySQL 5.0a) ? Regards From robert.kern at gmail.com Tue Apr 11 02:09:48 2006 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 11 Apr 2006 01:09:48 -0500 Subject: using vim as a python class/module/function etc.. browser In-Reply-To: <443B3427.1090902@optonline.net> References: <443B1B24.3070401@optonline.net> <443B3427.1090902@optonline.net> Message-ID: Chris Jones wrote: > Robert Kern wrote: >>Of course, modern versions of Exuberant Ctags also support Python, too. > > I apt-installed this package but the man page is rather intimidating so > I thought I might as well make sure I was going in the right direction. You will probably want to read the vim documentation on how to use ctags from vim. That will tell you all you need to know without extraneous cruft. > Just need to verify that the stable version (sarge) is modern enough.. It ought to be. It has supported Python for years and years. -- Robert Kern robert.kern at gmail.com "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From siona at chiark.greenend.org.uk Thu Apr 13 09:47:19 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 13 Apr 2006 14:47:19 +0100 (BST) Subject: quiet conversion functions References: Message-ID: <3Y*zw5dr@news.chiark.greenend.org.uk> Tim Chase wrote: >def CFloat(value): > try: > value = float(value) > except (ValueError, TypeError): > value = 0 > return value >>> type(CFloat(None)) I think you want value = 0.0 . And you might also want to consider what errors you may be masking in silently turning *anything* into a valid number. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From rvernica at gmail.com Mon Apr 17 01:12:29 2006 From: rvernica at gmail.com (Rares Vernica) Date: Sun, 16 Apr 2006 22:12:29 -0700 Subject: locale, format monetary values Message-ID: Hi, Can I use locale to format monetary values? If yes, how? If no, is there something I can use? E.g., I have 10000 and I want to get "$10,000". Thanks, Ray From steven.bethard at gmail.com Thu Apr 27 13:30:35 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 27 Apr 2006 11:30:35 -0600 Subject: OOP techniques in Python In-Reply-To: <1146158190.320947.108480@t31g2000cwb.googlegroups.com> References: <1146158190.320947.108480@t31g2000cwb.googlegroups.com> Message-ID: Panos Laganakos wrote: > we usually define private properties and provide public functions > to access them, in the form of: > get { ... } set { ... } > > Should we do the same in Python: > > self.__privateAttr = 'some val' > > def getPrivateAttr(self): > return self.__privateAttr > > Or there's no point in doing so? There is no point in doing so. You should use plain attributes whenever possible (that is, whenever you're really just doing a get or a set, with no computation). The only reason to use getters and setters is so that you can change the implementation later if you need to. But python allows you to do this with properties: >>> class C(object): ... def __init__(self, x): ... self.x = x ... >>> C(42).x 42 >>> class C(object): ... def _get_x(self): ... return self._x * 2 ... def _set_x(self, value): ... self._x = value / 2 ... x = property(_get_x, _set_x) ... def __init__(self, x): ... self.x = x ... >>> C(42).x 42 Which should not be interpreted as saying you should start writing a bunch of properties now. ;) Instead, only introduce a property when you find that something must remain an attribute (presumably for backwards compatibility reasons) but for whatever reason it now needs some additional computation. STeVe From peter at engcorp.com Sun Apr 9 17:21:54 2006 From: peter at engcorp.com (Peter Hansen) Date: Sun, 09 Apr 2006 17:21:54 -0400 Subject: Creating an event loop In-Reply-To: References: Message-ID: Fabian Steiner wrote: > I am currently wondering how to write something like an "event loop". > For example, if I want to write a function that checks whether a file > was added or removed in a directory I would think of a "while 1: ..." > construct that checks the mtime of the directory. Is this the right way > to achieve the exepected result or are there any better ways? That's fine for a start, provided you always insert a small time.sleep() call so that you don't use up all the CPU time wastefully checking for something that happens very rarely. In the end, it's a tradeoff between CPU usage and "latency", because if you use (for example) time.sleep(5), you won't waste much time but you will also take up to 5 seconds to notice that the directory has changed. Usually values like 0.1 (100ms) work well for things that need a quick response, while 2s works nicely for things that don't. Even Python is pretty unnoticeable if it wakes up only every two seconds for a brief bit of processing. -Peter From akameswaran at gmail.com Tue Apr 4 16:22:01 2006 From: akameswaran at gmail.com (akameswaran at gmail.com) Date: 4 Apr 2006 13:22:01 -0700 Subject: xml element tree to html problem In-Reply-To: References: Message-ID: <1144182121.786181.197070@j33g2000cwa.googlegroups.com> are you using PyXML? If this is a simple one to one relationship with dependence on order, I'd forgo the whole PyXML, read the file line by line, and replace tags as appropriate. You may have to do some simple checkin, in case there is n object Otherwise, have fun with the parsers - nothing is painless is SAX or DOM. as far as simple translation? once you have tokenized or used PyXML to get the elements, something like? for tag in listofTags: if tagDictionary.has_key(tag): doSomething(tagDictionary[tag]) IMHO - PyXML is a great tool, but for something like simple substitution, it's so so much overkill. For simple processing tasks like this I almost always just treat it as a text file. I resort to PyXML when things like heirarchy are important. Hope this helps From brianlum at gmail.com Sat Apr 29 06:51:11 2006 From: brianlum at gmail.com (brianlum at gmail.com) Date: 29 Apr 2006 03:51:11 -0700 Subject: Python "member of" function In-Reply-To: <0mg6529tvdm6g6nq04cos5uvph0rslrp1t@4ax.com> References: <1146306920.942286.35550@y43g2000cwc.googlegroups.com> <0mg6529tvdm6g6nq04cos5uvph0rslrp1t@4ax.com> Message-ID: <1146307871.757127.12810@e56g2000cwe.googlegroups.com> Thanks, I was using "in" incorrectly. Thanks a lot! From paddy3118 at netscape.net Thu Apr 20 16:10:23 2006 From: paddy3118 at netscape.net (Paddy) Date: 20 Apr 2006 13:10:23 -0700 Subject: How should multiple (related) projects be arranged (structured) and configured so that they can share code, have a related package structure and enable proper unittesting, and ensuring no namespace collisions In-Reply-To: <1145546785.268550.154240@e56g2000cwe.googlegroups.com> References: <1145546785.268550.154240@e56g2000cwe.googlegroups.com> Message-ID: <1145563823.160038.257950@j33g2000cwa.googlegroups.com> Your second point 'clear separation of "production" code and "test" code' is best handled by using a revision control system. I know Clearcase, because I use it at work, but I have heard good things about Subversion. From sijben at eemvalley.com Wed Apr 26 05:20:40 2006 From: sijben at eemvalley.com (Paul Sijben) Date: Wed, 26 Apr 2006 11:20:40 +0200 Subject: Python UPnP on Linux? Message-ID: <444f3b66$0$31642$e4fe514c@news.xs4all.nl> I am writing some client software that needs to accept connections from the Internet. So I am looking for a UPnP implementation for a client of an Internet gateway so I can request the NAT binding. Googling on this I have found win32 implementations and Twisted implementations yet I am looking for a way to do it on Linux WITHOUT Twisted. Who knows a pointer? Paul From john at castleamber.com Thu Apr 27 17:45:24 2006 From: john at castleamber.com (John Bokma) Date: 27 Apr 2006 21:45:24 GMT Subject: Xah's Edu Corner: What Languages to Hate References: <1145992903.834316.198370@u72g2000cwu.googlegroups.com> <1146172923.830732.187130@i40g2000cwc.googlegroups.com> <20060427223335.6c8537e6.alex.buell@munted.org.uk> Message-ID: Alex Buell wrote: > Send your complaints to: > abuse at sbcglobal dott net > abuse at dreamhost dott com Yup, done. If he's still with dreamhost he probably is in trouble now. If not, next. -- John MexIT: http://johnbokma.com/mexit/ personal page: http://johnbokma.com/ Experienced programmer available: http://castleamber.com/ Happy Customers: http://castleamber.com/testimonials.html From spamspam at spam.eggs Sat Apr 29 18:43:50 2006 From: spamspam at spam.eggs (Ben C) Date: 29 Apr 2006 22:43:50 GMT Subject: self modifying code References: <445399A1.9020506@jessikat.plus.net> Message-ID: On 2006-04-29, Robin Becker wrote: > When young I was warned repeatedly by more knowledgeable folk that self > modifying code was dangerous. > > Is the following idiom dangerous or unpythonic? > > def func(a): > global func, data > data = somethingcomplexandcostly() > def func(a): > return simple(data,a) > return func(a) It looks quite clever (a bit too clever ... :) > It could be replaced by > > data = somethingcomplexandcostly() > def func(a): > return simple(data,a) > > but this always calculates data. Why not just: data = None def func(a): global data if not data: data = somethingcomplexandcostly() return simple(data, a) Or nicer to use a "singleton" perhaps than a global, perhaps something like this: class Func(object): exists = False def __init__(self): assert not Func.exists Func.exists = True self.data = None def simple(self, a): assert self.data is not None # ... do something with self.data presumably return something def __call__(self, a): if self.data is None: self.data = somethingcomplexandcostly() return self.simple(a) func = Func() func(a) From onurb at xiludom.gro Thu Apr 13 12:02:14 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 13 Apr 2006 18:02:14 +0200 Subject: new-style classes and len method In-Reply-To: <1144938003.643170.111930@g10g2000cwb.googlegroups.com> References: <1144936961.203493.169840@v46g2000cwv.googlegroups.com> <1144938003.643170.111930@g10g2000cwb.googlegroups.com> Message-ID: <443e7652$0$5180$626a54ce@news.free.fr> Thomas Girod wrote: > Or maybe I'm mixing up what we call a "classmethod" with what we could > call an "instance method" ? > That's what I was about to point out !-) > class Data(list): > __slots__ = ["width", "height", "label"] > > def __init__(self,width,height,label=None): > list.__init__(self) > self.width = width > self.height = height > self.label = label > > def clear(cls): > while len(cls) > 0: del cls[0] > return > clear = classmethod(clear) What about this ? def clear(self): del self[:] As it's name (and signature) implies, a classmethod works on a class, not on an instance of the class. Here, you are trying to compute the length of *class* Data. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From tim.peters at gmail.com Sun Apr 23 14:03:20 2006 From: tim.peters at gmail.com (Tim Peters) Date: Sun, 23 Apr 2006 14:03:20 -0400 Subject: bug in modulus? In-Reply-To: <1145807918.069455.241510@i40g2000cwc.googlegroups.com> References: <1145807918.069455.241510@i40g2000cwc.googlegroups.com> Message-ID: <1f7befae0604231103u44cd2b81g3de86f7862d594bc@mail.gmail.com> [jantod at gmail.com] > I think there might be something wrong with the implementation of > modulus. > > Negative float values close to 0.0 break the identity "0 <= abs(a % b) < abs(b)". While that's a mathematical identity, floating point has finite precision. Many mathematical identities can fail when using floats. For example, (x+y)+z = x+(y+z) doesn't always hold when using floats either. > print 0.0 % 2.0 # => 0.0 > print -1e-010 % 2.0 # =>1.9999999999 > > which is correct, but: > > print -1e-050 % 2.0 # => 2.0 > print -1e-050 % 2.0 < 2.0 # => False See footnote 5.2 in the Language (not Library) reference manual, section 5.6 "Binary arithmetic operations": While abs(x%y) < abs(y) is true mathematically, for floats it may not be true numerically due to roundoff. For example, and assuming a platform on which a Python float is an IEEE 754 double-precision number, in order that -1e-100 % 1e100 have the same sign as 1e100, the computed result is -1e-100 + 1e100, which is numerically exactly equal to 1e100. Function fmod() in the math module returns a result whose sign matches the sign of the first argument instead, and so returns -1e-100 in this case. Which approach is more appropriate depends on the application. > This means I can't use modulus to "wrap around" before it reaches a > certain value. It's simply not possible to deliver a float result in all cases that satisfies all desirable identities. % and math.fmod make different tradeoffs, but neither is suitable for all applications, and it's possble that the neither is suitable for a particular application -- pick your poison, or brew your own. > I'm using Python 2.4.2 on WindowsXP. Because it's inherent to using finite-precision approximations to real numbers, this is a cross-platorm and cross-language phenomenon. If you can't tolerate approximations, rework your logic to use integers instead. From __peter__ at web.de Mon Apr 10 17:11:07 2006 From: __peter__ at web.de (Peter Otten) Date: Mon, 10 Apr 2006 23:11:07 +0200 Subject: challenging (?) metaclass problem References: <1144656384.077748.229010@u72g2000cwu.googlegroups.com> Message-ID: alainpoint at yahoo.fr wrote: > I have what in my eyes seems a challenging problem. > Thanks to Peter Otten, i got the following code to work. It is a sort > of named tuple. Don't trust code posted in a newsgroup -- it may sometimes be quality-challenged :-) > Now my problem is the following. I want to write a function called > createDerivedTuple in order to create a class derived from the one > created with the function createTuple, taking the parent class as first > argument: > def createDerivedTuple(parentclass,*names): > ....... code yet to be figured out .... > > The usage should be as follows: > > DerivedPoint=makeDerivedTuple(Point,'z') > p=DerivedPoint(4,7,9) > assert p.x==p[0] > assert p.y==p[1] > assert p.z==p[2] > assert DerivedPoint.x==0 > assert DerivedPoint.y==1 > assert DerivedPoint.z==2 > > I am still a newbie on metaclasses but i am convinced there are elegant > solutions to this challenging problem. Hey, if you don't try to solve it yourself we'll end up with me learning more than you... I didn't find a way to extend the approach with a per-class metaclass to support inheritance. I think you would have to subclass both class and metaclass. So I had to start all over again: class IndexProperty(object): def __init__(self, index): self.index = index def __get__(self, inst, cls): index = self.index if inst is None: return index return inst[index] class TupleType(type): def __new__(mcl, name, bases, classdict): names = classdict.get("_names") if names is not None: for base in bases: base_names = getattr(base, "_names", None) if base_names is not None: offset = len(base_names) break else: offset = 0 for i, n in enumerate(names): classdict[n] = IndexProperty(offset + i) if offset: names[:0] = base_names return type.__new__(mcl, name, bases, classdict) class Tuple(tuple): __metaclass__ = TupleType def __new__(cls, values): self = tuple.__new__(cls, values) if len(self) != len(cls._names): raise TypeError return self import unittest class P2(Tuple): _names = ["x", "y"] class P3(P2): _names = ["z"] def yield_them(seq): """Helper to ensure the implementation cannot rely on len().""" for item in seq: yield item class Test(unittest.TestCase): def test_P2(self): self.assertEquals(P2.x, 0) self.assertEquals(P2.y, 1) self.assertRaises(AttributeError, lambda: P2.z) def test_P3(self): self.assertEquals(P3.x, 0) self.assertEquals(P3.y, 1) self.assertEquals(P3.z, 2) def test_P2_inst(self): self.assertRaises(TypeError, P2, yield_them("A")) self.assertRaises(TypeError, P2, yield_them("ABC")) p = P2(yield_them("AB")) self.assertEquals(p.x, "A") self.assertEquals(p.y, "B") self.assertRaises(AttributeError, lambda: p.z) def test_P3_inst(self): self.assertRaises(TypeError, P3, yield_them("A")) self.assertRaises(TypeError, P3, yield_them("ABCD")) p = P3(yield_them("ABC")) self.assertEquals(p.x, "A") self.assertEquals(p.y, "B") self.assertEquals(p.z, "C") self.assertRaises(AttributeError, lambda: p.t) if __name__ == "__main__": unittest.main() I did not perform any tests other than the unittest given above. Peter From dylan.moreland at gmail.com Mon Apr 3 01:07:36 2006 From: dylan.moreland at gmail.com (Dylan Moreland) Date: 2 Apr 2006 22:07:36 -0700 Subject: Getting a list of all classes derived from a base class References: <1144039905.692207.8790@g10g2000cwb.googlegroups.com> Message-ID: <1144040855.982673.72640@g10g2000cwb.googlegroups.com> Vijairaj R wrote: > Hi, > I have a requirement to findout all the classes that are derived from a > single base class. > > This is how I do it currently. > > class Test: > case = [] > > class Test1(Test): > Test.case.append("Test1") > > class Test2(Test): > Test.case.append("Test2") > > 1. Is there a better way of doing this. > 2. Is there a way to generalize the Test.case.append("TestN") > statements to something like > Test.case.append(__myclass__) > > -- > Warm Regards, > Vijairaj If you're willing to use metaclass madness: class TestMeta(type): def __init__(cls, name, bases, dct): if bases == (object,): return # Prevent the appending of Test cls.case.append(cls) class Test(object): __metaclass__ = TestMeta case = [] class Test1(Test): pass class Test2(Test): pass print Test.case From johnjsal at NOSPAMgmail.com Tue Apr 4 13:42:18 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 04 Apr 2006 17:42:18 GMT Subject: ANNOUNCE: wxPython 2.6.3.2 In-Reply-To: References: Message-ID: <_dyYf.1899$No6.42228@news.tufts.edu> Robin Dunn wrote: > > Announcing > ---------- > > The 2.6.3.2 release of wxPython is now available for download at > http://wxpython.org/download.php. This is a mostly bug fix release > and takes care of several "unfortunate features" discovered in the > 2.6.3.0 release made last week. A summary of changes is listed below > and at http://wxpython.org/recentchanges.php. Does it just install over the previous version? From sturlamolden at yahoo.no Tue Apr 25 11:20:24 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 25 Apr 2006 08:20:24 -0700 Subject: How do I open a mysql database with python In-Reply-To: References: Message-ID: <1145978424.700137.49550@y43g2000cwc.googlegroups.com> http://sourceforge.net/projects/mysql-python From aleaxit at yahoo.com Tue Apr 25 10:32:42 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 25 Apr 2006 07:32:42 -0700 Subject: MinGW and Python References: <1145861223.509630.247350@y43g2000cwc.googlegroups.com> <444C79D7.4060007@v.loewis.de> <1145968025.903148.140700@i39g2000cwa.googlegroups.com> Message-ID: <1heca3f.14i9v2akwb61sN%aleaxit@yahoo.com> sturlamolden wrote: > Robert Kern wrote: > > > - gcc does not optimize particularly well. > > That is beyond BS. The more recent gcc releases optimize as well as any > commercial compiler. GCC 4 may even optimize better than MSVC. > > GCC is the compiler used to build the Linux kernel and MacOSX. If it > can deal with this I say it can handle Python as well. My guess is you > will not notice any performance difference for the Python interpreter. That is quite possible, of course: if, for example, the 14% speed difference I measured with pybench is representative, then you might not notice it because human beings have a hard time noticing time differences of that magnitude. But it might still be there, easy to measure, even though not to notice. At the same time, if the 14% slowdown is representative, then it's not true that the compiler responsible for it "optimizes as well" as the other; indeed, "does not optimize particularly well", under such a hypothesis, would be far from a "beyond BS" assertion. Alex From sjmachin at lexicon.net Sat Apr 8 23:37:25 2006 From: sjmachin at lexicon.net (John Machin) Date: 8 Apr 2006 20:37:25 -0700 Subject: More pythonic circle? In-Reply-To: <1144544696.577777.239130@e56g2000cwe.googlegroups.com> References: <1144544696.577777.239130@e56g2000cwe.googlegroups.com> Message-ID: <1144553845.240153.285040@e56g2000cwe.googlegroups.com> OTTOMH, in a rush to go out: never mind Pythonic, following apply to any language: (1) accuracy: (a) sue me if I'm wrong, but I think you need range(dx+1) so that the dx pixel is filled in (b) a few more digits after 0.71 might be useful (2) efficiency: seems that range(dy, dx+1) would save some wear & tear on the circuitry :-) (3) legibility: there's no prize for the script with the absolutely minimum number of space characters :-) I think I've got an article on better Bresenham somewhere in the archives; will dig it out later. Cheers, John From obeeker at gmail.com Sat Apr 1 07:12:36 2006 From: obeeker at gmail.com (obeeker at gmail.com) Date: 1 Apr 2006 04:12:36 -0800 Subject: why doesn't is work?a script to backup a directory In-Reply-To: References: <1143859031.679813.94400@i40g2000cwc.googlegroups.com> Message-ID: <1143893556.309560.53090@u72g2000cwu.googlegroups.com> thank you for your suggestion and apologize for my mistake. if i run it and answer the raw_input with "Enter" i get sth is wrong press Return> i comment the try-except and run it and answer the raw_input with "Enter" and get message following: Traceback (most recent call last): File "G:\9\Eb\updateEbBb.py", line 41, in -toplevel- updateNow(base) File "G:\9\Eb\updateEbBb.py", line 28, in updateNow update(d0) File "G:\9\Eb\updateEbBb.py", line 16, in update shutil.rmtree(i) File "D:\Program Files\Python24\lib\shutil.py", line 155, in rmtree onerror(os.listdir, path, sys.exc_info()) File "D:\Program Files\Python24\lib\shutil.py", line 153, in rmtree names = os.listdir(path) WindowsError: [Errno 3] : 'O:/eb/mb/SCIL/*.*' From val at vtek.com Thu Apr 27 13:36:25 2006 From: val at vtek.com (val at vtek.com) Date: 27 Apr 2006 10:36:25 -0700 Subject: list of functions question References: <4bai48Fu890hU1@individual.net><445082ED.4000600@lexicon.net> Message-ID: <1146159385.161280.154710@e56g2000cwe.googlegroups.com> John Machin wrote: > On 27/04/2006 10:38 AM, val bykoski wrote: > > Hi The List: > > I have a modeling app where i'm detecting events (in temporal > > dynamics) applying a set of (boolean) functions - kind of: > > > > event_list = "f1 f2 etc".split() # each fi detects a specific event > > i have defs for functions fi, or simple boolean expressions for each, so > > that evList is a list of defs or boolean expressions > > for ev in evList: > > if ev: # this supposedly is a call ev(t) > > # doing smth with the event > > > > I didn't succeed, though, (blindly) trying various options. > > I thought/tried "apply()" but couldn't get it work. > > I'd appreciate pointers to how to handle this kind of > > functions or events lists (or objects?) and how to call those > > functions in a loop. > > thanks,val > > This may be something like what you are trying to achieve: > > # untested > def fx(arg): > pass > def fy(arg): > pass > def fdefault(arg): > pass > > funcmap = { > 'x1': fx, > 'x2': fx, > 'y' : fy, > } > > eventlist = "y x2 x2 x1 y".split() > for ev in eventlist: > efunc = funcmap.get(ev, fdefault) > if efunc(t): # what is t???? > # do something John, Thanks alot. It does work with the fx, fy,etc as (boolean) expressions. And it is faster vs. using defs. Thanks again, the great list... Val From rpdooling at gmail.com Tue Apr 18 20:04:24 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 18 Apr 2006 17:04:24 -0700 Subject: indirect import of standard module In-Reply-To: <1145402312.069923.315960@g10g2000cwb.googlegroups.com> References: <1145386200.076643.253740@u72g2000cwu.googlegroups.com> <1145393476.931506.9650@e56g2000cwe.googlegroups.com> <1145401271.166891.86660@t31g2000cwb.googlegroups.com> <1145402312.069923.315960@g10g2000cwb.googlegroups.com> Message-ID: <1145405064.539889.194760@g10g2000cwb.googlegroups.com> Thank you for the elucidation. I'm just getting into Classes, but I wanted to get modules down first. Much appreciated. rick From ldo at geek-central.gen.new_zealand Tue Apr 11 05:37:24 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 11 Apr 2006 21:37:24 +1200 Subject: how relevant is C today? References: <44381ee4$0$4209$c3e8da3@news.astraweb.com> <871ww7elvu.fsf@ieee.org> <1144541959.611623.25540@i39g2000cwa.googlegroups.com> <44393167$1@nntp0.pdx.net> <443965f2$0$67257$157c6196@dreader2.cybercity.dk> Message-ID: In article , Thomas Bellman wrote: >Lawrence D'Oliveiro writes: > >> "const" is in C89/C90. > >Although with slightly different semantics from in C++... For >instance: > > static const int n = 5; > double a[n]; > >is valid C++, but not valid C. enum { n = 5, }; double a[n]; works in C. From khemkaamit at gmail.com Thu Apr 6 07:38:07 2006 From: khemkaamit at gmail.com (Amit Khemka) Date: Thu, 6 Apr 2006 17:08:07 +0530 Subject: Splitting a string with extra parameters In-Reply-To: <200604061806.44443.fulvio@pc.jaring.my> References: <200604061806.44443.fulvio@pc.jaring.my> Message-ID: <1360b7230604060438x5207e257x24fb2d07b9b669c7@mail.gmail.com> I guess you should use "re" module ... In this case re.split("\D,\D", YOUR_STRING) should work. (splits only when "," is between two non-digits). for details and more options see python-docs. cheers, amit. On 4/6/06, Fulvio wrote: > Alle 11:23, gioved? 06 aprile 2006, Chris P ha scritto: > > when splitting based on a delimiter of "," the above string gets broken up > > in 5 "columns" instead of 4 due to the "," in the money amount. > > There should be cvs package in the python directory. Why don't you try that > way? > Reading some help gives more details of its use. > > F > -- > http://mail.python.org/mailman/listinfo/python-list > -- ---- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. From reply.in.the.newsgroup at my.address.is.invalid Wed Apr 19 11:47:09 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Wed, 19 Apr 2006 17:47:09 +0200 Subject: Missing interfaces in Python... References: <1145306373.781129.305840@z34g2000cwc.googlegroups.com> <1145430546.625634.194710@g10g2000cwb.googlegroups.com> <7lrb429tg5c6dt1bt99d1131cafuulvqap@4ax.com> <4445f7f8$0$9451$626a54ce@news.free.fr> <1145438118.179643.140390@e56g2000cwe.googlegroups.com> <1he15id.pxmsobvfopabN%aleaxit@yahoo.com> Message-ID: <9qmc42hjms8h1olfa3ssk9r1nmm0g46jn7@4ax.com> Alex Martelli: >PEAK is an interesting counterexample, particularly since Philip Eby >tends to be "ahead of the curve": I never noticed PEAK before. Is it well worth studying? From tim.golden at viacom-outdoor.co.uk Mon Apr 10 09:25:41 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Mon, 10 Apr 2006 14:25:41 +0100 Subject: can't pass command-line arguments Message-ID: [BartlebyScrivener] | I had not seen the thread you linked to. I learned something, but it | still doesn't explain whatever is happening on my machine. When I run | assoc and ftype I get exactly the results you say I need to run the | scripts properly. However, this simple script (printargs.py) seems to | work whether I type the .py extention or not. | Whereas this more complex script (cbfindfiles.py) will NOT work unless | I type the .py extension. Otherwise the arguments don't seem to pass. Well, just to confirm, it works fine for me with: python.file="C:\Python24\python.exe" "%1" %* but if it always succeeds with the .py extension, it's not the file association which is getting in the way. I think someone else has suggested checking for non-python files of the same name. (Did you have a batch file which wrapped the python script? Some people do that to get more control over parameters). I've just checked the thread, and you don't seem to say what *does* happen when you run the script, so I'm not sure how certain you are that the params *aren't* getting through. Have you stuck a "print sys.argv" at the top of the "if __name__ == '__main__'" section? etc. etc. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From lennart at kommunicera.umea.se Mon Apr 3 16:02:01 2006 From: lennart at kommunicera.umea.se (lennart at kommunicera.umea.se) Date: 3 Apr 2006 13:02:01 -0700 Subject: overloading constructor in python? In-Reply-To: <44317B92.9010301@websafe.com> References: <1144092500.618489.204740@e56g2000cwe.googlegroups.com> <44317B92.9010301@websafe.com> Message-ID: <1144094521.281161.283480@v46g2000cwv.googlegroups.com> Larry Bates wrote: [...] > In python it is called duck typing but you don't need separate > constructors: > > def __init__(self, c): > if isinstance(c, int): ...do stuff... > elif isinstance(c, list): ...do stuff... > elif isinstance(c, tuple): ...do stuff... > else: > . > . > . > > Remember Python doesn't care what c is and doesn't do > type checking so you can do anything you want. > Thanx for the info. /Lennart > -Larry Bates From gregm-xyzpdq3 at toadmail.com Wed Apr 26 16:30:19 2006 From: gregm-xyzpdq3 at toadmail.com (Greg Menke) Date: 26 Apr 2006 16:30:19 -0400 Subject: (was Re: Xah's Edu Corner: Criticism vs Constructive Criticism) References: <1145992903.834316.198370@u72g2000cwu.googlegroups.com> <4GM3g.3084$TT.1768@twister.nyroc.rr.com> <1146079773.910552.217390@y43g2000cwc.googlegroups.com> <444fd488$0$33924$ed2619ec@ptn-nntp-reader03.plus.net> Message-ID: Mark Thomas writes: > Xah Lee wrote: > > Dear John Bokma, > > This is a public notice that what you are trying to do is getting close > > to harrassment from the law's perspective. > > Thanks. > > Xah > > xah at xahlee.org > > ? http://xahlee.org/ > > John Bokma wrote: > >> Eli Gottlieb wrote: > >> > >>> Oh, God, not another one. > >> Instead of cross posting more garbage, do as follows: > >> > >> Email a complaint to the email addresses you can look up yourself and > >> include the entire message of Xah: > >> > >> http://www.spamcop.net/sc?track=72.231.179.135 posting host > >> http://www.spamcop.net/sc?track=xahlee.org spamvertized site > >> > >> > >> If enough people complain with both, it might stop one day. > > > Ooooh! (Waggles fingers beneath chin) > > Mark So now Xah is an expert on law in addition to emacs. What a guy. Gregm From duncan.booth at invalid.invalid Sun Apr 2 15:20:35 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 2 Apr 2006 19:20:35 GMT Subject: Assignment in a while? References: <123071lnngm15da@corp.supernews.com> Message-ID: none wrote: > If I try to run the above code, I get a SyntaxError indicating that I > can't do an assignment in the while loop. I found a way around this > (see the commented out while loop), but it seems hackish. Assignment > within a while loop seems like a pretty standard thing, so I'm just > curious what I'm missing. > Not much, you cannot assign to a variable in the controlling expression of a while loop. However, for loops do assign values to variables, so if the form with the break offends you, try restructuring your code as a for loop. For example: for results in iter(sth.fetchone, None): print results or in many cases you can just fetch everything in one go: for results in sth.fetchall(): print results From duncan.booth at invalid.invalid Mon Apr 10 04:57:42 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 10 Apr 2006 08:57:42 GMT Subject: can't pass command-line arguments References: <1144636890.976327.253000@i39g2000cwa.googlegroups.com> <1144637633.814788.150270@i40g2000cwc.googlegroups.com> Message-ID: Lawrence D'Oliveiro wrote: > In article <1144637633.814788.150270 at i40g2000cwc.googlegroups.com>, > "BartlebyScrivener" wrote: > >>I was used to being able to run scripts by just typing the script name, >>even without the .py extension, but >> >>findmyfiles d:/notes notes*.* does not work > > The MS-DOS foundation on which Windows is built only supports a small > number of extensions for "executable" files (.COM, .EXE and .BAT), with > no provision for any extensions to these. That is wrong on so many levels: Windows variants such as NT/2000/XP are not based on MS-DOS in any way. The default set of "executable" file extensions recognised by Windows is: .COM .EXE .BAT .CMD .VBS .VBE .JS .JSE .WSF .WSH You can change the recognised extensions simply by setting the PATHEXT environment variable. From onurb at xiludom.gro Wed Apr 26 07:05:10 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 26 Apr 2006 13:05:10 +0200 Subject: OOP / language design question In-Reply-To: References: <1145961248.794496.80220@j33g2000cwa.googlegroups.com> <1145963311.348482.15080@i40g2000cwc.googlegroups.com> <444e0dec$0$27071$626a54ce@news.free.fr> <444e38e9$0$29686$636a55ce@news.free.fr> <1hedc5l.toeunc1twg6bsN%aleaxit@yahoo.com> <444f3f6f$0$27980$626a54ce@news.free.fr> Message-ID: <444f543b$0$22137$626a54ce@news.free.fr> Duncan Booth wrote: > bruno at modulix wrote: > > >>It's *already* split : __new__ construct the object, __init__ >>initialize it. >> >>>That's why I would go for the 2-phase construction: >> >>But that's already what you have. > > Very good point. > > >>>after the first phase >>>you have an object which is fully initialised, just not yet >>>used/connected/running. For example httplib.HTTPConnection does this: >>>you construct the object with a host and port, but the actual >>>connection is triggered by a separate object. >> >>If you look at file objects, they do try and open the file at init >>time. Is a net or db connection that different ? > > > Well, yes, since the whole point is that we are discussing overriding > methods and I bet you haven't subclassed Python file objects recently. And you win !-) Anyway, I didn't suggest that opening a connection to whatever should be done in the __init__ - I just wanted to point that acquiring a resource in the initializer (and freeing it in the finalizer) can sometimes be perfectly sensible. wrt/ initializer as a template method, I still fail to see why this should be a problem. The fact that one should avoid doing anything else than initialization in the initializer is just plain old common sense IMHO - the use of calls to other methods that can possibly be overriden in a subclass is orthogonal. And if the guy writing the subclass do stupid things when overridding these methods, well, too bad for him - but as the author of the base class, that's definitively not my problem (given proper documentation of course) Trying to protect stupid programmers from doing stupid things is a total waste of time anyway. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From hnt20 at msn.com Sat Apr 15 17:47:02 2006 From: hnt20 at msn.com (HNT20) Date: Sat, 15 Apr 2006 21:47:02 GMT Subject: How to Convert a string into binary In-Reply-To: References: Message-ID: Felipe Almeida Lessa wrote: > Em S?b, 2006-04-15 ?s 19:25 +0000, HNT20 escreveu: >> is there a way to convert a string into its binary representation of the >> ascii table.?? > > I'm very curious... why? > > And no, I don't have the answer. > well, once i get the binary representations, i can group the data and modulate it to a higher frequency and transmit it for example, if i am using BPSK modulation, i will then convert each zero into -1 and multiply it with the sin function with the sampling frequency with a hamming window. and so forth. yet, the first step is to have a successful representation of the data. HNT From aahz at pythoncraft.com Tue Apr 18 13:31:45 2006 From: aahz at pythoncraft.com (Aahz) Date: 18 Apr 2006 10:31:45 -0700 Subject: 2.5 excitement (was Re: Java Developer Exploring Python) References: <1145290449.735642.120860@i40g2000cwc.googlegroups.com> <1145292795.565277.288760@v46g2000cwv.googlegroups.com> <1hdyb46.1yllkst1o2asjlN%aleaxit@yahoo.com> Message-ID: In article , Roy Smith wrote: >In article <1hdyb46.1yllkst1o2asjlN%aleaxit at yahoo.com>, > aleaxit at yahoo.com (Alex Martelli) wrote: >> >> Consider for example that one of the additions to Python 2.5 (currently >> in alpha stage) is the inclusion in the Python standard library of >> ctypes > >Indeed, I think the inclusion of ctypes is far and away the most exciting >thing in 2.5. Really? More than pysqlite? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "LL YR VWL R BLNG T S" From aleaxit at yahoo.com Wed Apr 5 01:45:45 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 4 Apr 2006 22:45:45 -0700 Subject: Extending Python References: <1144213715.479622.51740@j33g2000cwa.googlegroups.com> Message-ID: <1hdajzq.1e3i7o51p4yto3N%aleaxit@yahoo.com> wrote: > We can extend the functionality of python using C,C++.I want to > know what are the other lang that we can use to extend the > functionality of Python? C# or any .NET one in the IronPython implementation, Java (or any other JVM one) in the Jython implementation; for the Classic implementation, just for starters, there's Pyrex, Fortran (see http://cens.ioc.ee/projects/f2py2e/), Delphi/ObjectPascal (see ), Erlang (see ), Objective C (with PyObjC), D (see ) -- I'm sure there are many other possibilites too (for example, given any language with an implementation that can generate a C library you should be able to wrap that with SWIG for Python use; given any language that can produce dynamic librairies you should be able to use those libraries with ctypes; etc etc). Alex From donn at u.washington.edu Tue Apr 11 12:50:41 2006 From: donn at u.washington.edu (Donn Cave) Date: Tue, 11 Apr 2006 09:50:41 -0700 Subject: [fcntl]how to lock a file References: Message-ID: In article , marcello wrote: > Carl J. Van Arsdall wrote: > > [...] > > > > If you end up having problems working with the python fcntl module let > > me know your configuration I'd be interested to see if anyone else had > > similar problems to me. > > > Python 2.2.3 (#1, Aug 8 2003, 08:44:02) > [GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-13)] on linux2 > kernel 2.4.21-4.0.1.ELsmp > glibc-2.3.2-95.6 > > > > What else can i add? Maybe something about the problem? There are four functions in that module - fcntl, flock, ioctl, lockf. Which one were you using? What were you trying to do with it? Did it raise an exception? Returned but didn't effectively interlock against other processes -- on the same host, on other hosts? Failed to return when the file should have been OK to lock? Is it possible that locks would work fine in a test program, but fail in your application due to brain damaged POSIX filesystem locking semantics? We can start with stuff you probably already know. - The Berkeley flock(2) function is great but is not supported by NFS. - fcntl(2) F_SETLK etc. are supported by NFS, but have extremely inconvenient semantics, part of the POSIX 1003.1 specifications, particularly the part about losing a lock on ANY close(), even if the file descriptor remains open for fcntl(2)'s caller. - lockf(3) is fcntl(2). - Some platforms provide an flock() that is actually fcntl(2), can't think of the right words to express how deplorable that practice is. - On the rare platform that doesn't do this - where they are honest enough to just admit that they don't support flock() - Python implements fcntl.flock() with fcntl(2), I guess on the theory that you can't have enough brain damage. The worst case would be if Python's configure missed a bona fide flock(2), which is unlikely but may be worth checking if you use flock(2) for a reason. Donn Cave, donn at u.washington.edu From robin at alldunn.com Tue Apr 4 13:31:47 2006 From: robin at alldunn.com (Robin Dunn) Date: Tue, 04 Apr 2006 10:31:47 -0700 Subject: ANNOUNCE: wxPython 2.6.3.2 Message-ID: <4432AD83.8080402@alldunn.com> Announcing ---------- The 2.6.3.2 release of wxPython is now available for download at http://wxpython.org/download.php. This is a mostly bug fix release and takes care of several "unfortunate features" discovered in the 2.6.3.0 release made last week. A summary of changes is listed below and at http://wxpython.org/recentchanges.php. What is wxPython? ----------------- wxPython is a GUI toolkit for the Python programming language. It allows Python programmers to create programs with a robust, highly functional graphical user interface, simply and easily. It is implemented as a Python extension module that wraps the GUI components of the popular wxWidgets cross platform library, which is written in C++. wxPython is a cross-platform toolkit. This means that the same program will usually run on multiple platforms without modifications. Currently supported platforms are 32-bit Microsoft Windows, most Linux or other Unix-like systems using GTK2, and Mac OS X 10.2+, in most cases the native widgets are used on each platform. Changes in 2.6.3.2 ------------------ Fixed reference leak in wx.gizmos.TreeListCtrl.GetSelections. wxMSW: Fixed sizing issue with wx.Choice and wx.ComboBox. This change was implemented by reverting a prior fix for a different problem (continuous painting/resizing when a combobox is used as a widget in a wx.html.HtmlWindow) so a method to fix both problems is still being investigated. wxGTK: Fixed potential buffer overrun when pasting from the clipboard. Fixed problem in wx.lib.splitter when used on 64-bit platforms. Used the current length of the list for specifying an append instead of sys.maxint. wxMSW: Support added for XP themed owner drawn buttons and bitmap buttons. For example, if you change the foreground color of a button it will now be drawn with the XP themed style rather than an ugly generic button style. XRCed: Fix for Copy/Paste objects with international characters. Fixed the equality and inequality operators for some of the basic data types (wx.Point, wx.Size, wx.Colour, etc.) to no longer raise a TypeError if the compared object is not compatible, but to just return a boolean as expected. For example:: wx.Colour(64,0,64) == 123 ==> False wxMSW: Fixed (again) sizing/positioning issues of calling Realize on a wx.ToolBar that is not manaaged directly by a frame and that is already shown. wxMSW: Fixed wx.Choice/wx.ComboBox so they send events when a new item is selected only with the keyboard. -- Robin Dunn Software Craftsman http://wxPython.org Java give you jitters? Relax with wxPython! From aurelien.campeas at free.fr Wed Apr 26 11:33:26 2006 From: aurelien.campeas at free.fr (aurelien.campeas at free.fr) Date: 26 Apr 2006 08:33:26 -0700 Subject: KeybordInterrupts and friends In-Reply-To: <1146044514.173026.323700@i39g2000cwa.googlegroups.com> References: <1146044514.173026.323700@i39g2000cwa.googlegroups.com> Message-ID: <1146065606.771530.155930@i40g2000cwc.googlegroups.com> Precision : it does not happen when running interactively. From grflanagan at yahoo.co.uk Sat Apr 15 06:16:24 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 15 Apr 2006 03:16:24 -0700 Subject: Should I learn Python instead? References: <1145048531.915798.97060@v46g2000cwv.googlegroups.com> Message-ID: <1145096184.130036.170510@i40g2000cwc.googlegroups.com> fyleow wrote: > Hi guys, > > I'm a student/hobbyist programmer interested in creating a web project. > It's nothing too complicated, I would like to get data from an RSS > feed and store that into a database. I want my website to get the > information from the database and display parts of it depending on the > criteria I set. > [...] > > This is how to access an RSS feed and create an XML document to > manipulate it. > > System.Net.WebRequest myRequest = System.Net.WebRequest.Create("//feed > url here"); > System.Net.WebResponse myResponse = myRequest.GetResponse(); > System.IO.Stream rssStream = myResponse.GetResponseStream(); > System.Xml.XmlDocument rssDoc = new System.Xml.XmlDocument(); > > rssDoc.Load(rssStream); > > Here's PHP. > > $rss_feed = file_get_contents($rss_url); > I've never used it myself but maybe this would be useful: http://feedparser.org/ >From the Homepage: >>> import feedparser >>> d = feedparser.parse("http://feedparser.org/docs/examples/atom10.xml") >>> d.feed.title u'Sample Feed' >>> d.channel.title u'Sample Feed' >>> d.feed.link u'http://example.org/' >>> d.feed.subtitle # parses escaped HTML u'For documentation only' >>> d.channel.description u'For documentation only' Gerard From EP at zomething.com Sat Apr 1 14:17:59 2006 From: EP at zomething.com (EP) Date: Sat, 01 Apr 2006 11:17:59 -0800 Subject: Site err? - modpython - django? Message-ID: <442ED1E7.6010003@zomething.com> Hi i am gettng slow response from thssite en wonder if problem with gil? or django bug. is this coded in modpython and to many instances? i need to select web teknology en maybe python en zope is too old to handle high volume of download objs. what cas problem? thks for your help. http://www2.sqlonrails.org/ From kalyanigoli at gmail.com Thu Apr 27 03:31:34 2006 From: kalyanigoli at gmail.com (kalyanigoli at gmail.com) Date: 27 Apr 2006 00:31:34 -0700 Subject: help Message-ID: <1146123094.238547.6130@u72g2000cwu.googlegroups.com> Hi! I am a new user to python. I want to draw a 2D graph with coordinates data as input. In the graph i want to fill some area and also include image maps. Can any one suggest which is the best library to use and some links for examples. Thanks in advance. Your help will be most appreciated. Kalyani From nobody at 127.0.0.1 Wed Apr 26 13:37:18 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 26 Apr 2006 17:37:18 GMT Subject: Counting elements in a list wildcard References: <1145921582.526072.120480@u72g2000cwu.googlegroups.com> <1145953610.077361.320290@y43g2000cwc.googlegroups.com> <444DEEC8.7000001@lexicon.net> <1146045430.686430.65440@t31g2000cwb.googlegroups.com> Message-ID: Iain King wrote: > steven = re.compile("Ste(v|ph|f|ff)(e|a)n") Also you can expand the RE a bit to improve readability: re.compile("Stev|Steph|Stef|Steff)(en|an)") From aahz at pythoncraft.com Sun Apr 16 23:32:04 2006 From: aahz at pythoncraft.com (Aahz) Date: 16 Apr 2006 20:32:04 -0700 Subject: Why new Python 2.5 feature "class C()" return old-style class ? References: <1144752553.305591.88050@j33g2000cwa.googlegroups.com> <443c22d1$0$11341$636a55ce@news.free.fr> Message-ID: In article , Petr Prikryl wrote: >"Aahz" wrote... >> Bruno Desthuilliers wrote: >>>Aahz a ?crit : >>>> >>>> Classic classes are *NOT* deprecated. >>> >>>Perhaps not *officially* yet... >> >> Not even unofficially. The point at which we have deprecation is when >> PEP8 gets changed to say that new-style classes are required for >> contributions. > >My question: Could the old classes be treated in a new Python treated >as new classes with "implicit" base object? (I know the Zen... ;-) > >Example: I use usually a very simple classes. When I add "(object)" to >my class definitions, the code continues to works fine -- plus I have >new features to use. Why this cannot be done automatically? What could >be broken in the old code if it was threated so? Method resolution order is the primary up-front difference, but introspective code can also have problems. If you're tired of adding "(object)", put __metaclass__ = type at the top of your modules. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "LL YR VWL R BLNG T S" From fiann at earthlink.net Sat Apr 8 11:31:43 2006 From: fiann at earthlink.net (Mike Joyce) Date: Sat, 08 Apr 2006 15:31:43 GMT Subject: recognize a drive as removable media (e.g. compact flash, sd card or usb drive) Message-ID: I am trying to write a portable script that will find removable media, such as compact flash, sd card, usb, etc. drive and then upload files from the media. I want this to be portable so that I can write and maintain one program for both Linux and Windows. Each platform uses different functions so even if I could find two platform dependent functions that would be fine. Basically, I would like to avoid checking fixed disks if possible. If anyone know of a good way to do this please let me know. Thanks in advance for any help. -Mike Joyce From eli.hen at gmail.com Sat Apr 22 16:49:32 2006 From: eli.hen at gmail.com (Eli) Date: 22 Apr 2006 13:49:32 -0700 Subject: check whether a value is scalar Message-ID: <1145738972.246620.317070@i40g2000cwc.googlegroups.com> Hi, I want to check whether a value is a scalar. A scalar can be: - None (null) - string - number (integer, float) - boolean How can I validate a value is one of these types? I care about the value only, and not its class methods. An object is not a scalar, since it's not a simple value. An array might be considered as scalar. The issue is I want to keep a set of values to share among several applications in different languages, and only scalar values can be shared. Since objects are not the same in all languages, it's possible to share only simple values. -thanks From stefan at damp.homeip.net Fri Apr 14 10:23:52 2006 From: stefan at damp.homeip.net (Stefan D) Date: Fri, 14 Apr 2006 16:23:52 +0200 Subject: Embedding python and multiple separate scripts Message-ID: <443FB078.80403@damp.homeip.net> Hi, I'm trying to embed python into an chat bot I've made in c++. After googling around and reading docs for almost a day I have a few questions. First of all it seems like the best way to be able to run separate scripts in different, isolated environments is to create a sub-interpreter (by using Py_NewInterprete()) with an associated thread for each script/file. Or is this wrong? The big problem I have is when I want to call a python function. When loading a script I use the following code: PyEval_AcquireLock(); // get global lock so we can create a new interpreter threadState = Py_NewInterpreter(); // create a new sub-interpreter and get a pointer to the first thread PyThreadState_Swap(threadState); // switch to our new thread state appModule = PyImport_AddModule("hostapp"); // create a module for this program PyModule_AddIntConstant(appModule, "SEVENTEEN", 17); // set a test constant FILE* fp = fopen(filename, "r"); // load the python script file PyRun_SimpleFile(fp, filename); fclose(fp); PyEval_ReleaseThread(threadState); // set current thread state to NULL and release global lock When loading a script that contains: import hostapp print "test: ",hostapp.SEVENTEEN it prints out "test: 17" nicely after the call to PyRun_SimpleFile(...). So far so good, but the problem starts when I try to call a python function from c++. Here's the code that isn't working: PyEval_AcquireThread(threadState); PyObject* func = PyDict_GetItemString(PyImport_GetModuleDict(), "testfunc"); if(PyCallable_Check(func)) { // never get this far } PyEval_ReleaseThread(threadState); PyDict_GetItemString always return NULL for me, although I've defined the function as: def testfunc(): print "hi there" in the python file. Running PyRun_SimpleString("testfunc()\n") just after PyEval_AcquireThread() works like a charm though. Any ideas? I kinda get the feeling that I don't get the dict from PyImport_GetModuleDict() that I'm expecting. Thanks in advance.. /Stefan From Bulkan at gmail.com Tue Apr 11 02:33:43 2006 From: Bulkan at gmail.com (placid) Date: 10 Apr 2006 23:33:43 -0700 Subject: import help In-Reply-To: References: <1144716990.314306.79950@v46g2000cwv.googlegroups.com> <443b1789$1@nntp0.pdx.net> <1144727730.972948.162920@t31g2000cwb.googlegroups.com> Message-ID: <1144737223.195077.48870@i39g2000cwa.googlegroups.com> Dennis Lee Bieber wrote: > On 10 Apr 2006 20:55:31 -0700, "placid" declaimed the > following in comp.lang.python: > > > > > > Traceback (most recent call last): > > File "LinkedList.py", line 7, in ? > > main() > > File "LinkedList.py", line 4, in main > > n = Node("test") > > NameError: global name 'Node' is not defined > > > That is NOT the same code as you posted. > > You posted: > import sys > import node > > def main(): > print "Does nothin ATM, as it doesnt work" > > main() > > Line 4 of that is "def main():" > > If you have any .pyc or .pyo files in the same directory as your > source, delete them, try again, and show us what happened. > > BTW: as for the code that is being run... IT NEEDS > > n = node.Node("test") > > You imported a module "node", but the class definition named "Node" > is INSIDE the module -- so you have to specify > module.class > to access it... > -- > > ============================================================== < > > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > > wulfraed at dm.net | Bestiaria Support Staff < > > ============================================================== < > > Home Page: < > > Overflow Page: < Sorry, i left some code out, my bad, LinkedList.py contains (well it doesnt anymore, but originally did) import node def main(): n = Node("Test") print n.element main() but now i know why this doesnt work and the solution (see previous post of mine) thanks for all the help! From kp8 at mac.com Sat Apr 29 19:37:48 2006 From: kp8 at mac.com (kpp9c) Date: 29 Apr 2006 16:37:48 -0700 Subject: midi input In-Reply-To: References: Message-ID: <1146353868.212284.245510@y43g2000cwc.googlegroups.com> http://www.mxm.dk/products/public/pythonmidi mxm rocks! i used to use it this to create midi files so i know it works... but now it has grown to big for my small brain, & have no clue how to actually use it... i keep hoping for a small tutorial and some more docs...., this partially due to the bizarre mysteries and dark science of the midi file format and how it actually works with time. I would love to be able to use this again... I just need to figure out how to change real human time into something that midi can use. If i could specify a tempo base (tempo of say 60) and have it go up a scale in quarter notes or something.. i could maybe figure it out from there. I just want to be able to specify notes like csound or something does: start_time, duration, freq etc.... but i think that this also will do realtime stuff and you can monitor/filter/pipe incoming midi data as well. I just don't know how to do that either.... another possibility is to look at csound or cmix or pd or supercollider all of which are free, mostly open source, and available on linux good luck on your quest! From michael at elehack.net Tue Apr 18 08:45:03 2006 From: michael at elehack.net (Michael Ekstrand) Date: Tue, 18 Apr 2006 07:45:03 -0500 Subject: freakin out over C++ module in python In-Reply-To: <1145324978.877495.12580@i40g2000cwc.googlegroups.com> References: <1145324978.877495.12580@i40g2000cwc.googlegroups.com> Message-ID: <4444DF4F.2070905@elehack.net> nephish at xit.net wrote: > i would go thru it line by line, but i just dont know enough about C++, > how it pulls off a socket connection, etc.. and some of the things i > dont know how to do in python. like how to make an unsigned long init. The networking code in C++ should be at least vaguely similar to the appropriate Python code using the socket module. Python's socket module is a fairly thin wrapper around BSD sockets; its method names, etc. match the socket system calls. If the C++ is using plain berkely-ish socket code, you'll find connect(), send(), recv() calls (or something similar - I don't know what Winsock calls them for sure); these map to appropriate methods and functions in the socket module. If the C++ code is using some C++ sockets wrapper, I don't know; it still would probably be somewhat similar. Or similar enough that you can read it. Unless they're somehow finagling sockets in to the iostreams library (possible, but unlikely). - Michael -- mouse, n: a device for pointing at the xterm in which you want to type. -- Fortune Visit me on the Web: http://www.elehack.net From grante at visi.com Fri Apr 21 10:19:01 2006 From: grante at visi.com (Grant Edwards) Date: Fri, 21 Apr 2006 14:19:01 -0000 Subject: proposed Python logo References: <1145585399.871299.31900@t31g2000cwb.googlegroups.com> <1145628079.749480.191190@g10g2000cwb.googlegroups.com> Message-ID: <124hqel51rur33b@corp.supernews.com> On 2006-04-21, Michael Tobis wrote: >> Too rigid-looking somehow. > > Hey, I'm an amateur... There are lots of variations on the concept I > can think of. I want someone with a lot of design talent *and a little > familiarity with the language* to take enough interest to have a go at > it. > > At least (unlike the tadpoles) it has some resonance with the product > it's trying to represent. Not that I'm disagreeing, but how to you rate "resonance with the product"? -- Grant Edwards grante Yow! ... the MYSTERIANS at are in here with my visi.com CORDUROY SOAP DISH!! From webraviteja at gmail.com Fri Apr 21 19:47:54 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 21 Apr 2006 16:47:54 -0700 Subject: what has python added to programming languages? (lets be esoteric, shall we ; ) In-Reply-To: References: Message-ID: <1145663274.488586.5780@g10g2000cwb.googlegroups.com> >>"like the hashtable in java" People don't give a reference to a language feature only because it added/invented it but also because it is a popular one that many are familiar with. Java did not invent HashTables. They existed long before and were available to most languages before Java. Neither is it even a Java programming language feature (it's a class in it's standard library). Actually, I can't think off the top of my head, any feature in the Java language (and I am making no assertions about the implementation of specific instances) that was truly innovative. But that's OK. Incremental is good. From kp8 at mac.com Sat Apr 29 19:19:01 2006 From: kp8 at mac.com (kpp9c) Date: 29 Apr 2006 16:19:01 -0700 Subject: time conversions [hh:mm:ss.ms <-> sec(.ms) In-Reply-To: References: <1146213549.597990.115220@y43g2000cwc.googlegroups.com> Message-ID: <1146352741.676775.200990@i39g2000cwa.googlegroups.com> timedelta looks to be just the ticket! bravo, thank you... i guess this must be pretty new to Python. Nice... more "batteries included" stuff... cheers, -kevin-- From facetious_nickname at hotmail.com Mon Apr 3 19:13:39 2006 From: facetious_nickname at hotmail.com (Peter) Date: Mon, 03 Apr 2006 18:13:39 -0500 Subject: question about nasty regex In-Reply-To: References: <4N2dnea4rqrZ26zZnZ2dnUVZ_tKdnZ2d@speakeasy.net> Message-ID: Tim Chase wrote: >> What I mean is, I want to change, e.g.: [snip regular expressions lesson] > Whoa. That is super-duper extra cool. Thank you *very* much. From vbgunz at gmail.com Fri Apr 28 01:54:32 2006 From: vbgunz at gmail.com (vbgunz) Date: 27 Apr 2006 22:54:32 -0700 Subject: print out each letter of a word In-Reply-To: <87y7xqfg44.fsf@localhost.localdomain> References: <87y7xqfg44.fsf@localhost.localdomain> Message-ID: <1146203672.797966.114550@g10g2000cwb.googlegroups.com> what errors are you getting? Could it be an indentation error? I don't see anything wrong with the script except the value of fruit is missing. if fruit is a string, it should work like a charm. double check the length of the fruit with print len(fruit) and check fruit with print type(fruit) and make sure it really is a 'str'. Also, fruit has to already exist in the script e.g. 'fruit = apple'. Next time post your errors too. From kent at kentsjohnson.com Tue Apr 18 07:36:30 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Tue, 18 Apr 2006 07:36:30 -0400 Subject: Missing interfaces in Python... In-Reply-To: <1145310058.584301.76320@g10g2000cwb.googlegroups.com> References: <1145306373.781129.305840@z34g2000cwc.googlegroups.com> <1145310058.584301.76320@g10g2000cwb.googlegroups.com> Message-ID: <4444cf2b_2@newspeer2.tds.net> I V wrote: > To use interfaces in python, just what you would do in Java, except > don't use interfaces. +1 QOTW From first180 at gmail.com Sat Apr 8 19:23:02 2006 From: first180 at gmail.com (Jay) Date: 8 Apr 2006 16:23:02 -0700 Subject: Tkinter Message-ID: <1144538582.829134.82040@e56g2000cwe.googlegroups.com> Cold somebody please enlighten me at why code 1 works perfectly and yet code to will not display the gif file. code 1 -----------START--------- from Tkinter import * root = Tk() MainFrame = Canvas(root) MainFrame.pack() BackgroundFile = PhotoImage(file="Background.GIF") Background = MainFrame.create_image(0, 0, image=BackgroundFile) root.mainloop() -----------END--------- code 2 -----------START--------- from Tkinter import * class App: def __init__(self, root): self.MainFrame = Canvas(root) self.MainFrame.pack(fill=BOTH, expand=1) BackgroundFile = PhotoImage(file="Background.GIF") Tank1 = self.MainFrame.create_image(0, 0, image=BackgroundFile) root = Tk() app = App(root) root.mainloop() -----------END--------- Thanks Jay From rpdooling at gmail.com Tue Apr 18 22:25:54 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 18 Apr 2006 19:25:54 -0700 Subject: test for None In-Reply-To: References: <1145409010.709268.14770@j33g2000cwa.googlegroups.com> Message-ID: <1145413554.900079.38630@j33g2000cwa.googlegroups.com> >> Have you followed the tutorial through, running and understanding each >> example, to get the basics of Python covered? Could be high time to try that again. At first it was way too much, so I've been doing Dive Into Python and some others. But I will try the Tutorial again, at least up to classes. Then I'm sure I'll have to return to the books. Thanks for your patience. rick From lashkariNO at SPAMworldviz.com Tue Apr 25 19:07:21 2006 From: lashkariNO at SPAMworldviz.com (Farshid Lashkari) Date: Tue, 25 Apr 2006 16:07:21 -0700 Subject: can someone explain why .. In-Reply-To: References: Message-ID: Sch?le Daniel wrote: > I don't understand what is the difference between commented lines > 1 and 2 > > with 1 uncommented and 2 commented it works as expected > with 1 commented and 2 uncommented the picture doesn't appear I'm not familiar with Tkinter, but it seems as thought with 2, the "image" variable is garbage collected after the constructor of Main is called. With 1, you save a reference to the image, so it does not get garbage collected. -Farshid From petr at tpc.cz Tue Apr 4 15:03:16 2006 From: petr at tpc.cz (Petr Jakes) Date: 4 Apr 2006 12:03:16 -0700 Subject: kinterbas and Python In-Reply-To: References: <1144169752.389326@anc-srv.fastnet.it> Message-ID: <1144177396.293117.142490@e56g2000cwe.googlegroups.com> Jarek, I am using it always like in the following example to connect to the remote host and it works for me flawlessly. Petr Jakes import kinterbasdb as k con = k.connect( host='router.maren.cz', database='/data/sysdat01.gdb', user='SYSDBA', password='masterkey') From steve at holdenweb.com Mon Apr 24 10:00:45 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 24 Apr 2006 15:00:45 +0100 Subject: proposed Python logo In-Reply-To: <1145640106.269556.276060@u72g2000cwu.googlegroups.com> References: <1145585399.871299.31900@t31g2000cwb.googlegroups.com> <1145628079.749480.191190@g10g2000cwb.googlegroups.com> <124hqel51rur33b@corp.supernews.com> <1145640106.269556.276060@u72g2000cwu.googlegroups.com> Message-ID: Michael Tobis wrote: >>Not that I'm disagreeing, but how to you rate "resonance with the product"? > > > Hmm, I'm not a marketing professional, but this is would I would do > with my focus groups: > > Ask people familar with the product to name what they like about the > image, and what they like about the product, and look for analogies > between them. Ask them what they dislike about the image and the > product, and minimize overlap. > > (The main thing I dislike about Python is that the documentation is too > sketchy. It's very unclear what the official logo represents. So > another strike against it; it reminds me of the confusion I often face > on making use of an unfamiliar module.) As opposed to, for example, Apache's feater, which immediately says ... er, er, ... ? Anyway, none of this is intended to discourage you, I think it's good that people are still interested in improving Python's image (as am I: see http://squidoo.com/pythonology). regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From n.estner at gmx.de Sat Apr 29 09:05:35 2006 From: n.estner at gmx.de (nikie) Date: 29 Apr 2006 06:05:35 -0700 Subject: best way to determine sequence ordering? References: <70q4g.2006$No6.43783@news.tufts.edu> <1146259620.636600.119710@u72g2000cwu.googlegroups.com> Message-ID: <1146315935.017018.65580@u72g2000cwu.googlegroups.com> Steven Bethard wrote: > nikie wrote: > > Steven Bethard wrote: > > > >> John Salerno wrote: > >>> If I want to make a list of four items, e.g. L = ['C', 'A', 'D', 'B'], > >>> and then figure out if a certain element precedes another element, what > >>> would be the best way to do that? > >>> > >>> Looking at the built-in list functions, I thought I could do something > >>> like: > >>> > >>> if L.index('A') < L.index('D'): > >>> # do some stuff > >> This is probably a pretty reasonable approach as long as you're not too > >> worried about efficiency. It scans the list twice though, so if you > >> start doing this with really big lists, it might be better to do > >> something like: > > > > On average, it'll only have go through half the list twice, as it can > > break as soon as it finds the item it searches for. Don't think you can > > get any more efficient than that. > > Sure you can: > > a_index = None > d_index = None > for i, item in enumerate(L): > if item == 'A': > a_index = i > elif item == 'D': > d_index = i > if a_index is not None and d_index is not None: > break > > if a_index < d_index: > # do some stuff > > That goes through exactly the minimum number of elements. But it's > probably slower than two .index() calls since .index() is coded in C. > But timeit and see if you're interested. On my PC, calling index twice is 5 times faster. But let's just pretend for a moment Python code was compiled and optimized as well as C code. Then, this function would still not be faster than calling index twice. You seem to be under the impression that "looping through a list" takes a lot of time and "comparing items" takes none. The reverse is the case: Looping through a list means the processor has to do something like "increment an index" once for every item in the list (for optimized C code! Looping through a generator like the one returned by enumerate in interpreted code is a lot more complex). Comparing two items on the other hand involves (as lists aren't statically typed) looking up a cmp-method dynamically, calling it dynamically, and, of course, a string comparison, which again involves two pointer lookups for every character that has to be compared. So, if you want to know how fast your function will be, you'll have to count the number of comparisons. (Of course, we're ignoring the fact that smaller functions tend to run quicker due to cache-, branch-prediction and optimization-effects) If you call your function with the list ['C', 'A', 'D', 'B'], it will compare the first item 'C' to 'A' and 'D', than the second, 'A' to 'A' and the third 'D' to 'A' and 'D', so it'll have to do 5 comparisons, correct? If you call index to find the first occurence of the item 'A' in the same list, it will have to do 2 comparisons (it can break as soon as it finds the iten), and 3 comparisons are needed for finding the item 'D', so it'll do 5 comparisons, too. Plus, you have a small overhead for comparing "a_index" and "d_index" to none (which is faster than a sting-comparison, but still takes time, probably more time than incrementing an index for looping through a list). Things get even worse if 'A' and 'D' aren't "neighbors" in the list, because than all the items bewteen 'A' and 'D' will have to be compared to 'A' and 'D' in the version above, but only to 'D' if you call index twice. So, the function above isn't only less readable, it's also slower on the average case. You might however be able to tweak the performance of the index-version a little bit if you call it only on small chunks of the array at a time, using the index()-versions that take a start- and stop index, so the whole list only has to be moved from the memory to the cache once. But I'm not sure the performance is memory-bound at all (always hard to tell in an interpreted language). > > > >> >>> L = ['C', 'A', 'D', 'B'] > >> >>> positions = dict((item, i) for i, item in enumerate(L)) > >> >>> positions > >> {'A': 1, 'C': 0, 'B': 3, 'D': 2} > >> >>> positions['A'] < positions['D'] > >> True > > > > Isn't this bound to be less efficient? I mean, inserting the items into > > a dict is probably O(n log n) > > No, it's O(N). Dicts are just hash tables. Insertion is O(1). So N > insertions is O(N). I've measured that with the timeit module. The time it takes to build a dict with N entries doesn't seem to be proportional to N, (t-c)/n keeps increasing. Try this: import timeit, math def time(N): return timeit.Timer("dict([('%%010i'%%i,i) for i in range(%i)])" % N).timeit(number=5) c = time(1000)*2-time(2000) for i in range(1000,1000000,1000): t = time(i) print "%5i -> %f (t/n = %f)" % (i,t, (t-c)/i*1000) > This route is also dramatically more efficient if you need to make M > comparisons between items instead of just 1 comparison. In that case, > using the dict is O(N + M) instead of the O(N * M) of the .index() route. Assuming (as I have said already) that you build the dict once, but call index again and again for every comparison, which is of course comparing apples with oranges. From jimlewis at emachineshop.com Wed Apr 5 06:49:24 2006 From: jimlewis at emachineshop.com (jimlewis at emachineshop.com) Date: 5 Apr 2006 03:49:24 -0700 Subject: String pattern matching In-Reply-To: <443159e6$1_1@newspeer2.tds.net> References: <1143888648.234963.326000@j33g2000cwa.googlegroups.com> <443159e6$1_1@newspeer2.tds.net> Message-ID: <1144234164.742160.173640@e56g2000cwe.googlegroups.com> Thanks to all for the various good approaches. Kent's plain RE approach seems the most straightforward - did not know that RE can handle this situation - good to know! From michele.simionato at gmail.com Thu Apr 6 03:54:19 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 6 Apr 2006 00:54:19 -0700 Subject: pre-PEP: The create statement In-Reply-To: <59Wdnbd8EazRCqnZnZ2dnUVZ_vudnZ2d@comcast.com> References: <59Wdnbd8EazRCqnZnZ2dnUVZ_vudnZ2d@comcast.com> Message-ID: <1144310059.925361.36780@t31g2000cwb.googlegroups.com> Steven Bethard wrote: > The PEP is based on a suggestion [1]_ from Michele Simionato on the > python-dev list. True, but I would also mention that the idea of the 'create' keyword come from Nick Coghlan: http://mail.python.org/pipermail/python-dev/2005-October/057531.html Michele Simionato From phpbird at gmail.com Fri Apr 21 01:41:58 2006 From: phpbird at gmail.com (Ju Hui) Date: 20 Apr 2006 22:41:58 -0700 Subject: how to use socks5 proxy in pycurl? In-Reply-To: References: <1145344870.973387.65290@v46g2000cwv.googlegroups.com> Message-ID: <1145598118.481967.61050@t31g2000cwb.googlegroups.com> sorry, I can'y find sample python code there. I don't know how to set PROXYTYPE.. :( From tdelaney at avaya.com Thu Apr 20 19:54:27 2006 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Fri, 21 Apr 2006 09:54:27 +1000 Subject: PyLint 0.11 / astng 0.16 Message-ID: <2773CAC687FD5F4689F526998C7E4E5FF1E681@au3010avexu1.global.avaya.com> vj wrote: > Are there any plans to release pylint under the LGPL license? Why would it matter? PyLint is a tool you run *on* your source - you don't distribute PyLint to your users. And even if you did - your Python code doesn't link to PyLint, so there's no need to GPL your code. Tim Delaney From luismgz at gmail.com Wed Apr 12 21:23:09 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 12 Apr 2006 18:23:09 -0700 Subject: Python2CPP ? In-Reply-To: References: <1144841207.694056.145050@i39g2000cwa.googlegroups.com> Message-ID: <1144891389.854265.277010@u72g2000cwu.googlegroups.com> You should check Shed Skin (Python-to-C++ Compiler): http://shed-skin.blogspot.com/ From tjreedy at udel.edu Sat Apr 1 03:35:27 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 1 Apr 2006 03:35:27 -0500 Subject: Python 2.4.3 Documentation: Bad link References: <1143879203.136199.32840@e56g2000cwe.googlegroups.com> Message-ID: wrote in message news:1143879203.136199.32840 at e56g2000cwe.googlegroups.com... > Hi everybody, > I found bug in link to download Python 2.4.3 documentation, > http://docs.python.org/download.html. All links is to > http://docs.python.org/ftp/python/doc/2.4.3/* . It does not works. It > works only with http://python.org/ftp/python/doc/2.4.3/* . > Bones I tried a couple and they worked fine. Bad 4/1 joke? tjr From onurb at xiludom.gro Thu Apr 13 14:25:44 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 13 Apr 2006 20:25:44 +0200 Subject: function prototyping? In-Reply-To: <87bqv51h7i.fsf@gmail.com> References: <87hd4x1hx4.fsf@gmail.com> <87bqv51h7i.fsf@gmail.com> Message-ID: <443e97f4$0$26218$626a54ce@news.free.fr> Burton Samograd wrote: > Duncan Booth writes: > > >>Burton Samograd wrote: >> >>>Is there any way to 'prototype' functions in python, as you would in >>>C? Would that be what the 'global' keyword is for, or is there a more >>>elegant or 'pythonic' way of doing forward references? >>> >> >>There isn't really such a thing as a forward reference in Python. Always >>remember that 'def' and 'class' are executable statements: > > > Ok, we'll here's what I'm trying to do. I have a dictionary that I > would like to initialize in a module file config.py: > > -- config.py ------------------------- > global a_fun, b_fun > dict = { dont use 'dict' as an identifier, it shadows the builtin dict type. > 'a': a_fun, > 'b': b_fun > } > -------------------------------------- > > where a_fun and b_fun are in fun.py: > > -- fun.py ---------------------------- > def a_fun(): pass > def b_fun(): pass Until this point, everything is (almost) fine. You'd just need to rewrite config.py so it imports a_fun and b_fun from fun.py: #-- config.py ------------------------- import fun conf = { 'a': fun.a_fun, 'b': fun.b_fun } # -------------------------------------- But then, we have this : > import config And then we have a circular import... *But* is it necessary to have the main() in the same file that defines a_fun and b_fun ? It's quite common (and not only in Python) to use a distinct file for the main(). So you can easily solve your problem by splitting fun.py into fun.py and main.py: #-- main.py ------------------------- import config def main(*args): config.dict['a']() config.dict['b']() # here we have a python trick: if __name__ == '__main__': import sys sys.exit(main(*sys.argv[1:]) # -------------------------------------- > I like having the module/namespace seperation with the configuration > variables but I would like to make them easily (re)defined in the > configuration file by the user. You may want to look at one of the existing configuration modules. > Does python have the idea of a 'weak' > reference Yes, but that's something totally different. (snip) HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From peter at engcorp.com Wed Apr 12 10:49:14 2006 From: peter at engcorp.com (Peter Hansen) Date: Wed, 12 Apr 2006 10:49:14 -0400 Subject: converting lists to strings to lists In-Reply-To: <1144850003.574939.261390@v46g2000cwv.googlegroups.com> References: <1144850003.574939.261390@v46g2000cwv.googlegroups.com> Message-ID: robin wrote: > i'm doing some udp stuff and receive strings of the form '0.870000 > 0.250000 0.790000;\n' > what i'd need though is a list of the form [0.870000 0.250000 0.790000] > i got to the [0:-3] part to obtain a string '0.870000 0.250000 Actually, that's already a bug. You want [0:-2] if you're going to do it that way. Unless you meant that your string actually has a backslash and an "n" character, which is doubtful... You should probably use something more like Steven's solution, although I'd personally use s.strip(';') or at least s.rstrip(';') if I had semicolons to remove, rather than a combined endswith(';') and slicing the last character off. > 0.790000' but i can't find a way to convert this into a list. i tried > eval() but this gives me the following error: > > Traceback (most recent call last): > File "", line 1, in ? > File "", line 1 > .870000 0.250000 0.79000 (If you'd posted the full error (that's an incomplete traceback), someone would probably have pointed out how to interpret what Python told you so that you'd already have figured out what was wrong with that...) -Peter From grante at visi.com Sat Apr 1 09:20:34 2006 From: grante at visi.com (Grant Edwards) Date: Sat, 01 Apr 2006 14:20:34 -0000 Subject: Python 2.5 licensing: stop this change References: Message-ID: <122t31idovvdc65@corp.supernews.com> On 2006-04-01, Steve Holden wrote: > As the only director of the Python Software Foundation to vote against a > recent Board motion to implement the change in licensing terms described in > > http://pyfound.blogspot.com/2006/04/python-25-licensing-change.html Good one Steve. I particularly liked the Comments section. :) -- Grant Edwards grante Yow! I represent a at sardine!! visi.com From andrew at trevorrow.com Mon Apr 24 22:11:24 2006 From: andrew at trevorrow.com (Andrew Trevorrow) Date: Tue, 25 Apr 2006 12:11:24 +1000 Subject: MS VC++ Toolkit 2003, where? References: <1he8pss.1yk7ug81rv7pw2N%aleaxit@yahoo.com> <1145811839.042394.73260@t31g2000cwb.googlegroups.com> <1he8sbx.dqqp3q10n5thaN%aleaxit@yahoo.com> <1145849491.347970.112150@e56g2000cwe.googlegroups.com> <1he9m4m.9d8okx1x7mxeaN%aleaxit@yahoo.com> <444C7896.9040104@v.loewis.de> <1heagzk.1pzfash1awhj3eN%aleaxit@yahoo.com> Message-ID: Ron Adam wrote: > > Try tinyurl http://tinyurl.com/gv8wr please. > > I still get the following with the tinyurl link: > > ~~~ > The download you requested is unavailable. If you continue to see this > message when trying to access this download, go to the "Search for a > Download" area on the Download Center home page. > ~~~ Ditto for me. And like Ron, the URL (tiny or long) to the 1.1 SDK *does* work. This is really frustrating. I've tried different browsers (Safari and IE on my Mac, IE on WinXP). I've tried emptying the browser cache. I'm in Australia, so maybe it depends on where the request is coming from? Any clues on this would be much appreciated. Or maybe someone is willing to make their VCToolkitSetup.exe available temporarily... Andrew From michael at elehack.net Thu Apr 6 08:39:25 2006 From: michael at elehack.net (Michael Ekstrand) Date: Thu, 06 Apr 2006 07:39:25 -0500 Subject: pre-PEP: The create statement In-Reply-To: <59Wdnbd8EazRCqnZnZ2dnUVZ_vudnZ2d@comcast.com> References: <59Wdnbd8EazRCqnZnZ2dnUVZ_vudnZ2d@comcast.com> Message-ID: <44350BFD.4000601@elehack.net> Steven Bethard wrote: > The PEP below should be mostly self explanatory. I'll try to keep the > most updated versions available at: > > http://ucsu.colorado.edu/~bethard/py/pep_create_statement.txt > http://ucsu.colorado.edu/~bethard/py/pep_create_statement.html > > > > PEP: XXX > Title: The create statement > Version: $Revision: 1.4 $ > Last-Modified: $Date: 2003/09/22 04:51:50 $ > Author: Steven Bethard > Status: Draft > Type: Standards Track > Content-Type: text/x-rst > Created: 05-Apr-2006 > Python-Version: 2.6 > Post-History: 05-Apr-2006 > [large amount of crunchy goodness snipped] +1 from me on this one. Something it could be useful to try to add, if possible: So far, it seems that this create block can only create class-like things (objects with a name, potentially bases, and a namespace). Is there a natural way to extend this to other things, so that function creation can be modified? For example: create tracer fib(x): # Return appropriate data here pass tracer could create a function that logs its entry and exit; behavior could be modifiable at run time so that tracer can go away into oblivion. Given the current semantics of create, this wouldn't work. What would be reasonable syntax and semantics to make something like this possible? Maybe this would need to be a separate PEP. But it seems at least somewhat related. - Michael -- mouse, n: a device for pointing at the xterm in which you want to type. -- Fortune Visit me on the Web: http://www.elehack.net From thomasbartkus at comcast.net Tue Apr 11 12:25:56 2006 From: thomasbartkus at comcast.net (Thomas Bartkus) Date: Tue, 11 Apr 2006 11:25:56 -0500 Subject: Override on terminal References: <1144766236.330882.142520@j33g2000cwa.googlegroups.com> Message-ID: "fivestars" wrote in message news:1144766236.330882.142520 at j33g2000cwa.googlegroups.com... > Hi there. > > I'm computer science student at the end of my degree. I'm new about > python. > > I've a question for all of you. > > Do you know how to write, from python code, on a unix(linux) terminal > on specified coordinates? Actually, there is no unix(linux) terminal. What you have are terminals, of various flavors, that can be attached to a unix(linux) session. Once you decide to stray from generic spaces and tab formatting, it is the terminal that has fancy features such as positioning the cursor at arbitrary coordinates. And every terminal type has a different command sequence to achieve that. That said, there are standards such as the VT-100 terminal that everything seems to emulate. You would need to have the VT-100 command set in front of you and you would code this into your python routines. Someone else has suggested the "curses" module. I haven't played with this but it is probably just the ticket you are looking for. It no doubt encloses cgoto commands, blink, highlight, clear screen, color command & yada yada for various terminal types inside nice python functions And I'll be surprised if it doesn't default to VT-100 ;-) > And also: is it possible to override, from python code, something on a > unix(linux) terminal? I don't know what that means. If you meant overwrite (rather than override!), then the answer would be yes. Thomas Bartkus > I would have a suggestion that won't use files. > > I hope that i've been clear. > > Thanks, > > Mattia > From Serge.Orlov at gmail.com Mon Apr 17 18:35:20 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 17 Apr 2006 15:35:20 -0700 Subject: Missing interfaces in Python... In-Reply-To: References: <20060417210541.GV7561@vulcan.cprogrammer.org> Message-ID: <1145313320.924434.199350@j33g2000cwa.googlegroups.com> Jonathan Daugherty wrote: > # so with interfaces, missing methods will suddenly appear out of thin > # air ? > > With interfaces, the idea is that they're enforced; so, they'll appear > because someone implements them. But if you're writing tests you will check method signatures anyway, so why bother? Besides how java-like interfaces will help you if one of interface methods is supposed to accept one parameter that can be list or dict and not accept None? From rridge at csclub.uwaterloo.ca Thu Apr 27 14:38:16 2006 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: 27 Apr 2006 11:38:16 -0700 Subject: MinGW and Python References: <1145861223.509630.247350@y43g2000cwc.googlegroups.com> <444C79D7.4060007@v.loewis.de> <444DC62B.7000702@v.loewis.de> <1145985979.369429.114040@i39g2000cwa.googlegroups.com> <1145995815.818582.166230@y43g2000cwc.googlegroups.com> <444FA85B.7010104@v.loewis.de> <1146088651.980286.97220@j33g2000cwa.googlegroups.com> <44505e03$0$13138$9b622d9e@news.freenet.de> Message-ID: <1146163096.021897.36620@v46g2000cwv.googlegroups.com> Ross Ridge wrote: > Nonetheless, Cygwin applications are not generally considered native > Win32 applications because of the dependency on CYGWIN1.DLL and the > related environment. While what you're saying a strictly true, the > term "native Win32" is used to make a distinction between a port of a > program that doesn't use or require the Cygwin environment from one > that does. Martin v. L?wis wrote: > I know it is common to take that view, but I believe it is wrong, no > matter how you look at it Regardless, that's what "native Win32 application" means in this context, and makes a useful and well understood distinction between ports. Ross Ridge From robin at NOSPAMreportlab.com Sat Apr 29 14:12:08 2006 From: robin at NOSPAMreportlab.com (Robin Becker) Date: Sat, 29 Apr 2006 18:12:08 +0000 Subject: opposite function to split? In-Reply-To: <1146334115.556040.54550@i40g2000cwc.googlegroups.com> References: <1146334115.556040.54550@i40g2000cwc.googlegroups.com> Message-ID: <4453AC78.9060109@jessikat.plus.net> randomtalk at gmail.com wrote: > hello everyone! I can't seem to find a function that combines a list of > items into a string with a seperator between the individual elements.. > Is there such a method that does the opposite of sting.split? thanks > alot! > join is your answer ','.join(['a','b','c']) == 'a,b,c' -- Robin Becker From nobody at 127.0.0.1 Wed Apr 26 13:46:18 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 26 Apr 2006 17:46:18 GMT Subject: The whitespaceless frontend References: <1145960119.998718.315550@j33g2000cwa.googlegroups.com> Message-ID: Sion Arrowsmith wrote: > Absolutely. I've written quite a lot of code (which I wasn't expecting > anyone else to maintain) using 'I' for the same reasons. Plus, it's > even shorter in terms of characters (if not keystrokes), stands out > reasonably well, and for how I read it makes for better English > grammar (eg I.send_response(...) -- I guess it depends on whether > you're doing the mental transformation of method call to message > passing). I didn't like 'I' because: 1. i don't like caps except for constants (which it sorta is, i guess) 2. it's too close to 'i' which is standard for temporary loop variables 3. the bad grammar (for message passing) is all the fun! > I stopped doing this when I started (a) maintaining other people's > Python code, and having them maintain mine and (b) using editors > whose Python syntax highlighting coloured "self" as special. > "Readability counts" wins over a couple of extra characters. Sadly, tis true. Which makes me wish they'd just hard-coded 'self' for the damn thing in the first place. Nothing worse than knowing what you're missing. From jantod at gmail.com Fri Apr 7 05:23:32 2006 From: jantod at gmail.com (jantod at gmail.com) Date: 7 Apr 2006 02:23:32 -0700 Subject: pre-PEP: The create statement In-Reply-To: <1144311866.568076.235070@j33g2000cwa.googlegroups.com> References: <59Wdnbd8EazRCqnZnZ2dnUVZ_vudnZ2d@comcast.com> <4434cc48$0$4629$636a55ce@news.free.fr> <1144311866.568076.235070@j33g2000cwa.googlegroups.com> Message-ID: <1144401812.890734.279310@e56g2000cwe.googlegroups.com> Serge Orlov wrote: > bruno at modulix wrote: > > Steven Bethard wrote: > > > The PEP below should be mostly self explanatory. I'll try to keep the > > > most updated versions available at: > > [snip] > > > > > Seems mostly clean. +1. > > > > That's what Trojans said when they saw a wooden horse at the gates of > Troy ;) > > Serge. QOTW! From ajay.padala at gmail.com Wed Apr 12 13:31:52 2006 From: ajay.padala at gmail.com (ajay.padala at gmail.com) Date: 12 Apr 2006 10:31:52 -0700 Subject: cheetah templating: place holders needed in a template Message-ID: <1144863112.701718.291080@t31g2000cwb.googlegroups.com> Hi I would like to be able to get the inputs that are needed into a template file programmatically. For example if we had a template: ===================== $name has $num marbles in his hand. ===================== I want to be able to initialise this template and call a method on it to get the list ['name', 'num'] Is there anything in cheetah which does this? At present, I am sending a "fake" dictionary into the searchList to do this. This is coded as. fake = Generic() t = Template(file=absFileName, searchList=[fake]) print fake.calledAtts ========================================= class Generic(object): """ Generic object can pretend to be a dictionary or a list and doesn't throw any errors whatever you call it for """ # def __new__(cls, *args, **kwargs): # if '_inst' not in vars(cls): # cls._inst = object.__new__(cls, *args, **kwargs) # return cls._inst calledAtts = sets.Set() def __init__(self, *args, **kwargs): pass def __call__(self, *args, **kwargs): return self def __repr__(self): return "Generic" def __nonzero__(self): return True def __getattr__(self, name): return self __delattr__ = __getattr__ def __setattr__(self, name, value): return self def __len__(self): return 1 def __iter__(self): return iter(("Generic",)) def __getitem__(self, i): if isinstance(i,types.StringType): self.calledAtts.add(str(i)) return self def __setitem__(self, i, v): return self def __contains__(self, itemName): print "contains " + itemName return True def has_key(self, *args, **kwargs): # print "has key called" return True __delitem__ = __getitem__ ======================================== This just logs each access to the dictionary and stores the key under self.calledAtts But obviously this won't work if I have #if statements etc. I am hoping cheetah already has this feature somewhere which is much more robust but I can't find it. Ajay From nomail at nixmail.com Sun Apr 30 04:30:00 2006 From: nomail at nixmail.com (DarkBlue) Date: Sun, 30 Apr 2006 16:30:00 +0800 Subject: Unpacking of query result Message-ID: <44547588@127.0.0.1> Hello Following part of an database query works fine : self.cur=con1.cursor self.cur.execute('select a,b,c,d from t1') for (a,b,c,d) in self.cur: print a,b,c,d but how to do this: self.cur.execute(sql_select_text_put_in_at_runtime) for (whatever_was_in_the_select_text_part_of_the_query) in self.cur: print 'returned result set' Will it be necessary to parse the sql string and find any possible return columns or is there a better way so that the query can be used generically , that is without knowing at coding time what or how many columns will be returned ? Thanks Db From mikelemmer6 at yahoo.com Tue Apr 18 23:39:04 2006 From: mikelemmer6 at yahoo.com (Jeff Groves) Date: 18 Apr 2006 20:39:04 -0700 Subject: Activating Batch Files from Python Message-ID: <1145417944.549477.198510@g10g2000cwb.googlegroups.com> I'm writing a launcher that should do the following: 1. Activate a .bat file to set environmental variables. 2. Start 3 programs, using said environmental variables as arguments. However, I can't get the environmental variables to stick because all of Pythons' system start/open functions split off into their own little subshells, therefore the .bat file doesn't affect the main shell. How can I use the .bat file to set environmental vars from Python? From arne.meissner at gmx.de Fri Apr 7 12:39:48 2006 From: arne.meissner at gmx.de (Arne) Date: Fri, 7 Apr 2006 18:39:48 +0200 Subject: GUI Treeview Message-ID: Hello ! I am looking for a widget with the following properties: - showing the tree file structure/ directory structure - next to each file should be a checkbox - the tree should only show certain files (i. e. only for the looked in user) Maybe you can post me a link. Thanks! Arne From sjmachin at lexicon.net Sun Apr 9 21:43:51 2006 From: sjmachin at lexicon.net (John Machin) Date: 9 Apr 2006 18:43:51 -0700 Subject: a unicode question? References: <1144631034.049820.62550@u72g2000cwu.googlegroups.com> Message-ID: <1144633431.375745.77670@z34g2000cwc.googlegroups.com> What do you mean by "ansi string"? Here is a superficially not-unreasonable answer to your more specific question: # >>> s1 = u'\xd6\xd0\xb9\xfa\xca\xaf\xbb\xaf(600028) ' # >>> s2 = '\xd6\xd0\xb9\xfa\xca\xaf\xbb\xaf(600028) ' # >>> s3 = s1.encode('latin1') # >>> s2 == s3 # True But what are you really trying to achieve? Where does your Unicode data come from? What ranges of characters do you expect it to contain? You need to crunch it into an 8-bit representation because ... what? From Aiwass333 at gmail.com Fri Apr 7 11:23:48 2006 From: Aiwass333 at gmail.com (RunLevelZero) Date: 7 Apr 2006 08:23:48 -0700 Subject: glob and curly brackets In-Reply-To: References: Message-ID: <1144423428.751633.181270@e56g2000cwe.googlegroups.com> You just need to literlize them with a forward slash. " globber = '/home/zhomer/test/{dir1*,dir2*}/{subdir1,subdir2}' globlist = glob.glob(globber) " globber = '/home/zhomer/test/\{dir1*,dir2*\}/\{subdir1,subdir2\}' globlist = glob.glob(globber) See if that works for you. From onurb at xiludom.gro Thu Apr 6 08:12:27 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 06 Apr 2006 14:12:27 +0200 Subject: pre-PEP: The create statement In-Reply-To: <1144311866.568076.235070@j33g2000cwa.googlegroups.com> References: <59Wdnbd8EazRCqnZnZ2dnUVZ_vudnZ2d@comcast.com> <4434cc48$0$4629$636a55ce@news.free.fr> <1144311866.568076.235070@j33g2000cwa.googlegroups.com> Message-ID: <443505f2$0$14265$626a54ce@news.free.fr> Serge Orlov wrote: > bruno at modulix wrote: > >>Steven Bethard wrote: >> >>>The PEP below should be mostly self explanatory. I'll try to keep the >>>most updated versions available at: > > > [snip] > > >>Seems mostly clean. +1. >> > > > That's what Trojans said when they saw a wooden horse at the gates of > Troy ;) > he he he... -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From sjmachin at lexicon.net Thu Apr 27 22:20:19 2006 From: sjmachin at lexicon.net (John Machin) Date: Fri, 28 Apr 2006 12:20:19 +1000 Subject: Converstion In-Reply-To: <1146181848.615239.281200@j33g2000cwa.googlegroups.com> References: <1146181848.615239.281200@j33g2000cwa.googlegroups.com> Message-ID: <44517BE3.8070400@lexicon.net> On 28/04/2006 9:50 AM, Chris wrote: > In a program I'm writing I have a problem where a bit of text sent over > a network arrives at my server. If the person who sent the text made a > mistake typing the word and pressed backspace the backspace code is > included in the word for example hello is hel\x08lo. Interesting. If the sender typed say ";" instead of the second "l", then corrected it, one would expect either the raw (in Unix terminology) string "hel;\x08lo" or the cooked string "hello". What network is that? What protocol is being used for sending user input? What happens if the user backspaces TWICE e.g. raw input at keyboard is "he;;\x08\x08llo"?? What other funny business could be going on that you haven't stumbled on yet? Can the user cancel a whole line by keying say Ctrl-X? If so, what happens? > The \x08 is the > backspace key. How do I convert this string to a normal string (without > the \x08). If I print it to screen it appears normal, "hello" but if I > store it in a list it appears as hel\x08lo. > If, as you say, the bad character is omitted, what do you think is wrong with input_string.replace("\x08", "") ? If the bad characters are not omitted, you would have to work a bit harder: step through the characters, appending them to a list. When you hit a backspace, delete the last character in the list (if any). At the end, do "".join(the_list). From exarkun at divmod.com Mon Apr 17 09:05:00 2006 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 17 Apr 2006 09:05:00 -0400 Subject: XML-RPC server via xinetd In-Reply-To: <20060417141751.A22675@xos037.xos.nl> Message-ID: <20060417130500.22481.1904863025.divmod.quotient.14434@ohm> On Mon, 17 Apr 2006 14:17:51 +0200, Jos Vos wrote: >On Mon, Apr 17, 2006 at 12:42:00PM +0200, Fredrik Lundh wrote: > >> except that if the OP's expecting the other end to use an ordinary XML-RPC >> library, he needs to implement some minimal HTTP handling as well. > >Which makes me wondering why the classes (this also applies to >BaseHTTPServer / BaseHTTPRequestHandler) ae designed the way they >are. The underlying stream medium (TCP sockets or plain file >streams like stdin/stdout) should not be integrated with the >protocol (HTTP) handling, IMHO... > Twisted agrees. A server that speaks real HTTP and real XML-RPC over stdin and stdout (untested ;): from twisted.web import xmlrpc, server from twisted.internet import stdio, reactor class YourApplication(xmlrpc.XMLRPC): def remote_somefunction(self, args): ... return result stdio.StandardIO(server.Site(YourApplication())) reactor.run() For more details, see . Jean-Paul From ldo at geek-central.gen.new_zealand Wed Apr 5 06:33:25 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 05 Apr 2006 22:33:25 +1200 Subject: HTMLParser fragility Message-ID: I've been using HTMLParser to scrape Web sites. The trouble with this is, there's a lot of malformed HTML out there. Real browsers have to be written to cope gracefully with this, but HTMLParser does not. Not only does it raise an exception, but the parser object then gets into a confused state after that so you cannot continue using it. The way I'm currently working around this is to do a dummy pre-parsing run with a dummy (non-subclassed) HTMLParser object. Every time I hit HTMLParseError, I note the line number in a set of lines to skip, then create a new HTMLParser object and restart the scan from the beginning, skipping all the lines I've noted so far. Only when I get to the end without further errors do I do the proper parse with all my appropriate actions. From nick at craig-wood.com Fri Apr 21 15:30:03 2006 From: nick at craig-wood.com (Nick Craig-Wood) Date: Fri, 21 Apr 2006 14:30:03 -0500 Subject: how to append to a list twice? References: <4282g.68392$H71.37777@newssvr13.news.prodigy.com> Message-ID: Edward Elliott wrote: > John Salerno wrote: > > If I want to create a list of the form [100, 99, 99, 98, 98, 97, 97...] > > (where each item is repeated twice after the first one), how might I do > > that most efficiently? > > Why not just this: > > series = [x/2 for x in range(200, 1, -1)] That should be series = [x//2 for x in range(200, 1, -1)] to be "from __future__ import division" safe -- Nick Craig-Wood -- http://www.craig-wood.com/nick From johnjsal at NOSPAMgmail.com Fri Apr 21 11:46:07 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 21 Apr 2006 15:46:07 GMT Subject: how to append to a list twice? In-Reply-To: <1B62g.16669$0Z4.581@tornado.texas.rr.com> References: <1B62g.16669$0Z4.581@tornado.texas.rr.com> Message-ID: <3772g.1992$No6.43411@news.tufts.edu> Paul McGuire wrote: > "John Salerno" wrote in message > news:ui62g.1991$No6.43121 at news.tufts.edu... >> If I want to create a list of the form [100, 99, 99, 98, 98, 97, 97...] >> (where each item is repeated twice after the first one), how might I do >> that most efficiently? >> >> Right now I have this: >> >> series = [100] >> for x in range(10): # just for testing >> series.append(series[-1] - 1) >> >> But of course that only does it once, and I don't want to have to copy >> and paste the append line. Perhaps there's a better way than this. >> >> Thanks. > > series = [100] > for x in range(10): # just for testing > series.extend([series[-1] - 1]*2) > > Interesting. I tried the *2 method twice, but I kept getting weird results, I guess because I was using append and not extend. I thought extend added lists to lists, but obviously that's not the case here. Thanks. From cam.ac.uk at mh391.invalid Sat Apr 15 03:39:08 2006 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sat, 15 Apr 2006 08:39:08 +0100 Subject: Improvements for import this Message-ID: As the capabilities of core Python have increased, I've noticed that the logic in import this can be simplified to one line: print s.decode("rot13") ;) At the very least the last line: print "".join([d.get(c, c) for c in s]) could use a generator expression instead of a list comprehension. -- Michael Hoffman From jos at xos.nl Mon Apr 17 06:20:01 2006 From: jos at xos.nl (Jos Vos) Date: Mon, 17 Apr 2006 12:20:01 +0200 Subject: XML-RPC server via xinetd In-Reply-To: ; from nick@craig-wood.com on Mon, Apr 17, 2006 at 03:30:04AM -0500 References: Message-ID: <20060417122001.B22258@xos037.xos.nl> On Mon, Apr 17, 2006 at 03:30:04AM -0500, Nick Craig-Wood wrote: > UTSL ;-) > > Look at /usr/lib/python2.4/SimpleXMLRPCServer.py (adjust as per your > distro) and in particular the definition of the CGIXMLRPCRequestHandler class. I did this before posting my question, in fact, but I did not look good enough maybe, as at first sight I thought tghe CGI... class would be too CGI-specific (it looks for environment variables etc. given by the HTTP server), but maybe it's good enough. > That looks as thought it almost, or maybe completely, does what you > want, ie an XMLRPC subclass which reads from stdin and writes to > stdout. Will try... -- -- Jos Vos -- X/OS Experts in Open Systems BV | Phone: +31 20 6938364 -- Amsterdam, The Netherlands | Fax: +31 20 6948204 From antroy at gmail.com Tue Apr 18 12:06:00 2006 From: antroy at gmail.com (Ant) Date: 18 Apr 2006 09:06:00 -0700 Subject: Why new Python 2.5 feature "class C()" return old-style class ? In-Reply-To: References: <1144752553.305591.88050@j33g2000cwa.googlegroups.com> <443bbdbe$0$15517$626a54ce@news.free.fr> <443c22d1$0$11341$636a55ce@news.free.fr> <443E4204.2020003@freakmail.de> Message-ID: <1145376360.463785.134970@v46g2000cwv.googlegroups.com> (OT) I don't have the same issue with Syntax highlighting, and I use jEdit as my main Python editor (Though some of the dedicated Python IDE's have some nice refactoring/code completion stuff, none has the raw editing power of jEdit). I'm using jEdit 4.3 pre3 - though I don't recall any problems with 4.2 (and it was only a week ago I changed). The Jython plugin enables Structure browsing if you haven't already got it installed. From rpdooling at gmail.com Mon Apr 10 09:25:11 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 10 Apr 2006 06:25:11 -0700 Subject: can't pass command-line arguments In-Reply-To: References: <1144636890.976327.253000@i39g2000cwa.googlegroups.com> <1144637633.814788.150270@i40g2000cwc.googlegroups.com> <1144672498.920860.110000@u72g2000cwu.googlegroups.com> Message-ID: <1144675511.132436.198490@z34g2000cwc.googlegroups.com> Thanks, Duncan Results of my ftype command d:\python>ftype python.file python.file="C:\Python24\python.exe" "%1" %* See below, the response with examples to Tim. I'm not worried about it. Thank you all for the education. rick From josecarlos.balderas at gmail.com Sun Apr 2 18:37:18 2006 From: josecarlos.balderas at gmail.com (Jose Carlos Balderas Alberico) Date: Mon, 3 Apr 2006 00:37:18 +0200 Subject: Sending a file to a remote server. Message-ID: Hi. I posted a message in the list a couple of days ago about sending a file to a remote SimpleXMLRPCServer. Well. my doubt still remains, so I come to you again in search of a clearer answer. The thing is I want to send a ZIP file to a server, and what I basically do is enclose the file data into a Binary object by doing something like "data = Binary(f.read())". Then I call a function in the server, passing the object as a parameter, and have the server process the same file by doing something like f = open("somefile.zip", 'w') f.write(binaryObject.data) Since I've never programmed server/client before, I've never faced the fact of sending a file to a remote machine. I just want to know if what I've done to send the file is acceptable, and if you know of a better way to send files to a SimpleXMLRPCServer. Thank you very much for your attention. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jparlar at cogeco.ca Wed Apr 12 11:55:30 2006 From: jparlar at cogeco.ca (Jay Parlar) Date: Wed, 12 Apr 2006 08:55:30 -0700 Subject: Python2CPP ? In-Reply-To: References: Message-ID: <9b6a4aec4c41e1d550c82320a2d83da7@cogeco.ca> On Apr 12, 2006, at 5:13 AM, Michael Yanowitz wrote: >> > > Thanks. I want to translate from Python to C++ for a few reasons: > 1) Curiosity. I would like to see how well the translation goes. > 2) Efficiency. It is alot quicker to code something in Python. If I can > write it in Python and auto-convert it to C++. I would save time > coding. > 3) Education. I would learn more about Python, C++, their similarities > and > differences. > 4) Other. Just want to know how well Language translators work these > days. I > have seen > Fortran2C and Pascal2C translators in the past. Would like to see > how > well these > work with Python. > > Thanks in advance: You want this: http://shed-skin.blogspot.com/ It can only do a subset of Python, but it does generate C++ code, and it can see some big speedups. Jay P. From robert.kern at gmail.com Sat Apr 22 23:47:26 2006 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 22 Apr 2006 22:47:26 -0500 Subject: Custom data type in a matrix. In-Reply-To: <1145762341.179288.234900@i39g2000cwa.googlegroups.com> References: <1145762341.179288.234900@i39g2000cwa.googlegroups.com> Message-ID: Gaz wrote: > Hi guys. I've been lookig for this in the numpy pdf manual, in this > group and on google, but i could not get an answer... You will probably want to look or ask on the numpy list, too. https://lists.sourceforge.net/lists/listinfo/numpy-discussion > Is there a way to create a custom data type (eg: Name: string(30), Age: > int(2), married: boolean, etc) and then use that custom data in a > matrix? Actually, this is a two question question :P Yes. Use record arrays. They are discussed in section 8.5 of the _The Guide to NumPy_ if you have the book. There is another example of using record arrays on the SciPy wiki (although it is less focused on combining different data types than it is named column access): http://www.scipy.org/RecordArrays Here is an example: In [18]: from numpy import * In [19]: rec.fromrecords([['Robert', 25, False], ['Thomas', 53, True]], names='name,age,married', formats=['S30', int, bool]) Out[19]: recarray([('Robert', 25, False), ('Thomas', 53, True)], dtype=[('name', '|S30'), ('age', '>i4'), ('married', '|b1')]) In [21]: Out[19].name Out[21]: chararray([Robert, Thomas], dtype='|S30') In [22]: Out[19].age Out[22]: array([25, 53]) In [23]: Out[19].married Out[23]: array([False, True], dtype=bool) You can also use object arrays if you need to implement classes and not just dumb, basic types: In [33]: class Hex(dict): ....: def __init__(self, **kwds): ....: dict.__init__(self, **kwds) ....: self.__dict__ = self ....: ....: In [34]: field = array([Hex(color=(0,0,0), owner='Player1', x=10, y=20, etc='Black hex owned by Player1'), ....: Hex(color=(1,1,1), owner='Player2', x=10, y=21, etc='White hex owned by Player2')], dtype=object) In [35]: In [35]: field Out[35]: array([{'y': 20, 'etc': 'Black hex owned by Player1', 'color': (0, 0, 0), 'owner': 'Player1', 'x': 10}, {'y': 21, 'etc': 'White hex owned by Player2', 'color': (1, 1, 1), 'owner': 'Player2', 'x': 10}], dtype=object) -- Robert Kern robert.kern at gmail.com "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From duncan.booth at invalid.invalid Thu Apr 20 05:00:59 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 20 Apr 2006 09:00:59 GMT Subject: Method Call in Exception References: <1145490879.789439.18030@t31g2000cwb.googlegroups.com> <1145498149.790387.289670@v46g2000cwv.googlegroups.com> Message-ID: Carl Banks wrote: > In fact a lot of Pythonistas recommend this way over the > alternative, even when you don't have to. For example, a lot of people > recommend this: > > try: > name = record.name > except AttributeError: > name = "Freddy" > > instead of this: > > if hasattr(record,"name"): > name = record.name > else: > name = "Freddy" > > In this specific case, either of these would be better written as: name = getattr(record, 'name', 'Freddy') From felipe.lessa at gmail.com Sat Apr 1 09:33:16 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Sat, 01 Apr 2006 11:33:16 -0300 Subject: newbie string conversion question In-Reply-To: <1143901061.088986.41120@v46g2000cwv.googlegroups.com> References: <1143901061.088986.41120@v46g2000cwv.googlegroups.com> Message-ID: <1143901997.6779.1.camel@kenshin> Em S?b, 2006-04-01 ?s 06:17 -0800, Rohit escreveu: > As part of a proprietary socket based protocol I have to convert a > string of length 10, > > say, "1234567890" > > to send it as 5 characters such that their hex values are > > 0x21 0x43 0x65 0x87 0x09 > > (Hex value of each character is got by transposing two digits at a > time) > > How can I do this in python? I would like the result to be available > as a string since I am concatenating it to another string before > sending it out. You mean: >>> a = "1234567890" >>> b = [] >>> for i in range(len(a)/2): ... b.append(chr(int(a[i*2:i*2+2][::-1], 16))) ... >>> b = ''.join(b) >>> print b !Ce? >>> print repr(b) '!Ce\x87\t' >>> print [ord(x).__hex__() for x in b] ['0x21', '0x43', '0x65', '0x87', '0x9'] ?? But I'm not sure if this is the best solution... > Thanks, > Rohit HTH, -- Felipe. From steve at REMOVETHIScyber.com.au Thu Apr 6 19:39:21 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Fri, 07 Apr 2006 09:39:21 +1000 Subject: output formatting for user-defined types References: <1144283268.217968.316100@i39g2000cwa.googlegroups.com> <1144287077.109309.16300@z34g2000cwc.googlegroups.com> <1144346706.300959.123610@i40g2000cwc.googlegroups.com> Message-ID: On Thu, 06 Apr 2006 11:05:06 -0700, Russ wrote: >>Really, your response seems a little bizarre to me, given that __float__ >>is the defined way in which float() gets a value from an instance, and >>float() is what the % operator calls when it encounters a '%f' in the >>format string. > > My class represents physical scalars with units. If I allow arbitrary > conversion to float, then the user can pass any units to trig > functions. But trig functions expect radians, so passing any other unit > (e.g., degrees or meters) is an error. I'm sorry, your system of units doesn't allow trig functions to operate on degrees? I presume you don't allow grads either. What about steradians or other arbitrary measures of angle or solid angle? Sounds like an awfully limited system of units to me. > To prevent such errors, I allow > conversion to float only when the units are actually radians (or > dimensionless). That is just one of several reasons for preventing > arbitrary conversion to float, but I won't go into the others here. Well, here are three reasons for allowing it: (1) It will make your job as programmer easier. (2) It will be useful for people to take one of your units, convert it to a float (or extract the scalar part), pass that to some other module's function, then convert the answer back to the appropriate unit. (3) You're not my mother. If I want to shoot myself in the foot by extracting the scalar part of one of your precious units and then doing inappropriate things to it, that's absolutely none of your business. I suggest another approach: play nice with the rest of Python by allowing people to convert your units into strings and floats. Once they have explicitly done so, it isn't your problem if they want to add 35 metres to 18 kilograms and convert the answer into minutes. -- Steven. From felipe.lessa at gmail.com Fri Apr 14 14:20:06 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Fri, 14 Apr 2006 15:20:06 -0300 Subject: instance variable weirdness In-Reply-To: References: <1145031518.658261.324540@e56g2000cwe.googlegroups.com> Message-ID: <1145038806.10779.17.camel@kenshin.CASA> Em S?b, 2006-04-15 ?s 04:03 +1000, Steven D'Aprano escreveu: > Sometimes you want the default to mutate each time it is used, for example > that is a good technique for caching a result: > > def fact(n, _cache=[1, 1, 2]): > "Iterative factorial with a cache." > try: > return _cache[n] > except IndexError: > start = len(_cache) > product = _cache[-1] > for i in range(start, n+1): > product *= i > _cache.append(product) > return product I prefer using something like this for the general case: def cached(function): """Decorator that caches the function result. There's only one caveat: it doesn't work for keyword arguments. """ cache = {} def cached_function(*args): """This is going to be replaced below.""" try: return cache[args] except KeyError: cache[args] = function(*args) return cache[args] cached_function.__doc__ = function.__doc__ cached_function.__name__ = function.__name__ return cached_function And for this special case, something like: def fact(n): "Iterative factorial with a cache." cache = fact.cache try: return cache[n] except IndexError: start = len(cache) product = cache[-1] for i in range(start, n+1): product *= i cache.append(product) return product fact.cache = [1, 1, 2] This may be ugly, but it's less error prone. Also, we don't expose the cache in the function's argument list. -- Felipe. From pmartin at snakecard.com Mon Apr 3 14:19:07 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Mon, 03 Apr 2006 13:19:07 -0500 Subject: Registration Code References: Message-ID: Hi, A suggestion: I would use encryption (ex: AES): Hide a secret key in your code and generate an encrypted (readable: ex 07 7B 6F ....) version of the correct info (such as full release, or demo expire in ...) with that very same key. Have your software input that encrypted info (some GUI dialog box), decypher the info then act accordingly. The trick is: where to store that ? I would use some binary data file (encrypted bziped pickle ?) with a hash or CRC built in to prevent obvious tampering. Hope that helps, Philippe Math wrote: > Hello, > > I wonder if I can ask this particular question here... > I'm writing this piece of Python Software and I'm almost done...:-) > But now I want the end-user to register this software with a registration > code or perhaps something like an evaluation demo version which expires > after some period of time... > Is this the right place to ask or does anybody know where to look for more > on the subject? > > Thanks From scott.daniels at acm.org Mon Apr 3 12:20:46 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 03 Apr 2006 09:20:46 -0700 Subject: binascii.a2b_binary In-Reply-To: References: Message-ID: <443148a6$1@nntp0.pdx.net> Ed Swarthout wrote: > Why is there no binascii.a2b_binary(bitstr) which returns the binary data > represented by the bit string? Like: > >>>> binascii.a2b_binary('0011001100110101') > '35' > perl has pack("B*", "0011001100110101"); What, you mean like: int('0011001100110101', 2) Which you could show as: hex(int('0011001100110101', 2)) I guess because Python is not so wonderful as Perl. Apparently Python stupidly forgot to follow Perl's great naming conventions. --Scott David Daniels scott.daniels at acm.org From __peter__ at web.de Tue Apr 4 09:22:29 2006 From: __peter__ at web.de (Peter Otten) Date: Tue, 04 Apr 2006 15:22:29 +0200 Subject: warning users of problems with logging References: <1144155093.493100.232740@i39g2000cwa.googlegroups.com> Message-ID: Chris Curvey wrote: > The following code exists in logging/config.py > > handlers[hand] = h > except: #if an error occurs when instantiating a handler, too bad > pass #this could happen e.g. because of lack of privileges > > The problem here is that if something did go wrong instantiating the > handler, you have no idea what the problem was (permissions, syntax > error, wrong parameters), and later on you get a message like: > > Traceback (most recent call last): > File "c:\python24\lib\logging\config.py", line 151, in fileConfig > log.addHandler(handlers[hand]) > KeyError: 'default' > > I propose that we change the code so that we have a fighting chance of > figuring out what's going on, like this: > > handlers[hand] = h > except Exception, e: #if an error occurs when instantiating a > handler, too bad > print e #this could happen e.g. because of > lack of privileges > > But I'm not sure if a "print" statement is the best way to go about it. I think this is fixed in subversion, see http://svn.python.org/view/python/trunk/Lib/logging/config.py?rev=42074&r1=38949&r2=42074 Peter From diffuser78 at gmail.com Fri Apr 7 15:41:29 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 7 Apr 2006 12:41:29 -0700 Subject: Newbie wxPython questions. In-Reply-To: <1144431488.217852.132790@j33g2000cwa.googlegroups.com> References: <1144431488.217852.132790@j33g2000cwa.googlegroups.com> Message-ID: <1144438889.111109.20490@u72g2000cwu.googlegroups.com> I am also a newbie and learning like you are. I was wondering if do you know any wxPython forum just for GUIs ? Good luck with your project and hope that some guru helps us out. From nico at netsys.co.za Wed Apr 12 05:27:30 2006 From: nico at netsys.co.za (Nico Kruger) Date: Wed, 12 Apr 2006 11:27:30 +0200 Subject: Problem with spawning an external process Message-ID: <1144834050.3376.35.camel@notamc2.snetsys.co.za> I want to execute a command (in this case, and it seems to be significant, a Java program) in a thread in Python. When I execute the java binary in the main python thread, everything runs correctly. But when I try and execute java in a thread, java segfaults. I am using Python 2.3.3 and trying to run the java binary from the 1.4.2 SDK from Sun. I have tried executing some arbitrary C program that I wrote, and it works fine in the main thread and the started thread. The problem seems to be specific to the Java binary. Here is the example code: --- START CODE --- import os import popen2 import time import select import threading # Change these to suit your system PATH = '/home/nico/j2sdk1.4.2/bin/java' #PATH = '/home/nico/j2sdk1.4.2/bin/java -invalid_arg' def get_ret(status): signal = status & 0xff if signal == 0: retcode = status >> 8 else: retcode = 0 return signal,retcode print "In main thread" # Using spawn pid = os.spawnl(os.P_NOWAIT,PATH,PATH) ret = os.waitpid(pid,0) print "PID: %i signal: %i return code: %i" % (ret[0],get_ret(ret[1])[0],get_ret(ret[1])[1]) class TestThread(threading.Thread): def run(self): # Using spawn pid = os.spawnl(os.P_NOWAIT,PATH,PATH) ret = os.waitpid(pid,0) print "PID: %i signal: %i return code: %i" % (ret[0],get_ret(ret[1])[0],get_ret(ret[1])[1]) print "In Thread" TestThread().start() print "Waiting..." time.sleep(2) print "...Finished" ---- END CODE ---- Here is the output that I get on my machine: [nico@ script]$ python testcrash2.py In main thread PID: 32107 signal: 0 return code: 1 In Thread PID: 32116 signal: 11 return code: 0 You will notice that in the main thread, the program executes correctly (return code 1, signal 0). When the command is executed in the thread, it segfaults (signal 11). The second PATH= line calls Java with an invalid argument. In this case, it does not crash in the thread. I have tried a fork() and then os.execv in the thread as well, and get the same behaviour. I would appreciate it if someone with both Java and Python could try and run this sample and report back. Any suggestions would be welcome, as this is quite the showstopper for me at the moment. I am sure I am missing something totally obvious... Thanks in advance, Nico. -- NetSys International (Pty) Ltd. Tel : +27 12 349 2056 Fax : +27 12 349 2757 Web : http://www.netsys.co.za P.O. Box 35798, Menlo Park, 0102, South Africa ---- The information contained in this communication is confidential and may be legally privileged. It is solely for use of the individual or entity to whom is addressed and others authorised to receive it. If you are not the intended recipient you are hereby notified that any disclosure, copying, distribution or taking of any action in reliance on the contents of this information is strictly prohibited and may be unlawful. This Message has been scanned for viruses and dangerous content by the NetSys International Mail Scanner and is believed to be clean. From Andreas.Ames at comergo.com Tue Apr 4 11:04:32 2006 From: Andreas.Ames at comergo.com (Ames Andreas) Date: Tue, 4 Apr 2006 17:04:32 +0200 Subject: How to get pyMinGW? Message-ID: <552B6B925278EF478EA8887D7F9E5AC363EDC1@tndefr-ws00024> Hi all, the download link on http://jove.prohosting.com/iwave/ipython/pyMinGW.html seems to be broken. Can anybody provide another link? Is there a current version for python 2.4.3 available? TIA, aa -- Andreas Ames | Programmer | Comergo GmbH | Voice: +49 69 7505 3213 | ames AT avaya . com From fredrik at pythonware.com Sat Apr 15 16:41:43 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 15 Apr 2006 22:41:43 +0200 Subject: How to Convert a string into binary References: Message-ID: "HNT20" wrote: > i am new to python language. i am working on a gnuradio project where it > uses python as the primary programming language. i am trying to convert > a message, text, or numbers into binary code so that i can process it. umm. characters and numbers are stored in binary code, inside your com- puter. what exactly makes you think you have to convert them to binary strings in order to process them ? From fulvio at pc.jaring.my Wed Apr 12 06:29:12 2006 From: fulvio at pc.jaring.my (Fulvio) Date: Wed, 12 Apr 2006 18:29:12 +0800 Subject: I meet problems while using the py2exe,Please help me! In-Reply-To: References: Message-ID: <200604121829.12937.fulvio@pc.jaring.my> Alle 10:17, mercoled? 12 aprile 2006, boyeestudio ha scritto: > What is wrong with this problem makes sense talking about the path on where cairo reside? F From rpdooling at gmail.com Fri Apr 28 12:04:00 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 28 Apr 2006 09:04:00 -0700 Subject: Using Databases in Python In-Reply-To: <1146237635.087759.312210@y43g2000cwc.googlegroups.com> References: <1146237635.087759.312210@y43g2000cwc.googlegroups.com> Message-ID: <1146240240.440044.258710@g10g2000cwb.googlegroups.com> It might be in his book, Python Web Programming, or just go to http://www.holdenweb.com/ and ask him yourself using the contact form. He's a generous contributor here. rick From brochu121 at gmail.com Thu Apr 20 19:02:26 2006 From: brochu121 at gmail.com (david brochu jr) Date: Thu, 20 Apr 2006 19:02:26 -0400 Subject: search files in a directory Message-ID: <9583ed900604201602m3f4478cdg85aa9d4e17446ea1@mail.gmail.com> Hello, I need to open every file in a directory and search for a string. What module is needed to do this and how would I go about searching each file? -------------- next part -------------- An HTML attachment was scrubbed... URL: From ldo at geek-central.gen.new_zealand Mon Apr 24 22:51:14 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 25 Apr 2006 14:51:14 +1200 Subject: Probability Problem References: Message-ID: In article , Elliot Temple wrote: >Problem: Randomly generate 10 integers from 0-100 inclusive, and sum >them. Do that twice. What is the probability the two sums are 390 apart? I think the sum would come close to a normal distribution. From kent at kentsjohnson.com Mon Apr 3 13:45:29 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Mon, 03 Apr 2006 13:45:29 -0400 Subject: String pattern matching In-Reply-To: <1143888648.234963.326000@j33g2000cwa.googlegroups.com> References: <1143888648.234963.326000@j33g2000cwa.googlegroups.com> Message-ID: <443159e6$1_1@newspeer2.tds.net> Jim Lewis wrote: > Anyone have experience with string pattern matching? > I need a fast way to match variables to strings. Example: > > string - variables > ============ > abcaaab - xyz > abca - xy > eeabcac - vxw > > x matches abc > y matches a > z matches aab > w maches ac > v maches ee > You can do this with a regular expression, actually: testText = '/abcaaab/abca/eeabcac/' import re m = re.search(r'/(?P.+)(?P.+)(?P.+)/(?P=x)(?P=y)/(?P.+)(?P=x)(?P.+)/', testText) print m.group('v', 'w', 'x', 'y', 'z') Output is: ('ee', 'ac', 'abc', 'a', 'aab') For variety, change the matches to non-greedy (.+?) and get this result: ('ee', 'bcac', 'a', 'bca', 'aab') Kent From pratik.ganguly at gmail.com Thu Apr 20 06:15:49 2006 From: pratik.ganguly at gmail.com (prats) Date: 20 Apr 2006 03:15:49 -0700 Subject: help wanted regarding displaying Japanese characters in a GUI using QT and python In-Reply-To: <1145519024.125421.327360@t31g2000cwb.googlegroups.com> References: <1145454203.770652.79920@j33g2000cwa.googlegroups.com> <1145460813.222787.302360@z34g2000cwc.googlegroups.com> <1145505985.664590.39580@t31g2000cwb.googlegroups.com> <1145515929.799871.29550@z34g2000cwc.googlegroups.com> <1145519024.125421.327360@t31g2000cwb.googlegroups.com> Message-ID: <1145528149.531579.5990@j33g2000cwa.googlegroups.com> sorry I did not correctly read your point. I works fine. Thanks for your help. I have one more query. It was said that the text I was supposed to show was written using "ISO-2022-JP" charset. But It didn't when I decoded it using that charset. But it worked fine with the "shift-jis" encoding. Is it the default charset used by python i.e. I mean to say bytes would be by default "shift-jis"? ~pratik From podi.ex at gmail.com Fri Apr 7 20:11:07 2006 From: podi.ex at gmail.com (Podi) Date: 7 Apr 2006 17:11:07 -0700 Subject: Programming Tutorial for absolute beginners In-Reply-To: <1144446815.697153.155750@v46g2000cwv.googlegroups.com> References: <1144439148.751062.16590@t31g2000cwb.googlegroups.com> <1144444872.962395.3310@z34g2000cwc.googlegroups.com> <1144446815.697153.155750@v46g2000cwv.googlegroups.com> Message-ID: <1144455067.685366.223350@g10g2000cwb.googlegroups.com> For tutorial in Windows, I think it is better to use the more user-friendly interpreter from http://activestate.com/store/languages/register.plex?id=ActivePython. Advise the user to just click on the "Next" button without submitting the optional contact information. My $0.02 From coyoteboyuk at hotmail.com Tue Apr 18 12:17:07 2006 From: coyoteboyuk at hotmail.com (Coyoteboy) Date: Tue, 18 Apr 2006 17:17:07 +0100 Subject: Speed abilities Message-ID: Ive read a few comments, the usual about it being slower,sometimes vastly slower than a C++ written item but I was wondering if its 'slow' incomparison with what I need. I'm looking at taking two arrays of 12 bytes over an ethernet connection, comparing them, recieving correction data (single byte) from another module over a pipe at approximately 900Hz and using all these with a fairly complex set of algorithms to generate a new set of 12 byte data. This has to be done in a very short time, preferably the same rate of throughput as the 900Hz. Am i asking too much of Python? I find C++/MFC fairly complex and python looked like a great alternative if it hadnt been 'flagged' as slow. Cheers J From amaltasb at gmail.com Wed Apr 12 00:48:28 2006 From: amaltasb at gmail.com (amaltasb at gmail.com) Date: 11 Apr 2006 21:48:28 -0700 Subject: executing perl script within python Message-ID: <1144817308.557404.305700@i40g2000cwc.googlegroups.com> I have few modules which are in perl, and all other scripts are in python. Is it possible to execute the perl scripts within python or import them like: Thanks From Dennis.Benzinger at gmx.net Mon Apr 24 09:37:29 2006 From: Dennis.Benzinger at gmx.net (Dennis Benzinger) Date: Mon, 24 Apr 2006 15:37:29 +0200 Subject: Update Demo/ and Tools/ directories Message-ID: <444cd49c$1@news.uni-ulm.de> Hi! I'd like to help with updating the Demo/ and Tools/ directories as it is suggested in the Python Wiki . How exactly should the directories be updated? Should it just be made sure that the demos and examples are working or should they be updated to use the newest applicable Python features (e.g. the new any/all functions)? Dennis From webraviteja at gmail.com Mon Apr 17 12:53:15 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 17 Apr 2006 09:53:15 -0700 Subject: Java Developer Exploring Python In-Reply-To: <1145290449.735642.120860@i40g2000cwc.googlegroups.com> References: <1145290449.735642.120860@i40g2000cwc.googlegroups.com> Message-ID: <1145292795.565277.288760@v46g2000cwv.googlegroups.com> >> I've traditionally been a Java developer, although I play around with LISP. For most java developers, understanding dynamic typing is a big step. Your Lisp background however would mean that you will pick up Python very quickly. >> I recently migrated to Linux and I was exploring Mono as an option for development on Linux. However, I've had some problems with the maturity and support when working with Mono. IronPython (still a beta) BTW, runs on Mono as well and you can use Mono through Python when you deem it ready. There is also Jython, which runs on the Java platform if you feel married to Java platform or class libraries. >> Is Python actively developed and supported on Linux? Yes and very well so. Many Linux distributions come with Python pre-installed and Python has quite a bit of following in the Linux crowd. Red Hat / Fedora installer - Anaconda, for example uses Python. >> Would it be a viable option for cross-platform application development? Python is a very good candidate for open source development. But then again, most open source languages these days are. The culture is a bit different though. Although Python is byte code compiled just like Java, Python programmers are not averse to using native extensions (which in most cases can be compiled painlessly on all popular platforms thanks to Python's distutils). Java programmers on the other hand generally extol 'Pure Java'. Both approaches have their own advantages and disadvantages (Swing vs SWT) and you can use either with Python. >> Can anyone recommend an open source IDE for Python that runs on Linux? Most Python IDEs are open source along with a few commercial ones. http://wiki.python.org/moin/IntegratedDevelopmentEnvironments Everyone has their favorites and you should pick your own. Since you have a Java background, PyDev is probably the best choice for you. JEdit also has a Python plugin. I just use SciTE (just an editor) most of the time. From dinov at exchange.microsoft.com Fri Apr 28 18:48:03 2006 From: dinov at exchange.microsoft.com (Dino Viehland) Date: Fri, 28 Apr 2006 15:48:03 -0700 Subject: Undocumented alternate form for %#f ? In-Reply-To: <4452743b$0$33928$ed2619ec@ptn-nntp-reader03.plus.net> Message-ID: <4039D552ADAB094BB1EA670F3E96214E02ADDF2B@df-foxhound-msg.exchange.corp.microsoft.com> Ahh, cool... Thanks for the explanation! Do you want to help develop Dynamic languages on CLR? (http://members.microsoft.com/careers/search/details.aspx?JobID=6D4754DE-11F0-45DF-8B78-DC1B43134038) -----Original Message----- From: python-list-bounces+dinov=microsoft.com at python.org [mailto:python-list-bounces+dinov=microsoft.com at python.org] On Behalf Of Dave Hughes Sent: Friday, April 28, 2006 1:00 PM To: python-list at python.org Subject: Re: Undocumented alternate form for %#f ? Dino Viehland wrote: > I'm assuming this is by-design, but it doesn't appear to be > documented: > > >>> '%8.f' % (-1) > ' -1' > >>> '%#8.f' % (-1) > ' -1.' > > > The docs list the alternate forms, but there isn't one listed for > f/F. It would seem the alternate form for floating points is > truncate & round the floating point value, but always display the . > at the end. Is that correct? The Python % operator follows the C sprintf function pretty darn closely in behaviour (hardly surprising really, though I've never peeked at the implementation). Hence "man sprintf" can provide some clues here. From man sprintf on my Linux box: # The value should be converted to an ``alternate form''. For o conversions, the first character of the output string is made zero (by prefixing a 0 if it was not zero already). For x and X conversions, a non-zero result has the string `0x' (or `0X' for X conversions) prepended to it. For a, A, e, E, f, F, g, and G conversions, the result will always contain a decimal point, even if no digits follow it (normally, a decimal point appears in the results of those conversions only if a digit follows). For g and G conversions, trailing zeros are not removed from the result as they would otherwise be. For other conversions, the result is undefined. Hence, I don't think it's the # doing the truncating here, but it certainly is producing the mandatory decimal point. If you get rid of the "." in the specification, it uses the default decimal precision (6): >>> "%8f" % (-1) '-1.000000' >>> "%#8f" % (-1) '-1.000000' No difference with the alternate specification here as the precision is non-zero. Again, from man sprintf: The precision [snip] If the precision is given as just `.', or the precision is negative, the precision is taken to be zero. This gives the minimum number of digits to appear for d, i, o, u, x, and X conversions, the number of digits to appear after the radix character for a, A, e, E, f, and F conversions, the maximum number of significant digits for g and G conversions, or the maximum number of characters to be printed from a string for s and S conversions. HTH, Dave. -- -- http://mail.python.org/mailman/listinfo/python-list From pmartin at snakecard.com Thu Apr 27 16:40:39 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Thu, 27 Apr 2006 15:40:39 -0500 Subject: OOP techniques in Python References: <1146158190.320947.108480@t31g2000cwb.googlegroups.com> <4I6dnWIRt762kMzZnZ2dnUVZ_sOdnZ2d@comcast.com> Message-ID: Duncan Booth wrote: > Philippe Martin wrote: >> Steven Bethard wrote: >>> [Please don't top-post] >> >> OK I won't, is that a general rule? (I've been top posting for quite some >> time now and it is the first time I see that warning) > > Yes. Other suggestions you might get are not to bottom post, and certainly > not (as you did elsewhere) to post your response as a signature (i.e. > following a line containing only two dashes and a space). > > The accepted way to follow up is to trim the post to which you are > responding so as to maintain sufficient context to make the post > intelligible on its own, but not to quote the entire post: most newsreader > programs will help you in this by either warning or indeed refusing to > post responses which have too many quoted lines compared with new content. > > It is perfectly reasonable if you are making several points to intersperse > your comments with other quoted sections. > > Some newsgroups use a different convention and expect top-posting without > trimming of the quoted posts, but these very much are in the minority. :-) I did try the signature for the first time today, and stopped as I get weird errors from my client and certainly do not wish to get flame just because I like a cute message. My assumption always was: 1) keep all data in the post so new viewers can understand get the full content, including the initial post 2) write on top because when you open a file, you want the chronological info on top instead of at the very bottom ... since because of 1) this could be miles away. But if the rules are otherwise then I'll just follow them. Regards, Philippe From flamesrock at gmail.com Thu Apr 6 14:21:36 2006 From: flamesrock at gmail.com (flamesrock) Date: 6 Apr 2006 11:21:36 -0700 Subject: XMLRPCLIB appears to be broken? In-Reply-To: References: <1144299571.452329.310640@j33g2000cwa.googlegroups.com> Message-ID: <1144347696.011868.268990@e56g2000cwe.googlegroups.com> Thanks for the response. I'm using IXR_library, which is one of the defato xml-rpc libs out there. It seems to be working for other people... The reason I think its a python error is because php doesn't understand lists, which is what the data is being returned as. From wildemar at freakmail.de Thu Apr 13 11:05:50 2006 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Thu, 13 Apr 2006 17:05:50 +0200 Subject: trying to grasp OO : newbie Q? In-Reply-To: <1144938934.900062.219600@i40g2000cwc.googlegroups.com> References: <1144937168.508799.67410@i40g2000cwc.googlegroups.com> <1144938934.900062.219600@i40g2000cwc.googlegroups.com> Message-ID: <443E68CE.2080504@freakmail.de> J Rice wrote: > Someone should correct me if I'm wrong but: > If > you want to change myVar for the whole class, you need to reference it > as self.myVar. > wrong: If you want to change myVar for the whole *class*, you need to reference it as Obj.myVar (prefix with classname). self.myVar will change it for that one instance only. other than that, agreed :) wildemar From s_david_rose at hotmail.com Tue Apr 25 12:38:49 2006 From: s_david_rose at hotmail.com (S. D. Rose) Date: Tue, 25 Apr 2006 12:38:49 -0400 Subject: Dell Support Web Site Automation. Message-ID: Hello all. Awhile back I was playing with win32all package to get system information from the Dell PCs. However, I'm using a win32 program, bginfo, to get the information on the PC and insert it into a MySQL database. Of the fields I'm recording, I am saving the system serial number. I was wondering if it's possible, or highly involved, to have a list of serial numbers and have a python script iterate thru and go on-line and automate the Support.Dell.Com website, inserting the serial number and choosing System Details, to be able to get the out-of-warranty date and maybe other information I can't get using bginfo or win32all. Thanks for your help! -Dave From fulvio at pc.jaring.my Sun Apr 9 03:41:08 2006 From: fulvio at pc.jaring.my (Fulvio) Date: Sun, 9 Apr 2006 15:41:08 +0800 Subject: Curses and Character Handling In-Reply-To: <1144550778.549805.19820@v46g2000cwv.googlegroups.com> References: <1144550778.549805.19820@v46g2000cwv.googlegroups.com> Message-ID: <200604091541.08317.fulvio@pc.jaring.my> Alle 10:46, domenica 09 aprile 2006, stormandstress at gmail.com ha scritto: > Does anyone know of a solution to this I still learning python, but probably some documentation is the basis of learning, rather than ask at the list. I suggest to see at http://docs.python.org/ for actual and growing python functions and/or builtins. F From rzantow at gmail.com Wed Apr 26 17:35:35 2006 From: rzantow at gmail.com (Rick Zantow) Date: Wed, 26 Apr 2006 17:35:35 -0400 Subject: do while loop References: <1146012542.166096.78690@g10g2000cwb.googlegroups.com> Message-ID: Marc 'BlackJack' Rintsch wrote in news:pan.2006.04.26.20.41.03.189115 at gmx.net: > In <1146012542.166096.78690 at g10g2000cwb.googlegroups.com>, ??? wrote: > >> suggest add do while loop in later version > > Please also suggest a clean syntax for this. :-) > Since Python already has a while : loop, I'm supposing you mean something like do: while or do: until Is that what you mean? In some languages that might be a "do x until y" loop, which I would suppose has been proposed before for Python. A clean syntax might be until : ... except that people seem to object to placing the condition specification so far from where the test would actually take place (at the bottom of the loop). I don't have a problem with that, but I can see why many would. It doesn't seem Pythonic somehow. There was a long thread about a loop-and-a-half construction where some of this was discussed, though I don't have a link for that. In any case, what would you want to do that you can't do (in some way) now? If you have a compelling use case, you could get a bit more attention than merely offering a suggested expansion of the language. -- rzed From larry.bates at websafe.com Tue Apr 11 09:58:25 2006 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 11 Apr 2006 08:58:25 -0500 Subject: waiting for file lock? In-Reply-To: <1144725394.174399.4030@j33g2000cwa.googlegroups.com> References: <1144725394.174399.4030@j33g2000cwa.googlegroups.com> Message-ID: <25GdnaeZYvdyKKbZnZ2dnUVZ_t6dnZ2d@comcast.com> s99999999s2003 at yahoo.com wrote: > hi > i need to go into a directory to grab some files and do some > processing. > The thing is, i need to wait till the process that generates the files > in that directory to finish > before i can grab the files. eg if file A is being generated and has > not finished, my python script will not go into the directory. > how can i check that file A has actually finished? thanks > I don't know if you have control of the program that is writing the file. If you do, change it so that it writes the files with some temporary name and renames them when it is done. Since rename is basically atomic, the file won't show up as a candidate to be processed until it is actually completed. Something like: Process A -> writes files into directory with .tmp extensions. Process B -> scans directory but never processes anything with .tmp extensions Process A -> renames file.tmp to file when it is finished so that process B picks it up on its next scan. -Larry Bates From duncan.booth at invalid.invalid Sat Apr 22 16:41:09 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 22 Apr 2006 20:41:09 GMT Subject: Lamdba forms References: <1145492986.738200.229690@i39g2000cwa.googlegroups.com> <1145523944.375146.275050@z34g2000cwc.googlegroups.com> <1145540823.159142.213180@z34g2000cwc.googlegroups.com> Message-ID: Ant wrote: > Fair enough. I've just found this as well, which implies that lambda > isn't being killed off in 3.0: > > http://www.python.org/dev/peps/pep-3100/ > > In particular: > "Lambdas will have to be parenthesized [23]" > Also: http://www.python.org/doc/essays/ppt/accu2006/Py3kACCU.ppt slide 14. From cretin at des.alpes.ch Wed Apr 12 14:55:19 2006 From: cretin at des.alpes.ch (Azolex) Date: Wed, 12 Apr 2006 20:55:19 +0200 Subject: Looking for a language/framework In-Reply-To: <1hcycad.ry2k0p5lns6lN%aleaxit@yahoo.com> References: <1143559444.045808.38790@u72g2000cwu.googlegroups.com> <1hcwg6n.b3jwv5xq910tN%aleaxit@yahoo.com> <122lav32plu1355@corp.supernews.com> <1hcycad.ry2k0p5lns6lN%aleaxit@yahoo.com> Message-ID: <443d4d1d$1_6@news.bluewin.ch> Alex Martelli wrote: > Jeffrey Froman wrote: > >> Alex Martelli wrote: >> >>> I've never seen an "object-relational mapping" (technical >>> term for cruft that tries to avoid people having to learn and use SQL) >>> which doesn't drive me into a murderous, foam-at-mouth rage in a very >>> short time -- I WANT my SQL, I LOVE SQL, it's WAY more powerful >>> and suitable for access to data than all those simulated "OO DB" people >>> lay on top of it >> How refreshing to discover I'm not the only person on earth who feels this >> way. > > Hey, there's two of us, if this was Italy we could found a new political > party!-) Me too - I rather prefer using SQL to ORMs, *but* my basic reason is that I find it ridiculous for python ORMs to claim they lower sql/python impedance while they lead away from the python construct that's the obvious fit in the role of sql representative : I mean generator expressions. And OK, generator expressions aren't quite as powerful as SQL, but... well, maybe they can yet be perfected. From harry.g.george at boeing.com Tue Apr 18 07:33:45 2006 From: harry.g.george at boeing.com (Harry George) Date: Tue, 18 Apr 2006 11:33:45 GMT Subject: Speed abilities References: Message-ID: "Coyoteboy" writes: > Ive read a few comments, the usual about it being slower,sometimes vastly > slower than a C++ written item but I was wondering if its 'slow' > incomparison with what I need. I'm looking at taking two arrays of 12 bytes > over an ethernet connection, comparing them, recieving correction data > (single byte) from another module over a pipe at approximately 900Hz and > using all these with a fairly complex set of algorithms to generate a new > set of 12 byte data. This has to be done in a very short time, preferably > the same rate of throughput as the 900Hz. Am i asking too much of Python? I > find C++/MFC fairly complex and python looked like a great alternative if it > hadnt been 'flagged' as slow. > > Cheers > J > > There is no way to tell from this info. This is a real-time problem. If you assume 1GHZ CPU, 10 clks/instruction, 10000 instructions/event then you require 0.001 sec/event. 900Hz event rate means you only have 0.0011 sec/event available, which is the same order of magnitude. Chances are, variation in the event rate or in the OS response time would violate this small safety factor, even if the assumptions were dead on. So you need a faster machine or fewer instructions. Some instructions will be used in the OS and interface stack, no matter what language you use. Some will be used in your "fairly complex set of algorithms". You may have used up your 10000 instructions without getting around to Python. Even assembler might be too slow. If you did implement in Python and found it was too slow by a moderate factor (e.g., you could only handle 500Hz event rate), then you can stay in python to explore alternative implementations. E.g., multiple processors in parallel, more efficient algorithms, ctypes or pyrex to speed up the python. In terms of the overall project notion-to-delivery duration, implementing in Python might be the right first step on your way to an assembler implementation. -- Harry George PLM Engineering Architecture From fredrik at pythonware.com Thu Apr 6 05:52:59 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 6 Apr 2006 11:52:59 +0200 Subject: How to catch python's STDOUT References: <1144314684.986767.131650@j33g2000cwa.googlegroups.com> <1144316619.928494.224270@t31g2000cwb.googlegroups.com> Message-ID: praveenkumar.117 at gmail.com wrote: > I have python script in which i have some print statements. > I dont want the outputs of print to be displayed on the console > since it is used my fellow-workers > But i need those prints for debugging purpose > So some how i want to capture those prints > can u please suggest you can print directly to a log file: mylogfile = open("logfile.txt", "a") print >>mylogfile, "my log message" or you can replace sys.stdout (and/or sys.stderr) with the log file object: import sys sys.stdout = sys.stderr = open("logfile.txt", "a") or you can use the "logging" module: http://docs.python.org/lib/module-logging.html etc. hope this helps! From nobody at 127.0.0.1 Sun Apr 23 17:55:53 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Sun, 23 Apr 2006 21:55:53 GMT Subject: getattr from local scope In-Reply-To: <1145827050.347326.84980@t31g2000cwb.googlegroups.com> References: <1145827050.347326.84980@t31g2000cwb.googlegroups.com> Message-ID: rob.haswell at gmail.com wrote: > Basically my application has a scheduler which stores names of functions > defined in the "schedule" module in a database, to be run on certain > days. Every night I call schedule.RunSchedule, which grabs all the rows on > the database that have to be run now, and I want to call the function > defined the same module according to that string. I know that sys.modules[__name__] gives the module object for the current module. You could do: m = sys.modules[__name__] # M now current module object func = m.__dict__ [fs] # func has function named by string fs func() If func isn't in the current module, replace __name__ with 'Foo'. Add try/catch as appropriate in case fs doesn't exist in module M. If your database stores the function arguments in the same string as the function name, you'll have to parse them out separately. I make no claims to this solution being optimal, as it pretty much stretches my knowledge of Python modules and reflection. From wolfgang.eichler at ca.com Thu Apr 27 11:17:24 2006 From: wolfgang.eichler at ca.com (eicwo01) Date: 27 Apr 2006 08:17:24 -0700 Subject: Get all attributes of a com object Message-ID: <1146151043.933987.145080@t31g2000cwb.googlegroups.com> Without to know the names, is it possible to dump all attributes of a com object? from win32com.adsi import * objDom = ADsOpenObject("LDAP:/ ... print ???"all attributes"??? of objDom Thanks Wolfgang From pwatson at redlinepy.com Sun Apr 30 16:08:24 2006 From: pwatson at redlinepy.com (Paul Watson) Date: Sun, 30 Apr 2006 15:08:24 -0500 Subject: installing pyodbc In-Reply-To: <1144781232.762308.177500@z34g2000cwc.googlegroups.com> References: <1144781232.762308.177500@z34g2000cwc.googlegroups.com> Message-ID: <44551938.8030800@redlinepy.com> timw.google wrote: > I just downloaded the pyodbc source to try and install on my Linux FC3 > box. I see that there is a setup.py file, but when I try to do a > 'python setup.py build' (or just 'python setup.py') I get > > Traceback (most recent call last): > File "setup.py", line 27, in ? > revision = latest_revision('.') > File "setup.py", line 25, in latest_revision > return int(output) > ValueError: invalid literal for int(): exported > > The README.txt doesn't really say anything about how to install, exept > that the easiest way is to use the Windows installer. That's fine for > Windows, but what about Linux? > > Thanks for any help. Have you read the http://sourceforge.net/projects/pyodbc/ summary page where the "Operating System" indicates which platforms are supported? That might be relevant information. From markscala at gmail.com Mon Apr 24 13:16:01 2006 From: markscala at gmail.com (markscala at gmail.com) Date: 24 Apr 2006 10:16:01 -0700 Subject: error In-Reply-To: <1145898225.802921.113780@j33g2000cwa.googlegroups.com> References: <1145886838.594093.102670@j33g2000cwa.googlegroups.com> <4b44hbFt29klU1@uni-berlin.de> <1145895649.203923.101370@u72g2000cwu.googlegroups.com> <1145898225.802921.113780@j33g2000cwa.googlegroups.com> Message-ID: <1145898961.287128.296000@i39g2000cwa.googlegroups.com> thanks for the help. cheers. From zetamu2 at yahoo.com Fri Apr 28 17:10:13 2006 From: zetamu2 at yahoo.com (John) Date: Fri, 28 Apr 2006 21:10:13 GMT Subject: popen3 on windows Message-ID: Hello. Can anyone tell me how to get p.poll() or a workaound to work when using popen3() on windows? I use python 2.3. I am trying to launch a command window to execute a command and then check periodically to see if the command has finished executing. If it has not finished after a given amount of time, I want to close the process. Is this possible on windows? p = win32pipe.popen3('command') will create the tuple of files p, but none have a poll() attribute. p[1].read() will hang up if the command has not finished. Any suggestions? The other alternative is that I use the above to start the command and then use another os command to see if my process is running in the background on windows. If it is, then perhaps I can close it if it if need be. Thanks. From uymqlp502 at sneakemail.com Sat Apr 8 00:39:24 2006 From: uymqlp502 at sneakemail.com (Russ) Date: 7 Apr 2006 21:39:24 -0700 Subject: output formatting for user-defined types References: <1144283268.217968.316100@i39g2000cwa.googlegroups.com> <1144287077.109309.16300@z34g2000cwc.googlegroups.com> <1144346706.300959.123610@i40g2000cwc.googlegroups.com> <1144368862.466490.58240@v46g2000cwv.googlegroups.com> Message-ID: <1144471164.307751.153790@z34g2000cwc.googlegroups.com> Let me just revise earlier my reply slightly. >But in any case, I suspect you do automatically convert units. What do you >do in this case: Yes, I do automatically convert units, but I only do correct conversions. Conversion from any unit other than radian to a dimensionless float is incorrect, so I don't do it automatically. >x = 45*ft >y = 16*m >z = x+y >Do you raise an error? I said in the previous reply that this works fine. Actually, I don't think that is true with the current version, but that is only because I did not include a meter/feet conversion in the two sample configuration files that are provided. It is trivial matter of two lines. From paolopantaleo at gmail.com Sun Apr 23 08:45:49 2006 From: paolopantaleo at gmail.com (Paolo Pantaleo) Date: Sun, 23 Apr 2006 14:45:49 +0200 Subject: list example In-Reply-To: References: <1145737240.221433.176160@i40g2000cwc.googlegroups.com> Message-ID: <83e8215e0604230545u20c1c9e8mcd4620c2d1b0d24a@mail.gmail.com> 2006/4/22, Edward Elliott : > No substantive problems. The str() calls are unnecessary, print calls > list.__str__ already. You can replace the loop with list comprehensions or > slices. Same result, a bit more succinct. See these pages for more: > > http://docs.python.org/lib/typesseq.html > http://docs.python.org/tut/node7.html (section 5.1.4) > > Thnx, I didn't catch the use of colon in print... Thanks to the other posting, but actually I want to write some code that one can modify to his own needings PAolo From michele.simionato at gmail.com Tue Apr 11 04:56:59 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 11 Apr 2006 01:56:59 -0700 Subject: About classes and OOP in Python In-Reply-To: References: <1144678797.749000.155010@t31g2000cwb.googlegroups.com> Message-ID: <1144745819.173322.174040@z34g2000cwc.googlegroups.com> Roy Smith wrote: > That being said, you can indeed have private data in Python. Just prefix > your variable names with two underscores (i.e. __foo), and they effectively > become private. Yes, you can bypass this if you really want to, but then > again, you can bypass private in C++ too. Wrong, _foo is a *private* name (in the sense "don't touch me!"), __foo on the contrary is a *protected* name ("touch me, touch me, don't worry I am protected against inheritance!"). This is a common misconception, I made the error myself in the past. Michele Simionato From mandelin at cs.berkeley.edu Mon Apr 10 16:46:33 2006 From: mandelin at cs.berkeley.edu (Dave Mandelin) Date: 10 Apr 2006 13:46:33 -0700 Subject: GridBagSizer References: <1144660584.283396.205520@u72g2000cwu.googlegroups.com> Message-ID: <1144701993.285309.131080@t31g2000cwb.googlegroups.com> Probably just that GridBagSizer is complicated and confusing, and you can usually get what you want more easily and maintainably by nesting simpler sizers like Box and FlexGrid. -- Want to play tabletop RPGs with your friends online? Try RPZen: http://koboldsoft.com From brieuc.gorin at gmail.com Thu Apr 13 10:56:02 2006 From: brieuc.gorin at gmail.com (brieuc.gorin at gmail.com) Date: 13 Apr 2006 07:56:02 -0700 Subject: py2exe wx.lib.activexwrapper win32com In-Reply-To: <1144932764.700816.129020@t31g2000cwb.googlegroups.com> References: <1144932764.700816.129020@t31g2000cwb.googlegroups.com> Message-ID: <1144940162.918735.219380@i39g2000cwa.googlegroups.com> it doesn't work only under windows 98 first edition, still don't know how to fix this. From niemand.leermann at thomas-guettler.de Tue Apr 4 10:28:50 2006 From: niemand.leermann at thomas-guettler.de (Thomas Guettler) Date: Tue, 04 Apr 2006 16:28:50 +0200 Subject: Framework/module for generating HTML documentation References: Message-ID: Hi, I have a little script which creates numbers by scanning the tags. But up to now it only works for single file. But it would be easy to split e.g. on every

tag. http://www.thomas-guettler.de/scripts/number-html-headings.py.txt Am Tue, 04 Apr 2006 17:01:43 +0900 schrieb Ryan Ginstrom: > E.g., I want to go from something like this: >

Introduction

>

Some text

>

Getting Started

>

Some text

>

Installation

>

Some text. See

Getting Started
for details.

> > To this: > [index.html] >

Contents

> 1. Introduction > 2. Getting Started >
> 2.1. Installation >
-- Thomas G?ttler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de Spam Catcher: niemand.leermann at thomas-guettler.de From sijben at eemvalley.com Thu Apr 20 04:10:06 2006 From: sijben at eemvalley.com (Paul Sijben) Date: Thu, 20 Apr 2006 10:10:06 +0200 Subject: UDP performance In-Reply-To: <1145519675.476745.119480@g10g2000cwb.googlegroups.com> References: <44473787$0$31643$e4fe514c@news.xs4all.nl> <1145519675.476745.119480@g10g2000cwb.googlegroups.com> Message-ID: <444741dc$0$31652$e4fe514c@news.xs4all.nl> Serge Orlov wrote: > Paul Sijben wrote: >> I am stumped by the following problem. I have a large multi-threaded >> server accepting communications on one UDP port (chosen for its supposed >> speed). >> >> I have been profiling the code and found that the UDP communication is >> my biggest drain on performance! Communication where the client and the >> server are on the same machine still takes 300ms or sometimes much more >> per packet on an Athlon64 3000+ running Linux (Fedora Core 5 x64). > > [snip] > >> buf, address = socket.recvfrom(8192) > > I'm not an expert here, but I AFAIK UDP packet size should be kept > below 512 bytes otherwise it can cause fragmentation and hence all the > slow stuff like acknoledgements, timeouts, etc... > good point in general but in practice they are in this case. but this is less of a problem on the loopback interface anyway. From wildemar at freakmail.de Thu Apr 13 08:20:20 2006 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Thu, 13 Apr 2006 14:20:20 +0200 Subject: Why new Python 2.5 feature "class C()" return old-style class ? In-Reply-To: References: <1144752553.305591.88050@j33g2000cwa.googlegroups.com> <443bbdbe$0$15517$626a54ce@news.free.fr> <443c22d1$0$11341$636a55ce@news.free.fr> Message-ID: <443E4204.2020003@freakmail.de> Petr Prikryl wrote: > My question: Could the old classes be treated in > a new Python treated as new classes with "implicit" > base object? (I know the Zen... ;-) > > Example: I use usually a very simple classes. When I add > "(object)" to my class definitions, the code continues to > works fine -- plus I have new features to use. > Why this cannot be done automatically? What could > be broken in the old code if it was threated so? > > Thanks for explanation, > pepr Well, apparently this is exactly whats going to happen in the future, but not until Python 3.0. Simple as that. But I guess I'll just keep adding the (object) appendix even after that, so all my class definitions get syntax highlighting. Also it clarifies "what the score is" (to paraphrase Bender). wildemar From no-spam at no-spam-no-spam.com Tue Apr 18 11:26:15 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Tue, 18 Apr 2006 17:26:15 +0200 Subject: pywin32 : scheduled weakup from standby/hiberate ? Message-ID: On Windows the task scheduler tool can program (the BIOS?) to weak up the machine from standby/hibernate at certain pre-configured times. Can this be done directly through the (py)win32 API? robert From Aiwass333 at gmail.com Thu Apr 27 17:52:52 2006 From: Aiwass333 at gmail.com (RunLevelZero) Date: 27 Apr 2006 14:52:52 -0700 Subject: Regular Expression help In-Reply-To: <1146173313.663586.258980@i39g2000cwa.googlegroups.com> References: <1146162048.903980.281290@y43g2000cwc.googlegroups.com> <1146172456.106195.243160@j33g2000cwa.googlegroups.com> <1146172914.383277.259940@u72g2000cwu.googlegroups.com> <1146173313.663586.258980@i39g2000cwa.googlegroups.com> Message-ID: <1146174772.630810.244550@v46g2000cwv.googlegroups.com> Interesting... thank you. From jstroud at ucla.edu Thu Apr 27 18:09:22 2006 From: jstroud at ucla.edu (James Stroud) Date: Thu, 27 Apr 2006 15:09:22 -0700 Subject: inheriting type or object? In-Reply-To: References: Message-ID: Fabiano Sidler wrote: > Hi folks! > > As stated in subject, how do I decide wether to inherit or > ? Whenever I want to intantiate my derived type, I taked > here, but inheriting from consequently would > be reasonable in cases of pure static objects (i.e. objects/types using > staticmethods exclusively), for whose I would prefer toplevel code outside > a class definition in python, since python does not oblige programmers to > use classes (like JAVA et. al.). > > So, finally, my question is: Is there a design pattern, that makes > a reasonable (direct) base type for new objects/types? > Right now, I can't see any. > > Thank you for answering! > Greetings, > F. Sidler I don't think these are the recommended usages for type and object. Usually class factories (metaclasses) inheret from type and classes that instantiate objects inheret from object. I think this might clear up the issue: http://www.python.org/download/releases/2.2/descrintro/ James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From wildemar at freakmail.de Wed Apr 19 09:57:18 2006 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Wed, 19 Apr 2006 15:57:18 +0200 Subject: semi-[OT]: adding a reply-to line to these mails? In-Reply-To: <87r73uh594.fsf@benfinney.id.au> References: <4444CD12.7080807@freakmail.de> <87r73uh594.fsf@benfinney.id.au> Message-ID: <444641BE.9050601@freakmail.de> Ben Finney wrote: > Wildemar Wildenburger writes: > > >> I've noticed that I replied to individual posters' private addresses >> several times now ... >> > > That's a much preferable, and much more easily corrected, error than > the alternative: replying to the entire group what was intended only > for the individual in private. > > >> So a quick note to the admin(s): see topic ;) >> > > The Reply-To header field is to be set by an individual on their own > messages, to indicate where a *private* reply should go. > > I guess that means no, huh? :) From peter at engcorp.com Tue Apr 11 06:52:31 2006 From: peter at engcorp.com (Peter Hansen) Date: Tue, 11 Apr 2006 06:52:31 -0400 Subject: How to initiate HotSync of Palm device? In-Reply-To: <1144725904.731539.142760@u72g2000cwu.googlegroups.com> References: <1144725904.731539.142760@u72g2000cwu.googlegroups.com> Message-ID: dylpkls91 wrote: > I know how to get the program to wait for a process to finish, but I'm > having trouble initiating a HotSync through Python. While poking around > the Palm Desktop and HotSync system files, I found a DLL called "HSAPI" > with the title "HotSync API", but I'm not sure if this is what I need. > There is no HotSync COM type library in my PythonWin COM browser. Have you inquired in a Palm forum to learn what the correct method is for doing this? Surely if there's a way to do it, using that same approach from Python would be the simplest thing to do. (In other words, unless there's a ready-made Python module that does this, and I suspect you've googled for that already, then this is a Palm question and not really a Python one...) -Peter From onurb at xiludom.gro Wed Apr 5 08:14:40 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 05 Apr 2006 14:14:40 +0200 Subject: Filters like old skool Jive, Fudd, Valspeak... Text transformation in Python In-Reply-To: <1144237161.700762.75630@e56g2000cwe.googlegroups.com> References: <1144237161.700762.75630@e56g2000cwe.googlegroups.com> Message-ID: <4433b3f1$0$24162$636a55ce@news.free.fr> dananrg at yahoo.com wrote: (snip part about filters) > Any good "generators" written in Python? I'd like to roll me one of > these as well; e.g. execute the program and it will create a few > paragraphs of text in the jargon of a discipline, subdiscipline, > subculture, etc. Anyone know what I'm talking about? There's a Kant generator example in Dive Into Python: http://diveintopython.org/xml_processing/index.html -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From rpdooling at gmail.com Wed Apr 26 17:37:42 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 26 Apr 2006 14:37:42 -0700 Subject: print names of dictionaries In-Reply-To: <1146087114.638400.149890@v46g2000cwv.googlegroups.com> References: <1146085818.242086.206290@e56g2000cwe.googlegroups.com> <1146087114.638400.149890@v46g2000cwv.googlegroups.com> Message-ID: <1146087462.563303.3570@j33g2000cwa.googlegroups.com> Wow, That's food for thought. Thanks. I see what they mean about change of approach. I'll just stick a key in each dictionary called, er, name with its name value. Thank you! rick From tim.hochberg at ieee.org Mon Apr 10 15:45:49 2006 From: tim.hochberg at ieee.org (Tim Hochberg) Date: Mon, 10 Apr 2006 12:45:49 -0700 Subject: unboundlocalerror with cgi module In-Reply-To: <443aaa76$1_3@newspeer2.tds.net> References: <1282490.JcRWy2CgMu@teancum> <443aa178$1_1@newspeer2.tds.net> <443aaa76$1_3@newspeer2.tds.net> Message-ID: Kent Johnson wrote: > Tim Hochberg wrote: > >>Kent Johnson wrote: >> >>>David Bear wrote: >>> >>> >>>>I'm attempting to use the cgi module with code like this: >>>> >>>>import cgi >>>>fo = cgi.FieldStorage() >>>># form field names are in the form if 'name:part' >>>>keys = fo.keys() >>>>for i in keys: >>>> try: >>>> item,value=i.split(':') >>>> except NameError, UnboundLocalError: >>>> print "exception..." >>>> item,value=(None,None) >>>>return(item,value) >>>> >>>>However, the except block does not seem to catch the exception and an >>>>unboundlocalerror is thrown anyway. What am I missing? >>>> >>> >>>I don't know why you would get an UnboundLocalError from the above code, >>>but the correct syntax is >>> except (NameError, UnboundLocalError): >> >>One possibility is that there are no keys. Then the loop finishes >>without ever setting item or values. This would give an unbound local >>error. I assume that the OP would have noticed that in the traceback, >>but perhaps he missed it. > > > I think that would be a NameError for the code shown because item and > value are global variables. Note that there is a return at the end of the posted code, so I suspect that this problem actually occurs in a function somewhere and the OP "simplified" things in order to post it. But anyway you raise a good point that > perhaps the reason the exception is not being caught is because it is > raised by code outside the scope of the try. > > Also UnboundLocalError is a subclass of NameError so catching NameError > should catch UnboundLocalError as well. Good point. -tim From aleaxit at yahoo.com Sun Apr 23 12:36:02 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 23 Apr 2006 09:36:02 -0700 Subject: MS VC++ Toolkit 2003, where? Message-ID: <1he8pss.1yk7ug81rv7pw2N%aleaxit@yahoo.com> So, I thought I'd tool up to let me build and test Python extensions on Windows (as well as Mac and Linux) -- I'm trying out Parallels Workstation beta on my new Macbook Pro (and so far it seems to work very well), I bought and installed a Win2000 Pro on it (since according to the grapevine it works better than XP in various kinds of virtual machines, and almost all SW supports w2k anyway -- I also found out that one exception is the Google Pack, which does require XP), did all the upgrades (why MS forces you to do 8+ rounds of download-install, from an off-the-CD win2k SP2 to a fully upgraded win2k SP4, rather than offering a single-round option, I just don't undersand!), got Python 2.4.3 -- phew, so far so good. So, I go to and start following the instructions, beginning with the download of Visual C++ Toolkit 2003... oops! I can't find that download any more at -- instead, what's at that URL is a page explaining that """ The Visual C++ Toolkit 2003 has been replaced by Visual C++ 2005 Express Edition. """ Hmmm -- I can't build extensions for the standard build of Python 2.4.3 with VC++ 2005, can I? Express or other, they just use separate and incompatible C-runtime libraries, I believe. So -- does anybody know if the 2003-level Toolkit is STILL available for download somewhere, or can suggest other (legal;-) ways in which I can build and test Python extensions (with an optimizing compiler -- NON-optimizing ones are right out;-) w/o shelling out beeg moolah to MS? So far my total investment is about $100 ($40 for Parallels Workstation, which I preordered after briefly checking out the free-for-1-month beta, since it worked so well; $60 for the cheapest legal CD+license of w2k I could find around) -- and I'm not complaining, since the current setup will still let me TEST many diverse things on Windows; to gain the further ability of *compiling* Python extensions, I'm not averse to spending a little more if needed, but certainly not as much as another $100 (I do prefer free to cheap, but for example the $40 Parallels product is well worth the money, to me, compared to the free 'Q', because the latter, while fun to hack around with, was absorbing countless hours of my time in many attempts to get everything working, while Parallels essentially "just worked" and saved me LOTS of time). Thanks in advance for any suggestions! Just to show that I'm an oldstyle Usenet dynosaur: suggestions in private mail are also welcome (but my real mailbox these days is at gmail, not as yahoo as the 'From' header above says), and I will undertake to summarize and post any suggestions thus received (unless the suggestions' authors request me to not repost). Alex From martin at v.loewis.de Sat Apr 8 05:54:18 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 08 Apr 2006 11:54:18 +0200 Subject: unicode wrap unicode object? In-Reply-To: <1144484827.891444.246920@z34g2000cwc.googlegroups.com> References: <1144452777.460885.131450@t31g2000cwb.googlegroups.com> <1144484827.891444.246920@z34g2000cwc.googlegroups.com> Message-ID: <4437884A.2030006@v.loewis.de> ygao wrote: > I must use utf-8 for chinese. Sure. But please don't do that: >>>> import sys >>>> reload(sys) >>>> sys.setdefaultencoding("utf-8") As Fredrik says, you should really avoid changing the default encoding. >>>> s='\xe9\xab\x98' #this uff-8 string >>>> ss=U'\xe9\xab\x98' >>>> ss1=ss.encode('unicode_escape').decode('string_escape') >>>> s1=s.decode('unicode_escape') >>>> s1==ss > True >>>> ss1==s > True Ok. But how about that: py> s='\xe9\xab\x98' py> ss=u'\u9ad8' py> s1=s.decode('utf-8') py> s1==ss True Here, ss is a single character, which uses 3 bytes in UTF-8. In your example, ss has three characters, which are not Chinese, but European. Regards, Martin From sturlamolden at yahoo.no Tue Apr 25 18:05:21 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 25 Apr 2006 15:05:21 -0700 Subject: MinGW and Python In-Reply-To: References: <1145861223.509630.247350@y43g2000cwc.googlegroups.com> <444C79D7.4060007@v.loewis.de> <444DC62B.7000702@v.loewis.de> <1145985979.369429.114040@i39g2000cwa.googlegroups.com> <1145996649.514911.99880@g10g2000cwb.googlegroups.com> Message-ID: <1146002721.150529.19640@e56g2000cwe.googlegroups.com> Edward Elliott wrote: > Sorry, I didn't mean you personally, I meant "you" in the general sense. OK :-) I've just tried to build Python 2.4.3 with MinGW (MSYS 1.0.10, GCC 3.4.2): $ ./configure --prefix=/c/Python243-mingw $ make The build then failed on posixmodule.c. Sturla Molden ./Modules/posixmodule.c:308: warning: function declaration isn't a prototype ./Modules/posixmodule.c: In function `posix_ttyname': ./Modules/posixmodule.c:1162: warning: implicit declaration of function `ttyname' ./Modules/posixmodule.c:1162: warning: assignment makes pointer from integer without a cast ./Modules/posixmodule.c: In function `posix_mkdir': ./Modules/posixmodule.c:1791: error: too many arguments to function `mkdir' ./Modules/posixmodule.c: In function `posix_execv': ./Modules/posixmodule.c:2199: warning: passing arg 2 of `execv' from incompatible pointer type ./Modules/posixmodule.c: In function `posix_execve': ./Modules/posixmodule.c:2332: warning: passing arg 2 of `execve' from incompatible pointer type ./Modules/posixmodule.c:2332: warning: passing arg 3 of `execve' from incompatible pointer type ./Modules/posixmodule.c: In function `posix_fork': ./Modules/posixmodule.c:2847: warning: implicit declaration of function `fork' ./Modules/posixmodule.c: In function `posix_openpty': ./Modules/posixmodule.c:2909: error: `O_NOCTTY' undeclared (first use in this function) ./Modules/posixmodule.c:2909: error: (Each undeclared identifier is reported only once ./Modules/posixmodule.c:2909: error: for each function it appears in.) ./Modules/posixmodule.c:2912: error: `SIGCHLD' undeclared (first use in this function) ./Modules/posixmodule.c:2914: warning: implicit declaration of function `grantpt' ./Modules/posixmodule.c:2919: warning: implicit declaration of function `unlockpt' ./Modules/posixmodule.c:2924: warning: implicit declaration of function `ptsname' ./Modules/posixmodule.c:2924: warning: assignment makes pointer from integer without a cast ./Modules/posixmodule.c:2931: warning: implicit declaration of function `ioctl' ./Modules/posixmodule.c:2931: error: `I_PUSH' undeclared (first use in this function) ./Modules/posixmodule.c: In function `posix_getegid': ./Modules/posixmodule.c:2973: warning: implicit declaration of function `getegid' ./Modules/posixmodule.c: In function `posix_geteuid': ./Modules/posixmodule.c:2986: warning: implicit declaration of function `geteuid' ./Modules/posixmodule.c: In function `posix_getgid': ./Modules/posixmodule.c:2999: warning: implicit declaration of function `getgid' ./Modules/posixmodule.c: In function `posix_getppid': ./Modules/posixmodule.c:3121: warning: implicit declaration of function `getppid' ./Modules/posixmodule.c: In function `posix_getuid': ./Modules/posixmodule.c:3163: warning: implicit declaration of function `getuid' ./Modules/posixmodule.c: In function `posix_kill': ./Modules/posixmodule.c:3193: warning: implicit declaration of function `kill' ./Modules/posixmodule.c: In function `posix_wait': ./Modules/posixmodule.c:4970: warning: implicit declaration of function `wait' ./Modules/posixmodule.c: In function `posix_pipe': ./Modules/posixmodule.c:5511: warning: implicit declaration of function `pipe' ./Modules/posixmodule.c: At top level: ./Modules/posixmodule.c:382: warning: 'posix_error_with_filename' defined but not used ./Modules/posixmodule.c:534: warning: 'posix_fildes' defined but not used ./Modules/posixmodule.c:6223: warning: 'conv_confname' defined but not used ./Modules/posixmodule.c:7126: warning: 'setup_confname_table' defined but not used make: *** [Modules/posixmodule.o] Error 1 From rbann11 at hotmail.com Sun Apr 30 15:31:48 2006 From: rbann11 at hotmail.com (rbann11 at hotmail.com) Date: 30 Apr 2006 12:31:48 -0700 Subject: Can I collapse a Panel in wxPython? In-Reply-To: <1146410720.541919.54910@j33g2000cwa.googlegroups.com> References: <1146410720.541919.54910@j33g2000cwa.googlegroups.com> Message-ID: <1146425508.643306.131140@i40g2000cwc.googlegroups.com> nuffnough at gmail.com wrote: > Hi. > > I have a gui with one frame and 5 panels. The second panel will only > be required in some cases, so I am wondering if there is some way I > can only create this panel in the circumstances where it is required, > confirmed by a simple len(list) > 1 > > If it is possible, I am wondering how I might go about it.... I am not > sure where to put an if statement as there are many different referrals > to panel_2 > > Letting me know or just pointing me to an example of such a thing would > be fabulous. > > TIA Check out http://wiki.wxpython.org/index.cgi/FoldPanelBar Roger From diffuser78 at gmail.com Wed Apr 5 14:32:56 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 5 Apr 2006 11:32:56 -0700 Subject: how to convert string Message-ID: <1144261976.640631.9280@e56g2000cwe.googlegroups.com> I want to print number 0 to 9 in one line like this 0 1 2 3 4 5 6 7 8 9 if I do like this, it prints in different lines for i in xrange(10): print i so i tried like this str = "" for i in xrange(10): str = i + " " print str but i want to know how convert int i to string. Every help is appreciate. From dadapapa at googlemail.com Sat Apr 22 17:09:00 2006 From: dadapapa at googlemail.com (harold) Date: 22 Apr 2006 14:09:00 -0700 Subject: check whether a value is scalar In-Reply-To: <1145738972.246620.317070@i40g2000cwc.googlegroups.com> References: <1145738972.246620.317070@i40g2000cwc.googlegroups.com> Message-ID: <1145740140.754279.152580@j33g2000cwa.googlegroups.com> would isinstance(value,(type(None),str,int,float,bool)) be enough? This yields true if the type value is in the list of type objects given as second argument, or a subtype of one of them. What, however, do you mean with "I care about the value only, and not its class method"? From Vijairaj.R at gmail.com Mon Apr 3 00:51:45 2006 From: Vijairaj.R at gmail.com (Vijairaj R) Date: 2 Apr 2006 21:51:45 -0700 Subject: Getting a list of all classes derived from a base class Message-ID: <1144039905.692207.8790@g10g2000cwb.googlegroups.com> Hi, I have a requirement to findout all the classes that are derived from a single base class. This is how I do it currently. class Test: case = [] class Test1(Test): Test.case.append("Test1") class Test2(Test): Test.case.append("Test2") 1. Is there a better way of doing this. 2. Is there a way to generalize the Test.case.append("TestN") statements to something like Test.case.append(__myclass__) -- Warm Regards, Vijairaj From deets at nospam.web.de Sun Apr 23 05:46:29 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 23 Apr 2006 11:46:29 +0200 Subject: Custom data type in a matrix. In-Reply-To: <1145762341.179288.234900@i39g2000cwa.googlegroups.com> References: <1145762341.179288.234900@i39g2000cwa.googlegroups.com> Message-ID: <4b10npFvcl4hU1@uni-berlin.de> Gaz schrieb: > Hi guys. I've been lookig for this in the numpy pdf manual, in this > group and on google, but i could not get an answer... > > Is there a way to create a custom data type (eg: Name: string(30), Age: > int(2), married: boolean, etc) and then use that custom data in a > matrix? Actually, this is a two question question :P > > Im doing a simple hex based game and i need a way to store every hex > property (color, owner,x, y, etc) in a matrix's "cell", representing > each cell a hex. You don't want numpy - you want ordinary lists in lists. Consider this: class Hex(object): def __init__(self, x, y): self.x, self.y = x, y self.terrain_type = "unknown" map = [[Hex(x, y) for y in xrange(height)] for x in xrange(width)] There is no advantage of using numpy whatsoever - your fields aren't subject to mathematical operations or other transformations/selections. Diez From timr at probo.com Fri Apr 21 01:33:39 2006 From: timr at probo.com (Tim Roberts) Date: Fri, 21 Apr 2006 05:33:39 GMT Subject: Activating Batch Files from Python References: <1145417944.549477.198510@g10g2000cwb.googlegroups.com> Message-ID: "Jeff Groves" wrote: > >I'm writing a launcher that should do the following: > >1. Activate a .bat file to set environmental variables. >2. Start 3 programs, using said environmental variables as arguments. > >However, I can't get the environmental variables to stick because all >of Pythons' system start/open functions split off into their own little >subshells, therefore the .bat file doesn't affect the main shell. > >How can I use the .bat file to set environmental vars from Python? One very real possibility is to parse your .bat files by hand, and make the changes to your os.environ. Your subprocesses inherit that. .BAT files are easy to parse, especially if they're just a bunch of 'set' statements. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From m.yanowitz at kearfott.com Fri Apr 21 07:41:47 2006 From: m.yanowitz at kearfott.com (Michael Yanowitz) Date: Fri, 21 Apr 2006 07:41:47 -0400 Subject: proposed Python logo In-Reply-To: <1145615455.477800.74730@i39g2000cwa.googlegroups.com> Message-ID: How about having something from Monty Python in the logo rather than something snakelike. Python was named after Monty Python and not the snake. Snakes also don't appear friendly to me. I used to have rats as pets. Snakes are murderers of rats. Which I do find strange that there is a rat on the cover of "Learning Python" by Oreilly but a Python snake on the "Progamming Python" by Oreilly book. I think something from Monty Python (I haven't watched it recently to know what would be ideal) would be more appropriate than an ugly reptile which is usually associated with evil and our reason for leaving the Garden of Eden. (Take me serious or not, I don't care, this is just my opinion, but with a little humor.) Thanks in advance: -----Original Message----- From: python-list-bounces+m.yanowitz=kearfott.com at python.org [mailto:python-list-bounces+m.yanowitz=kearfott.com at python.org]On Behalf Of Ant Sent: Friday, April 21, 2006 6:31 AM To: python-list at python.org Subject: Re: proposed Python logo Sorry dude, but it looks like a hairdryer! Imagine it at 16x16 pixels or smaller, and it'll look like little more than a circle with two sticks. The current image scales well. I think that the current logo is fine. Much more professional than the old image. The + formation is positive enough, and it has a yin-yang feel to it which to me conjures up the image of balance, not divisiveness. JM2PW I would like to see a Python Logo From pmartin at snakecard.com Tue Apr 4 00:00:07 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Mon, 03 Apr 2006 23:00:07 -0500 Subject: Loading a default browser under Windows Message-ID: <9bmYf.4581$fS6.3530@dukeread11> Hi, Is there (maybe through pywin) a way to call the default browser with a url as param ? Regards, Philippe From steve at REMOVETHIScyber.com.au Sat Apr 15 21:35:04 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 16 Apr 2006 11:35:04 +1000 Subject: Help with python output redirection References: <1145059153.392141.145360@u72g2000cwu.googlegroups.com> <1145111789.969239.270260@i40g2000cwc.googlegroups.com> Message-ID: On Sat, 15 Apr 2006 07:36:30 -0700, fatal.serpent wrote: > Thank you. Also this script is PublicDomain right? Oh heavens, I never even thought about that... the world was a much better place when you actually needed to *claim copyright* rather than just have it apply automatically on every stupid little doodle or comment. I've heard from authorities I trust that under US law private citizens can't "not copyright" something you write, even if you want it to go into the Public Domain. I've also heard the opposite from experts I equally trust. So, let me say firstly that I wish the following code to be put into the public domain, and if there is any reason why it has not been, I hereby give everybody an unlimited, non-exclusive, transferable, free of all charges and royalties, licence to use the following code in any way they see fit, with no conditions attached except there is no warranty. You don't even have to credit me. If you try to make a warranty claim against me for this code, the licence is instantly revoked. There. It probably won't stand up in a court of law, but I promise not to sue if you promise the same. > Steven D'Aprano wrote: >> On Fri, 14 Apr 2006 16:59:13 -0700, fatalserpent wrote: >> >> > Here is the basic code (yes, I know its tiny). >> > >> > x = ['print "x =", x', 'for m in x: print m'] >> > print "x =", x >> > for m in x: print m >> > >> > I want to modify this so it will output to a file called 1. What I want >> > is to have that file direct its output to a file called 2 and 2 direct >> > to 3 and so on. Hopefully this will be an easy-to-answer question. THX >> > in advance. >> >> From the shell, you are probably doing something like this: >> >> $ python mymodule.py >> >> Change it to this: >> >> $ python mymodule.py > 2 >> $ python 2 > 3 >> $ python 3 > 4 >> >> and so on. >> >> Alternatively, you can do this: >> >> x = ['f = file("2", "w")', 'print >>f, "x =", x', >> 'for m in x: >>f, print m'] >> print >>f, "x =", x >> for m in x: print >>f, m >> >> I'll leave changing the file name from "2" to "3" etc. as an exercise for >> you. >> >> >> -- >> Steven. -- Steven. From jdhunter at ace.bsd.uchicago.edu Tue Apr 25 16:19:25 2006 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 25 Apr 2006 15:19:25 -0500 Subject: Plotting package? References: Message-ID: <87r73lqugi.fsf@peds-pc311.bsd.uchicago.edu> >>>>> "Andrew" == Andrew Koenig writes: Andrew> This may be a foolish question, but what's the most Andrew> straightforward way to plot a bunch of data in Python? in matplotlib/pylab from pylab import figure, show x = range(10) y = [val**2 for val in x] fig = figure() ax = fig.add_subplot(111) ax.plot(x,y) ax.set_title('My first plot') ax.set_xlabel('x') ax.set_ylabel('y') show() Tutorial: http://matplotlib.sourceforge.net/tutorial.html Screenshots: http://matplotlib.sourceforge.net/screenshots.html JDH From durumdara at gmail.com Thu Apr 20 06:41:27 2006 From: durumdara at gmail.com (DurumDara) Date: Thu, 20 Apr 2006 12:41:27 +0200 Subject: SQLite (with APSW) and transaction separate In-Reply-To: References: Message-ID: <44476557.1050001@gmail.com> Hi ! Dennis Lee Bieber ?rta: > On Wed, 19 Apr 2006 17:29:28 +0200, Christian Stooker > declaimed the following in comp.lang.python: > > >> Please answer me: it is wrong I write about, or that is seems to be not >> working in SQLite ? >> >> > I don't think the feature you want to use is available -- heck, it > may ONLY be a firebird feature... (I've not seen anything similar in any > of the MySQL back-ends, or if there, I've not encountered it; and there > aren't enough easily read documents for MaxDB [aka SAP-DB] in print to > see if it has such a feature. My MSDE books don't mention it either, so > I suspect M$ SQL Server may not support such). > Sorry, but I don't think that this feature is exists in only Firebird. Good RDMBS systems ***must have*** many transaction isolation levels. The higher isolation level guaranteed a safely view for actual user. READ COMMITTED, and REPEATABLE READ isolation level makes me sure, that if I have a snapshot from the database, I get it same datas *everytime* while my transaction opened. Until trs. is closed and reopened, I can see the new modifications created by another user(s). But when I keep alive my transaction, never I see any modifications, only what I created. In this mode I don't see any user's updates - vainly he or she do many commits (As I see in SQLite, the another user's committed records visible for me - this is corrupting my view !) That is the only way to I get good reports from an invoice manager application, because I see current state of the database - the sum(subtotals) everytime equal with total. In lower isolation level I can see the new committed records - and that is bad thing, because in this time the sum(subtotals) sometimes not equal with total. That problem is just like thread synch. problem, where I need to protect my subresources with locks/semaphores to avoid corrupting of data. In Delphi I must protect string vars, because when every thread want to write/read from this string, they easily make corrupted string from the source... > SQLite is a "file server" style database; Firebird is a > client/server model. > > In Firebird, the server can track independent connections and > maintain state for each. SQLite runs "locally"; each connection > considers itself to be the only user of the database file (and locking > for updates is on a file basis, not table or record). Once you commit a > transaction in SQLite, the file itself is fully modified, and any other > connections see that modified file -- there is no temporary session > journal for a connection that holds a snapshot of that connection's > data. > So I cannot use a transaction number that identify transactions, and make same isolation effect what I said about before ? Thanx for help: dd From bj_666 at gmx.net Sat Apr 1 16:36:36 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 01 Apr 2006 23:36:36 +0200 Subject: Can I export my datas in pickle format safely ? References: Message-ID: In , DurumDara wrote: > I thinking about that I can use the pickle to serialize/load my datas > from the file. > > But: I remember that in the year of 2004(?) I tried this thing. I store > my CD informations in pickled objects (in files). > And when I changed my python version from ??? to 2.3(?), and I get some > error messages... What are the error messages? Pickled data should survive such a version change. Remember that even "text protocol" pickles are binary data which may break across platforms if the files are not opened in binary mode for writing and reading. And all classes of the types that were pickled must be "reachable" when unpickling. Ciao, Marc 'BlackJack' Rintsch From robert.kern at gmail.com Wed Apr 12 17:32:41 2006 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 12 Apr 2006 16:32:41 -0500 Subject: iPython and doctest In-Reply-To: <1144873857.232532.119160@t31g2000cwb.googlegroups.com> References: <1144873857.232532.119160@t31g2000cwb.googlegroups.com> Message-ID: Michael Tobis wrote: > It appears that doctest does not work straightforwardly within iPython. > > I would like to be able to use doctest within a file conditionally, so > that I can develop it within ipython and test it otherwise. > > It would seem that this would work: > > Python 2.4.1 (#2, Mar 31 2005, 00:05:10) > [GCC 3.3 20030304 (Apple Computer, Inc. build 1666)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > >>>>import testme >>>>testme._test() >>>> > > but it doesn't (the test above fails, but reports nothing) IPython replaces sys.displayhook(), the function that determines how an object gets printed when it is the result of an expression in the interactive interpreter. Consequently, if you write your doctests as if they were executed from the virgin interpreter, then you will get different values if you run the tests in IPython. And vice versa. Writing for IPython and executing for IPython may or may not work. -- Robert Kern robert.kern at gmail.com "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From johnjsal at NOSPAMgmail.com Tue Apr 4 10:47:04 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 04 Apr 2006 14:47:04 GMT Subject: what's going on here? In-Reply-To: References: <4431eb28$0$17995$c3e8da3@news.astraweb.com> <1144139139.659001.176300@j33g2000cwa.googlegroups.com> Message-ID: John Salerno wrote: > Ant wrote: >> You are along the right lines. Try printing out the content of each URL >> - one of the pages will match your expression, but has additional >> instructions... I think you are reaching the end of their false trail >> when you get None returned from the url. > > But the weird thing is that when I tried the same script earlier in the > day, it went through about 200+ links before encountering a situation > that my script didn't handle. But now when I get this latest error that > I posted, it's only going through about 150 links before stopping. > >> The set of pages themselves are the linked list - each contains a >> reference to the next element in the sequence. You don't need one to >> solve the problem, the problem *is* the linked list! > > Interesting! That's good news, and I'm glad I didn't spend hours trying > to use one to solve it! :) Ok, I'm confused. I ran the script again today (this time at work again) and it worked! I made no changes, so I'm not sure what the issue was. But thank god I'm passed this problem, although I'm sure it only gets worse now! From scott.daniels at acm.org Tue Apr 18 17:26:47 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Tue, 18 Apr 2006 14:26:47 -0700 Subject: Writing backwards compatible code - when? In-Reply-To: References: Message-ID: <44455670$1@nntp0.pdx.net> Bob Greschke wrote: > Is there a list of all of the Python commands and modules that tell when > (what version) they were added to Python? I was hoping the new Essential > Reference would have it, but it doesn't. Here's a reference that stops at 2.3: http://rgruet.free.fr/PQR2.3.html --Scott David Daniels scott.daniels at acm.org From phpbird at gmail.com Fri Apr 7 14:19:55 2006 From: phpbird at gmail.com (Ju Hui) Date: 7 Apr 2006 11:19:55 -0700 Subject: how to use urllib2 to get a page with a socks 5 proxy? Message-ID: <1144433995.418222.290190@t31g2000cwb.googlegroups.com> example, the proxy server is :123.123.123.123 and the port is :1080 and the username/password is : user/pass I want to open http://www.google.com how to write this script? thanks. From do_not_use_this_email at hotmail.com Wed Apr 19 15:44:22 2006 From: do_not_use_this_email at hotmail.com (rx) Date: Wed, 19 Apr 2006 21:44:22 +0200 Subject: Official Python logo References: <1145470122.145225.53110@z34g2000cwc.googlegroups.com> Message-ID: <44469319$0$9303$ba624c82@nntp02.dk.telia.net> wrote in message news:1145470122.145225.53110 at z34g2000cwc.googlegroups.com... > Where do I find one? Is it the banner by Just van Rossum or the Picasso > snake on python.org? > Thanks. > They talk about logos - I don't know the site. http://www.pythonology.com/logos google python official logo link 6 From fredrik at pythonware.com Thu Apr 20 05:22:34 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 20 Apr 2006 11:22:34 +0200 Subject: Lamdba forms References: <1145492986.738200.229690@i39g2000cwa.googlegroups.com><1145517117.216022.261360@g10g2000cwb.googlegroups.com> <1145523944.375146.275050@z34g2000cwc.googlegroups.com> Message-ID: "Ant" wrote: > No, I remembered correctly: > http://www.artima.com/weblogs/viewpost.jsp?thread=98196 > but probably not until Python 3.0. however, http://mail.python.org/pipermail/python-dev/2006-February/060415.html (one would have thought that someone might have added a note to the comments of the first post, but the most recent contributor to that thread is a mortgage spammer...) From tboon at comcast.net Wed Apr 19 21:35:18 2006 From: tboon at comcast.net (Taylor Boon) Date: Wed, 19 Apr 2006 21:35:18 -0400 Subject: Ironpython book? References: <1145329406.419299.12780@i40g2000cwc.googlegroups.com><1he15xj.1dy2h0vzbebqmN%aleaxit@yahoo.com> Message-ID: "Fredrik Lundh" wrote in message news:mailman.4755.1145460202.27775.python-list at python.org... > Alex Martelli wrote: > >> > Just out of curiosity, is Python.NET a dead project? >> >> AFAIK, it's a long-completed research project. I do not know of anybody >> planning to fork it to a new project, though that of course does not >> rule out that somebody might be planning to do so. > > brian's latest development blog entry is from april 13th, this year. > > http://brianlloyd.blogspot.com/ > > "I'm happy to say its been a pretty busy month in Python > for .NET-land" > > > > > Project page is at http://sourceforge.net/projects/pythonnet Brian and co. are in the process of putting together a 2.0 release that will work with .NET 2.0. Works with mono too, for all those "decent hacker" types out there... BTW, IronPython compiles Python code into CLR byte codes; Python.NET allows CPython code to call into managed code libraries and services. Cheers, Taylor From fredrik at pythonware.com Thu Apr 13 11:47:11 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 13 Apr 2006 17:47:11 +0200 Subject: list.clear() missing?!? References: <1144767680.583085.310160@v46g2000cwv.googlegroups.com><1144792144.168802.146310@i39g2000cwa.googlegroups.com><1144870852.886477.238570@u72g2000cwu.googlegroups.com> Message-ID: Mel Wilson wrote: > > for item in seq: > > L.append(item) > > Both extend and append have one-line slice equivalents, > except that the equivalents have to keep referring to > the length of the list.. (have to keep finding the > len function.) fwiw, the *tutorial* defines append and extend in terms of slicing... From grflanagan at yahoo.co.uk Mon Apr 24 04:08:46 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 24 Apr 2006 01:08:46 -0700 Subject: bug in modulus? References: <1145807918.069455.241510@i40g2000cwc.googlegroups.com> <1145824389.832245.62600@t31g2000cwb.googlegroups.com> Message-ID: <1145866126.015217.78640@t31g2000cwb.googlegroups.com> jantod at gmail.com wrote: > But maybe I'm reading it wrong. In any case what I wanted was simply a > way to extract the angle from a complex number where the angle is > between 0 and 2*pi. I think I'll just take the modulus twice. > > def angle(complex): > """Returns angle where 2*pi > angle >=0 > > >>> angle(1+1j) - atan(1) < 1e-3 > True > >>> angle(-1+1j) - (atan(-1) + 3*pi) % (2*pi) < 1e-3 > True > >>> angle(0+1j) == pi/2 > True > >>> angle(0-1j) == 1.5*pi > True > >>> angle(1+0j) == 0 > True > >>> angle(0+0j) == 0 > True > >>> angle(1-1e-100*1j) == 0 > True > """ > if complex.real == 0: > if complex.imag == 0: > return 0 > if complex.imag < 0: > return 1.5*pi > return pi/2 > theta = (atan2(complex.imag, complex.real) % (2*pi)) % (2*pi) > assert 2*pi > theta >=0, (theta, complex) > return theta > from math import atan2, pi def cangle(z): ret = atan2(z.imag, z.real) if ret < 0: ret += 2*pi return ret assert cangle(1+1j) * 180 / pi == 45.0 assert cangle(-1+1j) * 180 / pi == 135.0 assert cangle(-1-1j) * 180 / pi == 225.0 assert cangle(1-1j) * 180 / pi == 315.0 assert cangle(1+0j) * 180 / pi == 0.0 assert cangle(-1+0j) * 180 / pi == 180.0 assert cangle(1j) * 180 / pi == 90.0 assert cangle(-1j) * 180 / pi == 270.0 Gerard From deets at nospam.web.de Tue Apr 11 09:16:41 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 11 Apr 2006 15:16:41 +0200 Subject: RIIA in Python 2.5 alpha: "with... as" References: Message-ID: <4a1ojfFqla0aU1@uni-berlin.de> >> No, it means that Python 2.5 supports 'resource initialisation is >> acquisition', but that has nothing to do with the restricting the >> lifetime of a variable. > Sorry, I misworded the question - RIIA is indeed present at least by > the reason that the examples from PEP pass. Agree, my problem is a bit > different, and I a bit mixed up initialization/acquisition with > lifetime blocks. So, seems that we indeed have one and still don't > have another. > Or maybe you have an idea how this can be fixed? The > simplest way I see is putting all the "controlled" variables into a > dedicated class... and do that each time for each block of variables I > need control lifetime. Is there any simpler way? Wouldn't a small surrounding function suffice? Something like this (untested): def whatever(): def anon(): with open('/etc/passwd', 'r') as f: for line in f: print line Sure, not the nicest of all solutions. But if you really fear that f is reused, it might help. Diez From aleaxit at yahoo.com Sat Apr 29 20:49:21 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 29 Apr 2006 17:49:21 -0700 Subject: Can we create an_object = object() and add attribute like fora class? References: <1hek76f.48x7rvw33771N%aleaxit@yahoo.com> Message-ID: <1hekhfb.f5hiv4fg6pi5N%aleaxit@yahoo.com> Pierre Rouleau wrote: > Fredrik Lundh wrote: > > > Pierre Rouleau wrote: > > > > > >>I can understand the design decision not to give object a __dict__, but > >>I wonder if i'd be a good idea to have a class that derives from object > >>and has a __dict__ to be in the standard library. > > > > so you can replace one line of code in some of your programs with > > an import statement ? > > ok... I should have said "something like the built-in object type" > instead of "standard library"... I'm -1 on adding a new built-in for this functionality -- it's just not important enough to warrant a built-in (there are already too many built-ins!). Putting a "namespace type" in the standard library could provide enough helpful functionality to make an import well warranted, so I'm +1 on adding such a type to the standard library (in 2.6 -- I think it's too late for 2.6). Alex From henning at makholm.net Wed Apr 5 07:54:23 2006 From: henning at makholm.net (Henning Makholm) Date: Wed, 05 Apr 2006 13:54:23 +0200 Subject: A Lambda Logo Tour References: <1144233226.580090.216080@j33g2000cwa.googlegroups.com> Message-ID: <87u098nspc.fsf@kreon.lan.henning.makholm.net> Scripsit "Xah Lee" > Subroutines in lisps easily have side-effects, and sometimes > non-functional programing methodologies such as OOP are actually > encouraged in lisp. As most of you know, the lambda symbol chosen by > functional languages is to signify no side-effects. What are you smoking? You're sure you could stop anytime you wanted, right? -- Henning Makholm "What a hideous colour khaki is." From timothy.williams at nvl.army.mil Tue Apr 11 14:39:57 2006 From: timothy.williams at nvl.army.mil (timw.googlepost) Date: 11 Apr 2006 11:39:57 -0700 Subject: installing pyodbc Message-ID: <1144780797.368420.239220@i39g2000cwa.googlegroups.com> I just downloaded the pyodbc source to try and install on my Linux FC3 box. I see that there is a setup.py file, but when I try to do a 'python setup.py build' (or just 'python setup.py') I get Traceback (most recent call last): File "setup.py", line 27, in ? revision = latest_revision('.') File "setup.py", line 25, in latest_revision return int(output) ValueError: invalid literal for int(): exported The README.txt doesn't really say anything about how to install, exept that the easiest way is to use the Windows installer. That's fine for Windows, but what about Linux? Thanks for any help. From mandelin at cs.berkeley.edu Mon Apr 10 16:44:01 2006 From: mandelin at cs.berkeley.edu (Dave Mandelin) Date: 10 Apr 2006 13:44:01 -0700 Subject: Problem embedding Python... References: <1144676144.781487.266080@j33g2000cwa.googlegroups.com> Message-ID: <1144701841.219647.173880@g10g2000cwb.googlegroups.com> > C:\DOCUME~1\ANDY~1.MCC\LOCALS~1\Temp/cckhbaaa.o(.text+0x2b):main.cpp: > undefined reference to `_imp__Py_Initialize' These errors indicate that the linker can't find the Python library (python24.lib). > -L"C:\Python24\Lib" I think you want to say -L"C:\Python24\Libs" instead. 'libs' contains the binary lib files, while 'lib' contains the .py library files. -- Want to play tabletop RPGs online? Check out RPZen: http://koboldsoft.com From finite.automaton at gmail.com Mon Apr 24 16:18:32 2006 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 24 Apr 2006 13:18:32 -0700 Subject: SOAP server with WSDL? Message-ID: <1145909912.279051.48360@j33g2000cwa.googlegroups.com> Does anyone know of a Python SOAP package that will publish a SOAP service /and/ generate a corresponding WSDL file? Looking at SOAPpy and ZSI, it seems that their WSDL support is limited to client-side stuff. From steve at holdenweb.com Fri Apr 14 03:16:56 2006 From: steve at holdenweb.com (Steve Holden) Date: Fri, 14 Apr 2006 08:16:56 +0100 Subject: A problem with exec statement In-Reply-To: <1144996562.237621.110500@t31g2000cwb.googlegroups.com> References: <1144996562.237621.110500@t31g2000cwb.googlegroups.com> Message-ID: TPJ wrote: > I have the following code: > > ----------------------------------- > def f(): > > def g(): > a = 'a' # marked line 1 > exec 'a = "b"' in globals(), locals() > print "g: a =", a > > a = 'A' # marked line 2 > exec 'a = "B"' in globals(), locals() > print "f: a =", a > g() > > f() > ----------------------------------- > > I don't understand, why its output is: > > f: a = A > g: a = a > > instead of: > > f: a = B > g: a = b > > All works as intended, if the marked lines are commented out. I just > don't understand, why. (I suppose I don't understand, how the exec > statement works, or the way Python handles objects, their names and > namespaces...) In my opinion (according to my knowledge about Python), > with or without the marked lines commented, the code should work the > same. Well - I think I have to learn more about Python... > That's true of almost everybody reading this list, myself included. > According to my knowledge, the most important are the namespaces: the > local ones, in this case. When Python calls the f function, its > namespace is created. This namespace contains only the g function. > Then the a variable is created (and the "a" name is added to the f > function namespace). > That's a pretty good summary. In fact just after the call to f is started its namespace doesn't even contain "g", that's added by executing the def statement that defines g. The assignment does indeed create the name "a" in the function's (local) namespace. > The next statement is the exec one. Since the statement "knows" the > local namespace (obtained from the locals() function), it should > replace the value of the a variable in the local namespace with the > value of the new string "B". I don't understand, why this is not done. > So when you exec 'a = "B"' in globals(), locals() you might think you were changing the local namespace. In fact you are changing a *copy* of the local namespace: if you read the documentation carefully you will see under locals() it says """Warning: The contents of this dictionary should not be modified; changes may not affect the values of local variables used by the interpreter.""" > The situation in the g function is similar, the only difference is > that the local namespace contains the "a" name, that refers to a > different Python object. > The same answer presumably pertains here. If you modify your code to read: def f(): def g(): a = 'a' # marked line 1 print "globals:", globals(), '\nlocals:', locals() exec 'a = "b"' in globals(), locals() print "globals:", globals(), '\nlocals:', locals() print "g: a =", a a = 'A' # marked line 2 print "Globals:", globals(), '\nLocals:', locals() exec 'a = "B"' in globals(), locals() print "Globals:", globals(), '\nLocals:', locals() print "f: a =", a g() f() you will see quite clearly that you aren't making the changes you anticipate to the local namespace. I hope I have explained why. One last note. Newcomers to Python often seem fascinated by the ability to use exec to achieve namespace indirection. Even allowing for the difficulties you've already experienced, it's nearly always better in practical cases to use assignment to the keys of a dictionary. Then no exec is required, and you have direct control over your own namespace. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd www.holdenweb.com Love me, love my blog holdenweb.blogspot.com From luigipaioro at libero.it Mon Apr 3 11:33:46 2006 From: luigipaioro at libero.it (Luigi) Date: 3 Apr 2006 08:33:46 -0700 Subject: Capturing stdout without waiting for the process end Message-ID: <1144078426.023838.25970@i39g2000cwa.googlegroups.com> Hi to all! I'd like to execute an external program capturing the stdout/stderr messages at "real-time". I mean that I don't want to wait for the end of the process. If I write a code like this: import os import sys class Runner: def run(self, arg): try: fin, fout = os.popen4(arg) self.outData = fout.readlines() self.outStatus = fout.close() except Exception, err: print err def printOut(self): print "###" print self.outStatus print "###" for line in self.outData: print line r = Runner() r.run("ls /tmp") r.printOut() I can print out (in this case in the os.stdout, but it may be elsewhere) the whole external program output only once it ends. How can I do to intercept the external program output during the processing? Thank you in advance Luigi From pecoraREMOVE at THISanvil.nrl.navy.mil Thu Apr 20 19:47:45 2006 From: pecoraREMOVE at THISanvil.nrl.navy.mil (Lou Pecora) Date: Thu, 20 Apr 2006 19:47:45 -0400 Subject: Phython and graphing References: <1145573583.333670.300930@v46g2000cwv.googlegroups.com> Message-ID: In article <1145573583.333670.300930 at v46g2000cwv.googlegroups.com>, "mostro" wrote: > Hello, > > Can someone lead me to an easy way to create a graph in Python. > > For example, I have a script running that creates a list of dates, > times and values. I would like to turn this into a graph. > > I can grep the info into a new file creating two columns (x,y) but the > issue is the graph. > > P.S. I'm a Python newbie so keep that in mind. > > Thanks in advance... google matplotlib nice package. I've been told that another package called wsMpl.py also puts a nice API on the matplotlib. You might want to check that, too. -- Lou Pecora (my views are my own) REMOVE THIS to email me. From timr at probo.com Sat Apr 15 00:23:42 2006 From: timr at probo.com (Tim Roberts) Date: Sat, 15 Apr 2006 04:23:42 GMT Subject: Help for a complete newbie References: <7xY%f.1245$kz3.903@twister.nyroc.rr.com> Message-ID: "Ralph H. Stoos Jr." wrote: > >I am reading a Python tutorial for complete non-programmers. > >The code below is so simple as to be insulting but the assignment of the >"ready" variable gives a syntax error. > >The code reads letter-for-letter like the tutorial states. Letter for letter, maybe, but not space for space. Indentation is important in Python. The "ready =", "if ready", and "else:" statements must start in column 1. The two print statements need to be indented, as they are. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From steven.bethard at gmail.com Fri Apr 28 19:59:46 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 28 Apr 2006 17:59:46 -0600 Subject: best way to determine sequence ordering? In-Reply-To: <1146259620.636600.119710@u72g2000cwu.googlegroups.com> References: <70q4g.2006$No6.43783@news.tufts.edu> <1146259620.636600.119710@u72g2000cwu.googlegroups.com> Message-ID: nikie wrote: > Steven Bethard wrote: > >> John Salerno wrote: >>> If I want to make a list of four items, e.g. L = ['C', 'A', 'D', 'B'], >>> and then figure out if a certain element precedes another element, what >>> would be the best way to do that? >>> >>> Looking at the built-in list functions, I thought I could do something >>> like: >>> >>> if L.index('A') < L.index('D'): >>> # do some stuff >> This is probably a pretty reasonable approach as long as you're not too >> worried about efficiency. It scans the list twice though, so if you >> start doing this with really big lists, it might be better to do >> something like: > > On average, it'll only have go through half the list twice, as it can > break as soon as it finds the item it searches for. Don't think you can > get any more efficient than that. Sure you can: a_index = None d_index = None for i, item in enumerate(L): if item == 'A': a_index = i elif item == 'D': d_index = i if a_index is not None and d_index is not None: break if a_index < d_index: # do some stuff That goes through exactly the minimum number of elements. But it's probably slower than two .index() calls since .index() is coded in C. But timeit and see if you're interested. > >> >>> L = ['C', 'A', 'D', 'B'] >> >>> positions = dict((item, i) for i, item in enumerate(L)) >> >>> positions >> {'A': 1, 'C': 0, 'B': 3, 'D': 2} >> >>> positions['A'] < positions['D'] >> True > > Isn't this bound to be less efficient? I mean, inserting the items into > a dict is probably O(n log n) No, it's O(N). Dicts are just hash tables. Insertion is O(1). So N insertions is O(N). This route is also dramatically more efficient if you need to make M comparisons between items instead of just 1 comparison. In that case, using the dict is O(N + M) instead of the O(N * M) of the .index() route. STeVe From aleaxit at yahoo.com Tue Apr 25 00:14:31 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 24 Apr 2006 21:14:31 -0700 Subject: Probability Problem References: <1hebf8p.1sb844li5y2g3N%aleaxit@yahoo.com> Message-ID: <1hebh2i.v0yximmkmwktN%aleaxit@yahoo.com> Elliot Temple wrote: > On Apr 24, 2006, at 8:24 PM, Alex Martelli wrote: > > > Lawrence D'Oliveiro wrote: > > > >> In article , > >> Elliot Temple wrote: > >> > >>> Problem: Randomly generate 10 integers from 0-100 inclusive, and sum > >>> them. Do that twice. What is the probability the two sums are 390 > >>> apart? > >> > >> I think the sum would come close to a normal distribution. > > > > Yes, very close indeed, by the law of large numbers. > > > > However, very close (in a math course at least) doesn't get the cigar. > > > > You can compute the requested answer exactly with no random number > > generation whatsoever: compute the probability of each result from > > 0 to > > 1000, then sum the probabilities of entries that are exactly 390 > > apart. > > That was the plan, but how do I get the probability of any given > result? (in a reasonable amount of time) > > BTW I'm not in a math course, just curious. OK, I'll trust that last assertion (sorry for the hesitation, but it's all too easy to ``help'' somebody with a homework assignment and actually end up damaging them by doing it FOR them!-). I'm still going to present this in a way that stimulates thought, rather than a solved problem -- humor me...!-) You're generating a uniformly distributed random number in 0..100 (101 possibilities), 10 times, and summing the 10 results. How do you get a result of 0? Only 1 way: 0 at each attempt -- probability 1 (out of 1010 possibilities). How do you get a result of 1? 10 ways: 1 at one attempt and 0 at each of the others - probability 10 (again in 1010'ths;-). How do you get a result of 2? 10 ways for '2 at one attempt and 0 at each of the others', plus, 10*9/2 ways for '1 at two attempts and 0 at each of the others' -- probability 55 (ditto). ...and so forth, but you'd rather not work it out... So, suppose you start with a matrix of 101 x 10 entries, each of value 1 since all results are equiprobable (or, 1/1010.0 if you prefer;-). You want to compute the number in which you can combine two rows. How could you combine the first two rows (each of 101 1's) to make a row of 201 numbers corresponding to the probabilities of the sum of two throws? Suppose you combine the first entry of the first row with each entry of the second, then the second entry of the first row with each entry of the second, etc; each time, you get a sum (of two rolls) which gives you an index of a entry (in an accumulator row starting at all zeros) to increment by the product of the entries you're considering... Can you generalize that? Or, do you need more hints? Just ask! Alex From johnjsal at NOSPAMgmail.com Mon Apr 3 18:38:58 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 03 Apr 2006 18:38:58 -0400 Subject: string building In-Reply-To: References: Message-ID: <4431a54e$0$11236$c3e8da3@news.astraweb.com> John Salerno wrote: > Out of curiosity, is there any kind of equivalent in Python to the > StringBuilder class in C#? Here's a quick description from the .NET > documentation: > > "This class represents a string-like object whose value is a mutable > sequence of characters. The value is said to be mutable because it can > be modified once it has been created by appending, removing, replacing, > or inserting characters." > > It's used for dealing with large strings that otherwise would cause > performance problems if used as regular string objects. I'm just > wondering if Python has something like this, or if it is even really > necessary. I know there is even some discussion on when exactly > StringBuilder becomes useful over regular strings, but I imagine at some > point it is good to use. Thanks guys, two interesting options to investigate! :) From nobody at 127.0.0.1 Wed Apr 19 01:08:39 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 19 Apr 2006 05:08:39 GMT Subject: temporary scope change In-Reply-To: References: Message-ID: Michael Spencer wrote: > Just replace: > for y in list2: > with: > if True: Of course. I knew it would be blindingly obvious. Sometimes you just can't shake the blinders off though. Thanks. > Note that neither the `if` nor the `for` statement actually creates a > new scope. Good catch. I'm used to thinking block = scope. Old habits die hard I guess. From kent at kentsjohnson.com Thu Apr 27 09:02:23 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Thu, 27 Apr 2006 09:02:23 -0400 Subject: list of functions question In-Reply-To: <4bai48Fu890hU1@individual.net> References: <4bai48Fu890hU1@individual.net> Message-ID: <4450c09d_2@newspeer2.tds.net> val bykoski wrote: > Hi The List: > I have a modeling app where i'm detecting events (in temporal > dynamics) applying a set of (boolean) functions - kind of: > > event_list = "f1 f2 etc".split() # each fi detects a specific event > i have defs for functions fi, or simple boolean expressions for each, so > that evList is a list of defs or boolean expressions > for ev in evList: > if ev: # this supposedly is a call ev(t) > # doing smth with the event # Make a list of the actual functions, not their names # For the events that are expressions, encapsulate them in functions event_list = [f1, f2, etc] # Call each one: for ev in event_list: if ev(t): # do something Kent From spamspam at spam.eggs Wed Apr 5 14:45:13 2006 From: spamspam at spam.eggs (Ben C) Date: 5 Apr 2006 18:45:13 GMT Subject: how to convert string References: <1144261976.640631.9280@e56g2000cwe.googlegroups.com> Message-ID: On 2006-04-05, diffuser78 at gmail.com wrote: > I want to print number 0 to 9 in one line like this > 0 1 2 3 4 5 6 7 8 9 > > if I do like this, it prints in different lines > > for i in xrange(10): > print i for i in xrange(10): print i, should work (comma after the i). > so i tried like this > > str = "" > for i in xrange(10): > str = i + " " > print str > > but i want to know how convert int i to string. There's a builtin function str (better not to call your string str). Here I've called it s: s = "" for i in xrange(10): s = str(i) + " " print s But this puts an extra space on the end (so did the print i, version above). Might be better therefore to use string.join: import string s = string.join(map(str, xrange(10)), " ") print s From felipe.lessa at gmail.com Mon Apr 10 11:47:19 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Mon, 10 Apr 2006 12:47:19 -0300 Subject: python + access + odbc + linux In-Reply-To: References: Message-ID: <1144684039.6280.4.camel@kenshin.CASA> Em Seg, 2006-04-10 ?s 10:38 -0500, Philippe Martin escreveu: > I understand that access can be accessed through an ODBC driver under > windows (instead of Jet). > > I am wondering if the same can be done under Linux. As far as I know, no. But there is that http://mdbtools.sourceforge.net/ that may help you, but when I tried I had limited success. Cheers, -- Felipe. From fulvio at pc.jaring.my Wed Apr 12 06:45:18 2006 From: fulvio at pc.jaring.my (Fulvio) Date: Wed, 12 Apr 2006 18:45:18 +0800 Subject: the mysql for python cann't be install from the source! Help!! In-Reply-To: References: Message-ID: <200604121845.19004.fulvio@pc.jaring.my> Alle 22:24, marted? 11 aprile 2006, boyeestudio ha scritto: > I search the mysql directory but gain none of it! In the version MySQL-python-1.2.0 there isn't such file. Better you re-read README file inside the tarball or zip file. F From bearophileHUGS at lycos.com Sat Apr 1 05:07:59 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 1 Apr 2006 02:07:59 -0800 Subject: Python 2.5 licensing: stop this change In-Reply-To: <442e4dc6$0$62914$dbd49001@news.euronet.nl> References: <1143881699.232542.224960@j33g2000cwa.googlegroups.com> <442e4dc6$0$62914$dbd49001@news.euronet.nl> Message-ID: <1143886079.435254.118110@t31g2000cwb.googlegroups.com> Ivan Herman>I would certainly look at *all details* of the announcement,< Aww, but I liked the idea of copying Perl 6 REs, and porting python to the toy CPU :-) (But making strings mutable sounds too much strange). Bye and thank you, bearophile From reply.in.the.newsgroup at my.address.is.invalid Fri Apr 14 06:21:25 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Fri, 14 Apr 2006 12:21:25 +0200 Subject: sending email with charset utf-8 but subject is not coded properly References: Message-ID: <3qtu32tmdah8vn0hoh8f7oajlna6gk44q6@4ax.com> Grzegorz ?lusarek: >I sending email using standard python modules smtplib, email, >coding email in utf but subject of message is not coded properly. In >subject i use my national characters (polish) and after send i get XX in >place these characters. >Here is the code > >Message = email.message_from_string(pMessage) > Message.set_charset('utf-8') > Message['From'] = 'test at o2.pl' > Message['To'] = 'gt at o2.pl' > SMTPServer=smtplib.SMTP(ConfigurationManager.SMTPServer) > SMTPServer.sendmail('test at o2.pl','gt at o2.pl', Message.as_string()) I see no subject in this code. "If you want to include non-ASCII characters in your email headers, say in the Subject: or To: fields, you should use the Header class and assign the field in the Message object to an instance of Header instead of using a string for the header value." http://docs.python.org/lib/module-email.Header.html -- Ren? Pijlman From jjl at pobox.com Sat Apr 1 16:54:38 2006 From: jjl at pobox.com (John J. Lee) Date: 01 Apr 2006 21:54:38 +0000 Subject: Connecting to gnuplot with Popen? References: Message-ID: <87bqvlhsgx.fsf@pobox.com> Anton81 writes: > > Hi Anton, > > > > here is a little snippet using os.popen: > > Unfortunately I'm having more problem getting the output from Gnuplot, which > I'd like to examine for error messages and settings of options. If you must roll your own, look at standard module subprocess. John From dananrg at yahoo.com Fri Apr 7 05:51:12 2006 From: dananrg at yahoo.com (dananrg at yahoo.com) Date: 7 Apr 2006 02:51:12 -0700 Subject: Best way to process table rows from an RDBMS Message-ID: <1144403472.453332.213960@i39g2000cwa.googlegroups.com> I can handle making the connections and running queries, but what's the best way to process table rows returned in Python? What about turning a table definition into an object? Just looking for ways to be efficient, since I know I will be hitting the same external RDBMS from Python and regularly processing a fixed set of tables with a certain fixed set of attribute columns. Is there something better than tuples for this? From jpahullo at gmail.com Wed Apr 12 10:35:00 2006 From: jpahullo at gmail.com (jordi) Date: 12 Apr 2006 07:35:00 -0700 Subject: random.sample with long int items In-Reply-To: References: <1144848541.805554.122180@u72g2000cwu.googlegroups.com> Message-ID: <1144852500.860883.135790@v46g2000cwv.googlegroups.com> That is just what I need. I did't mind on 'divide and conquer' :( Thanks a lot! -- Jordi From prikryl at skil.cz Wed Apr 19 02:30:11 2006 From: prikryl at skil.cz (Petr Prikryl) Date: Wed, 19 Apr 2006 08:30:11 +0200 Subject: difference between class and static methods? References: Message-ID: "John Salerno" wrote... [...] > So a class method is specifically for using the class name itself as an > object in the method? If that's the case, then it makes some sense now. > I guess the reason I didn't get it before is that this is a feature of > dynamic languages, right? And something that couldn't have been done in > C# anyway? Yes, almost. You can think about a class method as about something that can be called even if no object of that class was created. It can be called through the class name. But it can also be called through the instance (the object). On the other hand, the normal method can be called only through the object. It does not belong to the class -- see below. The class method has access to the class variables, but not to the instance variables (no instance may exists) -- not shown here. Try the following script (I have stored it as a.py) --------------------------------------------------- class C: def __init__(self): print 'Instance of the class C was created.' @classmethod def myClassMethod(cls): print 'myClassMethod called' def myMethod(self): print 'myMethod (i.e. the normal one) was called.' C.myClassMethod() obj = C() obj.myClassMethod() obj.myMethod() C.myMethod() # cannot be done, error. --------------------------------------------------- And run it C:\tmp>python a.py myClassMethod called Instance of the class C was created. myClassMethod called myMethod (i.e. the normal one) was called. Traceback (most recent call last): File "a.py", line 18, in ? C.myMethod() TypeError: unbound method myMethod() must be called with C instance as first argument (got nothing instead) pepr From amorgan at xenon.Stanford.EDU Thu Apr 6 17:35:44 2006 From: amorgan at xenon.Stanford.EDU (Alan Morgan) Date: Thu, 6 Apr 2006 14:35:44 -0700 (PDT) Subject: efficiency of range() and xrange() in for loops References: Message-ID: In article , Georg Brandl wrote: >Alan Morgan wrote: > >>>range is giving you a real list, while xrange is giving you an xrange object. >>>Have you tried to slice an xrange object? Or using .append on it? >> >> No, I hadn't. I presume these could all be defined. > >How would xrange(100).remove(1) work? One way is by first converting the xrange to a list. If we think of the xrange as an efficient and space lean way to store certain types of lists then it isn't unreasonable to return a regular list when the conditions no longer hold. Or extend the xrange object to allow multiple ranges and return the union of xrange(0,1) and xrange(2,100). No reason why you can't define the whole range of list operations over xrange and still leave it as a nice, lazy list (other languages do). It's possible that no one needs it enough to make it worthwhile (although having full fledged lazy structures can really helpful when you need them) but it could be done. Alan -- Defendit numerus From tedroche at tedroche.com Fri Apr 28 13:10:18 2006 From: tedroche at tedroche.com (Ted Roche) Date: Fri, 28 Apr 2006 13:10:18 -0400 Subject: Awesome PySIG meeting last night In-Reply-To: <155dc4110604280731p7543c651g40695fa6a5fd2daa@mail.gmail.com> References: <353C0F99-9F34-44C4-9E0D-8B640C1F3B34@tedroche.com> <155dc4110604280731p7543c651g40695fa6a5fd2daa@mail.gmail.com> Message-ID: <9C2DF693-B3C3-439C-8CF4-1D6761CFF44A@tedroche.com> On Apr 28, 2006, at 10:31 AM, Ben Scott wrote: > I must say, the level of harrassment was fairly low. I expect a > higher quality of heckling from this group. Don't let it happen > again. Be careful what you wish for! Ted Roche Ted Roche & Associates, LLC http://www.tedroche.com From sambo at void.com Sat Apr 22 17:17:02 2006 From: sambo at void.com (Sambo) Date: Sat, 22 Apr 2006 17:17:02 -0400 Subject: Problem calling math.cos() In-Reply-To: References: <3ev2g.9680$%97.5795@newsfe15.lga> Message-ID: Roy Smith wrote: > In article <3ev2g.9680$%97.5795 at newsfe15.lga>, Sambo > wrote: > > >>I have the following module: >>------------------------------- >>import math >> >>def ac_add_a_ph( amp1, ph1, amp2, ph2 ): >> >> amp3 = 0.0 >> ph3 = 0.0 >> ac1 = ( 0, 0j ) >> ac2 = ( 0, 0j ) >> ac3 = ( 0, 0j ) >> ac1 = complex( amp1 * math.cos( math.radians( ph1 ) ), amp1 * math.sin( >> math.radians( ph1 ) ) ) >> ac2 = complex( amp2 * math.cos( math.radians( ph2 ) ), amp2 * math.sin( >> math.radians( ph2 ) ) ) >> ac3 = ac1 + ac2 >> amp3 = math.abs( ac3 ) >> ph3 = math.atan( ac3.imag / ac3.real ) >> return [amp3, ph3] >>-------------------------------------- >>when I import it (electronics) in python.exe in windows2000 and >>try to use it, it croaks. ??? >> >> >>>>>import math >>>>>import electronics >>>>>print electronics.ac_add_a_ph( 10, 0 , 6 , 45 ) >> >>Traceback (most recent call last): >> File "", line 1, in ? >> File "f:\devel\python\electronics.py", line 10, in ac_add_a_ph >> ac1 = complex( amp1 * math.cos( math.radians( ph1 ) ), amp1 * math.sin( >> math >>.radians( ph1 ) ) ) >>NameError: global name 'cos' is not defined >> > > That's not what I get when I run it (admittedly, not on windows). I get: > > >>>>import math >>>>import electronics >>>>print electronics.ac_add_a_ph( 10, 0 , 6 , 45 ) > > Traceback (most recent call last): > File "", line 1, in ? > File "electronics.py", line 13, in ac_add_a_ph > amp3 = math.abs( ac3 ) > AttributeError: 'module' object has no attribute 'abs' > > > which is exactly what I expected, since abs (which is indeed absolute > value) is a built-in function, not a part of the math module. Are you sure > the stack trace you posted matches the source code you posted? > Well I took the abs( 'complex' ) from the python documentation (python24.chm) section 3.1.1 has the following comment after it '# sqrt(a.real**2 + a.imag**2)' > By the way, when using math functions, I find it's usually easier to import > them into my namespace by doing "from math import *", then I can just use > sin(), cos(), etc directly, instead of having to do math.sin() or > math.cos(). Especially for common math functions, this makes your code a > lot easier to read. Ah, I thought I used to use module functions without the module name. I think my problem is reimporting electronics(.py) after modifications. Yes, now it complains about abs(). looks like enother reason to dump this w2000 installation just so I can install python from scratch and use idle. From quentel.pierre at wanadoo.fr Thu Apr 13 11:23:59 2006 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: 13 Apr 2006 08:23:59 -0700 Subject: New Karrigel page in Wikipedia In-Reply-To: References: <1144867025.095969.92870@e56g2000cwe.googlegroups.com> Message-ID: <1144941839.418567.273420@e56g2000cwe.googlegroups.com> The web server in Karrigell is actually application-independant. An application is a set of scripts or static files, generally stored in the same directory ; the server parses the http requests, searches for a file matching this request, processes the file according to its extension and sends the response For instance, the distribution provides a number of demo applications (a calendar, a wiki server, a forum etc) that can be all used when you start the server If you want to add a new application you just have to add the files, it will run without having to restart the server ; if you modify a script with a text editor, you see the result of the change the next time you reload the page Pierre From http Wed Apr 12 10:18:45 2006 From: http (Paul Rubin) Date: 12 Apr 2006 07:18:45 -0700 Subject: random.sample with long int items References: <1144848541.805554.122180@u72g2000cwu.googlegroups.com> Message-ID: <7xvete3mii.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > e.g. you would do this: random.sample(xrange(10**10), 60) > except it raises an exception. For a population that large and a sample that small (less than sqrt(population size), the chance of collision is fairly small, so you can just discard duplicates. This relies on Python 2.4's randrange function to generate arbitrarily large ranges, which in turn relies on having getrandbits (new 2.4 feature, thanks Ray) available: samp = Set() while len(samp) < 60: samp.add(random.randrange(10**10)) From maxerickson at gmail.com Sat Apr 29 10:22:34 2006 From: maxerickson at gmail.com (Max Erickson) Date: Sat, 29 Apr 2006 14:22:34 +0000 (UTC) Subject: Need help removing list elements. References: <1146316090.540227.278230@j73g2000cwa.googlegroups.com> Message-ID: nuffnough at gmail.com wrote in news:1146316090.540227.278230 at j73g2000cwa.googlegroups.com: > But this gives me "IndexError: list out of range You are making the list shorter as you are iterating. By the time your index is at the end of the original list, it isn't that long any more. Creating a new list and appending the elements you want to keep avoids the problem. Or you can just use a list comprehension(untested): returned_lines=[line for line in open("lines.txt", 'rb') if line != ""] or just returned_lines=[line for line in open("lines.txt") if line] max From nobody at 127.0.0.1 Sun Apr 30 20:26:18 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Mon, 01 May 2006 00:26:18 GMT Subject: ending a string with a backslash References: <445546c8$0$13341$c3e8da3@news.astraweb.com> Message-ID: John Salerno wrote: > Obviously the single backslash at the end of 'path' will cause a > problem, and escaping it with a backslash seems to fix this problem, but > how does escaping work when I already have it as a raw string? see the first two items here: http://www.ferg.org/projects/python_gotchas.html From fredrik at pythonware.com Thu Apr 13 02:59:39 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 13 Apr 2006 08:59:39 +0200 Subject: Regular Expression: Matching substring References: <1144895624.539696.322960@e56g2000cwe.googlegroups.com><443ded05$1@news.eftel.com> <1144910066.778083.304640@v46g2000cwv.googlegroups.com> Message-ID: "Kevin CH" wrote: news:1144910066.778083.304640 at v46g2000cwv.googlegroups.com... > Thank you for your reply. > > > Perhaps you are using grep, or you have stumbled on the old deprecated > > "regex" module and are using that instead of the "re" module. Perhaps > > not as you are using only 2 plain vanilla RE operations which should > > work the same way everywhere. Perhaps you are having trouble with > > search() versus match() -- if so, read the section on this topic in the > > re docs. It's rather hard to tell what you are doing without seeing the > > code you are using. > > Sorry I should have said it up front. I'm using Kudos (which I'm sure > uses re module) to test these strings on the pattern, and had the match > results as I stated. (search() of course gives me true since the > pattern appears in the substrings of both strings.) Python's "match" function doesn't return "true" or "false"; it returns a match object if the string matches the pattern, and None if not. since your pattern can match the empty string, it'll match any target string (all strings start with an empty string), and will never return false. looks like the "debugger" does a great job of hiding how things really work... From pmartin at snakecard.com Thu Apr 20 18:30:33 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Thu, 20 Apr 2006 17:30:33 -0500 Subject: Python IDE for linux References: <20060419214307.2e63c5cd.neil.isaac@sympatico.ca> Message-ID: If your PC can handle eclipse ... memory-wise, I strongly suggest you give pydev a shot. Philippe Neil Isaac wrote: > I have been writing python my little python scripts in gedit and running > them using the command line. At this point I'm thinking that I would like > to start using a real IDE. I don't need anything special or fancy, but > would like it to manage projects, etc... > > I do know about kdevelop and emacs/vi(m)/nano/pico, but I use gnome most > of the time and would rather (but not require) that the ide use anything > other than qt. Aside from just IDEs, I would love to hear about > eclipse/jedit/(anjuta?) plugins. > > Thanks. > > -- > Neil Isaac > neil.isaac at sympatico.ca From kent at kentsjohnson.com Thu Apr 6 09:02:03 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Thu, 06 Apr 2006 09:02:03 -0400 Subject: How to change the docs - a case study In-Reply-To: References: <4434fcb8$1_3@newspeer2.tds.net> Message-ID: <44350be9$1_1@newspeer2.tds.net> Fredrik Lundh wrote: > Kent Johnson wrote: > >> Here is an example. This morning I noticed a minor discrepancy in the >> docs for the 'rot13' encoding. I posted a bug to SourceForge at 10:05 >> GMT. At 10:59 someone commented that maybe the code was broken rather >> than the docs. At 11:18 another poster responded that the code should >> stay the same. At 11:25, less than two hours after my original report, a >> fixed was checked in. > > how many manhours did this take, in total ? did you clock your own efforts ? It took a few minutes of my time. Maybe a minute to verify that there was no similar bug report, a few minutes to write up my findings and submit them. I don't know how much time the other posters spent but the total clock time from OP to fix was 1 hour 20 minutes so that gives you an upper bound. > >> The complete exchange is here: >> https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1465619&group_id=5470 > > the 2.4.3 doc is still broken: > > http://docs.python.org/lib/standard-encodings.html > > (and if I hadn't kicked people around a couple of months ago, even the development > documentation, which still hasn't been updated, btw, would remain broken for another > 4-6 months.) My understanding is that there is a build step required. So the change isn't public yet but I expect it will be. > >> The point being that there is a system in place that in my experience works pretty >> well. > > so you're saying that we cannot do better, and that people who try should do some- > thing else with their time ? No, I didn't say that at all. You are welcome to spend your time as you like. I'm saying that IMO the current system works pretty well and suggesting that some people may find posting patches to SourceForge to be an easy and effective way to change the docs. Kent From eric_brunel at despammed.com Fri Apr 21 03:01:15 2006 From: eric_brunel at despammed.com (Eric Brunel) Date: Fri, 21 Apr 2006 09:01:15 +0200 Subject: How can I call a python method from the XML-RPC client in Java? References: <1145557883.584164.97830@t31g2000cwb.googlegroups.com> Message-ID: On 20 Apr 2006 11:31:23 -0700, wrote: > Hi all, > I have created a XML-RPC model (with server and client) written in > Java. > I want to call the methods in another XML-RPC model written in > Python. > I know that in Java, I can use like > "xmlrpc_client.excute("handler_name.method", param)" to call the > methods in my xml-rpc server written in java. > But how can I call the methods in Python? I cannot creat a handler > in my Python XML-RPC server..... I'm not quite sure I understand the question. You seem to say that you have both a client and a server in Java, and Python server. That means one client and 2 servers, right? Are both servers up and running? IOW, do you have a problem to *call* the Python server from the Java client, or to *write* the Python server? Can you post some code (maybe not the full one, but a simpler version showing what you're trying to do and what does not work)? -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From fanglicheng at gmail.com Wed Apr 26 04:51:06 2006 From: fanglicheng at gmail.com (Licheng Fang) Date: 26 Apr 2006 01:51:06 -0700 Subject: Nested Lists Assignment Problem In-Reply-To: References: <1146039200.264901.317920@j33g2000cwa.googlegroups.com> Message-ID: <1146041466.290523.15010@v46g2000cwv.googlegroups.com> Dennis Lee Bieber wrote: > On 26 Apr 2006 01:13:20 -0700, "Licheng Fang" > declaimed the following in comp.lang.python: > > > > > > Could anybody please explain to me why three values were change? I'm > > bewildered. Thanks! > > http://www.aifb.uni-karlsruhe.de/Lehrangebot/Winter2000-01/E-Shop/Python/Doku/The%20Whole%20Python%20FAQ.htm#4.50 > -- > > ============================================================== < > > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > > wulfraed at dm.net | Bestiaria Support Staff < > > ============================================================== < > > Home Page: < > > Overflow Page: < Thank you very much! But I still wonder why a nested assignment "a = [[0]*3]*3" generates 3 references to the same list, while the commands below apparently do not. >>> a = [0] * 2 >>> a [0, 0] >>> a[0] = 1 >>> a [1, 0] From goldfita at signalsguru.net Thu Apr 6 20:41:59 2006 From: goldfita at signalsguru.net (Todd) Date: 6 Apr 2006 17:41:59 -0700 Subject: confusing behaviour of os.system Message-ID: <1144370519.532028.37920@u72g2000cwu.googlegroups.com> I'm trying to run the following in python. os.system('/usr/bin/gnuclient -batch -l htmlize -eval "(htmlize-file \"test.c\")"') This connects to xemacs with gnuclient and runs htmlize. If I run it from a shell, xemacs gives me an error, but it generates the html file just fine. If I run the same statement in python, I get the exact same behaviour, but there's no file. I'm not sure what the issue is. I thought maybe it's putting it in another directory or there might be some permissions problem. Any ideas? If you want to try it, just make sure to run "M-x gnuserve-start" first. From fredrik at pythonware.com Thu Apr 6 01:21:28 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 6 Apr 2006 07:21:28 +0200 Subject: XMLRPCLIB appears to be broken? References: <1144299571.452329.310640@j33g2000cwa.googlegroups.com> Message-ID: "flamesrock" wrote: > So.. why the heck is it doing this???? Clearly it's pythons fault, but do you run PHP on a Python emulator ? if not, I completely fail to see how it can "clearly be Python's fault" that the XML-RPC binding you're using for PHP don't understand the XML-RPC protocol. > 1)why? > 2)how do I fix it? get a working XML-RPC binding for PHP. From ldo at geek-central.gen.new_zealand Sat Apr 22 05:34:18 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 22 Apr 2006 21:34:18 +1200 Subject: FOUNDIT (was Re: massive threading performance) References: <44473787$0$31643$e4fe514c@news.xs4all.nl> <44476832$0$31656$e4fe514c@news.xs4all.nl> <44476e82$0$31650$e4fe514c@news.xs4all.nl> Message-ID: In article <44476e82$0$31650$e4fe514c at news.xs4all.nl>, Paul Sijben wrote: >I found that the problem was caused by the sending thread not giving >control back quickly enough to the receiving thread. > >Also in going through the code I found an old self.s.setblocking(0)call >that was no longer relevant. Removing that solved my problem. > >Something that took 20 seconds now takes just 1. You might also find that it goes still faster if you forego threading and use a select.select loop. From jstroud at ucla.edu Sat Apr 29 21:28:17 2006 From: jstroud at ucla.edu (James Stroud) Date: Sat, 29 Apr 2006 18:28:17 -0700 Subject: resume picking items from a previous list In-Reply-To: <1146352140.248299.136880@g10g2000cwb.googlegroups.com> References: <1146352140.248299.136880@g10g2000cwb.googlegroups.com> Message-ID: kpp9c wrote: > I have a several list of songs that i pick from, lets, say that there > are 10 songs in each list and there are 2 lists. > > For a time i pick from my songs, but i only play a few of the songs in > that list... now my wife, Jessica Alba, comes home, and i start playing > from Jessica's list of songs. After playing a few songs, Jessica, who > needs her beauty sleep, goes to bed, and i start my play loop which > starts picking from my songs again... > > The wrinkle: > only now i want it to pick first from among the 6 songs yet not played > from the first time around, and *then* when the list is exhausted, > shuffle the whole original list of songs and start again. > > Here is some working but hilariously bad code that does most of this > funny biz... I've gotten this far, but can't figure out how to get the > loops to keep track of what was played and what wasn't and how to > pick-up the list where it left off. > > I know this is a dumb thing to want to do, but you know, being married > to bona-fide star is not easy. > > # ----------------------------------------------------------- > #!/usr/bin/env python > > import random > import os > > def shuffleloop(iterable): > """An iterator like itertools cycle, which returns elements from the > iterable and saves a copy of each. When the iterable is > exhausted, it return elements from the saved copy. > > The added wrinkle here is that the saved copy is randomly shuffled. > Repeats indefinitely.""" > saved = [] > for element in iterable: > yield element > saved.append(element) > while saved: > random.shuffle(saved) > for element in saved: > yield element > > def playall_reload(startime, playdur, smpl_lst): > '''a loop that shuffles and plays all sounds in a list. If the > sequence is exhausted the list is reloaded, re-shuffled, and plyed > through > again. It does this as many times as needed to fill the time > specified. > > Also returns the end of the last duration so that the begining of the > next > section can be fed to the next function or loop. > ''' > event = 0; incr = 0; lst_len = len(smpl_lst) > random.shuffle(smpl_lst) > smpl_loop = shuffleloop(smpl_lst) > endpoint = startime + playdur > while startime < endpoint: > sample = smpl_loop.next() > splt = os.path.split(sample) > # get the duration of the current soundfile > # (hard wire it for now) > #incr = DUR() > dur = 10 > #load the sample & play it > # > # input(sample) > # PLAY(startime, dur) > # > print "event %d @ %.4f --> [%s] dur: %.4f" % (event+1, startime, > splt[1], dur) > incr = dur > startime = startime + incr > event = event + 1 > if (event < lst_len): > print "\n\n*** Heads-up yo: > ***\n\n" > return startime > > > def test(): > kevins = ['/Users/kevin/snd/songs/loveisintheair.aif', > '/Users/kevin/snd/songs/boymeetsgirl.aif', > '/Users/kevin/snd/songs/yourcheatingheart.aif', > '/Users/kevin/snd/songs/kindletheflame.aif', > '/Users/kevin/snd/songs/mywifeissohot.aif', > '/Users/kevin/snd/songs/haha.aif', > '/Users/kevin/snd/songs/blueberryorstrawberry.aif', > '/Users/kevin/snd/songs/didyoupaytheelectricbill.aif', > '/Users/kevin/snd/songs/whereistheremote.aif', > '/Users/kevin/snd/songs/youspenthowmuchforthoseshoes.aif'] > > jessicas = ['/Users/kevin/snd/quiet_songs/iloveu.aif', > '/Users/kevin/snd/quiet_songs/uloveme.aif', > '/Users/kevin/snd/quiet_songs/wearehappy.aif', > '/Users/kevin/snd/quiet_songs/wearesad.aif', > '/Users/kevin/snd/quiet_songs/letsbreakup.aif', > '/Users/kevin/snd/quiet_songs/letsgetbacktogether.aif', > '/Users/kevin/snd/quiet_songs/walkinthesunshine.aif', > '/Users/kevin/snd/quiet_songs/iloveutruly.aif', > '/Users/kevin/snd/quiet_songs/whosefootisthat.aif', > '/Users/kevin/snd/quiet_songs/ohbaby.aif'] > > print > one = playall_reload(1.00, 20.00, kevins) > print > two = playall_reload(one, 180, jessicas) > print > three = playall_reload(two, 40.00, kevins) > > if __name__ == '__main__': > test() > I didn't read your code, but a class might make it simpler: class Playah(object): def __init__(self, playlist): self.playlist = playlist self.reset() def reset(self): self._order = randrange(len(self.playlist)) self._i = 0 def next(): song = self.playlist(self._i) self._i += 1 if self._i > len(self.playlist): self.reset() return song You could probably make it an iterable if you tried. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From mahs at telcopartners.com Sat Apr 8 18:12:50 2006 From: mahs at telcopartners.com (Michael Spencer) Date: Sat, 08 Apr 2006 15:12:50 -0700 Subject: How to determine if a line of python code is a continuation of the line above it In-Reply-To: <1144529313.234854.37960@e56g2000cwe.googlegroups.com> References: <1144520644.233293.81050@u72g2000cwu.googlegroups.com> <1144529313.234854.37960@e56g2000cwe.googlegroups.com> Message-ID: Sandra-24 wrote: > No it's not an academic excercise, but your right, the situation is > more complex than I originally thought. I've got a minor bug in my > template code, but it'd cause more trouble to fix than to leave in for > the moment. > > Thanks for your input! > -Sandra > Take a look at the codeop module in the standard library Michael From jstroud at ucla.edu Fri Apr 28 22:58:33 2006 From: jstroud at ucla.edu (James Stroud) Date: Fri, 28 Apr 2006 19:58:33 -0700 Subject: (was Re: Xah's Edu Corner: Criticism vs Constructive Criticism) In-Reply-To: <1146274750.197445.63470@e56g2000cwe.googlegroups.com> References: <1145992903.834316.198370@u72g2000cwu.googlegroups.com> <4GM3g.3084$TT.1768@twister.nyroc.rr.com> <1146231280.733609.143230@e56g2000cwe.googlegroups.com> <4452258e$0$655$bed64819@news.gradwell.net> <1146256087.184361.147730@g10g2000cwb.googlegroups.com> <1146274750.197445.63470@e56g2000cwe.googlegroups.com> Message-ID: Tagore Smith wrote: > I generally enjoy his posts. You should be happy then that they have all been archived on his website for quite some time. I'm thinking of cross-posting Soren Keirkegaards _Either/Or_. Its been archived for a while now and is full of nonsensical ramblings, but I feel the need to post it for some attention starved reason. You might enjoy it when I put it up on your favorite newsgroup (and several other groups to boot). James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From bignose+hates-spam at benfinney.id.au Thu Apr 27 20:22:04 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 28 Apr 2006 10:22:04 +1000 Subject: Using Parts of PEAK References: <1146166155.101720.24810@g10g2000cwb.googlegroups.com> Message-ID: <87zmi6eehf.fsf@benfinney.id.au> redefined.horizons at gmail.com writes: > I was intriuged by the concept of Python Eggs and some of the work > that has been done on PEAK. > > http://peak.telecommunity.com/ > > However, I think PEAK might be overkill for the particular design I > am considering. Is anyone using just part of PEAK in their Python > development. Yes, Python eggs, and thus the 'setuptools' and 'easy_install' features of PEAK, are commonly employed by projects in recent times. It's not necessary to use any other part of PEAK to use setuptools. -- \ "A free society is one where it is safe to be unpopular." -- | `\ Adlai Ewing Stevenson | _o__) | Ben Finney From pmartin at snakecard.com Sat Apr 29 11:00:21 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Sat, 29 Apr 2006 10:00:21 -0500 Subject: wxPython, wxcombobox opening References: Message-ID: <9cL4g.4233$B42.2019@dukeread05> Hi, I do not have the answer but am very interested in the issue. I tried this: l_ev = wx.MouseEvent(wx.wxEVT_LEFT_DOWN) l_ev.SetEventObject(self.GetCombo()) self.GetEventHandler().ProcessEvent(l_ev) Which did send the event to the combo (which is in a pannel in my case) .. but that is apparently not the event that triggers the dropping of the list. I posed elsewhere and will forward here any hint. Philippe Rony Steelandt wrote: > Hi, > > Does somebody knows a way to automaticely open the list part of a > wxCombobox when it gets the focus ? > > tia, > > Rony From sjuranic at gmail.com Tue Apr 4 10:43:09 2006 From: sjuranic at gmail.com (Steve Juranich) Date: Tue, 04 Apr 2006 07:43:09 -0700 Subject: Difference in Python and Ruby interactive shells References: <1144159204.450444.297870@t31g2000cwb.googlegroups.com> Message-ID: dmh2000 wrote: > I am experimenting with the interactive interpreter environments of > Python and Ruby and I ran into what seems to be a fundamental > difference. However I may be doing something wrong in Python. Please > comment and correct me if I am wrong > > In both languages, you can start up the interactive interpreter > ('python' and 'irb'), load source files and do stuff, like create > objects and call their methods. When you want to change something, you > can edit those same source files outside the environment and reload > them from within the interactive environment. But, here is the > difference: with Python, when you reload the source file (module in > Python terms), it seems that your existing variables stay bound to the > implementations from the old version of the module. In Ruby, after a > reload, your existing variables point to the new implementation. At > least, that is what happens with classes and their methods. This means > that in Python, if you have an application built up interactively, with > references to objects, data structures pointing to objects, etc., you > would have to reconstruct that application to get the new > implementation. With Ruby, when you load the new implementation, you > get it immediately. This is correct. I'm a bit fuzzy on the details, so some of this might be wrong, but here's what's going on (I'm pretty sure): When Python loads (or reloads) a module, it encounters a `class' block, which causes it to create a new type in memory. The instances created from this type are bound to the type object. This means that after a reload, your "B" class is pointing to a different object in memory. However, all of your previous instances are still bound to the old definition (which is still in memory, it's just not bound to the "B" name any more). As a simple test, do 'x.__class__ is y.__class__'. This should return False. Ruby, on the other hand, allows you to redefine classes on the fly. So when Ruby reads a 'class' block, it's either (1) redefining a previously defined object's definition, or (2) creating a new class with the definition in the block. I *think* that the reason for this is that the Python virtual machine (aka, the interpreter) is much more efficient than the Ruby VM. So if you want fast code, I'd stick with Python. However, if you regularly build large applications in memory from an interactive interpreter, then perhaps Ruby is the way for you to go. :-) Cheers. -- Steve Juranich Tucson, AZ USA From grante at visi.com Fri Apr 14 10:14:49 2006 From: grante at visi.com (Grant Edwards) Date: Fri, 14 Apr 2006 14:14:49 -0000 Subject: telnet read_sb_data References: <2khu32leqvokk8jnt67nsf4e1f4bnr5deq@4ax.com> Message-ID: <123vbipspjl9s96@corp.supernews.com> On 2006-04-14, Arne wrote: > Yes I have read the documentation. But I am not sure what is > the SB/SE suboption. Is this a suboption on the remote machine > or for Python. Maybe you could be so kind and explain it to me > with a little code example. SB/SE are used for telnet protocol option negotation for telnet protocol options that are more complicated that just on/off. It has absolutely nothing to do with what you're trying to do. For more info, read the RFC on the telnet protocol option negotiation: http://www.faqs.org/rfcs/rfc855.html Here's another decent article: http://www.scit.wlv.ac.uk/~jphb/comms/telnet.html -- Grant Edwards grante Yow! .. I at feel... JUGULAR... visi.com From michele.simionato at gmail.com Tue Apr 11 07:41:54 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 11 Apr 2006 04:41:54 -0700 Subject: updated pre-PEP: The create statement In-Reply-To: References: <1144741586.861381.190350@z34g2000cwc.googlegroups.com> Message-ID: <1144755714.001318.233020@z34g2000cwc.googlegroups.com> Peter Hansen wrote: > Michele Simionato wrote: > > You can pull out the example in the official > > PEP, if you like. > > Please do. If this is supposed to have anything to do with namespaces, > it has nothing to do with the type of data structures XML is capable of > and the presence of this example would only lead some people to think > there can't be a good use case for the whole idea if that's the best we > can come up with to demonstrate its benefits. Sorry for the multiple posting (Google failed me) and yes, let's remove the XML example. Michele Simionato From jzgoda at o2.usun.pl Tue Apr 18 15:29:54 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Tue, 18 Apr 2006 21:29:54 +0200 Subject: [OT] Any Python lullabies? In-Reply-To: References: Message-ID: Christos Georgiou napisa?(a): > Since there have been python limmericks, are there any Python lullabies that > I can sing to my newborn son (actually, born yesterday)? I tried to murmur > some select parts from the tutorial, but he somehow wasn't very interested > :) Your son is too small to understand all the good that comes with Python. Let him be a usual newborn, but prepare a harness like I did for my daughter (now nearly 2 y.o.): Tuxpaint. Now it's a big time to add Python scripting to this proggie. ;) Let our children see that programming can be straight and easy. Let them express their thoughts as programs, if they wish to do so. -- Jarek Zgoda http://jpa.berlios.de/ From wolfgang.eichler at ca.com Fri Apr 28 03:34:49 2006 From: wolfgang.eichler at ca.com (eicwo01) Date: 28 Apr 2006 00:34:49 -0700 Subject: Get all attributes of a com object References: <1146151043.933987.145080@t31g2000cwb.googlegroups.com> <4450e4b7$0$21092$626a54ce@news.free.fr> Message-ID: <1146209689.917251.224530@g10g2000cwb.googlegroups.com> Thanks for your tips. But dir() and inspect did not really help. dir(): ['GetIDsOfNames', 'GetTypeInfo', 'GetTypeInfoCount', 'Invoke', 'InvokeTypes', 'QueryInterface', '_ApplyTypes_', '_FlagAsMethod', '_LazyAddAttr_', '_NewEnum', '_Release_', '__AttrToID__', '__LazyMap__', '__call__', '__cmp__', '__doc__', '__getattr__', '__getitem__', '__init__', '__int__', '__len__', '__module__', '__nonzero__', '__repr__', '__setattr__', '__setitem__', '__str__', '_builtMethods_', '_enum_', '_find_dispatch_type_', '_get_good_object_', '_get_good_single_object_', '_lazydata_', '_make_method_', '_mapCachedItems_', '_oleobj_', '_olerepr_', '_print_details_', '_proc_', '_unicode_to_string_', '_username_', '_wrap_dispatch_'] pprint.pprint(inspect.getmembers(objDom)): [('GetIDsOfNames', ), ('GetTypeInfo', ), ('GetTypeInfoCount', ), ('Invoke', ), ('InvokeTypes', ), ('QueryInterface', >>), ('_ApplyTypes_', >>), ... Further more this nice method also did not know any more: objDom._print_details_(): AxDispatch container Dispatch wrapper around Methods: Props: Get Props: Put Props: Any additional hint ? Could it be, that you must know in advance, what to ask a com object; so there is no dump possibility ? Thanks Wolfgang From timr at probo.com Fri Apr 21 01:31:21 2006 From: timr at probo.com (Tim Roberts) Date: Fri, 21 Apr 2006 05:31:21 GMT Subject: Updated PEP 359: The make statement References: <_aydnYpYE_rjuNjZRVn-og@comcast.com> Message-ID: Steven Bethard wrote: >Steven Bethard wrote: >> I've updated PEP 359 with a bunch of the recent suggestions. ... > >Guido has pronounced on this PEP: > http://mail.python.org/pipermail/python-3000/2006-April/000936.html >Consider it dead. =) I tried to follow the thread backwards and find out what proposed change in the "class" construct would render "make" unnecessary, but I couldn't find it. Can you summarize, Steven? -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From robin at NOSPAMreportlab.com Sat Apr 29 15:01:14 2006 From: robin at NOSPAMreportlab.com (Robin Becker) Date: Sat, 29 Apr 2006 19:01:14 +0000 Subject: self modifying code In-Reply-To: References: <445399A1.9020506@jessikat.plus.net> Message-ID: <4453B7FA.3060407@jessikat.plus.net> John J. Lee wrote: > 1. I don't think most people would call that "self-modifying code". I > won't try defining that term precisely because I know you'll just > pick holes in my definition ;-) Don't really disagree about the rewriting code, but the function does re-define itself. > 2. The use of global func is just plain weird :-) > > 3. Peter Otten's version is OK, but how about this, using a closure > instead of globals (UNTESTED) > > def make_func(): > namespace = object() > namespace.data = None > def func(a): > if namespace.data is None: > namespace.data = somethingcomplexandcostly() > return simple(namespace.data, a) > return func > func = make_func() > ....... the inner function is almost precisely what I started with, except I used the global namespace. However, it keeps the test in side the function which costs about 1%. -- Robin Becker From paddy3118 at netscape.net Fri Apr 28 11:24:17 2006 From: paddy3118 at netscape.net (Paddy) Date: 28 Apr 2006 08:24:17 -0700 Subject: Converstion In-Reply-To: <4451BDDE.6030208@lexicon.net> References: <1146181848.615239.281200@j33g2000cwa.googlegroups.com> <1146206766.870443.297810@e56g2000cwe.googlegroups.com> <4451BDDE.6030208@lexicon.net> Message-ID: <1146237857.377980.15620@v46g2000cwv.googlegroups.com> the del version - is that an optimisation? Is it actually faster? - I did not have enough info. to check so just did what came naturally to me :-) - Pad. From g.brandl-nospam at gmx.net Wed Apr 5 10:21:02 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Wed, 05 Apr 2006 16:21:02 +0200 Subject: using range() in for loops In-Reply-To: References: <443324dc$0$11257$c3e8da3@news.astraweb.com> <7x1wwc237g.fsf@ruckus.brouhaha.com> Message-ID: AndyL wrote: > Paul Rubin wrote: >> Normally you'd use range or xrange. range builds a complete list in >> memory so can be expensive if the number is large. xrange just counts >> up to that number. > > so when range would be used instead of xrange. if xrange is more > efficient, why range was not reimplemented? Because of backwards compatibility. range() returns a list, xrange() an iterator: list(xrange(...)) will give the same results as range(...). In for loops, using xrange instead of range makes no difference since the loop only iterates over the range. But it's a problem when someone just does l = range(100) and assumes that he's got a list, probably doing l.remove(5) and so on. In Python 3000, plans are that range() will be the same as xrange() is now, and anyone needing a list can call list(range(...)). Georg From peter at engcorp.com Thu Apr 13 07:41:28 2006 From: peter at engcorp.com (Peter Hansen) Date: Thu, 13 Apr 2006 07:41:28 -0400 Subject: list.clear() missing?!? In-Reply-To: References: <1144767680.583085.310160@v46g2000cwv.googlegroups.com> Message-ID: Alan Morgan wrote: > Ah, but if you know your basic python then you wouldn't be looking for > s.clear() in the first place; you'd just use s[:]=[] (or s=[], whichever > is appropriate). One of very first things newcomers learn (I believe, though I don't know how soon the tutorial teaches it) is to use "dir()" on objects. The clear() method would show up there and quickly attract attention. Neither of the other techniques are likely to be discovered as quickly. (Well, okay, s=[] would be, I'm sure, but to many newcomers that might "feel wrong" as the way to empty out a list, but then we're back to wondering how often there's really a usecase for doing so.) > Personally, it seems more *reasonable* to me, a novice python user, > for s.clear() to behave like s=[] (or, perhaps, for s=[] and s[:]=[] to > mean the same thing). The fact that it can't might be an argument for > not having it in the first place. Then it's a good reason we had this thread, so you could learn something *crucial* to understanding Python and writing non-buggy code: name binding versus variables which occupy fixed memory locations like in some other languages. This has to be by far the most frequent area that newcomer's trip up. But that's another story... -Peter From schwehr at gmail.com Wed Apr 19 13:29:36 2006 From: schwehr at gmail.com (schwehr at gmail.com) Date: 19 Apr 2006 10:29:36 -0700 Subject: += append class operator In-Reply-To: References: <1145466931.858338.162110@z34g2000cwc.googlegroups.com> Message-ID: <1145467775.972278.231500@z34g2000cwc.googlegroups.com> Awesome. Thanks! -kurt From esj at harvee.org Wed Apr 12 15:21:33 2006 From: esj at harvee.org (Eric S. Johansson) Date: Wed, 12 Apr 2006 15:21:33 -0400 Subject: New Karrigel page in Wikipedia In-Reply-To: <1144867025.095969.92870@e56g2000cwe.googlegroups.com> References: <1144867025.095969.92870@e56g2000cwe.googlegroups.com> Message-ID: <443D533D.4090001@harvee.org> Luis M. Gonz?lez wrote: > For those interested in the simplest, easiest and most pythonic web > framework out there, there's a new page in Wikipedia: this all depends on your criteria for simplest and easiest. For me HTML is pure hell. I avoid it whenever possible because it literally makes my hands hurt (worse). It's a pain to modify unless you have a WYSIWYG editor and even then it's still difficult. Stuffing it into Python strings is a double pain because you have to figure out how may times you have to quote your percent signs depending on how may times you render a string. A year or so ago, I discovered aether (google aether manual) and my heart was filled with joy because here was a markup language I could dictate using speech recognition and save myself a great deal of pain when producing web applications. Or so I thought. [bold language is reasonably [bigger simple]] and unlike most higher-level markup languages, it's built out of English words,'[', and ']' which is why it is handicapped friendly. The other advantage of this framework is that it is easy to build your own [words and build application specific vocabularies. But aether by itself brought sorrow with it as well. The original creator was no longer interested in extensions and the ability to create CGI programs was flawed. So in conjunction with an unnamed accomplice, we set about expanding aether and renamed the project Akasha. I simplified the CGI environment significantly. the simplifications make creating CGI significantly easier than with the traditional python module. Each displayed page or page hierarchy is associated with an object. Each object uses the __init__ method for the usual (i.e. instance, and variable initialization). The page_init method is called before a page is rendered and displayed. This gives you the ability to dynamically create markup elements before rendering the page the first time. additional methods can be added and provided one follows the right naming convention, associates each method with a HTML form button. once the button has been pushed, all of the CGI variables are stuffed into a dictionary. Returning data from CGI is simple as well. there is a dedicated dictionary which contains information that can be revealed in a rendered page. The nice thing about this structure for me is that the markup environment doesn't embed any Python but there is a clear channel for communicating both data and markup notation to the display side of the house. I'm not happy that I have markup in my Python but at least I can restrict how far it spreads. Akasha is not perfect, it's not full-featured, it doesn't have any databases associated with it (thank god), but for me it's a dream to use in contrast to the half a dozen web frameworks I tried. if you want to play with it, let me know and I will update CVS at https://savannah.nongnu.org/projects/akasha with the current work in progress --- eric ps. If you check wikipedia it has some rather amusing uplifting definitions for Akasha and Akasha records. Although on bad days I think of Akasha as a code sucking vampire draining the life out of my hands. From sturlamolden at yahoo.no Tue Apr 25 13:26:19 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 25 Apr 2006 10:26:19 -0700 Subject: MinGW and Python In-Reply-To: References: <1145861223.509630.247350@y43g2000cwc.googlegroups.com> <444C79D7.4060007@v.loewis.de> <444DC62B.7000702@v.loewis.de> Message-ID: <1145985979.369429.114040@i39g2000cwa.googlegroups.com> Edward Elliott wrote: > if so, i do see good reason to build with mingw instead of gcc/cygwin. MinGW and Cygwin GCC is actually the same compiler. On Cygwin you can remove the dependency on the cygwin dll by compiling with -mno-cygwin. But as long as the cygwin dll is there, it creates an overhead for any system call. The worst overhead is associated with the Unix fork() system call, which Cygwin must emulate as there are no Win32 equivalent. In particular, a fork() on Unix will be optimized with copy-on-write semantics in the kernel, but Cygwin cannot emulate that as it has no access to the Windows kernel. Another issue is that MinGW and Cygwin implements C++ exceptions with setjmp/longjmp. Other verions of GCC (including DJGPP for DOS) does not do this and as a result produces faster code for C++. I don't know if there are any C++ in Python, but if there is, it will be an issue. it is not an issue for plain C though. Finally, MinGW (I am not sure about Cygwin) statically links the C++ standard library. VC++ and GCC on other platforms (e.g. Linux) does not (normally) do this, and as a result the executables get a smaller footprint. From ark at acm.org Tue Apr 25 16:05:17 2006 From: ark at acm.org (Andrew Koenig) Date: Tue, 25 Apr 2006 20:05:17 GMT Subject: list example References: <1145737240.221433.176160@i40g2000cwc.googlegroups.com> Message-ID: <1iv3g.1448$xX5.503@bgtnsc05-news.ops.worldnet.att.net> "PAolo" wrote in message news:1145737240.221433.176160 at i40g2000cwc.googlegroups.com... > for i in range(1,10): > if i%2: > odd.append(i) > else: > even.append(i) In 2.5 you'll be able to say for i in range(1,10): (odd if i%2 else even).append(i) Whether you want to do this is another question entirely, of course. From theller at python.net Fri Apr 28 11:23:17 2006 From: theller at python.net (Thomas Heller) Date: Fri, 28 Apr 2006 17:23:17 +0200 Subject: os.startfile() - one or two arguments? In-Reply-To: <1146236762.657595.23240@u72g2000cwu.googlegroups.com> References: <1146236762.657595.23240@u72g2000cwu.googlegroups.com> Message-ID: BartlebyScrivener wrote: > Can any Windows user give a working example of adding a "command verb" > to os.startfile()? > > When I try it, it squawks that it takes only one argument. > >>>> os.startfile('d:/','explore') > Traceback (most recent call last): > File "", line 1, in ? > TypeError: startfile() takes exactly 1 argument (2 given) > > from os module > > startfile( path[, operation]) > Start a file with its associated application. > > When operation is not specified or 'open', this acts like > double-clicking the file in Windows Explorer, or giving the file name > as an argument to the start command from the interactive command shell: > the file is opened with whatever application (if any) its extension is > associated. > > When another operation is given, it must be a ``command verb'' that > specifies what should be done with the file. Common verbs documented by > Microsoft are 'print' and 'edit' (to be used on files) as well as > 'explore' and 'find' (to be used on directories). The optional second argument was added in Python 2.5 (currently in alpha). These examples work for me, with python 2.5a2: os.startfile("Rechnung-28.10.pdf", "print") os.startfile("c:\\", "explore") Thomas From Norman.Shelley at freescale.com Fri Apr 21 11:12:21 2006 From: Norman.Shelley at freescale.com (Norman Shelley) Date: Fri, 21 Apr 2006 08:12:21 -0700 Subject: ANN: Pyrr 0.1 - Lexer and LR(1)-Parser Generator for Python In-Reply-To: References: Message-ID: FWIW: This has a similiar look/feel to how sabbey wrapped dparser. http://staff.washington.edu/sabbey/py_dparser/ Heiko Wundram wrote: > Hi list! > > Not long ago I was looking for an easy to use, but powerful parser and lexer > generating tool for Python, and to my dismay, I found quite a number of > Python projects implementing an (LA)LR(1) parser generator, but none of them > seemed quite finished, or even pythonic. > > As I required a parser generator for Python for one of my work projects, I set > out to write (yet another one), and currently am at (release-)version 0.1 for > Pyrr.ltk and ptk. > > An example for Pyrr.ltk and ptk usage implementing a (very) simple calculator: > > <<< > # -*- coding: iso-8859-15 -*- > > from ltk import LexerBase, IgnoreMatch > from ptk import ParserBase > from operator import add, sub, mul, div > > class NumLexer(LexerBase): > > def number(self,value): > """number -> r/[0-9]+/""" > return float(value) > > def ws(self,*args): > """ws -> r/\\s+/""" > raise IgnoreMatch > > def ops(self,op): > """addop -> /+/ > -> /-/ > mulop -> /*/ > -> r/\\//""" > return op > > class NumParser(ParserBase): > """/mulop/: left > /addop/: left""" > __start__ = "term" > > def term(self,value1,op,value2): > """term -> term /addop/ term > -> term /mulop/ term""" > return {"+":add,"-":sub,"*":mul,"/":div}[op](value1,value2) > > def value(self,value): > """term -> /number/""" > return value > > print NumParser.parse(NumLexer.tokenize("3 + 4 - 123 / 23")) > <<< > > Grammar rules and lexemes are specified in docstrings, where lines not > matching a definition of a rule or lexeme are ignored. The resulting lexer > and parser class is, thus, very much self-documenting, which was one of my > biggest goals for the project. > > I'm currently in the process of writing documentation for both packages (and > especially documenting the extensions to BNF-grammars that Pyrr.ptk allows, > such as your usual RE-operators ?, *, + and {x,y}, and forward arguments, and > documenting the stateful lexer support that Pyrr.ltk implements), but I > thought that I'd release early and often, so that people interested in this > project might have a look at it now to input suggestions and extensions that > they'd like me to add to make this a fully featured Python parser generating > toolkit which might be offered as a Python package. > > Anyway, the sources can be downloaded (via subversion) from: > > http://svn.modelnine.org/svn/Pyrr/trunk > > where I'll check in the documentation that I've written so far and a Python > distutils distribution over the weekend, and make sure that I don't check in > brocken code from now on. And, Pyrr.* is Python 2.4 only at the moment, and I > have no plans to make it backwards-compatible, but if you're interested in > backporting it, feel free to mail me patches. > > --- Heiko. From robert.kern at gmail.com Sat Apr 8 14:25:06 2006 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 08 Apr 2006 13:25:06 -0500 Subject: scipy/numpy inverse cumulative normal In-Reply-To: References: Message-ID: bartsimpson8882002 at yahoo.com wrote: > I was wondering if scipy/numpy has the inverse cumulative normal > function, ie the function f in this expression > > f(scipy.stats.norm.cdf(1.2)) = 1.2 > > or more generally, a function f which fits the criteria > > f(scipy.stats.norm.cdf(x)) = x Look in the file where all of the distributions are defined, Lib/stats/distributions.py . You will find that each distribution object also has a method call .ppf(), the Percent Point Function, the inverse of the CDF. In [1]: from scipy.stats import norm In [2]: norm.ppf(norm.cdf(1.2)) Out[2]: array(1.2000000000000004) > There is a distribution called invnorm, but I am not sure of how to use > it. invnorm is another probability distribution entirely. Don't bother with it. -- Robert Kern robert.kern at gmail.com "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From siona at chiark.greenend.org.uk Wed Apr 19 10:39:04 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 19 Apr 2006 15:39:04 +0100 (BST) Subject: multiline comments References: Message-ID: Edward Elliott wrote: >On top of that, the expressive power of nested comments seems greater than >an endless string of ^#s. Sometimes it's just easier to see what's going on. Really? Under what circumstances is it easier to see what's going on with start/end comments than with comment-to-end-of-line? -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From bill.pursell at gmail.com Fri Apr 7 17:21:13 2006 From: bill.pursell at gmail.com (bill pursell) Date: 7 Apr 2006 14:21:13 -0700 Subject: Programming Tutorial for absolute beginners References: <1144439148.751062.16590@t31g2000cwb.googlegroups.com> Message-ID: <1144444872.962395.3310@z34g2000cwc.googlegroups.com> Clodoaldo Pinto wrote: > I'm starting a programming tutorial for absolute beginners using Python > and I would like your opinions. > > http://programming-crash-course.com Very nicely laid out. Overall, a really nice presentation. 2 minor points: 1) in the section on the interactive interpreter you have the sentence: "In Linux open a shell and type python (must be lower case)". It would be nice if the word 'python' were in a different font, or perhaps in quotes, or something. You're targetting the "absolute beginner", so you should assume the reader is not familiar with the CLI. 2) In the section on installing, you begin with: "Python is an interpreted, interactive, object-oriented programming language.". The complete novice sees those words and expects them to be explained, but there is no definition given. I would recommend simplifying that sentence, or explaining the terms. From lialie at 126.com Sun Apr 23 12:33:49 2006 From: lialie at 126.com (Lialie) Date: Mon, 24 Apr 2006 00:33:49 +0800 Subject: how to write special value to a config file with ConfigParser Message-ID: <444BAC6D.6080804@126.com> Hello,all I found it easy to read configures from a config file. But how can I set a special value to an item or write it into the original file? I have tried this: import ConfigParser config = ConfigParser.ConfigParser() config.read('a.conf') config.get('Main', 'Something') # That is OK. config.set('Main', 'Something', '2') # without any fault #fp = open('a.conf') # can not be done, raise Error #fp = open('a.conf', 'a') # Something set to 2, but it copies the all items #config.write(fp) # How can I do it? From steven.bethard at gmail.com Thu Apr 6 11:41:39 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 06 Apr 2006 09:41:39 -0600 Subject: pre-PEP: The create statement In-Reply-To: <1144302248.639529.161700@j33g2000cwa.googlegroups.com> References: <59Wdnbd8EazRCqnZnZ2dnUVZ_vudnZ2d@comcast.com> <1144302248.639529.161700@j33g2000cwa.googlegroups.com> Message-ID: Carl Banks wrote: > Steven Bethard wrote: >> This PEP proposes a generalization of the class-declaration syntax, >> the ``create`` statement. The proposed syntax and semantics parallel >> the syntax for class definition, and so:: >> >> create : >> >> >> is translated into the assignment:: >> >> = ("", , ) >> >> where ```` is the dict created by executing ````. >> The PEP is based on a suggestion [1]_ from Michele Simionato on the >> python-dev list. > > And who needs a class statement after that? > > create type A: > > > That's probably even more readable than class A, if not as familiar. > My biggest concern with this is the special arguments of the caller. > It breaks my heart that we couldn't do something like this: > > create dict keymap: > A = 1 > B = 2 > > And it'll probably confuse people as well. We ought to keep that in > mind. This is definitely an important point. I've thought about this a bit and I'm still not sure which way is the right way to go on this. If the tuple and dict arguments actually get passed as *args and **kwargs arguments, the create statement could be used with a much wider variety of existing callables. I've updated the open issues section of the PEP to point this out. STeVe From fredrik at pythonware.com Sun Apr 2 03:34:11 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 2 Apr 2006 09:34:11 +0200 Subject: Doc suggestions (was: Why "class exceptions" are not deprecated?) References: <1142964085.356976.166620@t31g2000cwb.googlegroups.com><34bb7f5b0603310053u75ad7e9eq5e1c0ab873422483@mail.gmail.com> <1143915474.631514.44470@i39g2000cwa.googlegroups.com> Message-ID: rurpy at yahoo.com wrote: > > and for the record: the infogami setup had never happened if Ed hadn't > > written that post. > > I wouldn't rest on my laurels quite yet if I were you. > You've provided a good piece to take care of the input > collection side of the equasion but I've seen nothing > that deals with the output side (wiki -> docs). no, but that's because you're the kind of pathetic loser who only sees problem with things, and only pops up when you have a chance to piss on something. From penshe at 265.com Sat Apr 29 12:38:05 2006 From: penshe at 265.com (penshe at 265.com) Date: 29 Apr 2006 09:38:05 -0700 Subject: http://blog.wokkow.com/user1/xinyegong/index.shtml Message-ID: <1146328685.847432.16680@y43g2000cwc.googlegroups.com> http://blog.wokkow.com/user1/xinyegong/index.shtml From steven.bethard at gmail.com Sat Apr 29 20:06:36 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 29 Apr 2006 18:06:36 -0600 Subject: best way to determine sequence ordering? In-Reply-To: References: <70q4g.2006$No6.43783@news.tufts.edu> Message-ID: Steven Bethard wrote: > John Salerno wrote: >> If I want to make a list of four items, e.g. L = ['C', 'A', 'D', 'B'], >> and then figure out if a certain element precedes another element, >> what would be the best way to do that? >> >> Looking at the built-in list functions, I thought I could do something >> like: >> >> if L.index('A') < L.index('D'): >> # do some stuff > > This is probably a pretty reasonable approach Just to clarify, because there seems to be some confusion. I would absolutely go with this approach unless you have profiled and found it to be a bottleneck. It's clear, concise, and quite fast. STeVe From johnjsal at NOSPAMgmail.com Fri Apr 21 15:55:57 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 21 Apr 2006 19:55:57 GMT Subject: how to append to a list twice? In-Reply-To: <1145649038.408067.46010@z34g2000cwc.googlegroups.com> References: <4282g.68392$H71.37777@newssvr13.news.prodigy.com> <1145649038.408067.46010@z34g2000cwc.googlegroups.com> Message-ID: callmebill at gmail.com wrote: > I don't get it (the Elliot solution)... How is it that the first value > is repeated once times, and the remaining values are repeated twice > times? > Because of the way division works. The first number in the range is 200, and 200/2 is 100. The next number is 199, and 199/2 is (as division works right now) 99 (99.5 rounded). Next is 198, and that halved is also 99 (this time with no remainder). Every two sets of numbers thereafter also do the same. From aurelien.campeas at free.fr Wed Apr 26 08:29:16 2006 From: aurelien.campeas at free.fr (aurelien.campeas at free.fr) Date: 26 Apr 2006 05:29:16 -0700 Subject: KeybordInterrupts and friends In-Reply-To: References: <1146044514.173026.323700@i39g2000cwa.googlegroups.com> Message-ID: <1146054555.986529.293070@u72g2000cwu.googlegroups.com> Thanks Robert. But I'm not trying something at all with this, only asking if it is a bug (and it looks like one). I suspect too, that it is related to signal handling. Cheers, Aur?lien. From alainpoint at yahoo.fr Tue Apr 11 05:42:11 2006 From: alainpoint at yahoo.fr (alainpoint at yahoo.fr) Date: 11 Apr 2006 02:42:11 -0700 Subject: challenging (?) metaclass problem In-Reply-To: References: <1144656384.077748.229010@u72g2000cwu.googlegroups.com> Message-ID: <1144742649.335274.279800@e56g2000cwe.googlegroups.com> Hi Peter, I don't know if you noticed but i changed my mind and removed the post as i realised that people seemed to have much more interest in how relevant c code still is than in solving an interesting problem. I only speak French and Dutch and my knowledge of Belgium's third official language (German) is only passive. Otherwise i would have posted on the german newsgroup (the French newsgroup does not seem to be so interesting and there are no belgian or dutch newsgroups either). Anyway, thank you for accepting the challenge. I'll try out your code and get back if i have any problem. Viele dank. Alain From ryanlists at gmail.com Wed Apr 19 12:42:49 2006 From: ryanlists at gmail.com (Ryan Krauss) Date: Wed, 19 Apr 2006 12:42:49 -0400 Subject: accessing a classes code In-Reply-To: <444666af$0$12280$626a54ce@news.free.fr> References: <444666af$0$12280$626a54ce@news.free.fr> Message-ID: Because I want to store the results in one place so that in order to use the code later, all I have to do is import the classes that include the parameters that were previously unknown. I want to make using the results as easy and clean as possible for other users. Ryan On 4/19/06, bruno at modulix wrote: > Ryan Krauss wrote: > > I have a set of Python classes that represent elements in a structural > > model for vibration modeling (sort of like FEA). Some of the > > parameters of the model are initially unknown and I do some system > > identification to determine the parameters. After I determine these > > unknown parameters, I would like to substitute them back into the > > model and save the model as a new python class. > > Why ? Python is dynamic enough to let you modify classes at runtime... > > -- > bruno desthuilliers > python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for > p in 'onurb at xiludom.gro'.split('@')])" > -- > http://mail.python.org/mailman/listinfo/python-list > From rzantow at gmail.com Tue Apr 4 10:22:54 2006 From: rzantow at gmail.com (Rick Zantow) Date: Tue, 04 Apr 2006 10:22:54 -0400 Subject: how to comment lot of lines in python References: <1143760897.940841.285300@i39g2000cwa.googlegroups.com> <44310867$1_1@newspeer2.tds.net> <44311ecd$1_3@newspeer2.tds.net> Message-ID: Kent Johnson wrote in news:44311ecd$1_3 at newspeer2.tds.net: > Rick Zantow wrote: >> Kent Johnson wrote in news:44310867$1_1 >> @newspeer2.tds.net: >> >>> Sion Arrowsmith wrote: >>>> Out of curiousity, is there a modern editor which *doesn't* allow >>>> you to comment/uncomment a selected bunch of lines of code? >>>> >>> TextPad is my editor of choice but it doesn't have this feature. >>> >> >> I use TextPad all the time, and while it is true that the feature is >> not built in, it's misleading to say it doesn't have it. It is >> implemented by means of a macro definition. I assign a key to a >> 'comment' macro (basically replacing regex ^ with '# ' for the >> selected text) to do this. And of course I have a reciprocal >> 'uncomment' macro as well. > > Thank you! I don't suppose you have any tricks to make it work with > UTF-8 data outside the cp1252 character set, do you? > Sadly, I don't. TP claims Unicode support, but I'm not sure what they mean; it does seem to be restricted to cp1252. -- rzed From ldo at geek-central.gen.new_zealand Mon Apr 10 23:05:22 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 11 Apr 2006 15:05:22 +1200 Subject: Decorators, Identity functions and execution... References: <1144597938.664642.133100@v46g2000cwv.googlegroups.com> Message-ID: In article , Roy Smith wrote: >One of the most basic >maxims on the Internet has always been, "Be liberal in what you accept, be >conservative in what you produce". How do you explain top-posting, then? From johnjsal at NOSPAMgmail.com Tue Apr 4 00:10:56 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 04 Apr 2006 00:10:56 -0400 Subject: what's going on here? In-Reply-To: <4431eb28$0$17995$c3e8da3@news.astraweb.com> References: <4431eb28$0$17995$c3e8da3@news.astraweb.com> Message-ID: <4431f2c0$0$4209$c3e8da3@news.astraweb.com> John Salerno wrote: > Ok, long story Ok, I guess I should have used a better title for the thread. I hope someone still sees this post! :) From thomasbartkus at comcast.net Tue Apr 25 10:51:42 2006 From: thomasbartkus at comcast.net (Thomas Bartkus) Date: Tue, 25 Apr 2006 09:51:42 -0500 Subject: python application ideas. References: Message-ID: "Anthony Greene" wrote in message news:pan.2006.04.25.03.48.13.511654 at zetafunc.net... > Hello, I know this isn't really a python centric question, but I'm seeking > help from my fellow python programmers. I've been learning python for the > past year and a half, and I still haven't written anything substantial nor > have I found an existing project which blows my hair back. Python is my > first language, and I plan on learning lisp within the next week but > before I do so I'd like to write something meaningful, does anyone have > any suggestions? Something they always needed, but never got around to > writing it? Without an imagination you pretty much stagnate your whole > learning process. Thanks in advance. Just what is it, other than programming, that you have expertise in? What kind of problems do you know how to solve? > Without an imagination you pretty much stagnate your whole > learning process. So true! Unfortunately, no one can provide you with one. You have to develop that yourself. Tis the conundrum of programming in general. If all you know how to do is write code - then you truly have nothing to do. What *other* interests do you have? Hobbies? Job Skills? What *does* "blow your hair back" ;-) That's where your programming ideas need to come from. Thomas Bartkus From dausha at gmail.com Tue Apr 18 18:03:41 2006 From: dausha at gmail.com (Ben Wilson) Date: Tue, 18 Apr 2006 17:03:41 -0500 Subject: Better way to sift parts of URL . . . In-Reply-To: <17477.22880.625171.810170@montanaro.dyndns.org> References: <1145392079.720766.122310@z34g2000cwc.googlegroups.com> <17477.22880.625171.810170@montanaro.dyndns.org> Message-ID: Sorry. I'm writing a python script that retrieves source contents of a wiki page, edits, and re-posts changed content. The wiki breaks pages into groups and pages (e.g. ThisGroup/ThisPage). The sections that are camel cased (or otherwise contain title case) are the group and page for a given page. When a url is passed that is incomplete (i.e., has the base URL and the Group, or only the base URL), the wiki resorts to defaults (e.g. a base URL and Group would return the default page for that group, and a bare URL returns the base page for the base group). I'm playing with urlparse now. Looks like I can do the same thing in a lot fewer steps. I'll post results. Ben On 4/18/06, skip at pobox.com wrote: > > Ben> I am working on a script that splits a URL into a page and a > Ben> url. > > I couldn't tell quite what you mean to accomplish from your example. (In > particular, I don't know what you mean by "default_group", as it's never > defined, and I don't know why the desired output of examples 1 and 6 is the > same, since the URLs are clearly different.) You don't mention having tried > the urlparse module, so I thought I should ask: have you tried using > urlparse? > > Skip > -- Ben Wilson " Mundus vult decipi, ergo decipiatur" From qscomputing at gmail.com Sat Apr 29 01:57:23 2006 From: qscomputing at gmail.com (qscomputing at gmail.com) Date: 28 Apr 2006 22:57:23 -0700 Subject: Non-web-based templating system In-Reply-To: <1146269209.389106.42500@e56g2000cwe.googlegroups.com> References: <1146221757.653214.115090@g10g2000cwb.googlegroups.com> <4bec7mF10pfe5U1@uni-berlin.de> <4452073b$0$23034$626a54ce@news.free.fr> <1146269209.389106.42500@e56g2000cwe.googlegroups.com> Message-ID: <1146290243.218655.210400@u72g2000cwu.googlegroups.com> Actually, that looks even better that EmPy for what I need. I will try out these suggestions and then see what seems best. Thanks very much. From rowen at cesmail.net Mon Apr 10 16:39:59 2006 From: rowen at cesmail.net (Russell E. Owen) Date: Mon, 10 Apr 2006 13:39:59 -0700 Subject: Tkinter problem on Mac OS X References: Message-ID: In article , andrew at trevorrow.com (Andrew Trevorrow) wrote: > Our app uses embedded Python to allow users to run arbitrary scripts. > Scripts that import Tkinter run fine on Windows, but on Mac OS X there > is a serious problem. After a script does "root = Tk()" our app's menus > are permanently changed in the following way: > > - The top item in the application menu changes to "About Tcl & Tk...". > - The Quit item is disabled. > - The File and Edit menus are completely replaced. > - All further menus (except Help) are removed. > > Is there a way to prevent Tkinter clobbering our app's menus? > Or perhaps a way to restore them after the root.mainloop() call? > > I've read Fredrik Lundh's excellent tutorial on Tkinter and done a lot > of googling but haven't been able to find a solution. > > I can probably add some Mac-specific code to detect a menu change after > a script ends and then rebuild our menus, but I'm hoping there's a > simpler Tkinter (or Tcl?) solution. I am pretty sure it's the underlying Tcl/Tk that's causing you grief. Does your application itself use Tcl/Tk anywhere? I'm guessing not, as I'd expect you'd already have gone to some trouble to get the menus right. Unfortunately, I can't offer a solution. You may want to post to the Tkinter mailing list (via news you can use gmane, group gmane.comp.python.tkinter; I'm not sure if you have to sign up for the list before posting). You could import Tcl/Tk yourself "up front" and then fix your application's menus once. But Aqua Tcl/Tk is painfully slow to start up, so this could really slow down startup of your own application. (Note that you'd have to be prepared for Tkinter to be missing (it certainly is by default on 10.3). You might also have to make users use one mainloop (see next paragraph) for this to work. James Stroud also brings up an interesting point--that it could be dangerous if there are multiple scripts each trying to run their own mainloop. But if only one runs at a time, and cleans up after itself, you're probably OK. If that's not the case, you may want to start a Tk main loop yourself and ask users to use that loop. Again, though--it'll take time, and it'll only help those users who use Tkinter in their scripts. -- Russell From usidoesit at yahoo.com Wed Apr 19 15:35:16 2006 From: usidoesit at yahoo.com (RK) Date: 19 Apr 2006 12:35:16 -0700 Subject: Thanks from the Java Developer In-Reply-To: <1145474995.143893.31760@z34g2000cwc.googlegroups.com> References: <1145474995.143893.31760@z34g2000cwc.googlegroups.com> Message-ID: <1145475315.963630.192580@g10g2000cwb.googlegroups.com> Me too. I feel like I've been living under a rock. Did all this just happen in the last few years? From johnjsal at NOSPAMgmail.com Fri Apr 7 10:28:15 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 07 Apr 2006 14:28:15 GMT Subject: how you know you're a programming nerd Message-ID: <3GuZf.1940$No6.41580@news.tufts.edu> So last night I had a dream that me and two other guys needed to get a simple task done in Java. We were staring at the problem in confusion and I kept saying "First we have to create a class, then instantiate it, then..." etc. etc. They didn't agree with me so we kept arguing back and forth about it. Finally, in frustration, I shout "God, Python is so much easier than any other language!" :) It's not the first time I've had a dream about programming (and the others were much more uncomfortable because they involved math), but it's the first time Python has snuck into my subconscious. And as a sidenote, I don't know Java at all, so I have no idea how it found its way into my brain. Of course, it wasn't real Java syntax I was seeing, I'm sure... From michele.petrazzo at TOGLIunipex.it Thu Apr 27 12:00:14 2006 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Thu, 27 Apr 2006 18:00:14 +0200 Subject: pytiff for windows In-Reply-To: <4450ea1a$0$29092$5fc30a8@news.tiscali.it> References: <1146152190.649704.264820@j33g2000cwa.googlegroups.com> <4450ea1a$0$29092$5fc30a8@news.tiscali.it> Message-ID: <4450ea8d$0$29092$5fc30a8@news.tiscali.it> Michele Petrazzo wrote: > >>>> import FreeImagePy as FIPY lst_names = ("/tmp/f1.png", >>>> "/tmp/f2.jpg") F = FIPY.freeimage() F.convertToMultiPage(lst_names, >>>> "out.tif", FIPY.FIF_TIFF) > (0, 'All ok!! File saved on out.tif') > Sorry for this bad copy/paste/thunderbird :) >>> import FreeImagePy as FIPY >>> lst_names = ("/tmp/f1.png","/tmp/f2.jpg") >>> F = FIPY.freeimage() >>> F.convertToMultiPage(lst_names, "out.tif", FIPY.FIF_TIFF) Michele From amaltasb at gmail.com Sun Apr 9 22:15:31 2006 From: amaltasb at gmail.com (amaltasb at gmail.com) Date: 9 Apr 2006 19:15:31 -0700 Subject: Writing files on server through CGI In-Reply-To: References: <1144568121.238866.122800@i40g2000cwc.googlegroups.com> Message-ID: <1144635331.006980.133810@i39g2000cwa.googlegroups.com> this cgi script write different files, request 1 will write 1.html, 2 will write 2.html and so on. Its not updating the current file. For example create.py processes a form and write user.html file and every user is unique. so if 10 users fill up the form at the same time and click submit button, can create.py file write 10 html file simultaneously or will all the request be queued and executed one by one, because at any given point there can be several users creating this html page. From michele.simionato at gmail.com Fri Apr 21 09:29:41 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 21 Apr 2006 06:29:41 -0700 Subject: are docstrings for variables a bad idea? In-Reply-To: <1145615763.943050.170950@j33g2000cwa.googlegroups.com> References: <1145615763.943050.170950@j33g2000cwa.googlegroups.com> Message-ID: <1145626181.891190.31080@i39g2000cwa.googlegroups.com> Notice that class attributes can already be annoted (properties have a docstring). BTW in Python 2.5 you have a convenient way to define readonly attributes (for instance constants) and give them a docstring. Here is an example: class C(object): @property def pi(self): 'pi is 3.14159' return 3.14159 c = C() print c.pi help(C.pi) # gives you the docstring Michele Simionato From noway at sorry.com Wed Apr 5 18:09:29 2006 From: noway at sorry.com (Giovanni Bajo) Date: Wed, 05 Apr 2006 22:09:29 GMT Subject: efficiency of range() and xrange() in for loops References: Message-ID: Steve R. Hastings wrote: >> in Python 2.X, range is defined to return a list. if you start >> returning something else, you'll break stuff. > > Perhaps I'm mistaken here, but I don't see how this optimization could > possibly break anything. Because you assume that the only use-case of range() is within a for-loop. range() is a builtin function that can be used in any Python expression. For instance: RED, GREEN, BLUE, WHITE, BLACK = range(5) -- Giovanni Bajo From rrr at ronadam.com Sat Apr 1 19:42:40 2006 From: rrr at ronadam.com (Ron Adam) Date: Sat, 01 Apr 2006 18:42:40 -0600 Subject: any() and all() on empty list? In-Reply-To: References: <7x3bh1x0ym.fsf@ruckus.brouhaha.com> <42qWf.18211$uX5.7574@tornado.texas.rr.com> <7xzmj9u1di.fsf@ruckus.brouhaha.com> <85tWf.2748$Aa1.1605@dukeread05> <7xy7ytmtk2.fsf@ruckus.brouhaha.com> <7xpsk2f8ab.fsf@ruckus.brouhaha.com> Message-ID: Steve R. Hastings wrote: > On Sat, 01 Apr 2006 14:35:58 -0300, Felipe Almeida Lessa wrote: >> Two changes: >> - Use "is None". >> - Use "try ... except" instead of "in" > > Yes. > > >> Maybe you don't like my version, and the gains aren't that much, but >> please use "is None" instead of "== None". > > Actually, I do like your version. And I try to always use "is None" > instead of "== None"; today I made a mistake about it. Thank you for your > comments. > > Ideally there should be an official tally() function in some module in > Python, and then we can just use it and not worry about how to write it. :-) And it's a good candidate to be written in C as well. Cheers, Ron From aleaxit at yahoo.com Thu Apr 27 03:02:25 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 27 Apr 2006 00:02:25 -0700 Subject: Type-Def-ing Python References: <1146041765.423121.106840@i39g2000cwa.googlegroups.com> Message-ID: <1hefehe.gyyjap1my3zj0N%aleaxit@yahoo.com> wrote: ... > Brett Cannon's thesis in which he tweaks the compiler and shows that > type-defing python would not help the compiler achieve a 5% performace > increase. > > Brett Cannon, "Localized Type Inference of Atomic Types in Python": > http://www.ocf.berkeley.edu/~bac/thesis.pdf > > I was wondering if anyone had his contact information so that I could > might ask him for his source code and try to use type-defing as a > bug-finder. Brett is active on Python-Dev, so post there and you're likely to get a response from him -- your subject is not OT for that list, anyway! Alex From nobody at 127.0.0.1 Tue Apr 25 12:45:02 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Tue, 25 Apr 2006 16:45:02 GMT Subject: MinGW and Python References: <1145861223.509630.247350@y43g2000cwc.googlegroups.com> <444C79D7.4060007@v.loewis.de> <1145968496.649214.100040@i40g2000cwc.googlegroups.com> <1hec9xh.m7rzefh64am3N%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > about MacOSX, which also uses gcc: 14% faster pybench using Python 2.4.3 this is the second time I've seen that 14% figure. OOC, where does it come from? the data sets you posted show an average 12.6% speedup. 14 is an odd way to round. :) I don't think it's very useful to talk about average speedups from a benchmark of equally-weighted feature tests. the data shows wildly varying differences in performance for each test. a real-world application could be much slower or much faster on either platform depending on its feature mix. not the type of thing that's amenable to expression as a single value. From robert.kern at gmail.com Tue Apr 18 08:22:55 2006 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 18 Apr 2006 07:22:55 -0500 Subject: semi-[OT]: adding a reply-to line to these mails? In-Reply-To: <4444CD12.7080807@freakmail.de> References: <4444CD12.7080807@freakmail.de> Message-ID: Wildemar Wildenburger wrote: > I've noticed that I replied to individual posters' private addresses > several times now ... > So a quick note to the admin(s): see topic ;) (Ab)using Reply-To like that is undeservedly controversial. See the section "The Great Reply-To Debate" in Karl Fogel's book _Producing Open Source Software_: http://producingoss.com/html-chunk/mailing-lists.html#reply-to > Hey, maybe I'm just too dumb to use Thunderbird; I haven't figured out a > way to reply comfortably to list posts (take this as a half asses excuse > to why some of you got "private" mail from me ;)) OTOH, I am a big fan of a properly munged Reply-To for mailing lists, which I tend to treat like USENET newsgroups. These days, I read the python-list and many other mailing lists through the appropriate GMane newsgroup gateway, in this case, gmane.comp.python.general . Now, python-list does have a gateway to the regular USENET through comp.lang.python, but I can't access my home ISP's news server at work, so I use GMane instead. -- Robert Kern robert.kern at gmail.com "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From sjmachin at lexicon.net Fri Apr 28 03:01:50 2006 From: sjmachin at lexicon.net (John Machin) Date: Fri, 28 Apr 2006 17:01:50 +1000 Subject: Converstion In-Reply-To: <1146206766.870443.297810@e56g2000cwe.googlegroups.com> References: <1146181848.615239.281200@j33g2000cwa.googlegroups.com> <1146206766.870443.297810@e56g2000cwe.googlegroups.com> Message-ID: <4451BDDE.6030208@lexicon.net> On 28/04/2006 4:46 PM, Paddy wrote: > Something like (untested): > > out = [] > for ch in instring: > if ch==backspace: > if out: > out = out[:-1] > else: > out.append(ch) > outstring = ''.join(out) Instead of: if out: out = out[:-1] consider: del out[-1:] From kadeko at gmail.com Tue Apr 11 10:42:36 2006 From: kadeko at gmail.com (looping) Date: 11 Apr 2006 07:42:36 -0700 Subject: Why new Python 2.5 feature "class C()" return old-style class ? In-Reply-To: References: <1144752553.305591.88050@j33g2000cwa.googlegroups.com> <1144756774.177225.311120@z34g2000cwc.googlegroups.com> Message-ID: <1144766556.179782.146210@g10g2000cwb.googlegroups.com> Georg Brandl wrote: > If you have many classes in a module, putting > > __metaclass__ = type > > at the top can save you these keystrokes. > > Georg We could do that ? Nice trick that I've never thoughts about myself. Thanks Georg. From alisonken1 at gmail.com Fri Apr 21 19:27:51 2006 From: alisonken1 at gmail.com (alisonken1) Date: 21 Apr 2006 16:27:51 -0700 Subject: Pythonesque interface. In-Reply-To: <1145661752.254875.232980@i40g2000cwc.googlegroups.com> References: <1145639147.524042.260220@z34g2000cwc.googlegroups.com> <4asil8FuicdvU1@uni-berlin.de> <1145640417.247970.116480@v46g2000cwv.googlegroups.com> <1145656794.388937.60580@e56g2000cwe.googlegroups.com> <1145661752.254875.232980@i40g2000cwc.googlegroups.com> Message-ID: <1145662070.942102.256850@i40g2000cwc.googlegroups.com> OP = Original Poster From cretin at des.alpes.ch Mon Apr 10 07:59:45 2006 From: cretin at des.alpes.ch (Azolex) Date: Mon, 10 Apr 2006 13:59:45 +0200 Subject: how relevant is C today? In-Reply-To: References: <44381ee4$0$4209$c3e8da3@news.astraweb.com> Message-ID: <443a48b3$1_2@news.bluewin.ch> Daniel Nogradi wrote: >> "The Dice" (find tech jobs) has offerings >> (last 7 days, U.S. + unrestricted) for: >> *SQL 14,322 >> C/C++ 11,968 >> Java 10,143 >> ... > > Can anyone shed some light on the secret of Java? How is it that they > are so high on this list? Sun invented a roundabout strategy to enroll programmers to Java by first attracting the attention of the Wall Street Journal with Hotjava, and thus the attention of the programmers' management. From john at castleamber.com Sat Apr 29 03:16:43 2006 From: john at castleamber.com (John Bokma) Date: 29 Apr 2006 07:16:43 GMT Subject: (was Re: Xah's Edu Corner: Criticism vs Constructive Criticism) References: <1145992903.834316.198370@u72g2000cwu.googlegroups.com> <4GM3g.3084$TT.1768@twister.nyroc.rr.com> <1146231280.733609.143230@e56g2000cwe.googlegroups.com> <1146276319.504694.218970@v46g2000cwv.googlegroups.com> <1146285809.127897.24070@j33g2000cwa.googlegroups.com> <1146293661.242855.307580@j73g2000cwa.googlegroups.com> Message-ID: "Tagore Smith" wrote: > John Bokma wrote: [ .. ] >> An excessive crosspost is hardly ever on topic. > > Now you are just being dishonest. In what way? > No- if it were you would no longer have internet access. Try me. -- John MexIT: http://johnbokma.com/mexit/ personal page: http://johnbokma.com/ Experienced programmer available: http://castleamber.com/ Happy Customers: http://castleamber.com/testimonials.html From arne.meissner at gmx.de Sun Apr 2 16:48:30 2006 From: arne.meissner at gmx.de (Arne Meissner) Date: Sun, 2 Apr 2006 22:48:30 +0200 Subject: update or refresh a Listbox widget Message-ID: Hello! Is there a function to update/refresh a listbox widget. My one is connected to a database and after a change of the database I would like the listbox to be updated. Thank you for your help! Arne From iainking at gmail.com Wed Apr 12 05:27:21 2006 From: iainking at gmail.com (Iain King) Date: 12 Apr 2006 02:27:21 -0700 Subject: UDP max datagram size In-Reply-To: References: <1144830363.827740.198340@z34g2000cwc.googlegroups.com> Message-ID: <1144834041.382316.253680@i40g2000cwc.googlegroups.com> Heiko Wundram wrote: > Am Mittwoch 12 April 2006 10:26 schrieb Iain King: > > Hi. I've been looking everywhere for this and can't find it, apologies > > if I'm being obtuse: How do I set the max datagram packet size? I'm > > using the socket module. It seem like it's hardcoded at 255, but I > > need it to be larger. > > The minimal size any IP-stack has to be able to handle is 512 bytes. Normally, > modern IP stacks will handle packets up to 4096 bytes and possibly larger > packets (with correct fragmentation and rejoining). But this depends on the > IP stack that's used to send and to receive the packet. > > Anyway, a maximum size of 255 bytes is certainly not true for UDP packets. > > --- Heiko. Yep, I was just being dumb. Thanks anyway. Iain From Aiwass333 at gmail.com Tue Apr 11 15:57:38 2006 From: Aiwass333 at gmail.com (RunLevelZero) Date: 11 Apr 2006 12:57:38 -0700 Subject: RegExp question In-Reply-To: <1144781090.622493.252460@t31g2000cwb.googlegroups.com> References: <1144781090.622493.252460@t31g2000cwb.googlegroups.com> Message-ID: <1144785458.746030.153570@e56g2000cwe.googlegroups.com> In my opinion you would be best to use a tool like Kiki. http://project5.freezope.org/kiki/index.html/# This will allow you to paste in the actual text you want to search and then play with different RE's and set flags with a simple mouse click so you can find just what you want. Rember what re.DOTALL does. It will treat white spaces special and if there are line breaks it will follow them, otherwise it will not. It's a good idea to have a grasp of regular expressions or when you come back to your code months / weeks later, you will be just as lost, and always comment them very well :). Just my 2? From clodoaldo.pinto at gmail.com Sat Apr 8 12:02:22 2006 From: clodoaldo.pinto at gmail.com (Clodoaldo Pinto) Date: 8 Apr 2006 09:02:22 -0700 Subject: Programming Tutorial for absolute beginners References: <1144439148.751062.16590@t31g2000cwb.googlegroups.com> Message-ID: <1144512142.324056.281660@g10g2000cwb.googlegroups.com> James wrote: > On the calculator page you describe the difference between 3.0 / 2 and > 3 / 2, but an absolute beginner probably wouldn't know about the > difference between integers and floats, or even what the two terms > meant. If you don't know much about computers then the fact that they > are separate types would probably be surprising... > This point is not easy to aproach. The fact is that it is necessary that the beginner knows that there is a differerence between 3 / 2 and 3.0 / 2. I don't want him to now about types, at least not at that stage. I used the term "integer" for the lack of a better one and I didn't mention "float". Any suggestions? Regards, Clodoaldo. From jrivero at python.org.ve Mon Apr 3 14:05:39 2006 From: jrivero at python.org.ve (Jesus Rivero - (Neurogeek)) Date: Mon, 03 Apr 2006 14:05:39 -0400 Subject: Merging Objects In-Reply-To: References: Message-ID: <443163F3.20205@python.org.ve> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 >>> help(getattr) help(setattr) Regards, Jesus Rivero - (Neurogeek) Cloudthunder wrote: > Question: how do I merge two objects? I would like to be able to > have an instance of Foo and an instance of Boo and then be able to > add them together and create a new object that has the methods and > properties of both objects. I am going to be doing a lot of this > and I don't want to have to dynamically (or otherwise) create a > whole bunch of classes that inherit from both Foo and Boo then > create instances of those new children classes. In fact, this > wouldn't work for me anyway because I am going to have an instance > of Foo which will be used within my algorithm for sometime then > later I will want to merge it with a fresh instance of Boo or > otherwise give it all the methods and properties of the Boo class. > Am I making any sense here? > > Thanks. > > - OP > > P.S. I also noticed that we can no long use the __members__ > property to get a tuple of all a class's methods. How can I get the > same info from dir()? Dir(), I understand, tells you about all > properties and you can't tell it to just list the methods. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.1 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFEMWPzdIssYB9vBoMRAnkLAJ4mkUTlB9POlOyE5MeHukAJ5LeawQCghtoQ Dsn33bw0LYFsNS2AYStPLdU= =Dt4g -----END PGP SIGNATURE----- From praveenkumar.117 at gmail.com Thu Apr 6 05:43:39 2006 From: praveenkumar.117 at gmail.com (praveenkumar.117 at gmail.com) Date: 6 Apr 2006 02:43:39 -0700 Subject: How to catch python's STDOUT In-Reply-To: References: <1144314684.986767.131650@j33g2000cwa.googlegroups.com> Message-ID: <1144316619.928494.224270@t31g2000cwb.googlegroups.com> HI, I am a member of comp.lang.python. I posted a message saying how to capture python's STDOUT. sorry i did not clearly mentioned the problem. I have python script in which i have some print statements. I dont want the outputs of print to be displayed on the console since it is used my fellow-workers But i need those prints for debugging purpose So some how i want to capture those prints can u please suggest regards praveen kumar From robert.kern at gmail.com Mon Apr 17 22:28:19 2006 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 17 Apr 2006 21:28:19 -0500 Subject: Slicing matrix In-Reply-To: <20060418020438.18419.qmail@web35814.mail.mud.yahoo.com> References: <20060418020438.18419.qmail@web35814.mail.mud.yahoo.com> Message-ID: Anthony Liu wrote: > I am using numarray. I will be using numpy for this post, and if you are new to numarray, then you should probably skip it and use numpy instead. All new development is going towards numpy. http://numeric.scipy.org/ > Suppose I have > >>>>p = array(range(25), shape=(5,5)) >>>>p > > array([[ 0, 1, 2, 3, 4], > [ 5, 6, 7, 8, 9], > [10, 11, 12, 13, 14], > [15, 16, 17, 18, 19], > [20, 21, 22, 23, 24]]) In [4]: from numpy import * In [5]: p = arange(25).reshape((5,5)) In [6]: p Out[6]: array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]]) > How do I easily slice out [0,1,2] In [7]: p[0, :3] Out[7]: array([0, 1, 2]) > or [1,2,3] In [9]: p[0, 1:4] Out[9]: array([1, 2, 3]) > or [2,7,12] In [10]: p[:3, 2] Out[10]: array([ 2, 7, 12]) > or [7,12,17] and put it in a list? In [11]: p[1:4, 2] Out[11]: array([ 7, 12, 17]) -- Robert Kern robert.kern at gmail.com "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From tjreedy at udel.edu Thu Apr 20 13:46:40 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 20 Apr 2006 13:46:40 -0400 Subject: Error with OpenOffice References: <1145507419.10167.6.camel@localhost.localdomain> Message-ID: "Mario Lacunza" wrote in message news:1145507419.10167.6.camel at localhost.localdomain... > Hello, > > I try to make the exercises found in Ooo website but I receipt this > error: > > mario at laptop:~$ python > Python 2.4.2 (#2, Sep 30 2005, 21:19:01) > [GCC 4.0.2 20050808 (prerelease) (Ubuntu 4.0.1-4ubuntu8)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import uno > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib/python2.4/site-packages/uno.py", line 37, in ? > import pyuno > SystemError: dynamic module not initialized properly Nasty. My guess: either pyuno is not compiled correctly, or there is a mismatch between binaries. > Any idea?? Report this to OpenOffice and Ubuntu. tjr From sleytr at gmail.com Wed Apr 5 21:34:10 2006 From: sleytr at gmail.com (sleytr at gmail.com) Date: 5 Apr 2006 18:34:10 -0700 Subject: =?iso-8859-1?q?urllib.urlencode_wrongly_encoding__=B1_character?= Message-ID: <1144287250.071811.296390@i39g2000cwa.googlegroups.com> Hi, I'm trying to make a gui for a web service. Site using ? character in value of some fields. But I can't encode this character properly. >>> data = {'key':'?'} >>> urllib.urlencode(data) 'key=%C2%B1' but it should be only %B1 not %C2%B1. where is this %C2 coming from? From aleaxit at yahoo.com Fri Apr 21 00:24:16 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 20 Apr 2006 21:24:16 -0700 Subject: Thanks from the Java Developer References: <1145474995.143893.31760@z34g2000cwc.googlegroups.com> <1145568613.146056.135230@u72g2000cwu.googlegroups.com> Message-ID: <1he434n.vosf551izis2eN%aleaxit@yahoo.com> Ant wrote: > Python ruined my life. > > I am a Java programmer by profession, and ever since learning Python, I > find it a real chore to open Eclipse and write Java code (or worse - > the XML config files that seem to glue J2EE together). And while I > spend some of my spare time liberated by Python, I spend 10 times as > much time coding in Java at work. So switch jobs -- it's a good time. I did it at a very BAD time, right at the dotcom crash time, from a safe rewarding job as a senior developer doing mostly C++, to a scary risky freelance job doing mostly Python... and my quality of life became MUCH better. Now I'm an employee again, and even happier -- I work for Google, where Python, C++ and Java are all primary technologies, and every day's a joy. At least in the Bay Area, the jobmarket for Python programmers is wild, right now -- firms such as Google, Pixar, BitTorrent, IronPort, etc, etc, all hungry for Pythonistas -- BayPIGgies mailing list bitching over too many job-offer posts, and the nuisance of all those recruiters haunting our monthly meetings and how much time they take, ...!!! Alex From aleaxit at yahoo.com Wed Apr 5 22:15:19 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 5 Apr 2006 19:15:19 -0700 Subject: python on Mac References: <1144284073.446005.53950@t31g2000cwb.googlegroups.com> Message-ID: <1hdc51n.1qgtjne1mduk7gN%aleaxit@yahoo.com> Thomas Nelson wrote: ... > at http://www.python.org/download/mac/. Now I have IDLE, which runs Darn, that page needs to be fixed -- it's out of date!-( Sorry... See instead and download , you should be much happier. Alex From mtobis at gmail.com Sat Apr 22 09:41:57 2006 From: mtobis at gmail.com (Michael Tobis) Date: 22 Apr 2006 06:41:57 -0700 Subject: a flattening operator? In-Reply-To: <1145317740.898240.172830@i39g2000cwa.googlegroups.com> References: <1145317740.898240.172830@i39g2000cwa.googlegroups.com> Message-ID: <1145713317.195592.292580@t31g2000cwb.googlegroups.com> I think by "regular expressions" you mean "expressions". "regular expressions" are what you get from "import re" . mt From duncan.booth at invalid.invalid Sun Apr 23 10:36:02 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 23 Apr 2006 14:36:02 GMT Subject: test assignmet problem References: Message-ID: Paolo Pantaleo wrote: > So I tried this > > if(not (attr=global_re.match(line)) ): > break > > it says invalid syntax [on the =] > so it is not possible to do test and assignment in C style? > how can I write this otherwise? > With fewer parentheses for a start, but all you have to do here is to do the assignment and the test on separate lines: attr = global_re.match(line) if not attr: break In other cases you may have to work a bit harder to restructure your code. From renato.ramonda at gmail.com Tue Apr 18 03:30:32 2006 From: renato.ramonda at gmail.com (Renato) Date: 18 Apr 2006 00:30:32 -0700 Subject: Java Developer Exploring Python In-Reply-To: <1145305925.055791.89650@e56g2000cwe.googlegroups.com> References: <1145290449.735642.120860@i40g2000cwc.googlegroups.com> <1145292795.565277.288760@v46g2000cwv.googlegroups.com> <1145305925.055791.89650@e56g2000cwe.googlegroups.com> Message-ID: <1145345432.513870.212190@t31g2000cwb.googlegroups.com> You don't actually *need* a libglade/pyGtk IDE: glade will be more than enough :-) By its very nature glade will enable you to design the GUI and define the signals. Then you'll load the glade file in python, and use whatever editor you feel comfortable with. -- Have fun, Renato Ramonda From dave at waveform.plus.com Mon Apr 24 22:59:45 2006 From: dave at waveform.plus.com (Dave Hughes) Date: 25 Apr 2006 02:59:45 GMT Subject: Counting elements in a list wildcard References: <1145921582.526072.120480@u72g2000cwu.googlegroups.com> Message-ID: <444d90a1$0$2568$ed2619ec@ptn-nntp-reader02.plus.net> hawkesed wrote: > If I have a list, say of names. And I want to count all the people > named, say, Susie, but I don't care exactly how they spell it (ie, > Susy, Susi, Susie all work.) how would I do this? Set up a regular > expression inside the count? Is there a wildcard variable I can use? > Here is the code for the non-fuzzy way: > lstNames.count("Susie") > Any ideas? Is this something you wouldn't expect count to do? > Thanks y'all from a newbie. > Ed You might want to check out the SoundEx and MetaPhone algorithms which provide approximations of the "sound" of a word based on spelling (assuming English pronunciations). Apparently a soundex module used to be built into Python but was removed in 2.0. You can find several implementations on the 'net, for example: http://orca.mojam.com/~skip/python/soundex.py http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52213 MetaPhone is generally considered better than SoundEx for "sounds-like" matching, although it's considerably more complex (IIRC, although it's been a long time since I wrote an implementation of either in any language). A Python MetaPhone implementations (there must be more than this one?): http://joelspeters.com/awesomecode/ Another algorithm that might interest isn't based on "sounds-like" but instead computes the number of transforms necessary to get from one word to another: the Levenshtein distance. A C based implementation (with Python interface) is available: http://trific.ath.cx/resources/python/levenshtein/ Whichever algorithm you go with, you'll wind up with some sort of "similar" function which could be applied in a similar manner to Ben's example (I've just mocked up the following -- it's not an actual session): >>> import soundex >>> import metaphone >>> import levenshtein >>> my_strings = ['Bob', 'Sally', 'Susi', 'Dick', 'Susy', 'Jane' ] >>> found_suzys = [s for s in my_strings if soundsex.sounds_similar(s, 'Susy')] >>> found_suzys = [s for s in my_strings if metaphone.sounds_similar(s, 'Susy')] >>> found_suzys = [s for s in my_strings if levenshtein.distance(s, 'Susy') < 4] >>> found_suzys ['Susi', 'Susy'] (one hopes anyway!) HTH, Dave. -- From jaywgraves at gmail.com Wed Apr 26 17:31:54 2006 From: jaywgraves at gmail.com (jay graves) Date: 26 Apr 2006 14:31:54 -0700 Subject: print names of dictionaries References: <1146085818.242086.206290@e56g2000cwe.googlegroups.com> Message-ID: <1146087114.638400.149890@v46g2000cwv.googlegroups.com> BartlebyScrivener wrote: > Still new. Learning attributes and functions and so on. > Sorry if this is obvious, but if I'm defining a function for some > dictionaries, how can I print just the names of the dictionaries? Short answer: You can't. http://pyfaq.infogami.com/how-can-my-code-discover-the-name-of-an-object ... Jay Graves From onurb at xiludom.gro Fri Apr 21 06:57:30 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 21 Apr 2006 12:57:30 +0200 Subject: Looking for a programming resource for newbees In-Reply-To: <1145581209.588428.249770@v46g2000cwv.googlegroups.com> References: <1145581209.588428.249770@v46g2000cwv.googlegroups.com> Message-ID: <4448baec$0$12848$626a54ce@news.free.fr> bambooforest wrote: > Hi all, > > I'm from a Linguistics background and am new(er) to programming. Could > someone recommend a book or resource that teaches programming aspects > with Python? Python I hear is a very appropriate language for handling > text and language processing. You may want to have a look at David Mertz's "Text Processing in Python" > I'm searching for a resource that examines programming from a case > study like perspective. Such as, you're faced with problem of type X - > and here's how you should look at it to break it down to form an > optimal solution (e.g. because this type or problem is handled well > with this type of data structure, etc.). > > I've looked at the online Python tutorial at python.org and resources > like O'Reilly's Python in a Nutshell, but they seem to teach you > language syntax and concepts like data types, or assume you already > know how to program. I'm searching for something that teaches > programming. Learning to program usually imply learning the syntax and concepts of at least one language. Like with natural languages, there are some concepts that are difficult if not impossible to express in some languages - so sometime you need to learn a new language if you want to grasp the concept. Some other concepts you'll find, one way of another, in almost any language, so for more advanced books/tutorials/whatever, knowledge of these concepts is a prerequisite - just like a book on grammar suppose that the reader knows at least how to read and write, what's a verb, a sentence, a word, etc... Also, like natural languages, programming languages also have idioms, and learning these idioms is a non-trivial part of learning a language. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From skip at pobox.com Fri Apr 7 13:02:54 2006 From: skip at pobox.com (skip at pobox.com) Date: Fri, 7 Apr 2006 12:02:54 -0500 Subject: Why did someone write this? In-Reply-To: <1144428724.372163.240450@t31g2000cwb.googlegroups.com> References: <1144428724.372163.240450@t31g2000cwb.googlegroups.com> Message-ID: <17462.39742.107720.61394@montanaro.dyndns.org> Sandra> try: Sandra> exc_type, exc_value, exc_traceback = sys.exc_info() Sandra> # Do something Sandra> finally: Sandra> exc_traceback = None Sandra> Why the try/finally with setting exc_traceback to None? The intent is to decrement the reference count to any objects referenced by exc_traceback. Without it, the frame(s) referenced by the traceback remain alive until exc_traceback goes out of scope. Skip From trentm at ActiveState.com Tue Apr 11 13:07:58 2006 From: trentm at ActiveState.com (Trent Mick) Date: Tue, 11 Apr 2006 10:07:58 -0700 Subject: can't pass command-line arguments In-Reply-To: <443BDEB2.4060702@activestate.com> References: <443BDEB2.4060702@activestate.com> Message-ID: <20060411170758.GA25112@activestate.com> > You're welcome, and thanks for following this through. I still have > machines around that have PATHEXT=.pyc;.py;... and will now remove .pyc > from all of them. It would probably be nice to trace this back to the > origin, find whether there was a good rationale for it being that way in > the first place, and either update a FAQ somewhere or get the problem > fixed once and for all. > > I don't think the standard install messes with PATHEXT, so my bet is on > ActiveState right now. Can anyone confirm? Trent, if you're reading > this and it is from ActiveState's distribution, do you know where that > PATHEXT=.pyc;.py choice came from and whether it might have been an > ill-advised decision that should be undone? Yes, I can confirm as well. This is a bug in ActivePython. Definitely not an intended decision. That is: having .pyc (and/or .pyo) before .py (and/or .pyw) on PATHEXT is definitely a bug. The ActivePython MSI just added the .pyc, .pyo, .py and .pyw extensions to PATHEXT *backwards*. My apologies for not having caught this. http://bugs.activestate.com/ActivePython/show_bug.cgi?id=33311 As to whether to have .pyc (ditto .pyo) on PATHEXT at all: ActivePython has been doing so since time immemorial. I think that ActivePython should stop doing that (as implied by Duncan) unless someone can suggest a reason why to keep it. The only use case would be for calling a Python script on Windows without specifying the extension *and* for which there is ONLY a .pyc or .pyo. That seems to unlikely (or uncommon) a scenario to justify it. I'll get a new ActivePython for Windows out soon to take .pyo and .pyc off of PATHEXT. Trent -- Trent Mick TrentM at ActiveState.com From clodoaldo.pinto at gmail.com Tue Apr 11 13:22:24 2006 From: clodoaldo.pinto at gmail.com (Clodoaldo Pinto) Date: 11 Apr 2006 10:22:24 -0700 Subject: Programming Tutorial for absolute beginners References: <1144439148.751062.16590@t31g2000cwb.googlegroups.com> <1144512142.324056.281660@g10g2000cwb.googlegroups.com> <1144572585.147756.144240@i40g2000cwc.googlegroups.com> <1144734144.708314.119330@v46g2000cwv.googlegroups.com> Message-ID: <1144776144.572452.200480@g10g2000cwb.googlegroups.com> Frank Millman wrote: > Marc 'BlackJack' Rintsch wrote: > > In <1144572585.147756.144240 at i40g2000cwc.googlegroups.com>, Frank Millman > > wrote: > > > > > Then you can mention that, if they just want the integer portion, they > > > can use int(3/2). I think that most people with the slightest > > > understanding of basic arithmetic will relate to this without a > > > problem. > > > > Or instead of converting the `float` back to an `int`, they can use > > integer division: ``3 // 2`` > > > > I had thought of that. The reason I did not suggest it is that, as I > understand it, this tutorial is not about how to learn Python, it is > about teaching programming to the absolute beginner. Right !! > > I imagine (hope I am not making invalid assumptions here) that Python > was chosen as a base because it is easy and intuitive to learn, and in > most cases it is. It just happens that division is one area where it is > a bit awkward. Right again !! Although the Python way is almost always easy to learn I won't be pythonic (as in specific to Python) where it won't help. Regards, Clodoaldo From g.brandl-nospam at gmx.net Wed Apr 5 16:17:52 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Wed, 05 Apr 2006 22:17:52 +0200 Subject: efficiency of range() and xrange() in for loops In-Reply-To: References: Message-ID: Steve R. Hastings wrote: > When you compile the expression > > for i in range(1000): > pass > > does Python make an iterator for range(), and then generate the values > on the fly? Or does Python actually allocate the list [0, 1, 2, ..., 999] > and then step through it? It does. > I was under the impression that recent releases of Python optimize this > case, but upon reflection, I have no idea where I got that impression. > > If Python actually allocates the list, then clearly we should all use > "for i in xrange". But "for i in range" looks cleaner, and is potentially > more lightweight than xrange. Of course, if you want to write code that > runs well on older versions of Python, you need to use xrange(). > > > If Python doesn't currently optimize this case, is there any chance this > optimization could be added? As the alternative is so easy (adding a single character), I think this will not make it into the 2.x line. A patch for the old compiler existed on SF, but it will not work with the new AST compiler. > P.S. It looks like all the cool people look at the generated bytecodes to > answer questions like this one. I want to be cool too. Where can I find > information about how to get a bytecodes listing for my compiled Python? The "dis" module. Georg From aahz at pythoncraft.com Thu Apr 27 11:49:13 2006 From: aahz at pythoncraft.com (Aahz) Date: 27 Apr 2006 08:49:13 -0700 Subject: Type-Def-ing Python References: <1146041765.423121.106840@i39g2000cwa.googlegroups.com> <1hefehe.gyyjap1my3zj0N%aleaxit@yahoo.com> Message-ID: In article <1hefehe.gyyjap1my3zj0N%aleaxit at yahoo.com>, Alex Martelli wrote: > wrote: > ... >> Brett Cannon's thesis in which he tweaks the compiler and shows that >> type-defing python would not help the compiler achieve a 5% performace >> increase. >> >> Brett Cannon, "Localized Type Inference of Atomic Types in Python": >> http://www.ocf.berkeley.edu/~bac/thesis.pdf >> >> I was wondering if anyone had his contact information so that I could >> might ask him for his source code and try to use type-defing as a >> bug-finder. > >Brett is active on Python-Dev, so post there and you're likely to get a >response from him -- your subject is not OT for that list, anyway! Oh, so this is why we got an off-topic post on python-dev. Shouldn't you have told him to use Google?... ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Argue for your limitations, and sure enough they're yours." --Richard Bach From obeeker at gmail.com Sat Apr 1 08:41:52 2006 From: obeeker at gmail.com (obeeker at gmail.com) Date: 1 Apr 2006 05:41:52 -0800 Subject: why doesn't is work?a script to backup a directory In-Reply-To: <1143893556.309560.53090@u72g2000cwu.googlegroups.com> References: <1143859031.679813.94400@i40g2000cwc.googlegroups.com> <1143893556.309560.53090@u72g2000cwu.googlegroups.com> Message-ID: <1143898912.786820.317460@i40g2000cwc.googlegroups.com> i am very sorry . the erroer was from my Portable Hard Disk because its disk sign has changed from "o" to "h" ,from "p" to "i" i'm very sorry From nvasiliev at whiteriversoft.com Sat Apr 22 04:58:11 2006 From: nvasiliev at whiteriversoft.com (Nicolay A. Vasiliev) Date: Sat, 22 Apr 2006 12:58:11 +0400 Subject: ANN: XMLObject In-Reply-To: References: Message-ID: <4449F023.1000809@whiteriversoft.com> Hello! I tried to use this class in my work. But I Can't understand the next. I have an XML file, where I store an information by this way Wesley Hunter ie. How can I get the value between and ? Thanks in advance. aum wrote: > Hi folks, > > I've just released an XML object wrapper called XMLObject, which aims to > do for XML file handling what SQLObject does for database access. > > XMLObject wraps XML files as Python objects, and lets you work with XML > data more quickly and easily, and with code that's shorter and much more > readable than the raw python XML APIs. > > It borrows some ideas from 'xml_objectify', but uses none of its code. In > addition to 'xml_objectify', it lets you make changes within the document, > and to save back to an XML file. > > http://www.freenet.org.nz/python/xmlobject > > From robert.kern at gmail.com Mon Apr 3 12:22:46 2006 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 03 Apr 2006 11:22:46 -0500 Subject: Convertion of Unicode to ASCII NIGHTMARE In-Reply-To: <1144079830.734516.8390@z34g2000cwc.googlegroups.com> References: <1144079830.734516.8390@z34g2000cwc.googlegroups.com> Message-ID: ChaosKCW wrote: > Hi > > I am reading from an oracle database using cx_Oracle. I am writing to a > SQLite database using apsw. > > The oracle database is returning utf-8 characters for euopean item > names, ie special charcaters from an ASCII perspective. I'm not sure that you are using those terms correctly. From your description below, it seems that your data is being returned from the Oracle database as unicode strings rather than regular strings containing UTF-8 encoded data. These European characters are not "special characters from an ASCII perspective;" they simply aren't characters in the ASCII character set at all. > I get the following error: > >> SQLiteCur.execute(sql, row) >>UnicodeDecodeError: 'ascii' codec can't decode byte 0xdc in position 12: ordinal not in >range(128) > > I have googled for serval days now and still cant get it to encode to > ascii. Don't. You can't. Those characters don't exist in the ASCII character set. SQLite 3.0 deals with UTF-8 encoded SQL statements, though. http://www.sqlite.org/version3.html > I encode the SQL as follows: > > sql = "insert into %s values %s" % (SQLiteTable, paramstr) > sql.encode('ascii', 'ignore') The .encode() method returns a new value; it does not change an object inplace. sql = sql.encode('utf-8') -- Robert Kern robert.kern at gmail.com "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From brochu121 at gmail.com Fri Apr 28 15:13:02 2006 From: brochu121 at gmail.com (david brochu jr) Date: Fri, 28 Apr 2006 15:13:02 -0400 Subject: detect enter key Message-ID: <9583ed900604281213g5ad2c91erf39b2d5d12ec2fa6@mail.gmail.com> I am writing a script in which I need to wait for the user to press enter before continuing...how would I detect when the user presses the "Enter" key? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From titogarcia_nospamplease_ at gmail.com Sun Apr 9 06:24:51 2006 From: titogarcia_nospamplease_ at gmail.com (=?ISO-8859-1?Q?Ernesto_Garc=EDa_Garc=EDa?=) Date: Sun, 09 Apr 2006 12:24:51 +0200 Subject: [Newbie] Referring to a global variable inside a function Message-ID: Hi experts, I've built a class for parsing a user-defined list of files and matching lines with a user-defined list of regular expressions. It looks like this: import re import glob class LineMatcher: """ Parses a list of text files, matching their lines with the given regular expressions and executing associated actions.""" def __init__(self): # List of file names to parse for matching. self.file_names = [] # Association of reg expressions to actions to execute when match. self.regexp_action = {} def go(self): for file_name in self.file_names: file = open(file_name) for line in file: for regexp, action in self.regexp_action.items(): match = regexp.match(line) if match: action(line, match.groupdict()) def add_files(self, file_pattern): self.file_names.extend(glob.glob(file_pattern)) def add_action(self, regexp_string, action): self.regexp_action[re.compile(regexp_string)] = action But then, when I try to use my class using actions with "memory" it will fail: import LineMatcher global count count = 0 def line_action(line, match_dictionary): count = count + 1 line_matcher = LineMatcher.LineMatcher() line_matcher.add_files('*') line_matcher.add_action(r'(?P.*)', line_action) line_matcher.go() The error is: Traceback (most recent call last): File "Test.py", line 12, in ? line_matcher.go() File "LineMatcher.py", line 21, in go action(line, match.groupdict()) File "Test.py", line 7, in line_action count = count + 1 UnboundLocalError: local variable 'count' referenced before assignment How would you do this? Regards, Tito From duncan.booth at invalid.invalid Fri Apr 28 05:54:29 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 28 Apr 2006 09:54:29 GMT Subject: Get all attributes of a com object References: <1146151043.933987.145080@t31g2000cwb.googlegroups.com> <4450e4b7$0$21092$626a54ce@news.free.fr> <1146209689.917251.224530@g10g2000cwb.googlegroups.com> <4451e0bd$0$7724$636a55ce@news.free.fr> Message-ID: bruno at modulix wrote: > eicwo01 wrote: >> Thanks for your tips. >> But dir() and inspect did not really help. > > Really ? > > def dump(obj): > for name in dir(obj): > print getattr(obj, name) > That will show him the attributes of the Python wrapper around the COM object, it won't show him the attributes of the underlying COM object itself. If I remember correctly (and its a while since I did this), you may be able to use win32com/client/makepy.py to generate a .py file from a type library. If you do this then the python wrapper will have methods to forward the calls, so you can inspect it as above. Unfortunately, not all COM objects have to have type libraries, so it isn't always possible to do this and then you have to fall back on reading the documentation for whatever COM object you are using. You can also embed a call to gencache.EnsureModule() into your code to generate the needed wrappers automatically: the output from makepy tells you this. The easy way to run makepy is to run PythonWin and use 'COM makepy utility' from its tool menu. Then all you have to do is figure out which of the type libraries in the system is the relevant one. From pink at odahoda.de Fri Apr 7 14:33:38 2006 From: pink at odahoda.de (Benjamin Niemann) Date: Fri, 07 Apr 2006 20:33:38 +0200 Subject: Why did someone write this? References: <1144428724.372163.240450@t31g2000cwb.googlegroups.com> Message-ID: Sandra-24 wrote: > try: > exc_type, exc_value, exc_traceback = sys.exc_info() > # Do something > finally: > exc_traceback = None > > Why the try/finally with setting exc_traceback to None? The python docs > didn't give me any clue, and I'm wondering what this person knows that > I don't. You just have not found the right part of the doc: http://docs.python.org/lib/module-sys.html#l2h-337 -- Benjamin Niemann Email: pink at odahoda dot de WWW: http://pink.odahoda.de/ From aleaxit at yahoo.com Sat Apr 29 18:23:45 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 29 Apr 2006 15:23:45 -0700 Subject: Can we create an_object = object() and add attribute like for a class? References: Message-ID: <1hek76f.48x7rvw33771N%aleaxit@yahoo.com> Pierre Rouleau wrote: > Hi all, > > Is there any reason that under Python you cannot instantiate the object > class and create any attributes like you would be able for a normal class? Yep: instances of type object do not have a __dict__ and therefore there is no place to put any attributes. This is necessary to allow ANY subclass of object, and thus any type whatsoever, to lack a per-instance __dict__ (and thus to save its per-instance memory costs), since by the principle of inheritance (known as Liskov substutition, or also as the "IS-A" rule) a subclass cannot _remove_ superclass attributes, so if the universal superclass had a __dict__ so would every type in Python. > Being able to do it would seem a natural way of declaring namespaces. I find that ns = type('somename', (), dict(anattribute=23)) isn't too bad to make a namespace ns, though it has some undesirable issues (e.g., ns is implicitly callable, which may make little sense for a namespace). At any rate, any natural way of declaring a namespace SHOULD allow arbitrary named arguments in the instantiation call -- bending principles to give each instance of object a __dict__ would still not fix that, so that wouldn't do much. I think it's worth the minor bother to write out something like class Namespace(object): def __init__(self, **kwds): self.__dict__ = kwds and I generally go further anyway, by defining at least a repr that shows the attributes' names and values (very useful for debugging...). Alex From fredrik at pythonware.com Fri Apr 14 10:08:09 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 14 Apr 2006 16:08:09 +0200 Subject: %g not the same as %e or %f References: <443f89d1$1_1@newspeer2.tds.net> Message-ID: Kent Johnson wrote: > According to the docs, %g formatting is "Same as "e" if exponent is > greater than -4 or less than precision, "f" otherwise." So I would > expect that for any num, '%g'%num == '%e'%num or '%g'%num == '%f'%num. > But this is not the case in fact: > > Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. > > In [1]: num = 1234567898.2345678945 > > In [2]: print "%g\n%e\n%f" % (num,num,num) > 1.23457e+009 > 1.234568e+009 > 1234567898.234568 > > In [3]: num = 1234.456789 > > In [4]: print "%g\n%e\n%f" % (num,num,num) > 1234.46 > 1.234457e+003 > 1234.456789 > > So I'm wondering if the docs are wrong or the implementation is wrong or > there's something I don't understand? format != result. the phrase "same format" refers to decimal format vs. exponential format (see the descriptions of %e and %f in the same table), not the contents of the output string. (both formats use the same precision value, but %g interprets it as number of significant digits, while %f and %e interprets it as number of decimals). the C standard uses the word "style" instead: e) The double argument shall be converted in the style "[-]d.ddde?dd", where there is one digit before the radix character (which is non-zero if the argument is non-zero) and the number of digits after it is equal to the precision /.../ f) The double argument shall be converted to decimal notation in the style "[-]ddd.ddd", where the number of digits after the radix character is equal to the precision specification /.../ g) The double argument shall be converted in the style f or e (or in the style F or E in the case of a G conversion specifier), with the precision specifying the number of significant digits /.../ From andrewfelch at gmail.com Wed Apr 5 13:13:50 2006 From: andrewfelch at gmail.com (andrewfelch at gmail.com) Date: 5 Apr 2006 10:13:50 -0700 Subject: Best way to have a for-loop index? References: <1141950744.482666.4430@j33g2000cwa.googlegroups.com> Message-ID: <1144257230.393856.292540@e56g2000cwe.googlegroups.com> Sometimes C++ is the right tool/style for the job, but I don't need the speed or efficiency of C++. From rrrn at yahoo.com Tue Apr 4 23:20:08 2006 From: rrrn at yahoo.com (Butternut squash) Date: Wed, 05 Apr 2006 03:20:08 GMT Subject: wxpython in action book References: <1144135656.688071.170640@i39g2000cwa.googlegroups.com> Message-ID: momobear wrote: > > Butternut squash wrote: >> any recommendations? any opinions? >> >> I want to learn to program in python and need a gui reference. I'll be >> updating various mysql tables. I have most of the code ready to roll by >> using a command line. I need put some lipstick on my project. >> >> pyQT seems viable but there is not really a good reference and tutorial >> >> so now I'm considering wxPython and saw this book and I'm wanting to know >> if if's even worth spending my $40 on. >> >> Thanks. > what about pygtk, do u have any idea ab it? pyGTK? I don't really have a preference. I just want the best resource to have to learn this. I don't have that much time. From onurb at xiludom.gro Tue Apr 11 08:47:27 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 11 Apr 2006 14:47:27 +0200 Subject: Why new Python 2.5 feature "class C()" return old-style class ? In-Reply-To: <1144756774.177225.311120@z34g2000cwc.googlegroups.com> References: <1144752553.305591.88050@j33g2000cwa.googlegroups.com> <1144756774.177225.311120@z34g2000cwc.googlegroups.com> Message-ID: <443ba5a9$0$14281$626a54ce@news.free.fr> looping wrote: > Peter Hansen wrote: > >>Georg Brandl wrote: >> >>>class C(): >>> >>>is meant to be synonymous with >>> >>>class C: >>> >>>and therefore cannot create a new-style class. >> >>I think "looping" understands that, but is basically asking why anyone >>is bothering with a change that involves a part of the language that is >>effectively deprecated. In other words, class(): never used to be >>valid, so why make it valid now? >> >>-Peter > > > Exact. > But I think that if we make "class C():" a synonym of "class > C(object):", it will save lot of keystrokes ;-) Since the class statement without superclass actually creates an old-style class, I'd expect the "class MyClass():" variant to behave the same. Sacrifying readability and expliciteness just to save half a dozen keystrokes is not pythonic IMHO. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From jjl at pobox.com Thu Apr 20 15:43:49 2006 From: jjl at pobox.com (John J. Lee) Date: 20 Apr 2006 19:43:49 +0000 Subject: http request with cookie sending References: <1145396274.746861.40330@i39g2000cwa.googlegroups.com> <44462e31$1_1@newspeer2.tds.net> Message-ID: <871wvsxcay.fsf@pobox.com> Kent Johnson writes: > itay_k wrote: > > Hi, > > > > I want to send a cookie on some http request (with urllib2), > > so I created a Cookie but I cant associate it with CookieJar object. > > You have to use a cookielib.Cookie, not Cookie.SimpleCookie(): As I mention in the other thread Itay started, he probably doesn't want to do that either. John From michael at elehack.net Sat Apr 1 14:27:42 2006 From: michael at elehack.net (Michael Ekstrand) Date: Sat, 01 Apr 2006 13:27:42 -0600 Subject: DO NOT USE JAVA BECAUSE IT IS NOT OPEN SOURCE In-Reply-To: <20060401191353.GC21768@performancedrivers.com> References: <1143867556.814290.321740@i40g2000cwc.googlegroups.com> <20060401191353.GC21768@performancedrivers.com> Message-ID: <442ED42E.7070702@elehack.net> Jack Diederich wrote: > Xah, is that you? Nope, can't be. Xah doesn't use caps like that, and Xah also is very big Free Software not Open Source... Xah also tends to communicate in a slightly more intelligent fashion. (note: do not take this as a defense of Xah) - Michael -- mouse, n: a device for pointing at the xterm in which you want to type. -- Fortune Visit me on the Web: http://www.elehack.net From neil.isaac at sympatico.ca Wed Apr 19 21:43:07 2006 From: neil.isaac at sympatico.ca (Neil Isaac) Date: Wed, 19 Apr 2006 21:43:07 -0400 Subject: Python IDE for linux Message-ID: <20060419214307.2e63c5cd.neil.isaac@sympatico.ca> I have been writing python my little python scripts in gedit and running them using the command line. At this point I'm thinking that I would like to start using a real IDE. I don't need anything special or fancy, but would like it to manage projects, etc... I do know about kdevelop and emacs/vi(m)/nano/pico, but I use gnome most of the time and would rather (but not require) that the ide use anything other than qt. Aside from just IDEs, I would love to hear about eclipse/jedit/(anjuta?) plugins. Thanks. -- Neil Isaac neil.isaac at sympatico.ca From skip at pobox.com Sat Apr 22 15:26:08 2006 From: skip at pobox.com (skip at pobox.com) Date: Sat, 22 Apr 2006 14:26:08 -0500 Subject: repr() for Perl? In-Reply-To: <87ejzpaisg.fsf@pobox.com> References: <17482.6293.121041.659562@montanaro.dyndns.org> <87ejzpaisg.fsf@pobox.com> Message-ID: <17482.33616.175900.446809@montanaro.dyndns.org> >> Does Perl have something like Python's repr() function? John> perldoc Data::Dumper Thanks. Just what the doctor ordered (after setting Useqq). Skip From ldo at geek-central.gen.new_zealand Fri Apr 21 21:39:52 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 22 Apr 2006 13:39:52 +1200 Subject: perspective on ruby References: <1145555339.316764.123210@i39g2000cwa.googlegroups.com> <1he41sz.r7aasv1oo5lfN%aleaxit@yahoo.com> Message-ID: In article , Edward Elliott wrote: >XML? Conceptually (and more elegantly) covered >as LISP s-expressions. "...Lisp is still #1 for key algorithmic techniques such as recursion and condescension." -- Verity Stob >XSLT? Just a bastardized spawn of Prolog. As is any kind of pattern matching, including everyone's favourite regular expressions. Prolog did it all. From peter at engcorp.com Thu Apr 6 08:54:00 2006 From: peter at engcorp.com (Peter Hansen) Date: Thu, 06 Apr 2006 08:54:00 -0400 Subject: ``pickling'' and ``unpickling'' In-Reply-To: <1144300906.286664.75350@j33g2000cwa.googlegroups.com> References: <1144300906.286664.75350@j33g2000cwa.googlegroups.com> Message-ID: sushant.sirsikar at gmail.com wrote: > Hi, > I am new in Python World.I want to know what is mean by ``pickling'' > and ``unpickling'' ? > And how can we used it?Please Give Me some links of Picking Examples. > Thanks You can generally answer such questions yourself by heading to docs.python.org and typing the relevant words into the conveniently provided "Search" field in the upper right. With "pickling" the first result is http://docs.python.org/lib/module-pickle.html which answers all your questions, including a page of examples. -Peter From onurb at xiludom.gro Tue Apr 11 04:52:36 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 11 Apr 2006 10:52:36 +0200 Subject: Is this object counter code pythonic In-Reply-To: <1144670451.089729.205450@v46g2000cwv.googlegroups.com> References: <1144666496.940311.148120@j33g2000cwa.googlegroups.com> <1144668918.777564.310590@t31g2000cwb.googlegroups.com> <1144670451.089729.205450@v46g2000cwv.googlegroups.com> Message-ID: <443b6e9e$0$7952$636a55ce@news.free.fr> jnair at ensim.com wrote: > Fredrik is then this a valid "property" use case and pythonic to > get/set a common varibale across objects > > class E(object): > _i = 0 > def geti(self) : return E._i > def seti(self,val) : E._i = val > i = property(geti,seti) > > if __name__ == "__main__": > e1 = E() > e1.i = 100 > e2 = E() > print e2.i > Why do you want/think you need to hide the fact that i is an attribute of class E ? Actually, I find this use of properties very misleading: e1.i = 42 e2.i = 1138 assert e1.i == 42, "WTF ???" While this is perfectly obvious: E.i = 42 -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From tim.peters at gmail.com Tue Apr 11 15:02:08 2006 From: tim.peters at gmail.com (Tim Peters) Date: Tue, 11 Apr 2006 15:02:08 -0400 Subject: Memory limit to dict? In-Reply-To: <400BDC416E2A0042AA35DF3919BB8A5123A0EF@mail.mtl.proksim.com> References: <400BDC416E2A0042AA35DF3919BB8A5123A0EF@mail.mtl.proksim.com> Message-ID: <1f7befae0604111202n5fc69bccx1c20c52e89efad88@mail.gmail.com> [Olivier Langlois] > ... > I have kept thinking about the original problem and I now believe that > the only solution if he wants to store 3.6GB of data in a Python script > is to recompile Python in 64 bits. I do not know if this is something > that someone has already done successfully... I did the first port of Python to a 64-bit machine in 1993, and there may well not exist any 64-bit machine today on which Python doesn't run (for example, you can download a Python 2.4.3 Win64-Itanium installer from the main 2.4.3 download page). However, Python 2.4 still has lots of 32-bit limits internally. A massive effort is being made for Python 2.5 to relax those limitations, as explained in PEP 353: http://www.python.org/dev/peps/pep-0353/ Of course those still won't do you any good if the OS limits the process user address space to 32 (or, far more likely, 31) bits. From python.list at tim.thechases.com Fri Apr 21 20:00:02 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 21 Apr 2006 19:00:02 -0500 Subject: what has python added to programming languages? (lets be esoteric, shall we ; ) In-Reply-To: <1145663274.488586.5780@g10g2000cwb.googlegroups.com> References: <1145663274.488586.5780@g10g2000cwb.googlegroups.com> Message-ID: <44497202.7040707@tim.thechases.com> > Actually, I can't think off the top of my head, any > feature in the Java language (and I am making no > assertions about the implementation of specific > instances) that was truly innovative. Let's see...it has bytecode compliation. Oh...not original. Okay, howsabout cross-platform neutrality? You mean there are others?! Okay...how about a humongous class library? Nah. It's tough to call Java original... Well, Java does have this great feature called "market-hype"... -tkc From simon at brunningonline.net Tue Apr 11 05:47:18 2006 From: simon at brunningonline.net (Simon Brunning) Date: Tue, 11 Apr 2006 10:47:18 +0100 Subject: Web Service SOAP - Unknown element v1 In-Reply-To: References: Message-ID: <8c7f10c60604110247n7e2b45f0xb4b5a1d6aa00aae1@mail.gmail.com> On 4/11/06, Jesus.Javier.Masa.Lledo at dmr-consulting.com wrote: > > Im trying to develope a web service that comunicates python (client) with > Java (server). Everything works fine until the client calls a method that > takes parameters ( for example: setName("Joe") ). Any other method that > takes no parameteres works perfect ( For example: getDate() ), even the ones > that return stuff from the server. (snip Java stack trace.) > Could anyone tell me why is this happening???? Try using keyword arguments instead of positional keywords, like so: servidor.setDVD(title="Fight Club") I've guessed at 'title' for the keyword here, 'cos I can't see your WSDL to find out what the real one is. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From nobody at 127.0.0.1 Fri Apr 28 11:50:29 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Fri, 28 Apr 2006 15:50:29 GMT Subject: How to align the text of a Listbox to the right References: <1146212895.904335.66490@v46g2000cwv.googlegroups.com> Message-ID: <9Rq4g.18239$4L1.10376@newssvr11.news.prodigy.com> Leonardo da Vinci wrote: >> to limit the width to something acceptable, and show >> only the tail of the line. > > Yes, this is exactly what I wanted to do. Do you know a way to > accomplish that? Because Eric Brunel said it is impossible on a > Listbox. Use a string slice. From bencvt at gmail.com Tue Apr 11 21:43:28 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 11 Apr 2006 18:43:28 -0700 Subject: RIIA in Python 2.5 alpha: "with... as" References: <178359972.20060411145606@sinn.ru> Message-ID: <1144806208.496440.33990@e56g2000cwe.googlegroups.com> Terry Reedy wrote: > "Alexander Myodov" wrote in message > news:178359972.20060411145606 at sinn.ru... > > and even list comprehensions: > > b1 = [l for l in a1] > > print "l: %s" % l > > This will go away in 3.0. For now, del l if you wish. Or use a generator expression: >>> b1 = list(l for l in a1) >>> l NameError: name 'l' is not defined --Ben From steve at holdenweb.com Mon Apr 24 10:01:52 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 24 Apr 2006 15:01:52 +0100 Subject: proposed Python logo In-Reply-To: <1145659600.115550.270520@e56g2000cwe.googlegroups.com> References: <1145585399.871299.31900@t31g2000cwb.googlegroups.com> <1145628079.749480.191190@g10g2000cwb.googlegroups.com> <124hqel51rur33b@corp.supernews.com> <1145640106.269556.276060@u72g2000cwu.googlegroups.com> <124i8176of81331@corp.supernews.com> <1145659600.115550.270520@e56g2000cwe.googlegroups.com> Message-ID: Michael Tobis wrote: > A more Monty sort of Python logo would be fine with me. A flying sheep > perhaps? An exploding penguin? A giant hedgehog? A dog license with the > word "dog" crossed out and "cat" written in crayon? A great big book on > how to put your budgie down? > > This http://www.informatik.uni-trier.de/~roth/bilder/mpfc/GUMBY3.JPG > chap? > > I'm not sure that conveys the intended gravitas to the corporate > community, though. > > mt > How about a big "P" with the serif at the bottom being the foot that stamps on things? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From m.yanowitz at kearfott.com Tue Apr 4 09:11:26 2006 From: m.yanowitz at kearfott.com (Michael Yanowitz) Date: Tue, 4 Apr 2006 09:11:26 -0400 Subject: tuple syntax ',' (ending in comma?) In-Reply-To: <1144149532.845574.191690@e56g2000cwe.googlegroups.com> Message-ID: Hello: I am still relatively new to Python. I am confused by the syntax for tuples. I had: thread.start_new_thread(read_data_thread, (strDataFilename)) and got back the following error: File "scene.py", line 256, in readData thread.start_new_thread(read_data_thread, (strDataFilename)) TypeError: 2nd arg must be a tuple The way I fixed this error was I added an extra , (comma) to the tuple: thread.start_new_thread(read_data_thread, (strDataFilename,)) I am just confused by the syntax. I am used to a comma meaning that there should be another parameter after the comma and if no additional parameter the comma would not be necessary. Thanks in advance: From rpdooling at gmail.com Sat Apr 15 18:46:35 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 15 Apr 2006 15:46:35 -0700 Subject: shutil.copy time stamp errors on win XP Message-ID: <1145141195.572904.48140@i40g2000cwc.googlegroups.com> I'm working on various backup scripts, using filecmp and shutil. When I run a script to copy files to a mapped network drive, shutil creates a backup file with a date of 2002 or so. If I use shutil.copy2 it copies the dates of the original files, but creates folders with similary old dates and times. Anybody ever seen that before? My system clock is fine. I don't know what else to try. Thanks for any help. rick From bedouglas at earthlink.net Wed Apr 19 00:05:18 2006 From: bedouglas at earthlink.net (bruce) Date: Tue, 18 Apr 2006 21:05:18 -0700 Subject: mailing list for indian college student software developers Message-ID: <065001c66366$798c4e10$0301a8c0@Mesa.com> hi.... yeah.. i know this is off topic, but there might be someone who might be able to help... i'm trying to find a mialing list focused on indian students who are in indian colleges (india) studying software programming... searching google hasn't really helped.. any thoughts/ideas/etc... thanks -bruce From jbellis at gmail.com Sun Apr 16 01:11:07 2006 From: jbellis at gmail.com (Jonathan Ellis) Date: 15 Apr 2006 22:11:07 -0700 Subject: Why aren't these more popular (Myghty & Pylons)? In-Reply-To: References: Message-ID: <1145164266.984608.253970@u72g2000cwu.googlegroups.com> Karlo Lozovina wrote: > There's only one thing bothering me, and that is it's lack of publicity. > There are only few posts on thig NG with some refference to Myghty, and > even less when it comes to Pylons (http://pylonshq.com/), framework built > on top of Myghy. Myghy project isn't that new to explain why people don't > know about it, so is something fundamentaly wrong with it? The whims of mindshare are indeed mysterious. > Anyway, to make a long story short, those who haven't heard about it, be > sure to check it out, you just might like it, but I would really like to > hear from people (if there are such) using it in real world > applications... http://techspot.zzzeek.org/index.php?/archives/7-Bittorrent.com,-running-Myghty-Again.html -Jonathan From buzzard at urubu.freeserve.co.uk Sat Apr 8 13:43:00 2006 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Sat, 08 Apr 2006 18:43:00 +0100 Subject: Programming Tutorial for absolute beginners In-Reply-To: References: <1144439148.751062.16590@t31g2000cwb.googlegroups.com> <1144512142.324056.281660@g10g2000cwb.googlegroups.com> Message-ID: <4437f586.0@entanet> James wrote: > Perhaps use the phrase "whole number" there and mention that in > programming they're called integers. Having a glossary with > definitions for things like integer, float etc etc. would be good if > when you talked about integers it linked to the glossary. And > similarly use "decimals" for floats? Less sure about that one though. > But anyway you don't need to go into the whole type thing, just > mention that Python distinguishes between doing maths with whole > numbers and decimals. > In general they are integers, and "integer" is not a Python type, so I don't see a problem with the term. The problem I saw was that there was no explanation for the returned value. Using the term "decimal" is probably a bad idea, given Python decimals. But I'm not sure you need to come up with a suitable term until you actually get round to explaining types (at which point the problem disappears). Duncan From Serge.Orlov at gmail.com Wed Apr 19 03:27:43 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 19 Apr 2006 00:27:43 -0700 Subject: freakin out over C++ module in python References: <1145324978.877495.12580@i40g2000cwc.googlegroups.com> <1145422931.445215.112930@j33g2000cwa.googlegroups.com> Message-ID: <1145431663.153449.53260@v46g2000cwv.googlegroups.com> nephish at xit.net wrote: > pyconstruct looks cool. i dont know if the classes are using the plain > berkely-ish code. i couldn't find anything in it that pointed to send() > recv(), & such. i found other stuff like SetSocketOpt() and so on like > this : > > long CClientSocket::ConnectToServer(LPCTSTR serverAddr, UINT port) > > { > > BOOL socketOption = TRUE; > > const int rcvBuffsize = 64 *1024; > > const int sendBuffsize = 64*1024; > > > > if ( !Create() ) > > return ERR_SOCKET_CREATE; > > int intvalue = sizeof(int); > > if(!( SetSockOpt(SO_DONTROUTE,&socketOption,sizeof(BOOL),SOL_SOCKET) > && > > SetSockOpt(SO_RCVBUF,&rcvBuffsize,sizeof(int),SOL_SOCKET) && > > SetSockOpt(SO_SNDBUF,&sendBuffsize,sizeof(int),SOL_SOCKET) && > > SetSockOpt(TCP_NODELAY,&socketOption,sizeof(BOOL),SOL_SOCKET) && > > SetSockOpt(SO_KEEPALIVE,&socketOption,sizeof(BOOL),SOL_SOCKET))) > > return ERR_SOCKET_CREATE; > > > i looked around for some of these and found most references to UDP. I > guess its also a windows specific thing too. Nope. It's a UNIX function: http://www.opengroup.org/onlinepubs/007908799/xns/setsockopt.html And corresponding Python stuff is in the socket module. The code above can be roughly translated as def ConnectToServer(self, serverAddr, port): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.connection = s s.connect((serverAddr, port)) s.setsockopt(socket.SOL_SOCKET, socket.SO_DONTROUTE, 1) s.setsockopt(socket.SOL_SOCKET, socket.TCP_NODELAY, 1) s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) s.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 64*1024) s.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 64*1024) Note, you don't need to handle errors in this method like C++ code, instead catch socket.error exception where you handle *all* fatal exceptions during connection setup. With regards to your first question about automatic language translation - don't even dream about it. IMHO, C++ is one of the most complicated high-level languages for automatic translation. From cochrane at avon.esscc.uq.edu.au Mon Apr 24 12:11:07 2006 From: cochrane at avon.esscc.uq.edu.au (cochrane at avon.esscc.uq.edu.au) Date: 24 Apr 2006 16:11:07 GMT Subject: ANN: PyScript 0.6.0 released Message-ID: Overview: PyScript is a python module for producing high quality postscript graphics. Rather than use a GUI to draw a picture, the picture is programmed using python and the PyScript objects. Some of the key features are: * All scripting is done in python, which is a high level, easy to learn, well developed scripting language. * All the objects can be translated, scaled, rotated, ... in fact any affine transformation. * Plain text is automatically kerned. * You can place arbitrary LaTeX expressions on your figures. * You can create your own figure objects, and develop a library of figure primitives. * Output is publication quality. License: Released under the GPL Changes: The major change in this release is a complete rewrite of the Talk and Poster classes of the presentation library. There have also been many bug fixes and minor other improvements. For details see the PyScript web page: pyscript.sourceforge.net. Getting the software: One can download the latest version (0.6) from: PyScript Requirements: * Python 2.2 and above * An up-to-date LaTeX distribution Authors: * Alexei Gilchrist * Paul Cochrane If you use this software, have any suggestions, or bug reports, please let us know! -- paultcochrane at users.sourceforge.net From gherron at islandtraining.com Sun Apr 2 15:20:10 2006 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 02 Apr 2006 12:20:10 -0700 Subject: print() in Python 3000 return value? In-Reply-To: <1144000530.9449.0.camel@kenshin.CASA> References: <1143997643.857261.186430@i40g2000cwc.googlegroups.com> <44300797$0$28451$9b622d9e@news.freenet.de> <1143999680.091690.253340@g10g2000cwb.googlegroups.com> <1144000530.9449.0.camel@kenshin.CASA> Message-ID: <443023EA.6070104@islandtraining.com> Felipe Almeida Lessa wrote: >Em Dom, 2006-04-02 ?s 10:41 -0700, James Thiele escreveu: > > >>Martin chimedin: >> >> >>>James Thiele wrote: >>> >>> >>>>I noticed in PEP 3000 that print will become a function. The PEP >>>>references a thread where Guido explains this decision. The thread does >>>>not specify what the function will return. Has this been decided? >>>> >>>> >>>My intuition is that it should be a procedure (i.e. returning None). >>>What do you want it to return? >>> >>>Regards, >>>Martin >>> >>> >>The string that was printed. It could be useful inside expessions: >> >>message = "I don't need to see all of this:%s" % print(s) >> >> > >Or maybe: > >for i in sequence: > mylist.append(print(i)) > > > No no, please NO! You *know* that someday you'll want the return value without actually printing the text. So let's don't overload a single function with two operations. Let "print" print, and propose a separate function (named "format" --yuck-- or some such) that returns the same text as a string. Gary Herron From john at castleamber.com Wed Apr 26 19:39:22 2006 From: john at castleamber.com (John Bokma) Date: 26 Apr 2006 23:39:22 GMT Subject: (was Re: Xah's Edu Corner: Criticism vs Constructive Criticism) References: <1145992903.834316.198370@u72g2000cwu.googlegroups.com> <4GM3g.3084$TT.1768@twister.nyroc.rr.com> <1146079773.910552.217390@y43g2000cwc.googlegroups.com> Message-ID: Roedy Green wrote: > On 26 Apr 2006 12:29:33 -0700, "Xah Lee" wrote, > quoted or indirectly quoted someone who said : > >>This is a public notice that what you are trying to do is getting close >>to harrassment from the law's perspective. > > and what you do Xah, is very close to spam, another form of > harassment. I leave that up to Xah's ISP/USP and hosting provider to decide :-D But I am sure that if a few people email, that Xah's harassment is going to stop soon. Unless he wants to burn some cash. -- John Bokma Freelance software developer & Experienced Perl programmer: http://castleamber.com/ From svenn.are at bjerkem.de Tue Apr 11 11:33:17 2006 From: svenn.are at bjerkem.de (Svenn Bjerkem) Date: 11 Apr 2006 08:33:17 -0700 Subject: Removing an item from a QListView in PyQt Message-ID: <1144769597.763389.67500@j33g2000cwa.googlegroups.com> Hi, I am looking for a bit more elaboration on the problem of deleting elements from a QListsView. I know this is a tricky problem with references, but I have not been able to extract enough knowledge from the documentation to solve a specific problem: In a dialog I have a QListView called referenceList. Entries are added and deleted from this list with buttons addButton and removeButton connected with sockets: ---- class IdeaInputBase(QDialog): def __init__(self,parent = None,name = None,modal = 0,fl = 0): QDialog.__init__(self,parent,name,modal,fl) self.connect(self.addButton,SIGNAL("clicked()"),self.addNewReferenceSlot) self.connect(self.removeButton,SIGNAL("clicked()"),self.removeReferenceSlot) ... ---- class IdeaInput(IdeaInputBase): def __init__(self): IdeaInputBase.__init__(self) def addNewReferenceSlot(self): self.referenceList.insertItem(QListViewItem(self.referenceList, "An Item")) def removeReferenceSlot(self): print "selected has address %s" % (self.referenceList.selectedItem()) self.referenceList.removeChild(self.referenceList.selectedItem()) ---- Adding Items by pressing the addButton works fine. I then select one of the list elements and press the removeButton. This is the output I get. selected has address Traceback (most recent call last): File "./idea_input.py", line 20, in removeReferenceSlot self.referenceList.removeChild(self.referenceList.selectedItem()) TypeError: argument 1 of QScrollView.removeChild() has an invalid type I see that I have an address of a QListViewItem, but I am not able to delete it. What am I obviously doing wrong here? Kind regards, -- Svenn From nogradi at gmail.com Sun Apr 30 05:52:08 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Sun, 30 Apr 2006 11:52:08 +0200 Subject: setting file permissions on a web server In-Reply-To: <445449f6$0$9437$c3e8da3@news.astraweb.com> References: <445449f6$0$9437$c3e8da3@news.astraweb.com> Message-ID: <5f56302b0604300252r455f155qe699f35faeb8a49e@mail.gmail.com> > I always read about how you need to set certain file permissions (for > cgi files, for example), but it's never been clear to me *how* you do > this. I know you can run the line > > chmod 755 scriptname.py > > but *where* do you run this? Is this done on your personal system, or on > the server? What if you are using Windows? If it's done on the server, > how do you do it? > > The only way I've figured out so far how to do this is to upload my cgi > files to my server, then within my FTP program I right-click the file > and change its permission number that way, but that seems an inefficient > way to do it, especially having to do it each time. > > Is there a way to put the above line within the script perhaps, so that > the script sets its permission automatically? Or do certain editors > allow you to save files with a predetermined permission? > > Aside from my right-clicking method, I don't know how else to do it. I guess this would be a good starting point: http://www.linuxcommand.org/man_pages/chmod1.html In short, chmod refers to local files so wherever you run it it will refer to files on that machine. You run it simply by typing it in a shell as a user who has privilage to perform the operatation, which can mean you have to be an owner of the file but if you are root you can do it in any case. Depending on your ftp, scp, http or whatever method you use to transfer files the file permissions may or may not change during the transfer. If permissions are kept intact you can chmod on your local machine and then transfer, if they are not then you transfer first and chmod on the server. When you transfer files from a windows machine to *nix it again depends on the particular method you choose how the permissions will be set. There is no way of putting this permission information into the file itself but some (most?) editors can be set to save the file with a permission of your choice. Hope this helps. From conny.ledin at gmail.com Wed Apr 26 08:13:01 2006 From: conny.ledin at gmail.com (conny.ledin at gmail.com) Date: 26 Apr 2006 05:13:01 -0700 Subject: I have problems with creating the classic game Wumpus. the file: http://esnips.c In-Reply-To: <1146012810.912414.69650@t31g2000cwb.googlegroups.com> References: <1145986162.065611.168330@j33g2000cwa.googlegroups.com> <1145990271.018812.306050@e56g2000cwe.googlegroups.com> <1146012810.912414.69650@t31g2000cwb.googlegroups.com> Message-ID: <1146053581.589720.306560@v46g2000cwv.googlegroups.com> i just mailed it to you. Thanks for looking at it. From http Thu Apr 13 20:36:49 2006 From: http (Paul Rubin) Date: 13 Apr 2006 17:36:49 -0700 Subject: Forms with multiple submit buttons vs 'form' objects with single 'submit' methods References: <1144956412.286214.316800@u72g2000cwu.googlegroups.com> Message-ID: <7xbqv5c7ry.fsf@ruckus.brouhaha.com> neil.fitzgerald at ic.ac.uk writes: > Here's my question: Suppose a form has more than one submit button. > Now the COM 'form' object has a 'submit' method that doesn't take any > arguments, so how do I tell it which button I want to press? What difference does it make? Don't they all do the same thing? From Mike.S.Duffy at gmail.com Wed Apr 12 02:17:47 2006 From: Mike.S.Duffy at gmail.com (pyGuy) Date: 11 Apr 2006 23:17:47 -0700 Subject: Best way to emulate ordered dictionary (like in PHP)? Message-ID: <1144822667.220960.130190@v46g2000cwv.googlegroups.com> I am dealing with user profiles, which are simply a set of field-value pairs. I've tried to many things to list, but for one, I tried creating a wrapper class which inherits the dictionary and overrides the iterator. Unfortunately I don't understand iterators enough to get this working and before I waste any more time trying I figured I should check wether there is a better way. I have run into a similar problem once, and I resolved it by creating a wrapper class for the 'list' class which overides the get_item method, checks for string parameter, then accesses the appropriate item via a lookup 'list' contained within the class which maps the string parameter to the index number (eh, it just doesn't seem practical though). Now, I'e never used PHP, but apparently, it's dictionaries retain the order in which the items are entered and regurgitates them in that order when you iterate over them. That is exactly what I want, but can't seem to get in Python. Any help? Thanks in advance. From uymqlp502 at sneakemail.com Wed Apr 5 21:31:17 2006 From: uymqlp502 at sneakemail.com (Russ) Date: 5 Apr 2006 18:31:17 -0700 Subject: output formatting for user-defined types In-Reply-To: References: <1144283268.217968.316100@i39g2000cwa.googlegroups.com> Message-ID: <1144287077.109309.16300@z34g2000cwc.googlegroups.com> Thanks, but that is not acceptable for my application. Any other ideas? I thought I might be able to overload __rmod__, but apparently python applies the % operator before __rmod__ is even invoked if the left-hand argument is a string. From rpdooling at gmail.com Mon Apr 10 11:46:10 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 10 Apr 2006 08:46:10 -0700 Subject: can't pass command-line arguments References: <1144676885.317592.21780@e56g2000cwe.googlegroups.com> <1144681621.999659.78880@z34g2000cwc.googlegroups.com> Message-ID: <1144683970.374120.279670@t31g2000cwb.googlegroups.com> Running the script you recommended, I get d:\python>hansen.py cbfindfiles .\cbfindfiles.pyc .\cbfindfiles.py d:\python\cbfindfiles.pyc d:\python\cbfindfiles.py If I use XP search, searching all drives for any file with cbfindfiles in the name, I get just the two in d:\python. It has something to do with importing the cbfindfiles.py file as a module, right? Because I just did that, and now the .py and .pyc files are synchronized, and I'm getting the same result when I run cbfindfiles or cbfindfiles.py, whereas before I was not. Thank you so much for your generous help. Rick From jimlewis at miclog.com Sat Apr 1 07:00:10 2006 From: jimlewis at miclog.com (Jim Lewis) Date: 1 Apr 2006 04:00:10 -0800 Subject: Tkinter divider Message-ID: <1143892810.826596.237070@z34g2000cwc.googlegroups.com> Anyone know how to create a draggable divider between two Tkinter windows? From steve at REMOVETHIScyber.com.au Fri Apr 14 14:04:44 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 15 Apr 2006 04:04:44 +1000 Subject: Writing backwards compatible code Message-ID: I came across an interesting (as in the Chinese curse) problem today. I had to modify a piece of code using generator expressions written with Python 2.4 in mind to run under version 2.3, but I wanted the code to continue to use the generator expression if possible. My first approach was to use a try...except block to test for generator expressions: try: gen = (something for x in blah) except SyntaxError: def g(): for x in blah: yield something gen = g() This failed to work under 2.3, because the SyntaxError occurs at compile time, and so the try block never happens. I've been burnt by making assumptions before, so I tried a second, similar, approach: if sys.version_info >= (2, 4): gen = (something for x in blah) else: # you know the rest As expected, that failed too. The solution which worked was to put the generator expression in a second module, then import that: try: import othermodule except SyntaxError: # fall back code What techniques do others use? -- Steven. From onurb at xiludom.gro Tue Apr 11 13:15:17 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 11 Apr 2006 19:15:17 +0200 Subject: how relevant is C today? In-Reply-To: <1144765191.225146.130140@u72g2000cwu.googlegroups.com> References: <44381ee4$0$4209$c3e8da3@news.astraweb.com> <44382711.10403@v.loewis.de> <44393fbe$0$19226$c3e8da3@news.astraweb.com> <44398651$0$4206$c3e8da3@news.astraweb.com> <1144632983.039143.203330@u72g2000cwu.googlegroups.com> <443a4e8a$0$21013$626a54ce@news.free.fr> <443b9b91$0$27077$626a54ce@news.free.fr> <1144765191.225146.130140@u72g2000cwu.googlegroups.com> Message-ID: <443be46f$0$20430$636a55ce@news.free.fr> gregarican wrote: > bruno wrote: > > >>Err... > > >>And ? > > > It's the snide, curt replies such as your recent ones in this thread > that reinforce the generalization that the Python community can be > rude. I'm afraid you're right, at least for the second one, and I do apologise NB : the fist one didn't seem offensive to me, but english's not my first language so I may have missed some subtility - if so, please consider this message as applying to both. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From Aiwass333 at gmail.com Thu Apr 27 17:36:04 2006 From: Aiwass333 at gmail.com (RunLevelZero) Date: 27 Apr 2006 14:36:04 -0700 Subject: Regular Expression help In-Reply-To: References: <1146162048.903980.281290@y43g2000cwc.googlegroups.com> Message-ID: <1146173764.231699.320760@u72g2000cwu.googlegroups.com> r']*>(.*?)' With a slight modification that did exactly what I wanted, and yes the findall was the only way to get all that I needed as I buffered all the read. Thanks a bunch. From martin at v.loewis.de Sat Apr 15 05:28:27 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 15 Apr 2006 11:28:27 +0200 Subject: [Python-Dev] Building Python with the free MS Toolkit compiler In-Reply-To: <79990c6b0604131411j32a53793g5845107d3a648863@mail.gmail.com> References: <79990c6b0604131411j32a53793g5845107d3a648863@mail.gmail.com> Message-ID: <4440BCBB.5070907@v.loewis.de> Paul Moore wrote: > I've just added some instructions on how to build Python on Windows > with the free MS Toolkit C++ compiler. They are at > http://wiki.python.org/moin/Building_Python_with_the_free_MS_C_Toolkit. Cool! If you think that adding/changing files in Python would simplify the process, don't hesitate to produce patches. Regards, Martin From jmeile at hotmail.com Mon Apr 24 09:21:10 2006 From: jmeile at hotmail.com (Josef Meile) Date: Mon, 24 Apr 2006 15:21:10 +0200 Subject: MinGW and Python In-Reply-To: <1145861223.509630.247350@y43g2000cwc.googlegroups.com> References: <1145861223.509630.247350@y43g2000cwc.googlegroups.com> Message-ID: <444CD0C6.3080407@hotmail.com> > Is there any specific reason for not using MinGW to build the official > distribution of Python for Win32? > A quick Google search did not reveal the answer to my question. If a > link is available, please post it. You may look at this thread: * E02 - Support for MinGW Open Source Compiler http://tinyurl.com/lxfsz There was a big polemic and it is really long, but there are some useful posts there. Regards, Josef From sxanth at cs.teiath.gr Tue Apr 25 02:38:19 2006 From: sxanth at cs.teiath.gr (Stelios Xanthakis) Date: Mon, 24 Apr 2006 23:38:19 -0700 Subject: The whitespaceless frontend In-Reply-To: <1145102469.595611.19950@u72g2000cwu.googlegroups.com> References: <1145102469.595611.19950@u72g2000cwu.googlegroups.com> Message-ID: <444DC3DB.4050005@cs.teiath.gr> Hi, bearophileHUGS at lycos.com wrote: > but maybe instead of the global.name something to refer to the upper > namespace (that can be the global one or the namespace of the function > that contains this one) can be more general: > upper.x = 1 > upper.upper.x = 1 > Well, people have been trying to come up with a way to solve the nested scopes restrictions. This may work, but in my opinion nested functions are not so important and I wouldn't spend any time to improve them. Usually you can do anything with classes (and "method" makes that easier). If we say that """closures were invented so that we will avoid the extra typing in cases like def f (self): x = lambda self=self: return self.foo () and beyond that perhaps it is a sign that we should rethink our design""" we can accept the limitations of python's closures. > I think that making self a reserved word that can be used only for its > usual purpose can be positive. > I agree. EPL does not have shoot-self-in-the-foot protections yet, but it will :) > The $ and method statement seem interesting too, but the first is a > little perlish (but Ruby has something similar, and people like it), > and the method statement look a little redundant. I think the $ can be > acceptable (Mostly to reduce typing), even if it doesn't look very > nice. > '$' is perlish and rubyish (and I got it from ruby indeed). It's the cost of a dynamic language :) In static languages we know at compile-time whether a symbol is local, instance or global. In dynamic languages where scopes are modified when the program runs we have to type something. '$' being unused seems like a good choice. "method" is good not only because we avoid the extra typing in the definition, but also because -after experiments- it seems that restricting the use of $ in methods, will simplify some confusing cases. For example, what happens in: def foo (cls): def bar (self): return $x # what's that? cls.x or self.x? While now, when you see $ you know it refers to the instance of the "method". And nested methods in methods are very rare. Bye, Stelios - sorry for the delayed reply. Unexpected easter vacation. From _karlo_ at _mosor.net_ Sat Apr 15 21:45:30 2006 From: _karlo_ at _mosor.net_ (Karlo Lozovina) Date: Sun, 16 Apr 2006 01:45:30 +0000 (UTC) Subject: print without newline "halts" program execution References: Message-ID: Jay Parlar wrote in news:mailman.4537.1144976780.27775.python-list at python.org: > Your problem is that the 'print' statement is sending the text to > sys.stdout, and sys.stdout is buffered. I thought it was something like this, but I couldn't find it in the docs : (. > print 'Start: %f,'% st, > sys.stdout.flush() > sleep(10) > sp = time() > print 'Stop: %f, Duration: %f' % (sp, (st-sp)) This works excellent, *thank* you. > There are other ways to do this, but try this: And for purely academical purposes, what are those other ways to do it? I'm curious :). -- _______ Karlo Lozovina - Mosor | | |.-----.-----. web: http://www.mosor.net || ICQ#: 10667163 | || _ | _ | Parce mihi domine quia Dalmata sum. |__|_|__||_____|_____| From penshe at 265.com Sat Apr 29 12:38:12 2006 From: penshe at 265.com (penshe at 265.com) Date: 29 Apr 2006 09:38:12 -0700 Subject: http://blog.wokkow.com/user1/xinyegong/index.shtml Message-ID: <1146328692.417218.218430@e56g2000cwe.googlegroups.com> http://blog.wokkow.com/user1/xinyegong/index.shtml From gherron at islandtraining.com Thu Apr 20 19:38:06 2006 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 20 Apr 2006 16:38:06 -0700 Subject: search files in a directory In-Reply-To: <9583ed900604201602m3f4478cdg85aa9d4e17446ea1@mail.gmail.com> References: <9583ed900604201602m3f4478cdg85aa9d4e17446ea1@mail.gmail.com> Message-ID: <44481B5E.7050307@islandtraining.com> david brochu jr wrote: > Hello, > > I need to open every file in a directory and search for a string. What > module is needed to do this and how would I go about searching each file? os.listdir(dir) gives a list of all the file in a directory. You can then loop through the list. open can be used to open a file The open file has several methods to read bytes from the file: read() gets the whole file at once readline() return a line at a time other possibilities exist You can test to see if a string s is in another string t with if s in t: ... Hope that helps, Gary Herron From ldo at geek-central.gen.new_zealand Fri Apr 7 17:00:17 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 08 Apr 2006 09:00:17 +1200 Subject: socket.socket.settimeout implementation References: <1144228868.576227.186500@i40g2000cwc.googlegroups.com> Message-ID: In article <1144228868.576227.186500 at i40g2000cwc.googlegroups.com>, jnair at ensim.com wrote: >Now my observation on FC4 ( kernel version 2.6.11-1.1369_FC4) >"select()" can return before timeout with a >"Interrupted system call" (EINTR) error, Nothing Red-Hat-specific, or even Linux-specific, about this. It's a standard *nix thing. _All_ potentially time-consuming system calls (such as select(2), read(2), write(2)) can return EINTR, or some other indication that they didn't do everything they were asked to do. >my question is , is it possible that our internal_select() fuction as >seen on line 676 above returns "0" and we go on to do a "accept()" call >which returns with a "Resource temporarily unavailable" error if the >sockfd is not readable. The semantics of select(2) is that you're supposed to check the returrned bitmasks and only take the appropriate actions if the corresponding read-ready, write-ready and error bits are set. See the select(2) man page for more on this. From fredrik at pythonware.com Wed Apr 12 16:41:49 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 12 Apr 2006 22:41:49 +0200 Subject: Figure out month number from month abbrievation References: <1144873227.982973.18720@i40g2000cwc.googlegroups.com> Message-ID: "Bill" wrote: > I'm parsing the output of the finger command, and was wondering > something...If I'm given a month abbrievation (such as "Jan"), what's > the best way to figure out the month number? I see that there's > something called "month_abbr" in the calendar module. However, when I > try to do calendar.month_abbr.index("Jan"), I get "_localized_month > instance has no attribute 'index'." So it seems that month_abbr isn't > a regular list. I'm currently doing it this way: > > def month_number(monthabbr): > """Return the month number for monthabbr; e.g. "Jan" -> 1.""" > for index, day in enumerate(calendar.month_abbr): > if day == monthabbr: > return index > > which works well enough but isn't very clever. I'm pretty new to > Python; what am I missing here? a couple of things, I think. ... first, you can use list(seq) to convert any sequence to a list object, so you could do return list(calendar.month_abbr).index(monthabbr) if you prefer to do things in one line. ... but it also looks as if the meaning of the word "localized" isn't clear to you; if you changed the locale, those names will be translated: >>> list(calendar.month_abbr) ['', 'jan', 'feb', 'mar', 'apr', 'maj', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'dec'] which will cause your finger program to break... ... and I'm quite sure that you could have written down the abbreviations in far less time than it took you to compose that mail ;-) MONTHS = ['', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ] month_number = MONTHS.index From sturlamolden at yahoo.no Thu Apr 27 12:05:27 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 27 Apr 2006 09:05:27 -0700 Subject: Pyrex installation on windows XP: step-by-step guide In-Reply-To: <1146126507.086613.224070@j33g2000cwa.googlegroups.com> References: <1145449777.731155.181600@i40g2000cwc.googlegroups.com> <1146076193.605314.70200@g10g2000cwb.googlegroups.com> <1146126507.086613.224070@j33g2000cwa.googlegroups.com> Message-ID: <1146153927.211618.180350@t31g2000cwb.googlegroups.com> Julien Fiore wrote: > Thanks for your remark, Sturlamolden. > > Is there a free version of the "Visual C++ 2003" compiler available on > the web? I have found "Visual C++ 2005 Express edition" > (http://msdn.microsoft.com/vstudio/express/visualc/). According to > Micrsoft, it replaces VC++2003 > (http://msdn.microsoft.com/visualc/vctoolkit2003/). Is VC++2005ee the > good compiler to compile a Pyrex module (or any Python extension) ? > Does it link with msvcr71.dll ? The bad news is that "Visual C++ 2005 Express" links with msvcr80.dll, which incompatible with both msvcrt.dll and msvcr71.dll. What you need is the "Microsoft .NET Framework SDK Version 1.1". It contains version 7.1 of Microsoft's C/C++ compiler and links with the correct CRT. http://tinyurl.com/5flob I am not sure if this is an optimizing compiler. Microsoft did not give away their optimizing compiler prior to "Visual C++ 2005 Express". Even the standard version of Visual Studio did not have an optimizing compiler, it only shipped with the professional and enterprise versions. If this compiler does not optimize, you may try to make "Visual C++ 2005 Express" use the import library for msvcr71.dll which ships with the .NET SDK. Now you know the meaning of the word "DLL HELL". From gherron at islandtraining.com Mon Apr 24 18:40:04 2006 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 24 Apr 2006 15:40:04 -0700 Subject: What am I doing wrong here In-Reply-To: <1145916134.764210.235250@t31g2000cwb.googlegroups.com> References: <1145916134.764210.235250@t31g2000cwb.googlegroups.com> Message-ID: <444D53C4.2030205@islandtraining.com> Hitesh Joshi wrote: >Hi, > >I wanted to pass a popup mesage using windows messagin service to five >PCs. >If I just use following then PC1 gets the popup service message: > >import os >os.system('net send PC1 "Message"') > > >But if I try to create a for loop like this it doesn't work.... how can >I pass computerName var as an argument? >What am I doing wrong here? Thank you in advance.... > >import os > >Computerlist = ['PC1', 'PC2', 'PC3', 'PC4', 'PC5'] >for ComputerName in Computerlist: > print ComputerName > os.system('net send ComputerName "Message"') > > > Well... Just look at the name of the computer you are sending the message to. Its looking for a computer named 'ComputerName', not 'PC1' ... You want to create a command that has the computer's name in it, like this: 'net send PC1', not like this 'net send ComputerName'. You have several ways to from such a string. You have the same problem with the message. Your message will be the string 'Message' not the contents of a variable names Message. Try: os.system('net send %s "%s"' % (ComputerName, Message)) (where the % operator replaces %s's on the left with values taken from the variables on the right) or os.system('net send ' + ComputerName + ' "' + Message + '"') where the +'s build the command string up from pieces. You might try invoking Python interactively and try typing some of these expressions by hand to see that happens: python >>> ComputerName = 'Fred' >>> Message = 'HI' >>> print 'net send ComputerName "Message"' net send ComputerName "Message" >>> print 'net send %s "%s"' % (ComputerName, Message) net send Fred "HI" >>> Gary Herron From steve at hastings.org Sat Apr 1 01:22:14 2006 From: steve at hastings.org (Steve R. Hastings) Date: Fri, 31 Mar 2006 22:22:14 -0800 Subject: any() and all() on empty list? References: <7x3bh1x0ym.fsf@ruckus.brouhaha.com> <42qWf.18211$uX5.7574@tornado.texas.rr.com> <7xzmj9u1di.fsf@ruckus.brouhaha.com> <85tWf.2748$Aa1.1605@dukeread05> <7xy7ytmtk2.fsf@ruckus.brouhaha.com> <7xpsk2f8ab.fsf@ruckus.brouhaha.com> Message-ID: On Fri, 31 Mar 2006 16:29:00 -0800, Paul Rubin wrote: > I think "S and all(S)" is the right way to express that, if that's > what's intended. I still would like a standard function, because "S and all(S)" does not work with iterators. I proposed one possible function, truecount(S), that returns a tuple of how many were true and how many there were total. Then you could do true_count, count = truecount(S) if count and true_count == count: # nonempty list and all are true And S could be an iterator or generator function expression. You can easily write your own truecount() but it would be nice to have something like that as standard. I don't much like the name "truecount" though; I'm open to suggestions for a better name. -- Steve R. Hastings "Vita est" steve at hastings.org http://www.blarg.net/~steveha From grflanagan at yahoo.co.uk Sat Apr 22 04:48:20 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 22 Apr 2006 01:48:20 -0700 Subject: Generate a sequence of random numbers that sum up to 1? In-Reply-To: <1145693855.407215.102720@j33g2000cwa.googlegroups.com> References: <1145693855.407215.102720@j33g2000cwa.googlegroups.com> Message-ID: <1145695700.800395.219050@i40g2000cwc.googlegroups.com> Gerard Flanagan wrote: > Anthony Liu wrote: > > I am at my wit's end. > > > > I want to generate a certain number of random numbers. > > This is easy, I can repeatedly do uniform(0, 1) for > > example. > > > > But, I want the random numbers just generated sum up > > to 1 . > > > > I am not sure how to do this. Any idea? Thanks. > > > > -------------------------------------------------------------- > import random > > def partition(start=0,stop=1,eps=5): > d = stop - start > vals = [ start + d * random.random() for _ in range(2*eps) ] > vals = [start] + vals + [stop] > vals.sort() > return vals > > P = partition() > > intervals = [ P[i:i+2] for i in range(len(P)-1) ] > > deltas = [ x[1] - x[0] for x in intervals ] > > print deltas > > print sum(deltas) > --------------------------------------------------------------- > def partition(N=5): vals = sorted( random.random() for _ in range(2*N) ) vals = [0] + vals + [1] for j in range(2*N+1): yield vals[j:j+2] deltas = [ x[1]-x[0] for x in partition() ] print deltas print sum(deltas) >>> [0.10271966686994982, 0.13826576491042208, 0.064146913555132801, 0.11906452454467387, 0.10501198456091299, 0.011732423830768779, 0.11785369256442912, 0.065927165520102249, 0.098351305878176198, 0.077786747076205365, 0.099139810689226726] 1.0 From ejohnso9at at earthlink.dot.net Wed Apr 12 21:00:42 2006 From: ejohnso9at at earthlink.dot.net (ej) Date: Wed, 12 Apr 2006 19:00:42 -0600 Subject: CGI module: get form name Message-ID: <443da3af$1@nntp.zianet.com> I'm not seeing how to get at the 'name' attribute of an HTML
element. form = cgi.FieldStorage() gives you a dictionary-like object that has keys for the various named elements *within* the form... I could easily replicate the form name in a hidden field, but there ought to be some way to get directly at the form name but I'm just not seeing it. I looked in the os.environ() - don't see it there. Any ideas? Thanks! :) -------------------------------------------------------------- "I strongly believe what we're doing is the right thing. If I didn't believe it-I'm going to repeat what I said before-I'd pull the troops out, nor if I believed we could win, I would pull the troops out." --President George W. Bush, Charlotte, N.C., April 6, 2006 From fredrik at pythonware.com Thu Apr 27 07:20:25 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 27 Apr 2006 13:20:25 +0200 Subject: Packing a list of lists with struct.pack() References: <1145895732.963584.231100@j33g2000cwa.googlegroups.com> <1146072411.253848.108770@e56g2000cwe.googlegroups.com> Message-ID: Panos Laganakos wrote: > What I don't understand is what are you doing with *(...), this is > supposed to pack its contents as a list? the *arg form treats each value in the arg sequence as a separate argument. for example, arg = 1, 2, 3 function(*arg) is the same thing as function(1, 2, 3) when used with a generator expression, *(genexp) simply fetches the arguments from the generated sequence. (note that struct.pack expects a format string plus N additional arguments, not a format string and an N-item sequence) From deets at nospam.web.de Thu Apr 27 05:28:14 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 27 Apr 2006 11:28:14 +0200 Subject: begging for a tree implementation References: <1146091386.013265.153660@v46g2000cwv.googlegroups.com> <1146127110.773347.222270@e56g2000cwe.googlegroups.com> Message-ID: <4bbh68F10a2lbU1@uni-berlin.de> > I may start a tree data structure project - it's something I've been > thinking about for a while, and now it's clear that it's not just me > who uses trees as data structures! Oh, people do use them. It's just to easy to cough one up when you need it - either as nested tuples, lists, dicts or a simple class like yours - which I needed yesterday and wrote in 2 minutes. And that is tailored to the needs at hand and not some abstraction that might prevent you from e.g. using methods like __iter__ or the like with your own semantics. This is not to discourage you - just don't expect people to greet you as the next messiah who finally brought one of CS most fundamental data structures to Python... :) Diez From http Sat Apr 1 03:11:56 2006 From: http (Paul Rubin) Date: 01 Apr 2006 00:11:56 -0800 Subject: any() and all() on empty list? References: <7x3bh1x0ym.fsf@ruckus.brouhaha.com> <42qWf.18211$uX5.7574@tornado.texas.rr.com> <7xzmj9u1di.fsf@ruckus.brouhaha.com> <85tWf.2748$Aa1.1605@dukeread05> <7xy7ytmtk2.fsf@ruckus.brouhaha.com> <7xpsk2f8ab.fsf@ruckus.brouhaha.com> Message-ID: <7xpsk11zqr.fsf@ruckus.brouhaha.com> Ron Adam writes: > true_count, count = countall(S), len(S) In general it's preferable to not rely on len being available, since these are arbitrary iterators. From bencvt at gmail.com Tue Apr 11 22:05:45 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 11 Apr 2006 19:05:45 -0700 Subject: About classes and OOP in Python In-Reply-To: <1144745819.173322.174040@z34g2000cwc.googlegroups.com> References: <1144678797.749000.155010@t31g2000cwb.googlegroups.com> <1144745819.173322.174040@z34g2000cwc.googlegroups.com> Message-ID: <1144807545.369050.259040@t31g2000cwb.googlegroups.com> Michele Simionato wrote: > Roy Smith wrote: > > > That being said, you can indeed have private data in Python. Just prefix > > your variable names with two underscores (i.e. __foo), and they effectively > > become private. Yes, you can bypass this if you really want to, but then > > again, you can bypass private in C++ too. > > Wrong, _foo is a *private* name (in the sense "don't touch me!"), __foo > on the contrary is a *protected* name ("touch me, touch me, don't worry > I am protected against inheritance!"). > This is a common misconception, I made the error myself in the past. Sure, if you only consider "private" and "protected" as they're defined in a dictionary. But then you'd be ignoring the meanings of the public/private/protected keywords in virtually every language that has them. http://www.google.com/search?q=public+private+protected Python doesn't have these keywords, but most Python programmers are at least somewhat familiar with a language that does use them. For the sake of clarity: __foo ~= private = used internally by base class only _foo ~= protected = used internally by base and derived classes The Python docs use the above definitions. --Ben From pmartin at snakecard.com Fri Apr 14 17:17:45 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Fri, 14 Apr 2006 16:17:45 -0500 Subject: Passing a packed C structure to a c module References: <3OP%f.811$9c6.333@dukeread11> <443fcb63$0$3177$9b622d9e@news.freenet.de> Message-ID: I'll take a look, thanks. Jay Parlar wrote: > > On Apr 14, 2006, at 9:44 AM, Philippe Martin wrote: > >> Thanks, >> >> It's a pretty big structure: painfull to pass each item as a param. >> >> Regards, >> >> Philippe >> > > Maybe this can do something for you? > > http://pyconstruct.sourceforge.net/ > > > Jay P. From matt at biggmatt.com Tue Apr 18 23:07:21 2006 From: matt at biggmatt.com (Biggmatt) Date: Wed, 19 Apr 2006 03:07:21 GMT Subject: How protect proprietary Python code? (bytecode obfuscation?, what better?) Message-ID: >>I'm afraid that the only *proven* way to protect code from >>reverse-engineering is to not distribute it *at all*. ain't that the truth. A hex editor would stop the "PyRun_SimpleString(secret_code)" Even if you encrypt your string they have to run at some point. A couple clicks in decent disassembler like softice when the program is running, and the program will have un-encrypted it for you. And besides, when you introduce drm (copy protection) into a program, you you take a chance on introducing bugs. There's nothing worse than losing legitimate customers over copy protection. Clean, Stable, Working programs sell better. The people that steal are going to steal it. So why not make people want to give you money for the good job you did. Not some buggy crap of a program that's too worried you might steal something. From jjl at pobox.com Tue Apr 11 19:17:22 2006 From: jjl at pobox.com (John J. Lee) Date: 11 Apr 2006 23:17:22 +0000 Subject: modifying html input date for mysql, reg ex or string interpolation? References: Message-ID: <8764lf8zy5.fsf@pobox.com> Kun writes: [...] > for x in form.keys(): > print "%s=%s" % (x, form[x].value) + "
" [...] ...and the second thing that jumps out at me is that you're neglecting to HTML-quote the data you're inserting into your web page here (for example, using xml.sax.saxutils.escape()), which is another common cause of security holes, very similar to those with failing to use proper SQL parameter quoting. Google for "cross-site scripting". John From rrr at ronadam.com Sat Apr 8 03:48:13 2006 From: rrr at ronadam.com (Ron Adam) Date: Sat, 08 Apr 2006 02:48:13 -0500 Subject: Appending Elements in Element Tree In-Reply-To: References: Message-ID: Ron Adam wrote: > > In my program I have a lot of statements that append elements, but > sometimes I don't want to append the element so it requres an if > statement to check it, and that requires assigning the returned element > from a function to a name or calling the funtion twice. > > e = ET.Element('name') > e.append(get_subelement(obj)) # but raises an exception on None > > > > This works, but I have a lot of appends. > > sube = get_element(obj) > if sube is None: > e.append(sube) > > > > Now if Elements worked more like lists I could extend an element. > > alist = [] > alist.extend([]) # returns orginal list > > > > With strings. > > s = '' > s += '' # returns original string (or copy) > > > So is there an identity operation with Element Tree elements that I can > use to avoid putting a lot of if and or try statements around appending > elements? > > > > I could wrap the append and do it this way... > > def eappend(e1, e2): > if e2 is None: return e1 > e1.append(e2) > return e1 > > Then do... > > e = eappend(e, get_element(obj)) # Append if not None. > > > But maybe there's a better way? The following worked in cases where I needed to append a list of items. def extend(e1, elist): for e in elist: e1.append(e) return e1 Although I still need to return the list as elements aren't mutable. element = extend(element, elist) It would be nice if this was built in so I could do... Hint hint. :-) element.extend(elist) Where elist is a list of elements or an element with a number of sub elements. I still need to special case individual appends or put the returned item in a list so I use the extend() function on the returned element. I guess I need to look at the Element Tree source code. Cheers, Ron From johnjsal at NOSPAMgmail.com Sun Apr 9 13:03:58 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sun, 09 Apr 2006 13:03:58 -0400 Subject: Programming Tutorial for absolute beginners In-Reply-To: <1144585206.511736.131530@e56g2000cwe.googlegroups.com> References: <1144439148.751062.16590@t31g2000cwb.googlegroups.com> <1144512142.324056.281660@g10g2000cwb.googlegroups.com> <4437f586.0@entanet> <1144525755.278026.60200@g10g2000cwb.googlegroups.com> <4438700f.0@entanet> <1144585206.511736.131530@e56g2000cwe.googlegroups.com> Message-ID: <44393ed0$0$19226$c3e8da3@news.astraweb.com> Clodoaldo Pinto wrote: > Duncan Smith wrote: >> But as you use conversions to float in order to avoid integer division >> in your code examples, it might be best to explain what's going on, even >> if you do have to explain the relevant types. >> > > I changed the comments in the first program that uses float() to: > > # The raw_input() function asks the user for a text > # As a text can't be multiplied or divided the > # float() function tranforms the text into a decimal number Hmmm, maybe a picky point for a newbie, but since there actually is a decimal module now, you might want to change the description of float(). From robert.kern at gmail.com Mon Apr 24 12:29:59 2006 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 24 Apr 2006 11:29:59 -0500 Subject: MS VC++ Toolkit 2003, where? In-Reply-To: <1heag4u.19dksfxrbe14wN%aleaxit@yahoo.com> References: <1he8pss.1yk7ug81rv7pw2N%aleaxit@yahoo.com> <1145811839.042394.73260@t31g2000cwb.googlegroups.com> <1he8sbx.dqqp3q10n5thaN%aleaxit@yahoo.com> <1145849491.347970.112150@e56g2000cwe.googlegroups.com> <1he9m4m.9d8okx1x7mxeaN%aleaxit@yahoo.com> <444C784F.3000502@v.loewis.de> <1heag4u.19dksfxrbe14wN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Jocular, but not sarcastic. I have no problems using mingw if that's > what it takes -- the later instructions I saw were those suggesting the > Toolkit instead, so those are the ones I'm trying to follow. What's the > updated URL for the instructions about using mingw instead? Oh, that's right, you need an import library for Python24.dll . If you build numpy first, it will automatically build the import library for you. The implementation is fairly simple if you would rather bodge a script together. The driver is the function build_import_library() here: http://svn.scipy.org/svn/numpy/trunk/numpy/distutils/mingw32ccompiler.py This uses the following module: http://svn.scipy.org/svn/numpy/trunk/numpy/distutils/lib2def.py -- Robert Kern robert.kern at gmail.com "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From martin at v.loewis.de Wed Apr 12 14:09:23 2006 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Wed, 12 Apr 2006 20:09:23 +0200 Subject: list.clear() missing?!? In-Reply-To: References: <1144767680.583085.310160@v46g2000cwv.googlegroups.com> <443BE426.20501@v.loewis.de> Message-ID: <443D4253.1060007@v.loewis.de> Steven D'Aprano wrote: >>> $ python2.4 -mtimeit 'x = range(100000); ' >>> 100 loops, best of 3: 6.7 msec per loop >>> $ python2.4 -mtimeit 'x = range(100000); del x[:]' >>> 100 loops, best of 3: 6.35 msec per loop >>> $ python2.4 -mtimeit 'x = range(100000); x[:] = []' >>> 100 loops, best of 3: 6.36 msec per loop >>> $ python2.4 -mtimeit 'x = range(100000); del x' >>> 100 loops, best of 3: 6.46 msec per loop >>> >>> Why the first benchmark is the slowest? I don't get it... could someone >>> test this, too? >> In the first benchmark, you need space for two lists: the old one and >> the new one; > > Er, what new list? I see only one list, x = range(100000), which is merely > created then nothing done to it. Have I missed something? See Duncan's explanation. This code is run many times, allocating many lists. However, only two different lists exist at any point at time. A Python list consists of two memory blocks: the list proper (a few bytes), plus the "guts", i.e. a variable-sized block of pointers to the objects. del x[:] frees the guts. > I understood Felipe to be asking, why does it take longer to just create a > list, than it takes to create a list AND then do something to it? Actually, the same code (deallocation of all integers and the list blocks) appears in either case. However, in the one case it is triggered explicitly, and before the new allocation; in the other case, the allocation of the new objects occurs before the old ones are released. Regards, Martin From felipe.lessa at gmail.com Fri Apr 14 01:37:25 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Fri, 14 Apr 2006 02:37:25 -0300 Subject: list.clear() missing?!? In-Reply-To: References: <1144767680.583085.310160@v46g2000cwv.googlegroups.com> Message-ID: <1144993045.17836.6.camel@kenshin.CASA> Em Sex, 2006-04-14 ?s 09:17 +0400, Sergei Organov escreveu: > I, as a newcomer, don't have much trouble understanding the binding vs > the assignment by themselves. What does somewhat confuse is dual role of > the "=" operator, -- sometimes it means "bind" and other times it means > "assign", right? For me it seems that the language would be less > error-prone and easier to grok if these two operations had different > names/syntax (thinking about lisp "let" vs "set"), though it seems to be > too drastic change even for Python3000. The "=" operator *always* binds. -- Felipe. From tzot at sil-tec.gr Wed Apr 12 16:46:44 2006 From: tzot at sil-tec.gr (Christos Georgiou) Date: Wed, 12 Apr 2006 23:46:44 +0300 Subject: trouble with Tkinter and Tix References: <1144791581.447835.22660@g10g2000cwb.googlegroups.com> Message-ID: <7ioq32t18je3n2picmb8bcshtnutaf1lj0@4ax.com> On 11 Apr 2006 14:39:41 -0700, rumours say that "CT" might have written: >I installed python 2.4.3, Tcl 8.4 Tk8.4 and also with Tix 8.4 >I got some error like _tkinter.TclError:ambigous option "-col": must be >column, etc with my LabelFrame from Tix. > >It seems that the python interpreter is mixing my Tix with Tkinter? If >I put Tix.LabelFrame and use import Tix instead of from Tix import *, >the problem seems to be gone. > >Any idea how to fix it without editing all the codes? Please post a part of the code that illustrates this misbehaviour. Also try to describe what you are trying to do. -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From onurb at xiludom.gro Fri Apr 21 08:22:27 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 21 Apr 2006 14:22:27 +0200 Subject: python equivalent of VB code sample In-Reply-To: <1145620873.806376.206610@i39g2000cwa.googlegroups.com> References: <1145620873.806376.206610@i39g2000cwa.googlegroups.com> Message-ID: <4448ced5$0$502$626a54ce@news.free.fr> mirandacascade at yahoo.com wrote: > Situation is this: > 1) must write application that does the following: > a) creates an xml document, the contents of which, is a request > transaction > b) send xml document to destination; I am assuming that a process > at destination side processes the request and sends back a response > c) the application I'm writing must receive response and then > examine contents of response > 2) hope to write client application in python > 3) was provided VB code sample that does steps 1a, 1b and 1c; the > sample code is: > > '
is a request transaction> > set objXML = Server.CreateObject("MSXML2.ServerXMLHTTP") > 'Bank table image address field, location of Comm Admin. > sServer = Session("ImageAddress") > 'NT AUTH > ' note: I believe the next 2 lines in this post are really one line in > VB code that wrapped > ' because they didn't fit on one line in the post > objXML.open > "POST",sServer,false,Session("WebServerUserAuth"),Session("WebServerPassword") > objXML.send sXML > sXMLRs = objXML.responseText > This code is dealing with XMLHTTP request. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From alexci at web.de Sat Apr 15 04:49:17 2006 From: alexci at web.de (Aleksandar Cikota) Date: Sat, 15 Apr 2006 10:49:17 +0200 Subject: VB to Python References: Message-ID: Vielen Dank. Es funktioniert. Mit freundlichen gruessen, Aleksandar Cikota "Gregor Horvath" wrote in message news:e1ptt3$4tb$1 at newsreader1.utanet.at... > Aleksandar Cikota schrieb: > >> Can someone translate the VB code to Python? >> >> VB code: >> >> Dim chsr as New DriverHelper.Chooser >> chsr.DeviceType = "Telescope" >> scopeProgID = chsr.Choose(scopeProgID) >> Set scope = CreateObject(scopeProgID) >> scope.Connected = True >> > > (untested; late binding): > > import win32com.client > > chsr = win32com.client.Dispatch("DriverHelper.Chooser") #you may have to > choose the ProdID of the class from the registry here > > chsr.DeviceType = "Telescope" > scopeProgID = chsr.Choose(scopeProgID) > scope = win32com.client.Dispatch(scopeProgID) > scope.Connected = True > > > -- > Mit freundlichen Gr??en, > Ing. Gregor Horvath, Industrieberatung & Softwareentwicklung > Mobil: +43(0)69910879004 > Fax: +43(0)1/25330333931 http://www.gregor-horvath.com > > > > > -- > Mit freundlichen Gr??en, > Ing. Gregor Horvath, Industrieberatung & Softwareentwicklung > http://www.gregor-horvath.com From gabriel.dedietrich at gmail.com Thu Apr 6 04:57:29 2006 From: gabriel.dedietrich at gmail.com (Gabriel de Dietrich) Date: 6 Apr 2006 01:57:29 -0700 Subject: malloc'ed PyTypeObject Message-ID: <1144313849.044560.156110@u72g2000cwu.googlegroups.com> Hi, I'm doing my first project on embedding and then extending Python in an application. The idea is to import a set of C++ plug-ins into Python and then be able to run a script that uses these plug-ins. Please note that what I'm importing into Python are the plug-in classes in order to be able to instanciate as many objects as needed. As usual, all the plug-ins derive from a base class. But two important things differ for each plug-in, its name and a set of parameters. For instance, the C++ class class SNRFilter : public BaseFilter { ... }; can be instanciated in a Python script as snr = SNRFilter() (This is a quite simplified example as there is also a quite trivial SNRFilterClass class deriving fron BaseFilterClass. But those are implementation details). So, everything works OK, but there will probably be a memory issue. Each time I add a plug-in class into Python, I malloc a PyTypeObject and copy its contents from a template static PyTypeObject. Then I malloc and assign its tp_name and its tp_getset (array of PyGetSetDef). Now the question is, how can I be sure that all this memory will be properly free'd after calling Py_Finalize()? Is it enough to add Py_TPFLAGS_HEAPTYPE? Can I safely free tp_getset after calling PyType_Ready()? What will the weather be for the next week-end? Thank you for reading. -- Gabriel de Dietrich From spamspam at spam.eggs Thu Apr 13 10:27:27 2006 From: spamspam at spam.eggs (Ben C) Date: 13 Apr 2006 14:27:27 GMT Subject: new-style classes and len method References: <1144936961.203493.169840@v46g2000cwv.googlegroups.com> Message-ID: On 2006-04-13, Thomas Girod wrote: > Hi there. > > I'm trying to use new-style classes, but there is something i'm > obviously missing > > here it is : > > class Data(list): > __slots__ = ["width", "height", "label"] > > def __init__(self,width,height,label=None): > list.__init__(self) > self.width = width > self.height = height > self.label = label > > def clear(cls): > while len(cls) > 0: del cls[0] > return > clear = classmethod(clear) > > #> d = Data(2,2) > #> d.clear() > TypeError: len() of unsized object > > off course it was working with : > > [...] > def clear(self): > while len(self) > 0: del self[0] > return > > So, I guess you can't use "cls" as a replacement for "self". So, what > do I have to use ??? You can use cls in a classmethod to refer to the class. You can use any name you want (well so long as it's not a "reserved word" I suppose). The same is true of self, it's just a param name (quite unlike JavaScript's "this"...). But I don't think it makes sense for clear to be a classmethod, since you presumably want a method that clears instances of lists? The error is because you're trying to take the len of the class itself, not the len of an instance of it. What you had before was OK. Although you don't need to write the loop, just del self[:] will do, and you can leave out the return statement if you want. From webraviteja at gmail.com Mon Apr 17 09:36:02 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 17 Apr 2006 06:36:02 -0700 Subject: Translate Cpp into python code In-Reply-To: References: Message-ID: <1145280962.273214.36240@j33g2000cwa.googlegroups.com> If you are looking for ways to access C++ code in Python, there are several (Boost, SIP, CXX, SWIG, Weave etc). Unless your needs are somehow unique, this is the preferred approach. People usually convert higher level languages to lower level languages for performance (For example Python to C++ via ShedSkin or Eiffel to C etc), not the other way around since the principle benefit of HLLs is readable code and code generators don't usually generate human readable code because they can't see the intended theme of your code. From jjl at pobox.com Thu Apr 20 15:53:56 2006 From: jjl at pobox.com (John J. Lee) Date: 20 Apr 2006 19:53:56 +0000 Subject: urllib2.ProxyHandler References: <444545ec$0$8100$ba624c82@nntp02.dk.telia.net> Message-ID: <87wtdkvx9n.fsf@pobox.com> "rx" writes: > I'm trying to hide my IP with the following code: > > import urllib2 > proxy=[urllib2.ProxyHandler({'http':'24.232.167.22:80'})] > opener=urllib2.build_opener(proxy) build_opener takes *args, not a list: import urllib2 handlers = [urllib2.ProxyHandler({'http':'24.232.167.22:80'})] opener = urllib2.build_opener(*handlers) or just: import urllib2 proxy_handler = urllib2.ProxyHandler({'http':'24.232.167.22:80'}) opener = urllib2.build_opener(proxy_handler) Also, IIRC 2.4 does not allow ports in proxy specification strings (the values in the dict you pass to ProxyHandler's constructor), and IIRC 2.5a1 ProxyHandler is broken (it's fixed in the SVN repository). John From rridge at csclub.uwaterloo.ca Tue Apr 25 16:21:38 2006 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: 25 Apr 2006 13:21:38 -0700 Subject: MinGW and Python References: <1145861223.509630.247350@y43g2000cwc.googlegroups.com> <444C79D7.4060007@v.loewis.de> <1145967287.536182.311970@g10g2000cwb.googlegroups.com> Message-ID: <1145996498.654312.162420@u72g2000cwu.googlegroups.com> sturlamolden wrote: > MinGW can compile MFC. Download Windows Platform SDK and you get the > MFC source. Do not do this. The Platform SDK's EULA does not permit you to redistribute anything you build from the MFC sources included in the SDK. The only way to get a copy of MFC that you can legitimately use in anything you distribute you need to buy a Microsoft C++ compiler. Ross Ridge From jyoti.chhabra at gmail.com Wed Apr 12 09:24:27 2006 From: jyoti.chhabra at gmail.com (JyotiC) Date: 12 Apr 2006 06:24:27 -0700 Subject: Tkinter vs PyGTK In-Reply-To: <7xbqv7mas8.fsf@ruckus.brouhaha.com> References: <1144825422.167548.153860@z34g2000cwc.googlegroups.com> <1144826842.238389.63170@t31g2000cwb.googlegroups.com> <7xfykjmd9c.fsf@ruckus.brouhaha.com> <1144829749.490901.16830@v46g2000cwv.googlegroups.com> <7xbqv7mas8.fsf@ruckus.brouhaha.com> Message-ID: <1144848267.412008.257230@z34g2000cwc.googlegroups.com> Thanx for the help. Does all gui's take time to load. is there a way to dec this time. From ldo at geek-central.gen.new_zealand Mon Apr 17 03:55:45 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 17 Apr 2006 19:55:45 +1200 Subject: filling today's date in a form References: Message-ID: In article , Kun wrote: >... but i am >wondering if there is a way to create a button which would automatically >insert today's date in the date form field if the user chooses to use >today's date. If you're going to have a button to do it, then the button might as well invoke a JavaScript sequence to fill in the field. No sense bothering the server with something this simple. From iddw at hotmail.com Wed Apr 5 16:52:42 2006 From: iddw at hotmail.com (Dave Hansen) Date: Wed, 05 Apr 2006 15:52:42 -0500 Subject: Filters like old skool Jive, Fudd, Valspeak... Text transformation in Python References: <1144237161.700762.75630@e56g2000cwe.googlegroups.com> <4433b3f1$0$24162$636a55ce@news.free.fr> <1144269888.887561.247620@v46g2000cwv.googlegroups.com> Message-ID: On 5 Apr 2006 13:44:48 -0700 in comp.lang.python, dananrg at yahoo.com wrote: >bruno at modulix wrote: >> There's a Kant generator example in Dive Into Python: >> http://diveintopython.org/xml_processing/index.html > >Thanks Bruno! Perhaps I could modify it to throw in some Hume and >Wittgenstein, mix it all up in a syntactic / semantic blender and >REALLY confuse people. Word Games indeed. :-) > >Or throw in stuff by whichever philosopher who wrote a book called "The >Meaning of Meaning", to add some metaphoric recursion. And that what be >one heck of a Frankenstenian (but only 1 part Wittgensteinian) >Robo-philosopher. Don't forget the famous American philosopher who contemplated the meaning of is. Regards, -=Dave -- Change is inevitable, progress is not. From fredrik at pythonware.com Sat Apr 1 12:09:18 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 1 Apr 2006 19:09:18 +0200 Subject: wx.checklistbox References: <1143815725.730867.324970@j33g2000cwa.googlegroups.com><1143817821.621038.205640@g10g2000cwb.googlegroups.com><1143820847.823668.90720@j33g2000cwa.googlegroups.com><1143822322.589470.241040@z34g2000cwc.googlegroups.com> <1143900250.243912.309390@v46g2000cwv.googlegroups.com> Message-ID: "luca72" wrote: > i have again one simple problem: > the script is this: > > def output(self): > global lista2 > lista2 = open('/lista2', 'w') > iteminlista2 = self.checkListBox2.GetStrings() > lista2.writelines(iteminlista2) > > def input1(self): > lista2leggi = open('/lista2', 'r') > cd = lista2leggi.readlines() > self.checkListBox2.AppendItems(cd) > > The write file is like: > > item1item2item3 writelines doesn't add newlines; you have to do that yourself. try using a plain loop instead: for item in iteminlista2: lista2.write(item + "\n") From tchur at optushome.com.au Sat Apr 29 09:33:40 2006 From: tchur at optushome.com.au (Tim Churches) Date: Sat, 29 Apr 2006 23:33:40 +1000 Subject: Recommendations for a PostgreSQL db adapter, please? In-Reply-To: <44535ED7.4010007@ghaering.de> References: <44535ED7.4010007@ghaering.de> Message-ID: <44536B34.8080800@optushome.com.au> Gerhard H?ring wrote: > Keen Anthony wrote: >>> Hello, >>> >>> I am currently using psycopg 2 as my db adapter for a mod_python & >>> PostgreSQL web app. It's works fine, and I haven't any complaints. I >>> would appreciate some input on what other pythonistas like in an >>> adapter. There were several different options available to me, but there >>> was no particular informed reason for me to choose psycopg. Am I missing >>> anything? > > Considering pyPgSQL, psycopg1, PyGreSQL and psycopg2 - psycopg2 is a good > choice. Hmmm, Gerhard, you are listed as one of two developers for pyPgSQL on SourceForge ( http://sourceforge.net/projects/pypgsql/ ). The fact that you are recommending a different DB adaptor project suggests a degree of disengagement with pyPgSQL. Is Billy G. Allie still interested in pyPgSQL, or is it now completely unloved? If so, then perhaps some new maintainers can be found for it - several projects rely on pyPgSQL, including ours ( http://sourceforge.net/projects/netepi/ ) - for which we currently need to provide our own pyPgSQL tarball rolled from CVS plus some of our own minor but important patches - which were submitted for consideration but have not (AFAIK) been checked into the pyPgSQL CVS. The latest tarball for pyPgSQl available from the pyPgSQL SourceForge pages is dated 2003. No criticism is intended in any of the foregoing observations - it is inevitable that people move on to new projects (such as pySQLite), but it would be a shame if pyPgSQL just rotted, because it has several things in its favour, such as some unit tests (which were conspicuously absent from any of the alternatives when we evaluated them in 2003 - perhaps they have been added by now). Overall we have found pyPgSQL to be very reliable. Tim C From grflanagan at yahoo.co.uk Sat Apr 22 12:41:42 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 22 Apr 2006 09:41:42 -0700 Subject: problems when unpacking tuple ... In-Reply-To: <1145722900.647531.272680@i39g2000cwa.googlegroups.com> References: <1145722900.647531.272680@i39g2000cwa.googlegroups.com> Message-ID: <1145724102.800475.45270@i39g2000cwa.googlegroups.com> harold wrote: > Dear all, > > Maybe I stared on the monitor for too long, because I cannot find the > bug ... > My script "transition_filter.py" starts with the following lines: > > import sys > > for line in sys.stdin : > try : > for a,b,c,d in line.split() : > pass > > except ValueError , err : > print line.split() > raise err > > The output (when given the data I want to parse) is: > ['0.0','1','0.04','0'] > Traceback (most recent call last): > File "transition_filter.py", line 10, in ? > raise err > ValueError: need more than 3 values to unpack > > What is going wrong here? Why does python think that > I want to unpack the outcome of line.split() into three > values instead of four? I must be really tired, but I just > cannot see the problem. Any clues?? > The 3 values are coming from the first element in the list '0.0' - change it to '0' and you should get: ValueError: need more than 1 value to unpack. See? it's trying to get a,b,c,d from each element of the list not the whole list. Gerard From newptcai at gmail.com Sat Apr 15 23:56:47 2006 From: newptcai at gmail.com (=?utf-8?B?5LiA6aaW6K+X?=) Date: 15 Apr 2006 20:56:47 -0700 Subject: My python can not get addr info Message-ID: <1145159807.133572.103950@t31g2000cwb.googlegroups.com> D:\python24\Lib\idlelib>pyshell.py Traceback (most recent call last): File "D:\python24\Lib\idlelib\PyShell.py", line 1388, in ? main() File "D:\python24\Lib\idlelib\PyShell.py", line 1361, in main if not flist.open_shell(): File "D:\python24\Lib\idlelib\PyShell.py", line 277, in open_shell if not self.pyshell.begin(): File "D:\python24\Lib\idlelib\PyShell.py", line 962, in begin client = self.interp.start_subprocess() File "D:\python24\Lib\idlelib\PyShell.py", line 389, in start_subprocess self.rpcclt.accept() File "D:\python24\lib\idlelib\rpc.py", line 524, in accept working_sock, address = self.listening_sock.accept() File "D:\python24\lib\socket.py", line 169, in accept sock, addr = self._sock.accept() socket.gaierror: (10104, 'getaddrinfo failed') D:\python24\Lib\idlelib> From anton.vredegoor at gmail.com Fri Apr 28 08:53:48 2006 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Fri, 28 Apr 2006 14:53:48 +0200 Subject: not quite 1252 In-Reply-To: References: <444f5e6b$1@usenet.zapto.org> <1146091954.352996.16600@i40g2000cwc.googlegroups.com> <4451f9e9$1@usenet.zapto.org> Message-ID: <44520f09@usenet.zapto.org> Richard Brodie wrote: > "Anton Vredegoor" wrote in message > news:4451f9e9$1 at usenet.zapto.org... > >> Yes my header also says UTF-8. However some kind person send me an e-mail stating that >> since I am getting \x94 and such output when using repr (even if str is giving correct >> output) there could be some problem with the XML-file not being completely UTF-8. Or is >> there some other reason I'm getting these \x94 codes? > > Well that rather depends on what you are doing. If you take utf-8, decode > it to Unicode, then re-encode it as cp1252 you'll possibly get \x94. OTOH, > if you see '\x94' in a Unicode string, something is wrong somewhere. Well, I mailed the content.xml to someone as a text attachment and it was damaged at the other end, whereas sending it as a file resulted in flawless transfer. So I guess there is something not quite UTF-8 in it. However Firefox has no problem opening it either here or at the other persons computer (the undamaged file of course). By the way, I also sent an MSwWord document (not as text) that I edited using OO back to the same person who is using MsWord and he is at the moment still recovering from an MSWord crash. Could it have something to do with the OO document being half as big as the MsWord Doc :-) Anton From chrisoh at zoominternet.net Wed Apr 26 22:34:08 2006 From: chrisoh at zoominternet.net (Chris Pesarchick) Date: Wed, 26 Apr 2006 22:34:08 -0400 Subject: gcc errors Message-ID: <9033811E-05FC-4584-B94C-DB47B51C5194@zoominternet.net> I installed the Universal Mac OSX binary for Python 2.4.3 When I execute 'python setup.py install' for any of my applications that I need to build, I get errors like the following: gcc -arch ppc -arch i386 -isysroot /Developer/SDKs/MacOSX10.4u.sdk - fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused-madd - fno-common -dynamic -DNDEBUG -g -DHAVE_LIBJPEG -DHAVE_LIBZ - DWORDS_BIGENDIAN -I/System/Library/Frameworks/Tcl.framework/Headers - I/System/Library/Frameworks/Tk.framework/Headers -IlibImaging -I/sw/ include -I/Library/Frameworks/Python.framework/Versions/2.4/include - I/usr/local/include -I/usr/include -I/Library/Frameworks/ Python.framework/Versions/2.4/include/python2.4 -c _imaging.c -o build/temp.macosx-10.4-fat-2.4/_imaging.o gcc: installation problem, cannot exec 'i686-apple-darwin8- gcc-4.0.0': No such file or directory I am on a powerpc and it always thinks I'm on an intel box. What do I have to do so that it only cares about the powerpc? Thanks, Chris From fredrik at pythonware.com Sat Apr 8 03:39:11 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 8 Apr 2006 09:39:11 +0200 Subject: minidom + wxPython woes References: <1144448449.586601.293480@v46g2000cwv.googlegroups.com> <1144477016.011818.70290@e56g2000cwe.googlegroups.com> Message-ID: Frank Millman wrote: > This sounds similar to a problem I reported a few months ago. This is > the link. > http://groups.google.com/group/comp.lang.python/browse_frm/thread/6fc1097d26083e43/5fbdf493f3c38942?q=&rnum=1&hl=en#5fbdf493f3c38942 > > In my case, it turned out to be a bug in the pyexpat module - it is > known about, but for some reason difficult to fix, so it is still > there. no, it's not a bug in the pyexpat module -- the problem is that wxPython uses it's own incompatible version of the expat library, and loads it in a way that causes problems for any library that's tries to use its own statically linked version. see MvL's comments in the sourceforge tracker for more info. From ToddLMorgan at gmail.com Thu Apr 20 11:26:25 2006 From: ToddLMorgan at gmail.com (ToddLMorgan at gmail.com) Date: 20 Apr 2006 08:26:25 -0700 Subject: How should multiple (related) projects be arranged (structured) and configured so that they can share code, have a related package structure and enable proper unittesting, and ensuring no namespace collisions Message-ID: <1145546785.268550.154240@e56g2000cwe.googlegroups.com> Summary: How should multiple (related) projects be arranged (structured) and configured so that the following is possible: o Sharing common code (one of the projects would be a "common" project referenced by all others and likely the others would share at least the common project and possibly more as times goes on) o Clear separation of "production" code and "test" code (ie to readily ship source and test as separate components. Usually I'd do that with separate hierarchies (src vs test folders) o Enabling the running of individual unittests and aggregated testsuites o Avoiding namespace collisions - whilst still ensuring commonality (or ownership) of the projects (ie common base package) The longer version is detailed below which outlines my specific problem. I was hoping that someone could help me out with my python programming dilemma.I am having a huge problem organising my python projects so that the imports and from s to work correctly. I'm a Java/J2EE developer by trade so I have a reasonable grasp of the fundamentals regarding computer programming in general, but obviously not-so-good in python. I have noted from my reading on the web that my Java skills may actually be more of a hinderance - so feel free to tell me if I am making any programming java in python mistakes. I'm working on a few projects concurrently so I have tried to arranged my projects like this: COMMON src a.b.c.common test a.b.c.common APP1 src a.b.c.app1 test a.b.c.app1 APP2 src a.b.c.app2 test a.b.c.app2 But it has not worked due to import/from issues. It appears that using a common base package hierarchy (as is standard practice in the java world) caused issues. Ie not able to use "a.b.c" as the base package for all my projects, in order to avoid namespace collisions. I attempted to resolve this by altering the packages to make the project name as the base package. Ie the new packages were ? common.a.b.c.common ? app1.a.b.c.app1 ? app2.a.b.c.app2 My final problem is that I am not able to run my tests (unittest) as I can't seem to find the right imports or froms to use that will work for both from an aggregate (suite) test and the individual tests. I have an individual AllTests.py at the root of the test folder and all the appropriate __init__.pys in all the folders (to make them package loaders). It appears to be that the directory from which the AllTests.py is run is subverting the path/package hierarchy as it is loaded first and is conflicting with my PYTHONPATH env variables (or I am getting the python packaging and path totally wrong - which is entirely possible). So how should a project to be structured and configured to enable all of these requirements? Any special requirements for the __init__.py, PYTHONPATH, or other configuration tricks? Thanks Todd From no-spam at no-spam-no-spam.com Tue Apr 25 17:21:02 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Tue, 25 Apr 2006 23:21:02 +0200 Subject: Multithreading and Queue In-Reply-To: References: Message-ID: Jeffrey Barish wrote: > Several methods in Queue.Queue have warnings in their doc strings that they > are not reliable (e.g., qsize). I note that the code in all these methods > is bracketed with lock acquire/release. These locks are intended to > protect the enclosed code from collisions with other threads. I am > wondering whether I understand correctly that the reason these methods are > still not reliable is that from the point where a thread calls qsize (for > example) to the point in Queue where a thread acquires a lock there is a > bunch of code, none of which is protected by a lock, (and moreover there is > another bunch of code between the point where a thread releases a lock and > then actually returns to the calling program) and so despite the locks in > Queue it is still possible for values to change before a thread acts on > them. That warnings are quite meaningless: If you get a certain q size, it might be changed the next moment/OP anyway. simply len() is the same as that def qsize(self): """Return the approximate size of the queue (not reliable!).""" self.mutex.acquire() n = self._qsize() self.mutex.release() return n ... def _qsize(self): return len(self.queue) All that time-consuming locking in Queue is quite unnecessary. As assumed in many other locations in the std lib, list.append() / .pop() / len() are atomic. Thus doing in a single location a IndexError-catch on a .pop() race, and all care is done. (the only additional guarantee through that lock's ( at .append() time) is that the q size is never one over the exact "maximum" - but thats pedantic in a threaded multi-producer mess.) The whole CallQueue in http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/491281 for example doesn't use a single lock - though its an inter-thread communication hot spot. -robert From ldo at geek-central.gen.new_zealand Fri Apr 21 02:54:43 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 21 Apr 2006 18:54:43 +1200 Subject: Activating Batch Files from Python References: <1145417944.549477.198510@g10g2000cwb.googlegroups.com> <1145468951.826803.120860@i39g2000cwa.googlegroups.com> Message-ID: In article <1145468951.826803.120860 at i39g2000cwa.googlegroups.com>, "Jeff Groves" wrote: >>How about sourcing it from a shell, then using that same shell instance >>to run the programs? > >How would I do that? As I've said, I haven't found a Python command >that lets you send multiple commands to the same shell yet. If I could, >my problem would be solved. What about os.popen? Otherwise there's the usual fork/exec thing. From rupole at hotmail.com Thu Apr 27 03:27:38 2006 From: rupole at hotmail.com (Roger Upole) Date: Thu, 27 Apr 2006 03:27:38 -0400 Subject: Importing modules through directory shortcuts on Windows References: Message-ID: <1146122667_1905@sp6iad.superfeed.net> You can use win32file.DeviceIoControl to link directories. I can post some code to do so if anyone's interested. Roger "Brian Quinlan" wrote in message news:mailman.5014.1146058576.27775.python-list at python.org... > Recently, I became responsible for maintaining some Python code, which was organized as follows: > > user/pylib > ui > ... > project2/pylib > ui > ... > project3/pylib > ui > ... > python-packages/user => /user/pylib > project2 => /project2/pylib > project3 => /project3/pylib > > The idea is that "python-packages" is added to sys.path and then every project can import the library package from every other > project. NOTE: I think that this structure is crazy but I'm just the poor maintenance programmer. > > Anyway, the problem is that Windows does not have a symlink facility to accommodate this (AFAIK) and the Python import > mechanism does not resolve shortcuts. > > Therefore, I wrote a very simple import hook to get around that problem. If you are interested, the code is here: > http://www.sweetapp.com/shortcut/shortcutimporter.py > > BTW, does anyone else think that this functionality should be part of core Python? > > Cheers, > Brian ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= East/West-Coast Server Farms - Total Privacy via Encryption =--- From sturlamolden at yahoo.no Thu Apr 27 15:06:44 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 27 Apr 2006 12:06:44 -0700 Subject: MS VC++ Toolkit 2003, where? In-Reply-To: <1he9m4m.9d8okx1x7mxeaN%aleaxit@yahoo.com> References: <1he8pss.1yk7ug81rv7pw2N%aleaxit@yahoo.com> <1145811839.042394.73260@t31g2000cwb.googlegroups.com> <1he8sbx.dqqp3q10n5thaN%aleaxit@yahoo.com> <1145849491.347970.112150@e56g2000cwe.googlegroups.com> <1he9m4m.9d8okx1x7mxeaN%aleaxit@yahoo.com> Message-ID: <1146164804.118046.249250@e56g2000cwe.googlegroups.com> Alex Martelli wrote: > Provides the core msvcrt.lib for msvcr71.dll against which to link > your extensions. This is critically important, as without it you are > going to wind up linking against the wrong run-time and will see crashes > whenever a core object such as a file is shared across run-time > barriers. You can find msvcr71.dll in the same directory as Python. The problem is that you cannot redistribute msvcr71.dll unless you by a copy of Visual Studio 2003 or install VC++ Toolkit 2003. As far as I can tell, the .NET SDK license does not give you permission to redistribute msvcr71.dll. So if you are going to use Py2Exe, this is a dead end. But if you are just going to build a Python extension, you don't need to redistribute the DLL (it's already in Python). In that case you can use MinGW insted. Just make sure MinGW links with the correct CRT. That is, open c:\mingw\lib\gcc\mingw32\3.4.2\specs in an editor and change "-lmsvcrt" to "-lmsvcr71" There is a second advantage with this. MinGW is an optimizing compiler. The C/C++ compiler you get from the .NET SDK is not. There is a "Visual C++ 2005 Express" edition which has an optimizing compiler. But it links yet another version of the CRT, msvcr80.dll, and does not give you permission to redistribute msvcr71.dll. From reply.in.the.newsgroup at my.address.is.invalid Wed Apr 19 11:58:45 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Wed, 19 Apr 2006 17:58:45 +0200 Subject: Missing interfaces in Python... References: <1145306373.781129.305840@z34g2000cwc.googlegroups.com> Message-ID: Neal Becker: >I see various answers that Python doesn't need interfaces. OTOH, there are >responses that some large Python apps have implemented them (e.g., zope). >Does anyone have an explanation of why these large systems felt they needed >to implement interfaces? A programming language doesn't need interfaces, unless it insists on compile time checking of just about everything. The idea of interfaces arises from the construction and maintenance of large and complex software systems. It provides a level of abstraction that makes it easier to talk about a component and document what it requires from and offers to it's environment. Also, interfaces can make this documentation first-class objects, so test tools, IDE's and software design tools can take advantage of it. From tim.peters at gmail.com Fri Apr 28 23:37:08 2006 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 28 Apr 2006 23:37:08 -0400 Subject: Popping from the middle of a deque + deque rotation speed In-Reply-To: <1146264164.488782.96770@g10g2000cwb.googlegroups.com> References: <1146264164.488782.96770@g10g2000cwb.googlegroups.com> Message-ID: <1f7befae0604282037u1b53b17dldefad406b6bacf1@mail.gmail.com> [Russell Warren] |> Does anyone have an easier/faster/better way of popping from the middle > of a deque than this? > > class mydeque(deque): > def popmiddle(self, pos): > self.rotate(-pos) > ret = self.popleft() > self.rotate(pos) > return ret As Tim Chase said, the easiest way is to do "del self[pos]" instead of manually fiddling with rotations. However, deque's implementation of __delitem__ does rotations under the covers, so it's not necessarily faster. > I do recognize that this is not the intent of a deque, given the > clearly non-"double-ended" nature. I'm using a deque in a place where > 99.999 of the time it will be a fifo, but occasionally I will want to > pop from the middle. So does the speed of the remaining 0.001 cases really matter? Note that even just indexing into a deque takes O(index) time. > ... > I should stop guessing. Or at least figure out how to find the source > code for the deque implementation... It's in Modules/collectionsmodule.c. You'll see that a deque is implemented as a doubly-linked list of buckets, where each bucket is a contiguous vector of no more than 62 (pointers to) elements. There appears to be an invariant that all "interior" (non-endpoint) buckets contain exactly 62 elements, presumably to speed indexing. It all works very well for deque's intended purposes. > Should I avoid using deques with large iterables? Can't answer that without more detail about the criteria you use to judge ;-) From Jesus.Javier.Masa.Lledo at dmr-consulting.com Tue Apr 11 07:19:09 2006 From: Jesus.Javier.Masa.Lledo at dmr-consulting.com (Jesus.Javier.Masa.Lledo at dmr-consulting.com) Date: Tue, 11 Apr 2006 14:19:09 +0300 Subject: Web Service SOAP - Unknown element v1 Message-ID: This is the result of calling: >>>servidor.soapproxy.config.dumpSOAPOut = True >>>servidor.soapproxy.config.dumpSOAPIn = True >>> servidor.setDVD(title="BenHur") *** Outgoing SOAP ****************************************************** BENHUR ************************************************************************ *** Incoming SOAP ****************************************************** e:ServerUnknown element tituloorg.idoox.xmlrpc.MessageProcessingException: Unknown element titulo at org.idoox.wasp.wsdl.SOAPMethodInfo$RequiredElements$Invocation.notNillElement(SOAPMethodInfo.java:1033) at com.systinet.wasp.server.adaptor.JavaInvoker.fillCallParamsXml(JavaInvoker.java:1162) at com.systinet.wasp.server.adaptor.JavaInvoker.beginInvoke(JavaInvoker.java:491) at com.idoox.wasp.server.adaptor.JavaAdaptorImpl.beginInvoke(JavaAdaptorImpl.java:63) at com.idoox.wasp.server.AdaptorTemplate.javaInvocation(AdaptorTemplate.java:514) at com.idoox.wasp.server.AdaptorTemplate.doDispatch(AdaptorTemplate.java:395) at com.idoox.wasp.server.AdaptorTemplate.dispatch(AdaptorTemplate.java:328) at com.idoox.wasp.server.ServiceConnector.dispatch(ServiceConnector.java:390) at com.systinet.wasp.ServiceManagerImpl.dispatchRequest(ServiceManagerImpl.java:626) at com.systinet.wasp.ServiceManagerImpl.dispatch(ServiceManagerImpl.java:461) at com.systinet.wasp.ServiceManagerImpl$DispatcherConnHandler.handlePost(ServiceManagerImpl.java:2562) at com.idoox.transport.http.server.Jetty$WaspHttpHandler.handle(Jetty.java:97) at com.mortbay.HTTP.HandlerContext.handle(HandlerContext.java:1087) at com.mortbay.HTTP.HttpServer.service(HttpServer.java:675) at com.mortbay.HTTP.HttpConnection.service(HttpConnection.java:457) at com.mortbay.HTTP.HttpConnection.handle(HttpConnection.java:317) at com.mortbay.HTTP.SocketListener.handleConnection(SocketListener.java:99) at com.mortbay.Util.ThreadedServer.handle(ThreadedServer.java:254) at com.mortbay.Util.ThreadPool$PoolThreadRunnable.run(ThreadPool.java:607) at java.lang.Thread.run(Thread.java:534) ************************************************************************ -------------- next part -------------- An HTML attachment was scrubbed... URL: From axel.bock.news at googlemail.com Thu Apr 20 02:22:09 2006 From: axel.bock.news at googlemail.com (Axel Bock) Date: 19 Apr 2006 23:22:09 -0700 Subject: COM object pointer cast In-Reply-To: References: <1143447549.045826.291850@i40g2000cwc.googlegroups.com> Message-ID: <1145514129.186240.227870@z34g2000cwc.googlegroups.com> late but still - thanks a lot :) . works like a charm. cheers, Axel. From f.petri at steinbichler.de Sun Apr 9 15:58:36 2006 From: f.petri at steinbichler.de (blackno666) Date: 9 Apr 2006 12:58:36 -0700 Subject: wxStyledTextCtrl - Dead? In-Reply-To: <4438efbb$0$60784$157c6196@dreader1.cybercity.dk> References: <4438efbb$0$60784$157c6196@dreader1.cybercity.dk> Message-ID: <1144612716.140902.273480@e56g2000cwe.googlegroups.com> The wxPython Demo (http://prdownloads.sourceforge.net/wxpython/wxPython-demo-2.6.3.2.tar.gz) still contains the wxStyledTextCtrl: wx.stc.StyledTextCtrl The demo is probably also a good example of how to use wxStyledTextCtrl. Basic information can be found on http://www.yellowbrain.com/stc/init_repr.html Regards. David Rasmussen schrieb: > I have several questions about wxStyledTextCtrl: > > 1) Is it still being maintained? > > 2) Where are the docs and tutorials? > > 3) Is it wxStyledTextCtrl, wx.StyledTextCtrl, StyledTextCtrl, or... ? > > 4) Is there an alternative? > > /David From cjns3274 at optonline.net Tue Apr 11 00:44:23 2006 From: cjns3274 at optonline.net (Chris Jones) Date: Tue, 11 Apr 2006 00:44:23 -0400 Subject: using vim as a python class/module/function etc.. browser In-Reply-To: References: <443B1B24.3070401@optonline.net> Message-ID: <443B3427.1090902@optonline.net> Robert Kern wrote: > Chris Jones wrote: > >>I'm trying to make sense of a python program and was wondering if vim >>has any python-oriented functionalities (apart from syntax highlighting) >>that would make it somewhat easier to browse the source code. >> >>What I had in mind is something that would let me use CTRL+] to >>automatically display whatever object is under the cursor (a bit like >>ctags for code written in C..) >> >>I have read somewhere about something called 'ptags' but could not find >>it in debian - and I'm not 100% sure it's really a python equivalent of >>ctags. > > > On ptags: > http://www.vim.org/tips/tip.php?tip_id=1188 > > Of course, modern versions of Exuberant Ctags also support Python, too. > I apt-installed this package but the man page is rather intimidating so I thought I might as well make sure I was going in the right direction. Just need to verify that the stable version (sarge) is modern enough.. Thanks..! From bj_666 at gmx.net Tue Apr 18 17:02:45 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Tue, 18 Apr 2006 23:02:45 +0200 Subject: difference between class and static methods? References: Message-ID: In , John Salerno wrote: > I've been reading up on them, but I don't quite understand how they > differ in practice. I know how each is implemented, and from C# I > already know what a static method is. But I won't assume that it's the > same in Python. And on top of that, both the class and static methods of > Python seem to do what a C# static method does, so I don't see the > difference yet. The difference is that the classmethod gets the class as first argument much like self in instance methods. class A: def __init__(self, data): print 'A' self.data = data @classmethod def from_file(cls, filename): # read data return cls(data) class B(A): def __init__(self, data): print 'B' self.data = data If you call `B.from_file('spam.xyz')` now, the `from_file()` method inherited from class `A` is called but with `B` as the first argument so it returns an instance of `B`. A staticmethod is just a function attached to a class without any "magic". Ciao, Marc 'BlackJack' Rintsch From mhellwig at xs4all.nl Sun Apr 30 19:46:24 2006 From: mhellwig at xs4all.nl (Martin P. Hellwig) Date: Mon, 01 May 2006 01:46:24 +0200 Subject: setting file permissions on a web server In-Reply-To: <44554237$0$13323$c3e8da3@news.astraweb.com> References: <445449f6$0$9437$c3e8da3@news.astraweb.com> <4454f1e1$0$1963$c3e8da3@news.astraweb.com> <44554237$0$13323$c3e8da3@news.astraweb.com> Message-ID: <44554c53$0$31655$e4fe514c@news.xs4all.nl> John Salerno wrote: Most FTP servers do allow to use chmod in a ftp session, although you're client must support it. See for example a cli ftp client (and server) on FreeBSD. > mhellwig at xs2:~$ ftp ftp.xs4all.nl > Connected to ftp2.xs4all.nl. > 220 XS4ALL ftpd DCLXVI > Name (ftp.xs4all.nl:mhellwig): > 331 Password required for mhellwig. > Password: > 230 User mhellwig logged in. > Remote system type is UNIX. > Using binary mode to transfer files. > ftp> ls MHellwigCV_02_10_01.pdf > 150 Opening ASCII mode data connection for file list > ---------- 1 mhellwig user 211102 May 19 2003 MHellwigCV_02_10_01.pdf > 226 Transfer complete. > ftp> chmod 400 MHellwigCV_02_10_01.pdf > 200 SITE CHMOD command successful > ftp> ls MHellwigCV_02_10_01.pdf > 150 Opening ASCII mode data connection for file list > -r-------- 1 mhellwig user 211102 May 19 2003 MHellwigCV_02_10_01.pdf > 226 Transfer complete. > ftp> See? -- mph From onurb at xiludom.gro Thu Apr 27 11:33:53 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 27 Apr 2006 17:33:53 +0200 Subject: Get all attributes of a com object In-Reply-To: <1146151043.933987.145080@t31g2000cwb.googlegroups.com> References: <1146151043.933987.145080@t31g2000cwb.googlegroups.com> Message-ID: <4450e4b7$0$21092$626a54ce@news.free.fr> eicwo01 wrote: > Without to know the names, is it possible to dump all attributes of a > com object? > from win32com.adsi import * from module import * is Bad(tm) > objDom = ADsOpenObject("LDAP:/ ... > print ???"all attributes"??? of objDom Look at dir() and the inspect module. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From paddy3118 at netscape.net Fri Apr 28 02:46:06 2006 From: paddy3118 at netscape.net (Paddy) Date: 27 Apr 2006 23:46:06 -0700 Subject: Converstion In-Reply-To: <1146181848.615239.281200@j33g2000cwa.googlegroups.com> References: <1146181848.615239.281200@j33g2000cwa.googlegroups.com> Message-ID: <1146206766.870443.297810@e56g2000cwe.googlegroups.com> Something like (untested): out = [] for ch in instring: if ch==backspace: if out: out = out[:-1] else: out.append(ch) outstring = ''.join(out) - Pad. From felipe.lessa at gmail.com Tue Apr 11 14:10:22 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Tue, 11 Apr 2006 15:10:22 -0300 Subject: list.clear() missing?!? In-Reply-To: References: <1144767680.583085.310160@v46g2000cwv.googlegroups.com> Message-ID: <1144779022.11151.13.camel@kenshin.CASA> Em Ter, 2006-04-11 ?s 17:56 +0000, John Salerno escreveu: > Steven Bethard wrote: > > > > lst[:] = [] > > lst = [] > > What's the difference here? lst[:] = [] makes the specified slice become []. As we specified ":", it transforms the entire list into []. lst = [] assigns the value [] to the variable lst, deleting any previous one. This might help: >>> lst = range(10) >>> id(lst), lst (-1210826356, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> lst[:] = [] >>> id(lst), lst (-1210826356, []) >>> lst = range(10) >>> id(lst), lst (-1210844052, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> lst = [] >>> id(lst), lst (-1210826420, []) You see? lst[:] removes all elements from the list that lst refers to, while lst = [] just creates a new list and discard the only one. The difference is, for example: >>> lst = range(3) >>> x = [lst, lst, lst] >>> x [[0, 1, 2], [0, 1, 2], [0, 1, 2]] >>> lst[:] = [] >>> x [[], [], []] >>> lst = range(3) >>> x = [lst, lst, lst] >>> x [[0, 1, 2], [0, 1, 2], [0, 1, 2]] >>> lst = [] >>> x [[0, 1, 2], [0, 1, 2], [0, 1, 2]] HTH, -- Felipe. From steven.bethard at gmail.com Fri Apr 14 11:31:28 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 14 Apr 2006 09:31:28 -0600 Subject: PEP 359: The "make" Statement In-Reply-To: References: Message-ID: Steven Bethard wrote: > Duncan Booth wrote: >> Steven Bethard wrote: >> >>> Should users of the make statement be able to determine in which dict >>> object the code is executed? The make statement could look for a >>> ``__make_dict__`` attribute and call it to allow things like:: >>> >>> make Element html: >>> make Element body: >>> make Element h1: >>> '''First heading text''' >>> make Element h1: >>> '''Second heading text''' >> > [snip] >> There is another effect which should be considered here. If you allow >> Element to create an object to be used as the namespace, then as well >> as doing special tracking when values are set in the namespace it can >> also pre-seed it with names which magically appear in scope within the >> make. >> >> e.g. >> >> make Element html: >> make Element body: >> make Element p: >> text('But this ') >> make Element strong: >> text('could') >> text(' be made to work') > > This is nice. I'll have to play around with it a bit to see how hard it > would be to make it work. Okay, I think it'll work[1]. I'm going to update this section to something more like: Open Issues =========== ... Should users of the make statement be able to determine in which dict object the code is executed? This would allow the make statement to be used in situations where a normal dict object would not suffice, e.g. if order and repeated names must be allowed. Allowing this sort of customization could allow XML to be written like:: make Element html: make Element body: text('before first h1') make Element h1: attrib(style='first') text('first h1') tail('after first h1') make Element h1: attrib(style='second') text('second h1') tail('after second h1') assert etree.ElementTree.tostring(body) == '''\ \ \ before first h1\

first h1

\ after first h1\

second h1

\ after second h1\ \ \ ''' Assuming that the make statement calls the callable's ``__make_dict__`` to get the dict in which to execute the code, the following should make the above make statements work:: class Element(object): class __make_dict__(dict): def __init__(self, *args, **kwargs): self._super = super(Element.__make_dict__, self) self._super.__init__(*args, **kwargs) self.elements = [] self.text = None self.tail = None self.attrib = {} def __getitem__(self, name): try: return self._super.__getitem__(name) except KeyError: if name in ['attrib', 'text', 'tail']: return getattr(self, 'set_%s' % name) else: return globals()[name] def __setitem__(self, name, value): self._super.__setitem__(name, value) self.elements.append(value) def set_attrib(self, **kwargs): self.attrib = kwargs def set_text(self, text): self.text = text def set_tail(self, text): self.tail = text def __new__(cls, name, args, edict): get_element = etree.ElementTree.Element result = get_element(name, attrib=edict.attrib) result.text = edict.text result.tail = edict.tail for element in edict.elements: result.append(element) return result [1] Here's the code I used to test it. >>> def make(callable, name, args, block_string): ... try: ... make_dict = callable.__make_dict__ ... except AttributeError: ... make_dict = dict ... block_dict = make_dict() ... exec block_string in block_dict ... return callable(name, args, block_dict) ... >>> class Element(object): ... class __make_dict__(dict): ... def __init__(self, *args, **kwargs): ... self._super = super(Element.__make_dict__, self) ... self._super.__init__(*args, **kwargs) ... self.elements = [] ... self.text = None ... self.tail = None ... self.attrib = {} ... def __getitem__(self, name): ... try: ... return self._super.__getitem__(name) ... except KeyError: ... if name in ['attrib', 'text', 'tail']: ... return getattr(self, 'set_%s' % name) ... else: ... return globals()[name] ... def __setitem__(self, name, value): ... self._super.__setitem__(name, value) ... self.elements.append(value) ... def set_attrib(self, **kwargs): ... self.attrib = kwargs ... def set_text(self, text): ... self.text = text ... def set_tail(self, text): ... self.tail = text ... def __new__(cls, name, args, edict): ... get_element = etree.ElementTree.Element ... result = get_element(name, attrib=edict.attrib) ... result.text = edict.text ... result.tail = edict.tail ... for element in edict.elements: ... result.append(element) ... return result ... >>> body = make(Element, 'body', (), textwrap.dedent("""\ ... text('before first h1') ... h1 = make(Element, 'h1', (), textwrap.dedent(''' ... attrib(style='first') ... text('first h1') ... tail('after first h1') ... ''')) ... h1 = make(Element, 'h1', (), textwrap.dedent(''' ... attrib(style='second') ... text('second h1') ... tail('after second h1') ... ''')) ... """)) >>> assert etree.ElementTree.tostring(body) == '''\ ... \ ... before first h1\ ...

first h1

\ ... after first h1\ ...

second h1

\ ... after second h1\ ... \ ... ''' STeVe From jg.lists at sympatico.ca Sun Apr 9 11:13:40 2006 From: jg.lists at sympatico.ca (Jim Gallacher) Date: Sun, 09 Apr 2006 11:13:40 -0400 Subject: mod_python + apache + winxp => nogo In-Reply-To: <1144584361.462089.63170@v46g2000cwv.googlegroups.com> References: <1144445910.877992.80210@v46g2000cwv.googlegroups.com> <4436E2BE.8060802@sympatico.ca> <1144584361.462089.63170@v46g2000cwv.googlegroups.com> Message-ID: <443924A4.6060206@sympatico.ca> cyberco wrote: > Thanks Jim, I indeed did not look in the mailinglist archive (you have > to subscribe for that and Google didn't cache it yet). > > The problem was indeed the missing .DLL's. After adding them to my > 'PATH' variable apache was at least able to start. Unfortunately things > still don't work. When I try to load a .py file I get the error: > > ============== > [Sun Apr 09 14:03:46 2006] [error] make_obcallback: could not import > mod_python.apache.\n > [Sun Apr 09 14:03:46 2006] [error] python_handler: no interpreter > callback found. > [Sun Apr 09 14:03:46 2006] [error] [client 192.168.2.100] > python_handler: Can't get/create interpreter., referer: > http://myserver/test/ > ============== You are halfway there. Apache has found the mod_python loadable module, but now *it* can't find the correct mod_python lib files. This may happen when you have several different python versions installed on your system, and mod_python is trying to use the wrong one. If this is the case, adjust the path that apache sees so that the correct python appears first in the path. > This seems more like a bug in mod_python. Not a bug - unless you consider poor documentation a bug ;). Your configuration is still not correct. Any suggestions? I'm not sure if our Windows guy reads c.l.p. on a regular basis and I'm rather clueless about Windows issues. Subscribe to the mod_python mailing list. You can always unsubscribe later. :). Jim From kent at kentsjohnson.com Fri Apr 28 06:57:51 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Fri, 28 Apr 2006 06:57:51 -0400 Subject: Regular Expression help In-Reply-To: References: <1146162048.903980.281290@y43g2000cwc.googlegroups.com> <1146172456.106195.243160@j33g2000cwa.googlegroups.com> Message-ID: <4451f4e5$1_2@newspeer2.tds.net> Edward Elliott wrote: > johnzenger at gmail.com wrote: >> If you are parsing HTML, it may make more sense to use a package >> designed especially for that purpose, like Beautiful Soup. > > I don't know Beautiful Soup, but one advantage regexes have over some > parsers is handling malformed html. Beautiful Soup is intended to handle malformed HTML and seems to do pretty well. Kent From redefined.horizons at gmail.com Thu Apr 27 15:29:15 2006 From: redefined.horizons at gmail.com (redefined.horizons at gmail.com) Date: 27 Apr 2006 12:29:15 -0700 Subject: Using Parts of PEAK Message-ID: <1146166155.101720.24810@g10g2000cwb.googlegroups.com> I was intriuged by the concept of Python Eggs and some of the work that has been done on PEAK. http://peak.telecommunity.com/ However, I think PEAK might be overkill for the particular design I am considering. Is anyone using just part of PEAK in their Python development. Are there alternative distribution enhancements for Python besides PEAK that I might take a look at? Thanks, Scott Huey From duncanm255 at hotmail.com Mon Apr 10 23:56:06 2006 From: duncanm255 at hotmail.com (D) Date: 10 Apr 2006 20:56:06 -0700 Subject: Backing Up VMWare Message-ID: <1144727766.603611.226070@i40g2000cwc.googlegroups.com> Hello - has anyone written a Python script to backup VMWare servers? If so, I'd appreciate any pointers as to how to go about doing so. Thanks. From steve at REMOVETHIScyber.com.au Fri Apr 7 20:43:11 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 08 Apr 2006 10:43:11 +1000 Subject: Characters contain themselves? References: Message-ID: On Fri, 07 Apr 2006 15:50:53 +0200, WENDUM Denis 47.76.11 (agent) wrote: > While testing recursive algoritms dealing with generic lists I stumbled > on infinite loops which were triggered by the fact that (at least for my > version of Pyton) characters contain themselves. A "character" is just a string of length 1. [snip] > Leading to paradoxes and loops objects which contain themselves (and > other kinds of monsters) are killed in set theory with the Axiom of > Foundation:=) Let me see if I understand you... you would like behaviour like this? >>> 'a' in 'bbabb' True >>> 'a' in 'bbab' True >>> 'a' in 'bab' True >>> 'a' in 'ab' True >>> 'a' in 'a' False # not the real result Ain't going to happen. > But let's go back to more earthly matters. I couldn't find any clue in a > python FAQ after having googled with the following "Python strings FAQ" > about why this design choice and how to avoid falling in this trap > without having to litter my code everywhere with tests for stringiness > each time I process a generic list of items. > > Any hints would be appreciated. I think that if you want to do work with sets, use sets, not strings. In Python 2.3, you need: >>> import sets In Python 2.4, Sets (note the initial capital) are a built-in. -- Steven. From fredrik at pythonware.com Wed Apr 12 17:22:17 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 12 Apr 2006 23:22:17 +0200 Subject: base64 References: <1144865224.094993.149200@u72g2000cwu.googlegroups.com> <443d6a0d@news.eftel.com> Message-ID: John Machin wrote: > *After* encoding it, you can break up the base64 string into > bite-size chunks, append a newline (that's "\n", NOT "/n") to each > chunk /.../ base64.encodestring(data) does all that in one step, of course. From robert.differentone at gmail.com Sun Apr 2 10:34:11 2006 From: robert.differentone at gmail.com (robert.differentone at gmail.com) Date: 2 Apr 2006 07:34:11 -0700 Subject: DOM and HTML Message-ID: <1143988451.239828.75900@i39g2000cwa.googlegroups.com> Hi All, I am looking for any Python library which can help to get DOM tree from HTML. Is there any way to access HTML DOM, just like accessing it using javascript. Any kind of help is appreciated. Thanks. R From aleaxit at yahoo.com Sun Apr 23 18:24:28 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 23 Apr 2006 15:24:28 -0700 Subject: getattr from local scope References: <1145827050.347326.84980@t31g2000cwb.googlegroups.com> Message-ID: <1he96ru.12l8tuv1tphnddN%aleaxit@yahoo.com> Edward Elliott wrote: > rob.haswell at gmail.com wrote: > > Basically my application has a scheduler which stores names of functions > > defined in the "schedule" module in a database, to be run on certain > > days. Every night I call schedule.RunSchedule, which grabs all the rows on > > the database that have to be run now, and I want to call the function > > defined the same module according to that string. > > I know that sys.modules[__name__] gives the module object for the current > module. You could do: > > m = sys.modules[__name__] # M now current module object > func = m.__dict__ [fs] # func has function named by string fs > func() sys.modules[__name__].__dict__ may be more handily accessed by the built-in function globals(). Alex From __peter__ at web.de Fri Apr 21 18:09:24 2006 From: __peter__ at web.de (Peter Otten) Date: Sat, 22 Apr 2006 00:09:24 +0200 Subject: how to append to a list twice? References: Message-ID: John Salerno wrote: > If I want to create a list of the form [100, 99, 99, 98, 98, 97, 97...] > (where each item is repeated twice after the first one), how might I do > that most efficiently? series = [100]*21 series[1::2] = series[2::2] = range(99, 89, -1) :-) Peter From neurogasm at gmail.com Tue Apr 11 23:23:54 2006 From: neurogasm at gmail.com (Kun) Date: Tue, 11 Apr 2006 23:23:54 -0400 Subject: turning python-cgi into an html output Message-ID: i have a python cgi script that displays tables from a mysql database in html. the problem is, i want to use excel's web query to pull this data and the web query doesn't read .py files. thus i am wondering what is the easiest way to just turn my .py html output into a .html output. you can check the query here: http://opimx.wharton.upenn.edu/~fengk/getfinances.html just click 'submit' any help would be appreciated. From evenprimes at gmail.com Thu Apr 27 14:02:17 2006 From: evenprimes at gmail.com (Chris Cioffi) Date: Thu, 27 Apr 2006 14:02:17 -0400 Subject: Slightly OT: Adding Objective C to my toolbox Message-ID: Question background: I've been using Python as my primary language for several years now and have done all my non-trivial development in Python. I've now got a Mac and want to do some development using the Core * features in OS X in ObjC. I know I could use the PyObjC bindings, but ObjC seems to have enough stretch-my-brain features that I think it would be fun to learn. My question: If you've learned ObjC after Python, what resources did you use? Right now I'm focusing on the free docs, but would like to pickup some decent reference books. Stuff along the lines of "Learning Python, 2nd ed" where you learn not just the basics, but also develop "real" apps in the process. Also, are there any gotcha's that got you? Curious...Thanks! -- "A little government and a little luck are necessary in life, but only a fool trusts either of them." -- P. J. O'Rourke -------------- next part -------------- An HTML attachment was scrubbed... URL: From antroy at gmail.com Fri Apr 21 16:01:06 2006 From: antroy at gmail.com (Ant) Date: 21 Apr 2006 13:01:06 -0700 Subject: Thanks from the Java Developer In-Reply-To: <1he434n.vosf551izis2eN%aleaxit@yahoo.com> References: <1145474995.143893.31760@z34g2000cwc.googlegroups.com> <1145568613.146056.135230@u72g2000cwu.googlegroups.com> <1he434n.vosf551izis2eN%aleaxit@yahoo.com> Message-ID: <1145649666.399235.290810@i40g2000cwc.googlegroups.com> > So switch jobs -- it's a good time. If it were that easy I would.. However, I have family commitments keeping me in Yorkshire (UK) (as well as the fact that I really like the area!), and the jobs in the area are all Java, .NET (predominantly C#) and C++. Always on the lookout for Python work though, and I actively try to inject at least a bit of it into the work I do, even if it's just scripts or test programs. When the time comes, I'll be there though :-) From fanmail at micah-wedemeyer.net Wed Apr 26 18:43:06 2006 From: fanmail at micah-wedemeyer.net (Micah) Date: 26 Apr 2006 15:43:06 -0700 Subject: begging for a tree implementation Message-ID: <1146091386.013265.153660@v46g2000cwv.googlegroups.com> I'm looking for a simple tree implementation: 0-n children, 1 root. All the nice methods would be appreciated (getLeaves, isLeaf, isRoot, depthfirst, breadthfirst,...) That's really all I need. I could code one up, but it would take time to debug, and i'm really short on time right now. Thanks! Micah From scott.daniels at acm.org Wed Apr 5 15:29:51 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Wed, 05 Apr 2006 12:29:51 -0700 Subject: how to convert string In-Reply-To: References: <1144261976.640631.9280@e56g2000cwe.googlegroups.com> Message-ID: <443417e7$1@nntp0.pdx.net> Ben C wrote: > ... But this puts an extra space on the end (so did the print i, > version above). Actually, no (the trailing-comma prints do a funny dance). Check it out: from StringIO import StringIO dest = StringIO() for i in range(10): print >>dest, i, print >>dest print repr(dest.getvalue()) prints: '0 1 2 3 4 5 6 7 8 9\n' -- -Scott David Daniels scott.daniels at acm.org From robert.kern at gmail.com Mon Apr 24 12:24:14 2006 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 24 Apr 2006 11:24:14 -0500 Subject: MS VC++ Toolkit 2003, where? In-Reply-To: <1heag4u.19dksfxrbe14wN%aleaxit@yahoo.com> References: <1he8pss.1yk7ug81rv7pw2N%aleaxit@yahoo.com> <1145811839.042394.73260@t31g2000cwb.googlegroups.com> <1he8sbx.dqqp3q10n5thaN%aleaxit@yahoo.com> <1145849491.347970.112150@e56g2000cwe.googlegroups.com> <1he9m4m.9d8okx1x7mxeaN%aleaxit@yahoo.com> <444C784F.3000502@v.loewis.de> <1heag4u.19dksfxrbe14wN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Jocular, but not sarcastic. I have no problems using mingw if that's > what it takes -- the later instructions I saw were those suggesting the > Toolkit instead, so those are the ones I'm trying to follow. What's the > updated URL for the instructions about using mingw instead? Install mingw (an large task in and of itself that I'm not going to go into here, but look at http://www.mingw.org/) and make sure the bin/ directory is on your PATH. You will have to edit the gcc specs file to replace "-lmsvcrt" with "-lmsvcr71". Its filename is lib/mingw32/3.4.2/specs . After that, use the --compiler=mingw32 option on build_ext when using distutils. -- Robert Kern robert.kern at gmail.com "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From nobody at 127.0.0.1 Sun Apr 23 23:07:06 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Mon, 24 Apr 2006 03:07:06 GMT Subject: Using distutils in Windows XP / "Python in a Nutshell" In-Reply-To: References: Message-ID: Blair LeGent wrote: > error: The .NET Framework SDK needs to be installed before building > extensions for Python. > > ...but the .NET Framework IS installed Just a guess, but is the C compiler in your PATH when you run python? I'm assuming python on xp still uses environment variables and not some windows-specific method for locating binaries. From rpdooling at gmail.com Fri Apr 14 17:44:12 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 14 Apr 2006 14:44:12 -0700 Subject: requestion regarding regular expression In-Reply-To: <444009a0$1@nntp0.pdx.net> References: <1145006270.632156.144790@j33g2000cwa.googlegroups.com> <443f91d7$1_2@newspeer2.tds.net> <1145026037.790344.205630@e56g2000cwe.googlegroups.com> <443fc460$1_2@newspeer2.tds.net> <1145031538.601388.71130@j33g2000cwa.googlegroups.com> <444009a0$1@nntp0.pdx.net> Message-ID: <1145051052.835041.166560@u72g2000cwu.googlegroups.com> This is very helpful. I wasn't the OP. I'm just learning, but I'm on the verge of making my own file searching scripts. This will be a huge help. Thanks for posting, and especially thanks for the comments in the code. Big help! rick From aurelien.campeas at free.fr Wed Apr 26 05:19:17 2006 From: aurelien.campeas at free.fr (aurelien.campeas at free.fr) Date: 26 Apr 2006 02:19:17 -0700 Subject: Type-Def-ing Python In-Reply-To: <1146041765.423121.106840@i39g2000cwa.googlegroups.com> References: <1146041765.423121.106840@i39g2000cwa.googlegroups.com> Message-ID: <1146043157.894876.54370@u72g2000cwu.googlegroups.com> If you are interested in static analysis for bug hunting purposes, then you might want to have a look at Pylint. Cheers, Aur?lien. From ivoras at __-fer.hr-__ Tue Apr 18 20:12:04 2006 From: ivoras at __-fer.hr-__ (Ivan Voras) Date: Wed, 19 Apr 2006 02:12:04 +0200 Subject: Simple DAV server? In-Reply-To: References: Message-ID: robert wrote: > For testing purposes I'm looking for a simple DAV server - best a python > thing serving a folder tree. Don't want to install/change/setup the > complex apache dav .. > You can try this one: http://ivoras.sharanet.org/projects/pandav.html It's been a while since I last updated it so no guarantees :) From johnzenger at gmail.com Wed Apr 19 04:22:13 2006 From: johnzenger at gmail.com (johnzenger at gmail.com) Date: 19 Apr 2006 01:22:13 -0700 Subject: local greediness ??? In-Reply-To: <1145423359.206549.52510@v46g2000cwv.googlegroups.com> References: <1145423359.206549.52510@v46g2000cwv.googlegroups.com> Message-ID: <1145434933.473249.311550@i39g2000cwa.googlegroups.com> How about using the numbers as delimiters: >>> pat = re.compile(r"[\d\.\-]+") >>> pat.split("[(some text)2.3(more text)4.5(more text here)]") ['[(some text)', '(more text)', '(more text here)]'] >>> pat.findall("[(some text)2.3(more text)4.5(more text here)]") ['2.3', '4.5'] >>> pat.split("[(xxx)11.0(bbb\))8.9(end here)] ") ['[(xxx)', '(bbb\\))', '(end here)] '] >>> pat.findall("[(xxx)11.0(bbb\))8.9(end here)] ") ['11.0', '8.9'] tygerc at gmail.com wrote: > hi, all. I need to process a file with the following format: > $ cat sample > [(some text)2.3(more text)4.5(more text here)] > [(aa bb ccc)-1.2(kdk)12.0(xxxyyy)] > [(xxx)11.0(bbb\))8.9(end here)] > ....... > > my goal here is for each line, extract every '(.*)' (including the > round > brackets, put them in a list, and extract every float on the same line > and put them in a list.. here is my code: > > p = re.compile(r'\[.*\]$') > num = re.compile(r'[-\d]+[.\d]*') > brac = re.compile(r'\(.*?\)') > > for line in ifp: > if p.match(line): > x = num.findall(line) > y = brac.findall(line) > print x, y len(x), len(y) > > Now, this works for most of the lines. however, I'm having problems > with > lines such as line 3 above (in the sample file). here, (bbb\)) contains > an escaped > ')' and the re I use will match it (because of the non-greedy '?'). But > I want this to > be ignored since it's escaped. is there a such thing as local > greediness?? > Can anyone suggest a way to deal with this here.. > thanks. From zpincus at stanford.edu Sat Apr 22 13:32:28 2006 From: zpincus at stanford.edu (Zachary Pincus) Date: Sat, 22 Apr 2006 10:32:28 -0700 Subject: Define type of 'module' object that is imported In-Reply-To: References: Message-ID: <15EB1B27-B69D-4663-8FBC-CBE0C8790913@stanford.edu> >> I would like a given module to be created as an >> instance of that particular subclass on import, so that if I do: >> >> import foo >> type(foo) >> >> I get instead of . >> >> Is there any way to effect this? Something like __metaclass__ >> = ... but >> at the beginning of a module instead of at the beginning of a class? > > Would be interesting to know about the motivation. Is foo just your > own > module or "any" module. No, just one particular module that needs to do some slow things. I'd like for a user to just be able to type "import foo" and have the foo module's type be some special type. None of the options below really allow this to happen with one step. It would be more like "import lazyFoo; import foo". What I'm doing now is in 'foo.py' performing surgery a la: sys.modules[__name__] = MyModuleClass(...) but that's ugly, and can break the reload mechanism, and causes some other troubles. I would like to do: sys.modules[__name__].__class__ = MyModuleClass but that fails because the module is "not a heap type" or something. I have also tried: sys.modules[__name__].__getattribute__ = MethodType(myGetattr, sys.modules[__name__], ModuleType) but the custom __getattribute__ never gets called. Hmm, oh well. Zach > * you can replace __import__ > * you can set sys.modules['foo']=mymod (in sitecustomize.py ? ) > * your module can be a class instance as well in newer pythons (2.2 > +?); > => you can set sys.modules['foo']=Foo() # Foo having > properties ... > * simply import certain expensive modules only ad-hoc > * maybe you don't need it as module at all, but an instance. or you > avoid pre-computing things in global namespace. > ... From Serge.Orlov at gmail.com Thu Apr 20 19:08:44 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 20 Apr 2006 16:08:44 -0700 Subject: mini component distribution question References: Message-ID: <1145574524.673807.182390@g10g2000cwb.googlegroups.com> Eric S. Johansson wrote: > as one would expect when creating a body of software, eventually you > create a series of relatively generic components you find yourself using > over and over again. As a result, I'm finding myself slightly bit by > the same problem I have faced multiple times of the past. Namely, how > do you distribute "small" components that are used in a series of larger > applications. > > Yes, I could turn each 300 line file into a Python module complete with > its own source code control and installation framework. Seems like a > bit of overkill however. I also know I could cluster them together into > a larger module but I would end up with something as unwieldy as twisted > or zope. I'm just trying to make a couple of nuts and bolts available, > not a whole railcar full. > > Then there's the assembly problem, pulling together all of the disparate > pieces into the application for distribution. Do you pull them together > before you make a tar ball or do you pull them together during > installation ala cpan. there really should be some automated method for > pulling together components when building an application. how many > components is it reasonable to expect an admin to manually download? > Two? Five? 100? How about one? I bundle everything together. Sharing modules at end user host is more difficult because you have to test many combinations. Needless to say, end users also have a strange ability to create untested combinations of modules :) > > I'd like to know if I'm missing something. Mini modules management and > distribution should be possible without too much headache. I organize projects in workspaces, where workspace consist of several projects pulled together from different source code repositories. And I also have small scrips to manage workspaces, for example, I don't use versioning system directly like "svn update" but run project specific update.py. If I want to share a mini-module I modify update.py not to update this module by default. So it works like this: projects X and Y share module C. Project X improves C and commits new version of C, which actually can break project Y. But since my update script won't fetch a new version of C by default, project Y is not affected. When project Y is ready for update, they run "update.py C", test, fix C and commit the fixed C. Project X updates C when they are ready to do it. Work like a charm for me. From johnmc at velseis.com.au Wed Apr 19 21:52:43 2006 From: johnmc at velseis.com.au (John McMonagle) Date: Thu, 20 Apr 2006 11:52:43 +1000 Subject: Image open problem In-Reply-To: <4446D5E3.1030600@lexicon.net> References: <4446D5E3.1030600@lexicon.net> Message-ID: <1145497963.7947.17.camel@cornell> On Thu, 2006-04-20 at 10:29 +1000, John Machin wrote: > On 20/04/2006 6:55 AM, Aleksandar Cikota wrote: > > Hi all, > > > > I have a problem with openning of an image. > > > > Here is the Code: > > > > from Tkinter import * > > from PIL import Image, ImageTk Change from PIL import Image, ImageTk to import PIL and change all your corresponding Image calls to PIL.Image and all your ImageTk calls to PIL.ImageTk. If that works, then something else is mangling Image. Regards, John -- This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean. From ivoras at __-fer.hr-__ Mon Apr 24 11:38:47 2006 From: ivoras at __-fer.hr-__ (Ivan Voras) Date: Mon, 24 Apr 2006 17:38:47 +0200 Subject: freebsd thread problem In-Reply-To: References: Message-ID: Dorian Mcfarland wrote: > Hi there, > I have installed python(2.4.3) & trac(0.9.4) on freebsd(4.8) from the > ports collection and I seem to have an underlying problem with the > thread module. > Salling 'import thread' from the python prompt yields the same result. > > I have a 'threading.py' and a 'dummy_thread.py' in my > /usr/local/lib/python2.4 folder and I only have one version of python > installed. How did you install python? By default, if built from ports, it should pop up a configuration dialog in which one of the options is to enable thread support. If you have a bad configuration record, you can do a "make config" in /usr/ports/lang/python to re-create it. (if there's no such option, then maybe using threads with python is disabled in 4.x) From http Sat Apr 29 19:36:57 2006 From: http (Paul Rubin) Date: 29 Apr 2006 16:36:57 -0700 Subject: Generate a sequence of random numbers that sum up to 1? References: Message-ID: <7xlktokl7q.fsf@ruckus.brouhaha.com> Anthony Liu writes: > OK, I actually just want to "manually" create Hidden > Markov Models by randomly generating the initial state > probabilities PI, OK, this sounds like you actually want to divide the unit interval up into pieces of varying sizes. Example (untested): n = 10 # number of pieces desired # Take the unit interval [0,1] and sprinkle in n-1 random points s = sorted([0,1] + [random() for i in xrange(n-1)]) # now find the size of each sub-interval and make a list r = [(s[i+1] - s[i]) for i in xrange(n)] print sum(r) # should be 1.0 within rounding error From nobody at 127.0.0.1 Tue Apr 25 13:38:54 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Tue, 25 Apr 2006 17:38:54 GMT Subject: The whitespaceless frontend References: <1145102469.595611.19950@u72g2000cwu.googlegroups.com> <1145960119.998718.315550@j33g2000cwa.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > It's less explicit than self. but it's shorter, this improves typing, > and allows to produce more compact code: > > return "".join(["Graph(", repr($o), ", ", repr($nodeData), ")"]) > > Instead of: > > return "".join(["Graph(", repr(self.o), ", ", repr(self.nodeData), > ")"]) It also creates a special case. Object attributes are generally accessed as obj.foo, while $foo only works from within obj. There are more tradeoffs involved than just compactness and syntax gestalt. If compactness is all you want, shorten self to s. Personally I like 'me' as it's both shorter and more vernacular: def do_GET (me): me.send_response (200, "ok") As an added bonus, you get to channel Cookie Monster when you program. :) c = Cookie ("good enough") # for me From bearophileHUGS at lycos.com Fri Apr 21 08:24:00 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 21 Apr 2006 05:24:00 -0700 Subject: are docstrings for variables a bad idea? In-Reply-To: <1145615763.943050.170950@j33g2000cwa.googlegroups.com> References: <1145615763.943050.170950@j33g2000cwa.googlegroups.com> Message-ID: <1145622240.520545.196550@t31g2000cwb.googlegroups.com> Docstrings for variables seems a new interesting idea to me, but I don't know how much useful it can be. Do you mean something like this? >>> rcar_speed = 25 >>> print rcar_speed 25 >>> print rcar_speed.__doc__ int(x[, base]) -> integer ... >>> rcar_speed.__ndoc__ = "Speed of the red car, km/h" ... Can you show me some examples of its possible usefulness? Bye, bearophile From sjmachin at lexicon.net Sun Apr 30 09:02:41 2006 From: sjmachin at lexicon.net (John Machin) Date: Sun, 30 Apr 2006 23:02:41 +1000 Subject: how not use memmove when insert a object in the list In-Reply-To: References: Message-ID: <4454b572@news.eftel.com> On 30/04/2006 11:57 AM, kyo guan wrote: > Hi : > > python list object like a stl vector, if insert a object in the front or the middle of it, > all the object after the insert point need to move backward. > > look at this code ( in python 2.4.3) > > for (i = n; --i >= where; ) /// here, why not use memmove? it would be more speed then this loop. > items[i+1] = items[i]; Here's a guess, based on similar work on another language a few reincarnations ago :-) memmove() is very general-purpose, and starts with byte addresses and a byte count. For a small number of list elements, by the time that memmove has determined (1) the move overlaps (2) both source and target are on word boundaries and it is moving a whole number of words (3) what direction (up or down), the DIY code has already finished. For a large number of items, memmove *may* be faster (depending on the architecture and the compiler) but you are using the wrong data structure anyway. From mystilleef at gmail.com Thu Apr 13 10:18:33 2006 From: mystilleef at gmail.com (Mystilleef) Date: 13 Apr 2006 07:18:33 -0700 Subject: list.clear() missing?!? References: <1144767680.583085.310160@v46g2000cwv.googlegroups.com> Message-ID: <1144937913.006463.241520@j33g2000cwa.googlegroups.com> I agree. Lists should have a clear method. But what's shocking is that it doesn't seem obvious to others. list.clear() is a whole lot more readable, intuitive, "flowable" and desirable than del list. Or maybe I haven't had enough coffee this morning. I'd go as far as saying all container objects should have a clear method. This is the reason why those Rubyist whine about Python being inconsistent and not being "OO enough." From sjdevnull at yahoo.com Tue Apr 25 17:13:11 2006 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 25 Apr 2006 14:13:11 -0700 Subject: MinGW and Python In-Reply-To: <1145985979.369429.114040@i39g2000cwa.googlegroups.com> References: <1145861223.509630.247350@y43g2000cwc.googlegroups.com> <444C79D7.4060007@v.loewis.de> <444DC62B.7000702@v.loewis.de> <1145985979.369429.114040@i39g2000cwa.googlegroups.com> Message-ID: <1145999591.695677.18960@t31g2000cwb.googlegroups.com> sturlamolden wrote: > But as long as the cygwin dll is there, it creates an overhead for any > system call. The worst overhead is associated with the Unix fork() > system call, which Cygwin must emulate as there are no Win32 > equivalent. In particular, a fork() on Unix will be optimized with > copy-on-write semantics in the kernel, but Cygwin cannot emulate that > as it has no access to the Windows kernel. Cygwin doesn't do COW fork() for historical reasons. Windows 95/98 didn't expose support for such a thing, but NT, XP, etc do (pass NULL as the SectionHandle parameter to ZwCreateProcess or the older NtCreateProcess to do a COW duplicate of the calling process). Cygwin at one point had a fork() implementation using this in the development tree (or being discussed on the mailing lists) but decided not to use it since it wasn't much faster than full-copy fork for some reason, and it would've split the code for NT/95. From michele.simionato at gmail.com Tue Apr 11 04:58:18 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 11 Apr 2006 01:58:18 -0700 Subject: updated pre-PEP: The create statement In-Reply-To: References: <443a9c60$1_1@news.bluewin.ch> Message-ID: <1144745898.844767.233530@t31g2000cwb.googlegroups.com> Steven Bethard wrote: > Azolex wrote: > > Steven Bethard wrote: > >> and named, nested hierarchies like XML documents could be created > >> like:: > >> > >> create ETobject html: > >> "This statement would generate an ElementTree object" > >> > >> create ETobject head: > >> "generate the head" > >> ... > >> > >> create ETobject body: > >> "generate the body" > >> ... > > > > I think this is is a most important eventual use-case, and would like to > > see it better worked out - or else declared outside the scope of the > > proposed statement. As far as I can see, this does not cut it, since xml > > and html allow /sequencial repetition/ of tags and the results of the > > statement suites are passed as unordered namespaces/dicts. > > Good point. The code above would only work if you didn't care about the > order of elements. I'm half inclined to pull the example, but the > original was due to Michele Simionato, and I haven't quite convinced > myself yet that you couldn't hack it to have ETObject append to an > internal list somehow to keep order. Michele? Did you have a plan for > how this would work? > > STeVe Honestly, I don't want the 'create' statement to be used to write XML in Python. I think this would be a misuse of the functionality. OTOH I believe that the main selling point for the 'create' statements is that it make it easy to implement declarative minilanguages, so I have given an XML example. To solve the ordering issue one should change the internals of Python, in such a way to pass an ordered dict to the 'create' statement instead of an usual dictionary. I think the main use case for 'create' would be in things like object-relational-mappers, not in XML generation. You can pull out the example in the official PEP, if you like. It was just matter for thought. Michele Simionato From nephish at xit.net Tue Apr 25 08:42:19 2006 From: nephish at xit.net (nephish at xit.net) Date: 25 Apr 2006 05:42:19 -0700 Subject: need a thread to keep a socket connection alive? In-Reply-To: <1145956131.110122.104790@i40g2000cwc.googlegroups.com> References: <1145718638.526525.235090@i39g2000cwa.googlegroups.com> <1145885130.140370.166490@t31g2000cwb.googlegroups.com> <1145891966.658138.31310@i40g2000cwc.googlegroups.com> <1145900352.203424.105890@i40g2000cwc.googlegroups.com> <1145934520.835771.123500@u72g2000cwu.googlegroups.com> <1145956131.110122.104790@i40g2000cwc.googlegroups.com> Message-ID: <1145968939.276812.220520@i39g2000cwa.googlegroups.com> yeah, he he From http Thu Apr 13 06:37:21 2006 From: http (Paul Rubin) Date: 13 Apr 2006 03:37:21 -0700 Subject: List comp bug? References: <1144923444.813998.61650@v46g2000cwv.googlegroups.com> Message-ID: <7x8xq969su.fsf@ruckus.brouhaha.com> tasjaevan at gmail.com writes: > I seem to have stumbled across a problem with list comprehensions (or > perhaps it's a misunderstanding on my part) > > [f() for f in [lambda: t for t in ((1, 2), (3, 4))]] List comprehensions are syntactic sugar for "for" loops. The thing to notice is that in "lambda: t", t is unbound. It's not the same as the loop index inside the list comp. Try: [f() for f in [lambda t=t: t for t in ((1, 2), (3, 4))]] From me+python at modelnine.org Tue Apr 18 00:58:36 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Tue, 18 Apr 2006 06:58:36 +0200 Subject: Ironpython book? In-Reply-To: <1145329406.419299.12780@i40g2000cwc.googlegroups.com> References: <1145329406.419299.12780@i40g2000cwc.googlegroups.com> Message-ID: <200604180658.36335.me+python@modelnine.org> Am Dienstag 18 April 2006 05:03 schrieb alacrite at gmail.com: > it seems like there are some new language > features added to handle some quirks with working within the CLR. > Although I could be wrong. I'm no Microsoft friend (let me begin by saying that), but I don't think I'm very paranoid if I consider new language features Microsoft adds to an existing Language Specification not to be a necessity for the language to run on Windows systems (and in this case .NET), but rather an attempt to secure a grip on proprietyzing a language, and to make users ultimately depend on their implementation of it. Remember what Microsoft tried/did with Visual J and Java? --- Heiko. From onurb at xiludom.gro Tue Apr 25 08:16:34 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 25 Apr 2006 14:16:34 +0200 Subject: Zope 3 In-Reply-To: <1145965796.432891.274310@i39g2000cwa.googlegroups.com> References: <1145965796.432891.274310@i39g2000cwa.googlegroups.com> Message-ID: <444e1377$0$30724$636a55ce@news.free.fr> Derick van Niekerk wrote: > I have been developing in PHP for some time now and needed to look into > application frameworks to speed up my development. I was looking into > Horde and CakePHP before I was introduced to Python. I started learing > python and within a few *hours* I already wrote my first small program > and I still use it! > > I love Python! Then I was introduced to Zope by freak accident. While > Zope looked like the answer to my dillemma, I still can't get my head > wrapped around it. Is it because I don't know Python well enough? Or is > it just that difficult to learn? Zope is a world in itself - and is certainly not the simplest tool to learn (nor the most pythonic). You may want to consider other options like Django, Pylon or Turbogears. My 2 cents. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From mtobis at gmail.com Fri Apr 21 13:06:48 2006 From: mtobis at gmail.com (Michael Tobis) Date: 21 Apr 2006 10:06:48 -0700 Subject: proposed Python logo In-Reply-To: <1145615455.477800.74730@i39g2000cwa.googlegroups.com> References: <1145585399.871299.31900@t31g2000cwb.googlegroups.com> <1145615455.477800.74730@i39g2000cwa.googlegroups.com> Message-ID: <1145639208.569365.135440@i40g2000cwc.googlegroups.com> > Sorry dude, but it looks like a hairdryer! I'm afraid you have a point :-/ . > I think that the current logo is fine. Much more professional than the old image. Yes, it is a MUCH more professional rendering than the old image, and it leaves a MUCH better first impression of the homepage. That said, and conceding that the first impression is positive, I don't see how it represents Python. More to the point, the longer I look at it the less I like it, and I would NOT wear it on a T-shirt. > The + formation is positive enough, and it has a yin-yang > feel to it which to me conjures up the image of balance, not > divisiveness. Both the cross and the yin-yang have religious associations, which will be positive for some and negative for others but will certainly be unrepresentative of what Python is. This would be a great logo for Taoist Christians, if such a group exists. How is Python about "balance"? It is about abstraction, composition, the whole greater than the parts, yes, but there's nothing there that really draws on duality. So the whole two-ness of the thing is one of the parts that disturbs me. mt From invalidemail at aerojockey.com Tue Apr 25 10:42:41 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 25 Apr 2006 07:42:41 -0700 Subject: OOP / language design question In-Reply-To: References: <1145961248.794496.80220@j33g2000cwa.googlegroups.com> <444e0e97$0$2052$626a54ce@news.free.fr> <1145969107.837185.212970@e56g2000cwe.googlegroups.com> Message-ID: <1145976161.549860.65780@g10g2000cwb.googlegroups.com> Duncan Booth wrote: > In other words, the object is constructed in Python before any __init__ is > called, but in C++ it isn't constructed until after all the base class > constructors have returned. That's true. Good point. Carl Banks From pmartin at snakecard.com Tue Apr 4 13:10:11 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Tue, 04 Apr 2006 12:10:11 -0500 Subject: Standalone Python functions in UML? References: <4432a339$0$13233$626a54ce@news.free.fr> Message-ID: But not in UML: a class diagram will represent classes while a sequence diagram objects. Philippe bruno at modulix wrote: > Philippe Martin wrote: >> Roman Susi wrote: >> > (snip) > >>>More theoretical question is if I create classes on the fly, how UML can >>>reflect that? >> >> >> You mean objects I think: > > Yes : class objects !-) > > Python's classes *are* objects. And you can create new classes at runtime. > > (snip) From pmartin at snakecard.com Tue Apr 4 04:07:21 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Tue, 04 Apr 2006 03:07:21 -0500 Subject: Loading a default browser under Windows References: <9bmYf.4581$fS6.3530@dukeread11> <1144125055.441632.5970@z34g2000cwc.googlegroups.com> Message-ID: BartlebyScrivener wrote: > Philippe, > > import webbrowser > > webbrowser.open("http://groups.google.com/group/comp.lang.python") > > rpd Many thanks, Philippe From ldo at geek-central.gen.new_zealand Fri Apr 21 02:52:04 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 21 Apr 2006 18:52:04 +1200 Subject: newbie OO question References: Message-ID: In article , Jeremy Winters wrote: >>>> from SegmentValue import * I remember in the old days a computing support guy saying he refused to help any users with FORTRAN questions unless they had an "IMPLICIT NONE" in every program block. The corresponding rule nowadays would be no help to Java or Python programmers who use wildcard imports. From mattia.5stars at gmail.com Tue Apr 11 10:37:16 2006 From: mattia.5stars at gmail.com (fivestars) Date: 11 Apr 2006 07:37:16 -0700 Subject: Override on terminal Message-ID: <1144766236.330882.142520@j33g2000cwa.googlegroups.com> Hi there. I'm computer science student at the end of my degree. I'm new about python. I've a question for all of you. Do you know how to write, from python code, on a unix(linux) terminal on specified coordinates? And also: is it possible to override, from python code, something on a unix(linux) terminal? I would have a suggestion that won't use files. I hope that i've been clear. Thanks, Mattia From jUrner at arcor.de Tue Apr 4 07:18:52 2006 From: jUrner at arcor.de (jUrner at arcor.de) Date: 4 Apr 2006 04:18:52 -0700 Subject: ANN: uuid-0.1 Released In-Reply-To: References: <1143414112.454574.29100@t31g2000cwb.googlegroups.com> Message-ID: <1144149532.845574.191690@e56g2000cwe.googlegroups.com> I would like to contact Ka-Ping Yee, but got no answer to my emails so far. Maybe s.o. knows how to contact Ka-Ping Yee. BTW persistant storage for clock sequence is not implemented in my module so far. I will consider it for the next release. Any ideas how to implement ? From bborcic at gmail.com Mon Apr 24 05:39:18 2006 From: bborcic at gmail.com (Boris Borcic) Date: Mon, 24 Apr 2006 11:39:18 +0200 Subject: what has python added to programming languages? (lets be esoteric, shall we ;) In-Reply-To: References: Message-ID: <444c9ccb$1_4@news.bluewin.ch> Wildemar Wildenburger wrote: > Over the time I've seen lots of remarks about python that read like "a > lot like lists in lisp" or "like the hashtable in java" or any other > form of "like in ". > > Are there any concepts that python has not borrowed, Esoterically speaking, you should better distinguish between historic and individual time. "Python's foo is like Java's foo" speaks of the individual's "exoteric" order of experience with Python and Java, that may reverse "esoteric" historical chronology (and in fact, does so). From sjmachin at lexicon.net Fri Apr 14 02:33:36 2006 From: sjmachin at lexicon.net (John Machin) Date: Fri, 14 Apr 2006 16:33:36 +1000 Subject: Remove Whitespace In-Reply-To: References: <9583ed900604131200n5c43829ckeb01ba4503763954@mail.gmail.com> Message-ID: <443f4257$1@news.eftel.com> On 14/04/2006 12:51 PM, Felipe Almeida Lessa wrote: > Em Sex, 2006-04-14 ?s 12:46 +1000, Steven D'Aprano escreveu: >> Why would you want to call in the heavy sledgehammer of regular >> expressions for cracking this peanut? > > And put heavy on that! > > $ python2.4 -mtimeit -s "str = 'D c a V e r \" = d w o r d : 0 0 0 0 0 6 > 4 0'" 'str.replace(" ", "")' Oi! The OP mentioned "whitespace" ... > 100000 loops, best of 3: 3.07 usec per loop > $ python2.4 -mtimeit -s "str = 'D c a V e r \" = d w o r d : 0 0 0 0 0 6 > 4 0'" '"".join(str.split())' > 100000 loops, best of 3: 4.16 usec per loop > $ python2.4 -mtimeit -s "from re import sub; str = 'D c a V e r \" = d w > o r d : 0 0 0 0 0 6 4 0'" 'sub("\\s", "", str)' > 10000 loops, best of 3: 23.6 usec per loop > $ calc 23.6 / 3.07 > ~7.68729641693811074919 > > I couldn't be expressed better: > > "Some people, when confronted with a problem, think "I know, I'll use > regular expressions." Now they have two problems." > ? Jamie Zawinski, in comp.lang.emacs > C:\junk>python -mtimeit -s "str = 23 * ' X'" "str.replace(' ', '') 100000 loops, best of 3: 3.65 usec per loop C:\junk>python -mtimeit -s "str = 23 * ' X'" "str.replace(' ', '').replace('\t', '') 100000 loops, best of 3: 4.33 usec per loop C:\junk>python -mtimeit -s "str = 23 * ' X'; cmap = ''.join(chr(k) for k in range(256)); delchars = ' \t'" "str.translate(cmap, delchars)" 1000000 loops, best of 3: 0.883 usec per loop 0.883 / 3.65 -> 0.242 Some people, in Gadarene flight from regular expressions, don't read far enough in the Library Reference Manual :-) From rune.strand at gmail.com Sun Apr 30 17:18:10 2006 From: rune.strand at gmail.com (Rune Strand) Date: 30 Apr 2006 14:18:10 -0700 Subject: Measure memory usage in Python Message-ID: <1146431890.904603.98620@i39g2000cwa.googlegroups.com> Is there a way to measure how much memory a data structure use? For instance, what is the footprint of a particular list object like [0,1,2,3,4,5,6,7,8,9]? From percivall at gmail.com Thu Apr 27 12:31:23 2006 From: percivall at gmail.com (Simon Percivall) Date: 27 Apr 2006 09:31:23 -0700 Subject: gcc errors References: Message-ID: <1146155483.787362.58700@t31g2000cwb.googlegroups.com> It doesn't think you're on an intel box, it thinks you want to compile universal libraries, since you installed a universal python. The problem is likely to be that you haven't installed SDK's for intel as well as powerpc when you installed Apple's Developer Tools. Do that, and it should work ... I think. From michele.simionato at gmail.com Tue Apr 11 10:38:55 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 11 Apr 2006 07:38:55 -0700 Subject: Creating an event loop In-Reply-To: References: Message-ID: <1144766335.044600.218080@u72g2000cwu.googlegroups.com> Fabian Steiner wrote: > Hello! > > I am currently wondering how to write something like an "event loop". > For example, if I want to write a function that checks whether a file > was added or removed in a directory I would think of a "while 1: ..." > construct that checks the mtime of the directory. Is this the right way > to achieve the exepected result or are there any better ways? Well, if you feel like cheating, you could use the Tkinter mainloop: import os from Tkinter import Tk root = None # invisible tk window DELTA_T = 10000 # 10 seconds def checkdir(path='.'): print os.listdir(path) # do whatever check you wish root.after(DELTA_T, checkdir) if __name__ == '__main__': root = Tk() root.withdraw() checkdir() try: root.mainloop() except KeyboardInterrupt: pass The advantage is that you can every easily schedule recurring and non-recurring events. Michele Simionato From felipe.lessa at gmail.com Wed Apr 12 15:52:58 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Wed, 12 Apr 2006 16:52:58 -0300 Subject: list.clear() missing?!? In-Reply-To: <1144870852.886477.238570@u72g2000cwu.googlegroups.com> References: <1144767680.583085.310160@v46g2000cwv.googlegroups.com> <1144792144.168802.146310@i39g2000cwa.googlegroups.com> <1144870852.886477.238570@u72g2000cwu.googlegroups.com> Message-ID: <1144871578.5740.0.camel@kenshin.CASA> Em Qua, 2006-04-12 ?s 12:40 -0700, Raymond Hettinger escreveu: > * the existing alternatives are a bit perlish I love this argument =D! "perlish"... lol... Cheers, -- Felipe. From sturlamolden at yahoo.no Tue Apr 25 18:56:38 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 25 Apr 2006 15:56:38 -0700 Subject: MinGW and Python In-Reply-To: <444E7FC0.9070705@v.loewis.de> References: <1145861223.509630.247350@y43g2000cwc.googlegroups.com> <444C79D7.4060007@v.loewis.de> <1145967287.536182.311970@g10g2000cwb.googlegroups.com> <444E7FC0.9070705@v.loewis.de> Message-ID: <1146005798.025382.148250@j33g2000cwa.googlegroups.com> Look what I just found: http://jove.prohosting.com/iwave/ipython/pyMinGW.html A build process for python 2.4.2 (i.e. not the latest) for MinGW. From mirandacascade at yahoo.com Sat Apr 22 00:27:51 2006 From: mirandacascade at yahoo.com (mirandacascade at yahoo.com) Date: 21 Apr 2006 21:27:51 -0700 Subject: python equivalent of VB code sample In-Reply-To: <4448ced5$0$502$626a54ce@news.free.fr> References: <1145620873.806376.206610@i39g2000cwa.googlegroups.com> <4448ced5$0$502$626a54ce@news.free.fr> Message-ID: <1145680070.985988.185700@e56g2000cwe.googlegroups.com> Thank you for pointing me in the direction of XMLHTTP. I'm still thinking about this in terms of creating a python script that is functionally equivalent to the VB code in the original post. The information I reviewed about XMLHTTP makes me think that it may be possible to use the win32com.client to provide the python script with the same methods and properties that the VB program is using. Is win32com.client what I should be using? The Dispatch method of win32com.client? From malvert at telenet.be Sat Apr 8 04:33:50 2006 From: malvert at telenet.be (malv) Date: 8 Apr 2006 01:33:50 -0700 Subject: Programming Tutorial for absolute beginners References: <1144439148.751062.16590@t31g2000cwb.googlegroups.com> Message-ID: <1144485229.605504.12560@g10g2000cwb.googlegroups.com> Looks pretty good, except for your difficult to read examples. Don't use black backrounds with green characters. A plain white background with black text would be a major improvement. From brenNOSPAMbarn at NObrenSPAMbarn.net Thu Apr 20 03:35:17 2006 From: brenNOSPAMbarn at NObrenSPAMbarn.net (OKB (not okblacke)) Date: Thu, 20 Apr 2006 07:35:17 +0000 (UTC) Subject: Updated PEP 359: The make statement References: <_aydnYpYE_rjuNjZRVn-og@comcast.com> Message-ID: Steven Bethard wrote: > Guido has pronounced on this PEP: > http://mail.python.org/pipermail/python-3000/2006-April/000936.h > tml > Consider it dead. =) This is the most frustrating pronouncement ever. -- --OKB (not okblacke) Brendan Barnwell "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown From antonyliu2002 at yahoo.com Fri Apr 21 22:36:23 2006 From: antonyliu2002 at yahoo.com (Anthony Liu) Date: Fri, 21 Apr 2006 19:36:23 -0700 (PDT) Subject: Generate a sequence of random numbers that sum up to 1? Message-ID: <20060422023623.84946.qmail@web35813.mail.mud.yahoo.com> I am at my wit's end. I want to generate a certain number of random numbers. This is easy, I can repeatedly do uniform(0, 1) for example. But, I want the random numbers just generated sum up to 1 . I am not sure how to do this. Any idea? Thanks. __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From scott.daniels at acm.org Tue Apr 25 20:10:16 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Tue, 25 Apr 2006 17:10:16 -0700 Subject: help finding In-Reply-To: <87y7xt5k1o.fsf@localhost.localdomain> References: <87y7xt5k1o.fsf@localhost.localdomain> Message-ID: <444eb70c$1@nntp0.pdx.net> Gary Wessle wrote: > Hi > > I am going through some tutorials, how do I find out about running a > script from the python prompt? Normally you don't do that. What OS and Python versions are you using? Do think about following the advice in "smart questions". > is there a online ref and how to access it? Yes. Your install may have one, what OS? Start here: http://www.python.org/about/gettingstarted/ or http://www.python.org/doc/faq/ or http://wiki.python.org/moin/ or http://www.python.org/doc/ --Scott David Daniels scott.daniels at acm.org From rpdooling at gmail.com Fri Apr 14 11:37:46 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 14 Apr 2006 08:37:46 -0700 Subject: Python editing with emacs/wordstar key bindings. In-Reply-To: References: <1144887253.027194.198750@i39g2000cwa.googlegroups.com> <1144949128.068372.129600@t31g2000cwb.googlegroups.com> <1144992497.402792.153560@t31g2000cwb.googlegroups.com> Message-ID: <1145029065.728956.98170@i39g2000cwa.googlegroups.com> Yes, thanks. I was just going to reinstall anyway. That usually fixes it. Rick From nobody at 127.0.0.1 Sun Apr 30 16:41:00 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Sun, 30 Apr 2006 20:41:00 GMT Subject: setting file permissions on a web server References: <445449f6$0$9437$c3e8da3@news.astraweb.com> <4454f1e1$0$1963$c3e8da3@news.astraweb.com> Message-ID: John Salerno wrote: > Thanks, but I'm still a little confused. Since I'm running Windows You misplaced your period, it goes at the end of that line. ;) > assume that I can't run the chmod line on my own computer. Sure you can, install cygwin. chmod only affects files on your computer, and won't alter the Windows permissions (which use a different scheme), but you can do it. > My web server > uses Unix, but is it possible for me to have access to a command line > for the server? I didn't know that was possible for basic web hosting > plans (I'm using 1and1 right now). It is entirely possible (indeed, I don't know how most things would ever get done without it). Most basic hosting plans however don't provide shell access. > I suppose I could write a script that would set the permissions of all > the files in a particular folder on my computer to 755, but is there a > Windows equivalent command for chmod to do this? Or am I stuck having to > do it on the server side? 1. Settings permissions on your computer won't do a thing. 2. There's probably a Windows-equiv of chmod for your own files, but it won't affect files placed on another machine. 3. You're stuck having to do it on the server side. Now a good ftp program can automate this for you, but it's still your job, not the servers. These sound like good questions for your hosting provider, or failing that, google. From Nad.Oby at gmail.com Fri Apr 21 17:10:24 2006 From: Nad.Oby at gmail.com (Evgeny) Date: Sat, 22 Apr 2006 00:10:24 +0300 Subject: Looking for a programming resource for newbees In-Reply-To: <1145581209.588428.249770@v46g2000cwv.googlegroups.com> References: <1145581209.588428.249770@v46g2000cwv.googlegroups.com> Message-ID: <4449455e$1@news.bezeqint.net> maybe How to Think Like a Computer Scientist: http://www.ibiblio.org/obp/thinkCSpy/ will help From johnjsal at NOSPAMgmail.com Tue Apr 4 13:41:33 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 04 Apr 2006 17:41:33 GMT Subject: how do you use pickle? In-Reply-To: <1144170857.069178.115440@i39g2000cwa.googlegroups.com> References: <1144167350.837406.172430@i39g2000cwa.googlegroups.com> <1144169459.630621.240510@i40g2000cwc.googlegroups.com> <1144170857.069178.115440@i39g2000cwa.googlegroups.com> Message-ID: Pythor wrote: > Whis is why I said carefully ;) I missed it several times myself when > I was working on the challenge. Ok, frustration has set in again. I see the file name in the source code, but am I meant to actually access a file, or just use the name itself? I also had to look up what 'banner' meant in Unix, which wasn't a very fun thing to have to do for a Python puzzle. From jparlar at cogeco.ca Tue Apr 25 05:02:29 2006 From: jparlar at cogeco.ca (Jay Parlar) Date: Tue, 25 Apr 2006 02:02:29 -0700 Subject: Instruction at "0x00FC3D70" use memory address "0x00000000". Can't be "read". In-Reply-To: <20060425003848.43160.qmail@web54202.mail.yahoo.com> References: <20060425003848.43160.qmail@web54202.mail.yahoo.com> Message-ID: <9981537d152538f13aaea0e12612aead@cogeco.ca> On Apr 24, 2006, at 5:38 PM, Neil Adams wrote: > How do Ifix memory? message Ox033fc512 at Ox00000000 can't be read > You're going to have to provide a LOT more information if you expect anyone here to help you with that. What program caused that? For all we know, notepad.exe could have crashed and caused that error. You have to tell us what program (I'm assuming Python, but who knows, maybe you sent the message to the wrong list), what your OS is, what you were doing, what *exactly* happened, etc. etc. Then maybe someone can provide some insight. Jay P. From johnjsal at NOSPAMgmail.com Sat Apr 8 16:32:31 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sat, 08 Apr 2006 16:32:31 -0400 Subject: how relevant is C today? Message-ID: <44381ee4$0$4209$c3e8da3@news.astraweb.com> Because of my 'novice-ness' in programming, I had always thought that C was replaced by C++ and wasn't really used anymore today. I know that's not the case at all now, but I'm still curious how much C is used anymore in programming today, and what purpose it serves. Is it used for actual application programming, or is its use more for something like extending Python? Would it help for a newbie to learn C for any reason? From michele.simionato at gmail.com Thu Apr 6 09:50:31 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 6 Apr 2006 06:50:31 -0700 Subject: pre-PEP: The create statement In-Reply-To: <1144328362.729594.173160@z34g2000cwc.googlegroups.com> References: <59Wdnbd8EazRCqnZnZ2dnUVZ_vudnZ2d@comcast.com> <1144328362.729594.173160@z34g2000cwc.googlegroups.com> Message-ID: <1144331431.696334.248850@u72g2000cwu.googlegroups.com> Kay Schluehr wrote: > Steven Bethard wrote: > > > Python-Version: 2.6 > > Have you a rough estimation how many modules will be broken when > "create" is introduced as a keyword? This is a very relevant question. I would expect the new keyword would break lots of modules. However measuring is better than speculating. $ echo count_name.py """ Count the occurrences of a name in a Python script. For instance: $ find /usr/lib/python2.4 -name \*.py | xargs python2.4 count_name.py create """ import sys, tokenize, token def count_name(name, script): "Count the occurrences of a Python name in a script" counter = 0 for tok_code, tok_value, (srow, scol), (erow, ecol), line in \ tokenize.generate_tokens(file(script).readline): if tok_code == token.NAME and tok_value == name: counter += 1 print 'line %s: %s' %(srow, line), if counter: print '*** %s ***\n' % script return counter if __name__ == '__main__': name = sys.argv[1] scripts = sys.argv[2:] total = sum(count_name(name, script) for script in scripts) print 'Found %d occurrences of %r' % (total, name) Here is the output on my box: line 132: def __init__(self, filename, dbhome, create=0, truncate=0, mode=0600, line 140: if create: *** /usr/lib/python2.4/bsddb/dbtables.py *** line 312: def get_finalized_command (self, command, create=1): line 318: cmd_obj = self.distribution.get_command_obj(command, create) *** /usr/lib/python2.4/distutils/cmd.py *** line 828: def get_command_obj (self, command, create=1): line 835: if not cmd_obj and create: *** /usr/lib/python2.4/distutils/dist.py *** line 379: def create(self, mailbox): *** /usr/lib/python2.4/imaplib.py *** line 1569: self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use) *** /usr/lib/python2.4/lib-tk/Tkinter.py *** From correia_j at KILLTHIShotmail.com Tue Apr 4 12:47:04 2006 From: correia_j at KILLTHIShotmail.com (J Correia) Date: Tue, 04 Apr 2006 16:47:04 GMT Subject: Python and microsoft outlook-using com, can I interact with msoutlook? References: Message-ID: > wrote in message >news:mailman.4050.1144118536.27775.python-list at python.org... >Hi All, > know that Microsoft Exchange has a com interface, CDO, but I can't seem to >find one for Microsoft outlook. >does anyone have code snippets for using msoutlook and python, or >suggestions? Check out: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/173216 also: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/266625 and: http://www.win32com.de/index.php?option=com_content&task=view&id=97&Itemid=192 Also I've emailed you a pdf I'd downloaded a while back, unfortunately I can't remember the source to credit here. That should get you started. HTH, JC From jUrner at arcor.de Sat Apr 8 07:16:20 2006 From: jUrner at arcor.de (jUrner at arcor.de) Date: 8 Apr 2006 04:16:20 -0700 Subject: calculating system clock resolution In-Reply-To: <1144452910.634097.117310@e56g2000cwe.googlegroups.com> References: <1144434899.840346.220780@z34g2000cwc.googlegroups.com> <1144452910.634097.117310@e56g2000cwe.googlegroups.com> Message-ID: <1144494980.132199.237290@i39g2000cwa.googlegroups.com> def calc_time_res(): now = time.time start = now() x = start while start == x: x = now() print x, start # <-- print x - start print calc_time_res() >> 1.50203704834e-05 Something is going wrong here. If you look at the function ,time.time() returns time in microseconds (most oses and so does mine). So the calculation goes, lets say 1.23 - 1.24 How can the result be something like 1.50203704834e-05 ? I would expect 0.01. Next is, the first print statement prints out x and start equal up to the fraction. Is it Python giggeling? Maybe it's python throwing the rounded float at us but internally keeps calculating with the float returned by the os. Maybe I'm wrong. From collinw at gmail.com Thu Apr 27 12:26:20 2006 From: collinw at gmail.com (Collin Winter) Date: Thu, 27 Apr 2006 12:26:20 -0400 Subject: [ANNOUNCE]: functional 0.6 released Message-ID: <43aa6ff70604270926q5844af26o4205a73b4ba7ea92@mail.gmail.com> Hello all, I have released version 0.6 of my functional module, a collection of higher-order and functional programming tools for Python. Currently offered are tools for function composition, partial function application, plus flip, foldl, foldr, scanl and scanr functions. Two version of the release are available: one is written in pure Python and aims for maximum readability and portability. The other is coded as a C extension module and is focused on raw performance. Where to get it: ######### functional is available from the project's website at http://oakwinter.com/code/functional/download/ and from the Python Package Index at http://cheeseshop.python.org/pypi/functional. Both source tarballs and Python Eggs are available for both the pure Python and C releases. Eggs are available for Python versions 2.3, 2.4 and 2.5. Release Notes ######## + flip will now reverse all non-keyword arguments, as opposed to simply reversing the first two as it did in version 0.5 (by popular request). + functional.compose now comes with an optional unpack parameter to make up for the fact that Python functions aren't fully curried. The unpack parameter means that you can now do something like this with compose: >>> f(*g(*arg,**kw)) i.e., automatically unpacking g's return value and passing the result to f. To get this functionality, you'd write something like: >>> compose(f, g, unpack=True)(*args, **kwargs) This was impossible with functional 0.5. + Weakref support has been added to flip and compose objects in the C version. + Sundry performance improvements for the C implementation. As always, feedback welcome! Collin Winter From max at alcyone.com Wed Apr 5 18:50:23 2006 From: max at alcyone.com (Erik Max Francis) Date: Wed, 05 Apr 2006 15:50:23 -0700 Subject: efficiency of range() and xrange() in for loops In-Reply-To: References: Message-ID: Alan Morgan wrote: > In article , > Giovanni Bajo wrote: > >>Because you assume that the only use-case of range() is within a for-loop. >>range() is a builtin function that can be used in any Python expression. For >>instance: >> >>RED, GREEN, BLUE, WHITE, BLACK = range(5) > > Hmmm, this worked fine when I used xrange as well. Am I missing something? Not in your use case. Tuple unpacking will iterate, and so it doesn't matter whether it's an actual list or an iterator: >>> a, b, c = xrange(3) >>> a 0 >>> b 1 >>> c 2 There are certainly contexts where a sequence and its iterator are not interchangeable. You missed an obvious one: >>> range(3) == xrange(3) False -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis I will always remember / This moment -- Sade From grante at visi.com Tue Apr 11 13:00:15 2006 From: grante at visi.com (Grant Edwards) Date: Tue, 11 Apr 2006 17:00:15 -0000 Subject: Override on terminal References: <1144766236.330882.142520@j33g2000cwa.googlegroups.com> Message-ID: <123no4v3chdtg1e@corp.supernews.com> On 2006-04-11, fivestars wrote: > Do you know how to write, from python code, on a unix(linux) > terminal on specified coordinates? Yes, I do. > And also: is it possible to override, from python code, > something on a unix(linux) terminal? What do you mean "override"? -- Grant Edwards grante Yow! Was my SOY LOAF left at out in th'RAIN? It tastes visi.com REAL GOOD!! From da.martian at gmail.com Mon Apr 10 04:39:11 2006 From: da.martian at gmail.com (ChaosKCW) Date: 10 Apr 2006 01:39:11 -0700 Subject: Convertion of Unicode to ASCII NIGHTMARE In-Reply-To: <1144169929.449801.98520@t31g2000cwb.googlegroups.com> References: <1144079830.734516.8390@z34g2000cwc.googlegroups.com> <1144081137.137744.253790@i39g2000cwa.googlegroups.com> <34b9g3-ku8.ln1@home.rogerbinns.com> <1144169929.449801.98520@t31g2000cwb.googlegroups.com> Message-ID: <1144658351.434852.259350@e56g2000cwe.googlegroups.com> > > There's an Oracle environment variable that appears to make a > difference: NLS_CHARSET, perhaps - it's been a while since I've had to > deal with Oracle, and I'm not looking for another adventure into > Oracle's hideous documentation to find out. > That is an EVIL setting which should not be used. The NLS_CHARSET environment variable causes so many headaches its not worth playing with it at all. From pmartin at snakecard.com Fri Apr 21 17:59:11 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Fri, 21 Apr 2006 16:59:11 -0500 Subject: Tkinter hiding/showing widgets References: <1145649525.027965.148840@t31g2000cwb.googlegroups.com> Message-ID: Maybe like this ? http://www.faqts.com/knowledge_base/view.phtml/aid/21215/fid/264 I noticed with wxWidget, which uses the same packing principle (xlib inheritance ?) that hidding a widget can have a strange effect on the layout of the "other guys" still visible ... so I just disable them now instead of hiding them. Regards, Philippe Anony wrote: > Is it possible to hide and show widgets while the window is open? From aghazalp at ucla.edu Sun Apr 2 17:15:31 2006 From: aghazalp at ucla.edu (aghazalp) Date: 2 Apr 2006 14:15:31 -0700 Subject: very very basic question In-Reply-To: References: <1144011128.206400.275270@e56g2000cwe.googlegroups.com> <1144011650.148681.173910@t31g2000cwb.googlegroups.com> Message-ID: <1144012531.467476.121760@z34g2000cwc.googlegroups.com> thanx ...it works great now...you re awesome...the only thing is that the program only executes once though...I guess I ll have to read up more anout it but for now that helped me a lot...I appreciated the help From kay.schluehr at gmx.net Sat Apr 1 02:58:21 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 31 Mar 2006 23:58:21 -0800 Subject: Python 2.5 licensing: stop this change In-Reply-To: References: Message-ID: <1143878301.234998.300730@e56g2000cwe.googlegroups.com> Steve Holden wrote: > As the only director of the Python Software Foundation to vote against a > recent Board motion to implement the change in licensing terms described in > > http://pyfound.blogspot.com/2006/04/python-25-licensing-change.html > > I would like to place on record my protest against this change. I think > it will harm the Python language and ultimately be counter-productive, > reducing the user base and discouraging open source programmers from > contributing to the code base. > > If you disagree with this proposed change it's not too late to do > something about it. If this change goes ahead it will be the end of > Python as we know it. > > regards > Steve > -- > Steve Holden +44 150 684 7255 +1 800 494 3119 > Holden Web LLC/Ltd www.holdenweb.com > Love me, love my blog holdenweb.blogspot.com I'm +1 on the new license because I want to spend good money for good products. My own take is more close to Xah Lees: lets be ultimately responsible and found an insurance for all kind of damages related to Python script usages. Part of the money the PSF earns for insurance fees could be donated to a charitable foundation that cares for indian children that suffer from snake bites. From reply.in.the.newsgroup at my.address.is.invalid Tue Apr 25 06:41:10 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Tue, 25 Apr 2006 12:41:10 +0200 Subject: OOP / language design question References: <1145961248.794496.80220@j33g2000cwa.googlegroups.com> Message-ID: cctv.star at gmail.com: >I was wondering, why you always have to remember to call bases' >constructors explicitly from the derived class constructor? Why hasn't >this been enforced by the language? Probably because the language doesn't know whether the subclass wants to override its base class's constructor, or enhance it. -- Ren? Pijlman From onurb at xiludom.gro Thu Apr 20 07:04:35 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 20 Apr 2006 13:04:35 +0200 Subject: how to transfer a python object to other computer? In-Reply-To: References: Message-ID: <44476b13$0$5195$626a54ce@news.free.fr> Daniel Nogradi wrote: >> Hey, all.Now I wanna to transfer a object to other computer, Maybe I >>could serialize the object to a file by pickle moudle, then send the file >>and get it from the file.But I think the efficency is awful, because the >>disk io is very slow. >> Someone could do me a favor to give me some idea? http://pyro.sourceforge.net/ -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From enleverlesX.XmcX at XmclaveauX.com Thu Apr 13 15:01:20 2006 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI) Date: Thu, 13 Apr 2006 21:01:20 +0200 Subject: Looking for thoughts on PyMPI References: <443E7044.4040709@mvista.com> Message-ID: <443ea0fa$0$21293$8fcfb975@news.wanadoo.fr> Hi! And a small glance on Candygram (http://candygram.sourceforge.net/) can be funny... @-salutations -- Michel Claveau From lists at fabis-site.net Sun Apr 9 13:44:24 2006 From: lists at fabis-site.net (Fabian Steiner) Date: Sun, 09 Apr 2006 19:44:24 +0200 Subject: Creating an event loop Message-ID: Hello! I am currently wondering how to write something like an "event loop". For example, if I want to write a function that checks whether a file was added or removed in a directory I would think of a "while 1: ..." construct that checks the mtime of the directory. Is this the right way to achieve the exepected result or are there any better ways? Cheers, Fabian From tjreedy at udel.edu Thu Apr 27 16:28:48 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 27 Apr 2006 16:28:48 -0400 Subject: finding IP address of computer References: <1146150198.737288.37640@i40g2000cwc.googlegroups.com> <12525ctc1ane5e5@corp.supernews.com> Message-ID: "Grant Edwards" wrote in message news:12525ctc1ane5e5 at corp.supernews.com... > On 2006-04-27, Gregor Horvath wrote: >> Chris schrieb: >>> How do I find and print to screen the IP address of the computer my >>> python program is working on? >>> >> >> IP adresses are bound to network interfaces not to computers. >> One Computer can have multiple network interfaces. > > And each interface can have any number if IP addresses > (including none). To answer the OP for typical situations: if you are accessing the internet via a local network, the network administrator should be able to tell you. In fact, for some networks, the IP address is part of the interface setup. If the network is run by a router, it should be able to tell you. If you are sitting behind a NAT (network address translation) router and you want to know the external address, there are web pages that echo your externally visible address back to you. Terry Jan Reedy From nobody at 127.0.0.1 Mon Apr 24 19:11:45 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Mon, 24 Apr 2006 23:11:45 GMT Subject: RESOLVED Re: PYTHONPATH References: <1145535721.138411.145790@z34g2000cwc.googlegroups.com> <44478f30$0$12862$626a54ce@news.free.fr> Message-ID: Brian van den Broek wrote: > It > didn't work here until I used ':' rather than ';' as the path > element separator. Sorry, I missed the semi-colon before. Yes, unix uses colon to separate path elements. Glad you figured it out and got it working. FYI you can type 'man ' at the shell to get information about most command-line programs (and a number of other things). That's where the bash man page snippet I posted came from. Just in case you don't already know. From ian at excess.org Sat Apr 15 11:44:40 2006 From: ian at excess.org (Ian Ward) Date: Sat, 15 Apr 2006 11:44:40 -0400 Subject: ANN: Urwid 0.9.3 - Console UI Library Message-ID: <444114E8.3020509@excess.org> Announcing Urwid 0.9.3 ---------------------- Urwid home page: http://excess.org/urwid/ Tarball: http://excess.org/urwid/urwid-0.9.3.tar.gz About this release: =================== This release adds support for gpm and mouse dragging to the raw_display module, improves mouse release reporting and fixes a few text layout bugs. If you are interested in Urwid's mouse support please try the input test example program and let me know if it works properly in your environment. user at host:~/urwid-0.9.3$ ./input_test.py will test the input of the curses_display module. user at host:~/urwid-0.9.3$ ./input_test.py raw will test the input of the raw_display module. Please post your results and details about your environment to the mailing list. New in this release: ==================== - Improved mouse reporting. The raw_display module now detects gpm mouse events by reading "/usr/bin/mev" output. The curses_display module already supports gpm directly. Mouse drag events are now reported by raw_display in terminals that provide button event tracking and on the console with gpm. Note that gpm may report coordinates off the screen if the user drags the mouse off the edge. Button release events now report which button was released if that information is available, currently only on the console with gpm. - Added display of raw keycodes to the input_test.py example program. - Fixed a text layout bug affecting clipped text with blank lines, and another related to wrapped text starting with a space character. - Fixed a Frame.keypress(..) bug that caused it to call keypress on unselectable widgets. About Urwid =========== Urwid is a console UI library for Python. It features fluid interface resizing, UTF-8 support, multiple text layouts, simple attribute markup, powerful scrolling list boxes and flexible interface design. Urwid is released under the GNU LGPL. From has.temp2 at virgin.net Fri Apr 14 14:20:10 2006 From: has.temp2 at virgin.net (has) Date: 14 Apr 2006 11:20:10 -0700 Subject: Kross - Start of a Unified Scripting Approach In-Reply-To: <1145020778.953720.86750@u72g2000cwu.googlegroups.com> References: <1144866431.999725.293670@v46g2000cwv.googlegroups.com> <1hdqj4h.1ixp24v1dqm4wrN%aleaxit@yahoo.com> <1144988779.784290.53620@g10g2000cwb.googlegroups.com> <1145016269.843447.143680@e56g2000cwe.googlegroups.com> <1145020778.953720.86750@u72g2000cwu.googlegroups.com> Message-ID: <1145038810.156287.190460@u72g2000cwu.googlegroups.com> Cool. I hope I got the bits about Kross right; I only just found out about it from seeing your post so haven't been long learning about it (I'm a sucker for this stuff). Hopefully some nice expert can correct anything I may've got wrong. :) BTW, if you're curious about how Python hooks into this stuff on the Mac, check out the appscript bridge (shameless self-link) and PythonOSA language component . Appscript uses a lot of syntactic sugar to put a nice easy-to-use syntax (which looks like OO but isn't) on top of the underlying RPC+query mechanism; the underlying aem package gives a better idea of how things actually work. If you don't have a Mac to play with, you might still find the appscript and aem documentation in the source distribution worth reading. The PythonOSA component provides basic OSA support (compile/load/store/execute), allowing you to edit and run Python scripts in Script Editor and other OSA editors and trigger them from OSA-based application script menus and so on. There is a more advanced but unfinished MacPythonOSA component on my site that can do message sending and receiving as well, but it needs a bit of poking to get it built and working at all. And I've also got an unfinished osawrapper module that allows you to load and use OSA languages in Python. HTH From Bulkan at gmail.com Tue Apr 11 01:11:46 2006 From: Bulkan at gmail.com (placid) Date: 10 Apr 2006 22:11:46 -0700 Subject: import help In-Reply-To: <443b1789$1@nntp0.pdx.net> References: <1144716990.314306.79950@v46g2000cwv.googlegroups.com> <443b1789$1@nntp0.pdx.net> Message-ID: <1144732306.567269.299560@i39g2000cwa.googlegroups.com> so there is a record of this problem i had, to solve this problem either use import node . . . n = node.Node("test") or from node import * . . . n = Node("test") Cheers From pramod at tumkur.com Wed Apr 26 10:58:11 2006 From: pramod at tumkur.com (Pramod TK) Date: Wed, 26 Apr 2006 20:28:11 +0530 Subject: Query : sys.excepthook exception in Python Message-ID: Hi, Sometimes during execution of python scripts below mentioned error string is displayed on the console. "Unhandled exception in thread started by Error in sys.excepthook: Original exception was:" The scripts are not terminated, they continue to execute normally. Is this is a problem with python? Is there any known solution. I am using Python 2.4. Thanks in Advance With Best Regards, Pramod TK From frank at chagford.com Tue Apr 4 03:07:53 2006 From: frank at chagford.com (Frank Millman) Date: 4 Apr 2006 00:07:53 -0700 Subject: Best way to create a copy of a list In-Reply-To: References: <1144130464.918371.143160@u72g2000cwu.googlegroups.com> Message-ID: <1144134473.327848.307040@g10g2000cwb.googlegroups.com> Fredrik Lundh wrote: > Frank Millman wrote: > > > I have found two ways of doing it that seem to work. > > > > 1 - row = table[23][:] > > > > 2 - row = [] > > row[:] = table[23] > > > > Are these effectively identical, or is there a subtle distinction which > > I should be aware of. > > > > I did some timing tests, and 2 is quite a bit faster if 'row' > > pre-exists and I just measure the second statement. > > quite a bit ? maybe if you're using very short rows, and all rows > have the same length, but hardly in the general case: > > python -mtimeit -s "data=[range(100)]*100; row = []" "row[:] = data[23]" > 100000 loops, best of 3: 5.35 usec per loop > > python -mtimeit -s "data=[range(100)]*100" "row = data[23][:]" > 100000 loops, best of 3: 4.81 usec per loop > > (for constant-length rows, the "row[:]=" form saves one memory > allocation, since the target list can be reused as is. for longer rows, > other things seem to dominate) > > Interesting. My results are opposite. python -mtimeit -s "data=[range(100)]*100; row = []" "row[:] = data[23]" 100000 loops, best of 3: 2.57 usec per loop python -mtimeit -s "data=[range(100)]*100" "row = data[23][:]" 100000 loops, best of 3: 2.89 usec per loop For good measure, I tried Rune's suggestion - python -mtimeit -s "data=[range(100)]*100" "row = list(data[23])" 100000 loops, best of 3: 3.69 usec per loop For practical purposes these differences are immaterial - I do not anticipate huge quantities of data. If they are all equivalent from a functional point of view, I lean towards the second version. I agree with Rune that the third one is nicer to read, but somehow the [:] syntax makes it a bit more obvious what is going on. Thanks Frank From ericcngan at gmail.com Fri Apr 21 15:06:32 2006 From: ericcngan at gmail.com (vduber6er) Date: 21 Apr 2006 12:06:32 -0700 Subject: Can my python script return a value to the c program executing it? Message-ID: <1145646392.037236.105750@u72g2000cwu.googlegroups.com> I have a C program that calls my python script by exec_pycode(code); code = "import CheckFasta\nCheckFasta.CheckFasta (\"sampledata.txt\", %d)\n", PyNum); CheckFasta.py is my python script with a def CheckFasta in it that returns a string. Is there a way for my C code to get the return value from CheckFasta? Example: If CheckFasta returns "hello world" can I somehow do something like returnstring = exec_pycode(code); where returnstring will contain "hello world" after the line above? Thanks From nogradi at gmail.com Thu Apr 20 05:27:08 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Thu, 20 Apr 2006 11:27:08 +0200 Subject: how to transfer a python object to other computer? In-Reply-To: References: Message-ID: <5f56302b0604200227j25192581oed59e1f029237663@mail.gmail.com> > Hey, all.Now I wanna to transfer a object to other computer, Maybe I > could serialize the object to a file by pickle moudle, then send the file > and get it from the file.But I think the efficency is awful, because the > disk io is very slow. > Someone could do me a favor to give me some idea? > > Best Wish. You will send the pickle file over a network, won't you? Then that will be much slower than disk i/o anyway so no need to worry about that. Pickling/unpickling by the cPickle module is fast and sending the pickle file is probably the best way to send python objects. From tim.golden at viacom-outdoor.co.uk Mon Apr 10 11:58:32 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Mon, 10 Apr 2006 16:58:32 +0100 Subject: can't pass command-line arguments Message-ID: [BartlebyScrivener] | >> You missed the other option: if PATHEXT has .pyc in front | of .py then you | >> get exactly the described behaviour. | | That's it!! | | Trust me, I didn't do it. It was either ActiveState, Wing, or Komodo | Dragon, or some combination thereof. Amazing. I had a look, and my PATHEXT has .pyc too... but *after* .py. I was a little confused because you seemed to be running this as a script, not importing it as a module, but it's clear from your other post that you had imported it as a module at least once. Just goes to show... TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From konrad.hinsen at laposte.net Thu Apr 6 06:46:56 2006 From: konrad.hinsen at laposte.net (konrad.hinsen at laposte.net) Date: Thu, 6 Apr 2006 12:46:56 +0200 Subject: IMPORTANT 2.5 API changes for C Extension Modules In-Reply-To: <1144219456.668201.201620@g10g2000cwb.googlegroups.com> References: <1144219456.668201.201620@g10g2000cwb.googlegroups.com> Message-ID: <37F862A8-1E49-4CA8-859E-42FB79E7698E@laposte.net> On 05.04.2006, at 08:44, nnorwitz at gmail.com wrote: > Python 2.5 alpha 1 is in the process of being released later today. > There are important changes that are in 2.5 to support 64-bit systems. > These changes can cause Python to crash if your module is not upgraded > to support the changes. Python was changed internally to use 64-bit > values on 64-bit machines for indices. If you've got a machine with > more than 16 GB of RAM, it would be great if you can test Python with > large (> 2GB) strings and other sequences. > > For more details about the Python 2.5 schedule: > http://www.python.org/dev/peps/pep-0356/ > For more details about the 64-bit change: > http://www.python.org/dev/peps/pep-0353/ > How to fix your module: > http://www.python.org/dev/peps/pep-0353/#conversion-guidelines Thanks for the information! One question: Is there a safe way to keep extension modules backward- compatible with older Python versions? I am thinking of something like #ifndef PY_SSIZE_T_DEFINED typedef Py_ssize_t int; #endif assuming that Python 2.5 defines PY_SSIZE_T_DEFINED. Konrad. -- ------------------------------------------------------------------------ ------- Konrad Hinsen Laboratoire Leon Brillouin (CEA-CNRS), CEA Saclay, 91191 Gif-sur-Yvette Cedex, France Tel.: +33-1 69 08 79 25 Fax: +33-1 69 08 82 61 E-Mail: konrad.hinsen at cea.fr ------------------------------------------------------------------------ ------- From john at castleamber.com Wed Apr 26 22:23:05 2006 From: john at castleamber.com (John Bokma) Date: 27 Apr 2006 02:23:05 GMT Subject: [Reported] (was Re: Xah's Edu Corner: Criticism vs Constructive Criticism) References: <1145992903.834316.198370@u72g2000cwu.googlegroups.com> <4GM3g.3084$TT.1768@twister.nyroc.rr.com> Message-ID: Ken Tilton wrote: > and if he were a troll, he would respond to each and every shusher to > increase the flames. There are several ways to troll. He writes up a rant, and let others do the flaming. He probably saves up his energy for the next rant. Like someone else wrote: put it on a website (he already does). Turn it into a blog, make people comment. But stop cross posting rants. > in this case he just responded to someone who > threatened him. Maybe because he got a not so nice email from his hosting provider ;-) -- John MexIT: http://johnbokma.com/mexit/ personal page: http://johnbokma.com/ Experienced programmer available: http://castleamber.com/ Happy Customers: http://castleamber.com/testimonials.html From rpdooling at gmail.com Sat Apr 22 16:37:41 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 22 Apr 2006 13:37:41 -0700 Subject: Python on WinXP: 7 Minutes To "Hello World!" Message-ID: <1145738261.373550.104290@e56g2000cwe.googlegroups.com> I started a long email to a friend about how to get up and running on Python, then I thought, why not make something I can post? It's NOT a tutorial. Just a specific, narrow, quick installation guide for Windows XP users. Would love comments, but probably can't incorporate them until Monday, because I have a long drive ahead of me. Thanks for any help. http://www.dooling.com/index.php/category/geekophilia rpd From struggleyb at gmail.com Fri Apr 7 12:20:27 2006 From: struggleyb at gmail.com (Bo Yang) Date: Sat, 08 Apr 2006 00:20:27 +0800 Subject: How can I get the text under the cusor ? Message-ID: <4436914B.3070402@gmail.com> Hello , I want to develop an application to record some of the best words and ideas in the web when I surfing with the Firefox or IE . I would like the application have such a GUI : 1.it appear in the system tray area in the Windows ; 2.whenever I select some words (ether in an IE or MS word),I hope the application to display a small window to ask me wether I will add these words to the application and whether I append some notes to the text . So , how can I trace the cusor , and the text selected in Python ? From k.r.fry at durham.ac.uk Mon Apr 3 08:03:18 2006 From: k.r.fry at durham.ac.uk (k r fry) Date: Mon, 03 Apr 2006 13:03:18 +0100 Subject: Oserror: [Errno 20] In-Reply-To: References: Message-ID: Sorry for not copying the whole traceback before, I hop I have done it right this time. I am now getting: Traceback (most recent call last): File "katiescint.py", line 153, in ? for subdir in os.path.istdir(DATADIR): #loop through list of strings AttributeError: 'module' object has no attribute 'istdir' I did think maybe it was meant to be "listdir" instead of "istdir", but that doesn't work either. Sorry to be a pain. Peter Hansen wrote: > k r fry wrote: > >> Hi, I am new to this list and also programming with python. >> >> I have an error: oserror [errno 20] not a directory "katiescint.py" > > > Please always post complete tracebacks, and without manually reentering > the data. In most cases you'll save us and you lots of time and guessing. > >> The piece of code causing the problem is: >> [code] >> >> for subdir in os.listdir(DATADIR): #loop through list of >> strings >> >> file=FITS.Read(DATADIR+'/'+subdir+'/flux.fits') #opens >> flux.fits file and reads > > > os.listdir() returns a list of all files and directories inside the > directory specified (DATADIR), so you can't assume that "subdir" is > always going to be a directory. Use os.path.isdir() to confirm that it > is and ignore those items for which that function returns False. > > -Peter > From josecarlos.balderas at gmail.com Wed Apr 12 07:23:42 2006 From: josecarlos.balderas at gmail.com (Jose Carlos Balderas Alberico) Date: Wed, 12 Apr 2006 13:23:42 +0200 Subject: Can't connect to SimpleXMLRPCServer. Help needed. In-Reply-To: <443CDFBE.1090200@plus.net> References: <443CDFBE.1090200@plus.net> Message-ID: Thank you for the quick reply John... Is there a way to sort this out? Should I specify another address here: server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 8000), ....) instead of "localhost" ? I'm kind of new to client/server programming, so I'm at a loss here. Thank you very much for your attention. Jose Carlos. 2006/4/12, John Abel : > > Your server is only listening on 127.0.0.1. > > Jose Carlos Balderas Alberico wrote: > > Up till now I've been setting up my server and client in the same > > machine, using the "localhost" address for everything. > > Once I've made it work, I need to move my client application to the > > computer where it'll be run from, and for some reason, I get a > > socket.error: (111, 'connection refused'). > > > > The server is listening on port 8000. I've used the line > > > > server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 8000), > ....) > > ##register functions... > > ... > > ... > > server.serve_forever() > > > > > > And the client does the following: > > > > host = "XXXX:8000" (where XXXX is the server's IP address) > > conn = xmlrpclib.connect(host) > > data = conn.requestData() (requestData is a function previously > > registered in the server) > > > > I've made sure the server is listening on port 8000, since the netstat > > command says it's listening on port 8000. > > I've also pinged the server from the client and viceversa and I get an > > answer. So they can see each other. > > > > I've tried looking in google but couldn't find a solution to this > > problem. Anyone can give me a hand on this? > > Thank you very much. > > > > Jose Carlos. > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Thu Apr 6 06:36:18 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 6 Apr 2006 12:36:18 +0200 Subject: how to create file with spaces References: <1144318680.674373.111220@j33g2000cwa.googlegroups.com> Message-ID: > try > > filename = dirpath + "-dummy" > if not os.path.isfile(filename): > open(filename, "w").close() better make that basename = os.path.basename(dirpath) + "-dummy" filename = os.path.join(dirpath, basename) if not os.path.isfile(filename): open(filename, "w").close() From jUrner at arcor.de Fri Apr 7 14:34:59 2006 From: jUrner at arcor.de (jUrner at arcor.de) Date: 7 Apr 2006 11:34:59 -0700 Subject: calculating system clock resolution Message-ID: <1144434899.840346.220780@z34g2000cwc.googlegroups.com> Hello all I have the problem of how to calculate the resolution of the system clock. Its now two days of head sratching and still there is nothing more than these few lines on my huge white sheet of paper stiring at me. Lame I know. import time t1 = time.time() while True: t2 = time.time() if t2 > t1: print t1, t2 # start calculating here break BTW t1 and t2 print out equal up to the fraction on my machine. What does python know that I don't? A pointer to the source lines where this is implemented would even be helpfull to clear this out. Can't seem to find it. Anyone any ideas? From sxanth at cs.teiath.gr Sat Apr 15 06:12:49 2006 From: sxanth at cs.teiath.gr (Stelios Xanthakis) Date: Sat, 15 Apr 2006 03:12:49 -0700 Subject: The whitespaceless frontend Message-ID: <4440C721.8000006@cs.teiath.gr> It had to happen :) http://pyvm32.infogami.com/EPL Seriously, this is not so much about the whitespace as for the new features, which might interest people who are thinking about new features. More specifically, "methods" and the "$" operator are really great and seem to solve the problem with having to type "self." all the time. The new syntax has been tested in core libraries of pyvm. Feedback is welcome, but preferably not in c.l.py because indentation can be a dangerous topic :) Cheers, Stelios From felipe.lessa at gmail.com Mon Apr 3 20:04:25 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Mon, 03 Apr 2006 21:04:25 -0300 Subject: [ANN] markup.py - 1.2 - an HTML/XML generator In-Reply-To: References: <5f56302b0604031509r51af902dh2e908561bbf78d44@mail.gmail.com> <1144103244.20245.2.camel@kenshin.CASA> Message-ID: <1144109065.24893.1.camel@kenshin.CASA> Em Seg, 2006-04-03 ?s 17:57 -0500, Robert Kern escreveu: > Felipe Almeida Lessa wrote: > > Em Ter, 2006-04-04 ?s 00:09 +0200, Daniel Nogradi escreveu: > > [snip] > > > >>page.ul.open( klass='mylist' ) > >>page.li( items, klass='myitem' ) > > > > [/snip] > > > > "klass"? Why not "cls" or "class_"? > > Why not "klass"? IMHO, it's strange and ugly. Besides, AFAIK everybody uses "cls" or "class_", this is the first place I see "klass", so this breaks consistency, too. But that's just my opinion... -- Felipe. From prinster at mail.com Sat Apr 8 18:23:17 2006 From: prinster at mail.com (Stephen Prinster) Date: Sat, 08 Apr 2006 22:23:17 GMT Subject: Do I Need This? In-Reply-To: References: <1PSZf.18681$cY3.16958@news-wrt-01.rdc-nyc.rr.com> Message-ID: Terry Reedy wrote: There > may be a page at python.com that explains more. > I think you meant python.org. From robert.kern at gmail.com Mon Apr 3 18:57:59 2006 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 03 Apr 2006 17:57:59 -0500 Subject: [ANN] markup.py - 1.2 - an HTML/XML generator In-Reply-To: <1144103244.20245.2.camel@kenshin.CASA> References: <5f56302b0604031509r51af902dh2e908561bbf78d44@mail.gmail.com> <1144103244.20245.2.camel@kenshin.CASA> Message-ID: Felipe Almeida Lessa wrote: > Em Ter, 2006-04-04 ?s 00:09 +0200, Daniel Nogradi escreveu: > [snip] > >>page.ul.open( klass='mylist' ) >>page.li( items, klass='myitem' ) > > [/snip] > > "klass"? Why not "cls" or "class_"? Why not "klass"? -- Robert Kern robert.kern at gmail.com "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From trentm at ActiveState.com Wed Apr 12 17:43:40 2006 From: trentm at ActiveState.com (Trent Mick) Date: Wed, 12 Apr 2006 14:43:40 -0700 Subject: ANN: ActivePython 2.4.3.12 is now available (bugfix for Windows) In-Reply-To: <20060406164517.GA16253@activestate.com> References: <20060406164517.GA16253@activestate.com> Message-ID: <20060412214340.GB31550@activestate.com> I'm happy to announce that ActivePython 2.4.3.12 builds for Windows are now available for free download from: http://www.ActiveState.com/Products/ActivePython/ This is a bug fix release to for one Windows issue: - Fix a bug that results in ".pyo" and ".pyc" being placed on the PATHEXT environment variable before ".py" for clean installs. Bug 33311. This can cause surprises for command-line usage for Python scripts when not specifying the ".py" extension. The new installer will fix PATHEXT on machines that hit this bug. See this thread for more details: http://tinyurl.com/poyhp If you use ActivePython on any other platform, 2.4.3.11 is still the latest build. What is ActivePython? --------------------- ActivePython is ActiveState's quality-assured binary distribution of Python. Builds for AIX, HP-UX, Linux, Mac OS X, Solaris, and Windows are made freely available. ActivePython includes the Python core and core extensions (zlib 1.2.3, bzip2 1.0.3, bsddb 4.2.52.NC, Tk 8.4.12, and Tix 8.1.4) and is fully compatible with other Python distributions of the same version. ActivePython also includes a wealth of Python documentation, including: - the core Python docs; - Andrew Kuchling's "What's New in Python" series; - the Non-Programmer's Tutorial for Python; - Mark Pilgrim's excellent "Dive into Python"; and - a snapshot of the Python FAQs, HOWTOs, and PEPs. An online version of the docs can be found here: http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/welcome.html We would welcome any and all feedback to: ActivePython-feedback at ActiveState.com Please file bugs against ActivePython at: http://bugs.ActiveState.com/ActivePython On what platforms does ActivePython run? ---------------------------------------- ActivePython now includes installers for the following ten platforms: - AIX/PowerPC - HP-UX/PA-RISC - Linux/x86 - Linux/x86_64: "x86_64" is also known as "AMD64" - Solaris/SPARC - Solaris/x86 - Mac OS X/PowerPC - Mac OS X/x86 - Windows/x64: "x64" is also known as "AMD64" - Windows/x86 Extra Bits ---------- ActivePython releases also include the following packages: - Windows "debug" package: Debug-built binaries for ActivePython users building debug versions of their binary Python extensions. - ActivePython24.chm: An MS compiled help collection of the full ActivePython documentation set. Linux users of applications such as xCHM might find this useful. This package is installed by default on Windows. These packages are available from: ftp://ftp.activestate.com/ActivePython/etc/ Thanks, and enjoy! Trent, Python Tech Lead -- Trent Mick TrentM at ActiveState.com From kbk at shore.net Fri Apr 21 00:09:17 2006 From: kbk at shore.net (Kurt B. Kaiser) Date: Fri, 21 Apr 2006 00:09:17 -0400 (EDT) Subject: Weekly Python Patch/Bug Summary Message-ID: <200604210409.k3L49H9n031160@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 371 open (-12) / 3195 closed (+39) / 3566 total (+27) Bugs : 908 open (+22) / 5767 closed ( +8) / 6675 total (+30) RFE : 211 open ( +1) / 212 closed ( +0) / 423 total ( +1) New / Reopened Patches ______________________ Fix test_augassign in p3yk (2006-04-14) CLOSED http://python.org/sf/1470424 opened by Thomas Wouters fix test_exceptions in p3yk (2006-04-14) CLOSED http://python.org/sf/1470459 opened by Thomas Wouters fix test_bisect (2006-04-14) CLOSED http://python.org/sf/1470460 opened by Thomas Wouters partially fix test_class in p3yk (2006-04-14) CLOSED http://python.org/sf/1470504 opened by Thomas Wouters fix test_descrtut in p3yk (2006-04-14) CLOSED http://python.org/sf/1470515 opened by Thomas Wouters fix test_enumerate in p3yk (2006-04-14) CLOSED http://python.org/sf/1470522 opened by Thomas Wouters Fix test_descr in p3yk (2006-04-14) CLOSED http://python.org/sf/1470536 opened by Thomas Wouters fix test_getargs2 in p3yk (2006-04-14) CLOSED http://python.org/sf/1470543 opened by Thomas Wouters Bugfix for #1470540 (XMLGenerator cannot output UTF-16) (2006-04-15) http://python.org/sf/1470548 opened by Nikolai Grigoriev fix test_inspect in p3yk (2006-04-14) CLOSED http://python.org/sf/1470560 opened by Thomas Wouters fix test_itertools in p3yk (2006-04-14) CLOSED http://python.org/sf/1470566 opened by Thomas Wouters urllib2 ProxyBasicAuthHandler broken (2006-04-15) http://python.org/sf/1470846 opened by John J Lee Building Python with MS Free Compiler (2006-04-15) CLOSED http://python.org/sf/1470875 opened by Paul Moore Fix for urllib/urllib2 ftp bugs 1357260 and 1281692 (2006-04-15) http://python.org/sf/1470976 opened by John J Lee Forbid iteration over strings (2006-04-16) http://python.org/sf/1471291 opened by Guido van Rossum start testing strings > 2GB (2006-04-16) http://python.org/sf/1471578 opened by Neal Norwitz test for broken poll at runtime (2006-04-17) http://python.org/sf/1471761 opened by Ronald Oussoren --enable-universalsdk on Mac OS X (2006-04-17) http://python.org/sf/1471883 opened by Ronald Oussoren Weak linking support for OSX (2006-04-17) http://python.org/sf/1471925 opened by Ronald Oussoren pdb 'clear' command doesn't clear selected bp's (2006-04-18) http://python.org/sf/1472184 opened by Kuba Ko??czyk fix for #1472251 (2006-04-18) http://python.org/sf/1472257 opened by Kuba Ko??czyk fix for #1472251 (2006-04-18) http://python.org/sf/1472263 opened by Kuba Ko??czyk Updates to PEP 359 and 3002 (2006-04-18) CLOSED http://python.org/sf/1472459 opened by Steven Bethard make range be xrange (2006-04-19) http://python.org/sf/1472639 opened by Thomas Wouters rlcompleter to be usable without readline (2006-04-19) http://python.org/sf/1472854 opened by kxroberto Improve docs for tp_clear and tp_traverse (2006-04-19) http://python.org/sf/1473132 opened by Collin Winter Add a gi_code attr to generators (2006-04-19) http://python.org/sf/1473257 opened by Collin Winter Patches Closed ______________ fix for 764437 AF_UNIX socket special linux socket names (2004-11-07) http://python.org/sf/1062014 closed by arigo Make -tt the default (2006-04-12) http://python.org/sf/1469190 closed by twouters Alternative to rev 45325 (2006-04-12) http://python.org/sf/1469594 closed by montanaro Compiling and linking main() with C++ compiler (2005-10-12) http://python.org/sf/1324762 closed by loewis Python-ast.h & Python-ast.c generated twice (#1355883) (2005-11-13) http://python.org/sf/1355971 closed by loewis don't add -OPT:Olimit=0 for icc (2005-03-12) http://python.org/sf/1162023 closed by loewis improved configure.in output (2004-10-12) http://python.org/sf/1045620 closed by loewis environment parameter for popen2 (2003-02-28) http://python.org/sf/695275 closed by loewis Fix test_augassign in p3yk (2006-04-14) http://python.org/sf/1470424 closed by twouters Kill off docs for unsafe macros (2003-03-13) http://python.org/sf/702933 closed by loewis fix test_exceptions in p3yk (2006-04-14) http://python.org/sf/1470459 closed by twouters fix test_bisect in p3yk (2006-04-14) http://python.org/sf/1470460 closed by twouters IDNA codec simplification (2006-03-18) http://python.org/sf/1453235 closed by doerwalter partially fix test_class in p3yk (2006-04-14) http://python.org/sf/1470504 closed by twouters fix test_descrtut in p3yk (2006-04-14) http://python.org/sf/1470515 closed by twouters fix test_enumerate in p3yk (2006-04-14) http://python.org/sf/1470522 closed by twouters Fix test_descr in p3yk (2006-04-14) http://python.org/sf/1470536 closed by twouters fix test_getargs2 in p3yk (2006-04-14) http://python.org/sf/1470543 closed by twouters fix test_inspect in p3yk (2006-04-14) http://python.org/sf/1470560 closed by twouters fix test_itertools in p3yk (2006-04-14) http://python.org/sf/1470566 closed by twouters urllib2 dloads failing through HTTP proxy w/ auth (2005-04-18) http://python.org/sf/1185444 closed by loewis Using size_t where appropriate (2005-03-18) http://python.org/sf/1166195 closed by loewis python-config (2005-03-12) http://python.org/sf/1161914 closed by loewis socketmodule.c's recvfrom on OSF/1 4.0 (2005-04-27) http://python.org/sf/1191065 closed by loewis wrong offsets in bpprint() (2005-04-28) http://python.org/sf/1191700 closed by loewis Use GCC4 ELF symbol visibility (2005-04-30) http://python.org/sf/1192789 closed by loewis _ssl.mak Makefile patch (Win32) (2005-05-07) http://python.org/sf/1197150 closed by loewis Bugfix for signal-handler on x64 Platform (2005-05-20) http://python.org/sf/1205436 closed by loewis option to allow reload to affect existing instances (2005-06-01) http://python.org/sf/1212921 closed by loewis More robust MSVC6 finder (2003-07-31) http://python.org/sf/780821 closed by loewis Incremental codecs (2006-02-21) http://python.org/sf/1436130 closed by doerwalter declspec for ssize_t (2006-03-12) http://python.org/sf/1448484 closed by loewis Building Python with MS Free Compiler (2006-04-15) http://python.org/sf/1470875 closed by loewis Tkinter clipboard_get method (new in Tk 8.4) (2004-11-10) http://python.org/sf/1063914 closed by loewis byteorder issue in PyMac_GetOSType (2005-06-10) http://python.org/sf/1218421 closed by ronaldoussoren Direct framework linking for MACOSX_DEPLOYMENT_TARGET < 10.3 (2005-01-07) http://python.org/sf/1097739 closed by jackjansen breakpoint command lists in pdb (2003-08-18) http://python.org/sf/790710 closed by loewis Updates to PEP 359 and 3002 (2006-04-18) http://python.org/sf/1472459 closed by goodger Log gc times when DEBUG_STATS set (2005-01-11) http://python.org/sf/1100294 closed by montanaro New / Reopened Bugs ___________________ mailbox.PortableUnixMailbox fails to parse 'From ' in body (2006-04-14) http://python.org/sf/1470212 opened by Lars Kellogg-Stedman QNX4.25 port (2006-04-14) CLOSED http://python.org/sf/1470300 opened by kbob_ru test_ctypes fails on FreeBSD 4.x (2006-04-14) CLOSED http://python.org/sf/1470353 opened by Andrew I MacIntyre Logging doesn't report the correct filename or line numbers (2006-04-14) http://python.org/sf/1470422 opened by Michael Tsai Mention coercion removal in Misc/NEWS (2006-04-14) CLOSED http://python.org/sf/1470502 opened by Brett Cannon Error in PyGen_NeedsFinalizing() (2006-04-14) CLOSED http://python.org/sf/1470508 opened by Tim Peters XMLGenerator creates a mess with UTF-16 (2006-04-15) http://python.org/sf/1470540 opened by Nikolai Grigoriev Visual Studio 2005 CRT error handler (2006-04-16) http://python.org/sf/1471243 opened by ShireII setup.py --help-commands exception (2006-04-16) http://python.org/sf/1471407 opened by James William Pye reload(ctypes) leaks references (2006-04-16) CLOSED http://python.org/sf/1471423 opened by Thomas Heller tarfile.py chokes on long names (2006-04-16) http://python.org/sf/1471427 opened by Alexander Schremmer IDLE does not start 2.4.3 (2006-04-17) http://python.org/sf/1471806 opened by Erin Python libcrypt build problem on Solaris 8 (2006-04-17) http://python.org/sf/1471934 opened by Paul Eggert curses mvwgetnstr build problem on Solaris 8 (2006-04-17) http://python.org/sf/1471938 opened by Paul Eggert mimetools module getencoding error (2006-04-17) http://python.org/sf/1471985 opened by James G. sack Recursive class instance "error" (2002-03-20) http://python.org/sf/532646 reopened by bcannon sgmllib do_tag description error (2006-04-18) http://python.org/sf/1472084 opened by James G. sack interactive: no cursors ctrl-a/e... in 2.5a1/linux/debian (2006-04-18) http://python.org/sf/1472173 opened by kxroberto pdb 'clear' command doesn't clear selected bp's (2006-04-18) http://python.org/sf/1472191 opened by Kuba Ko??czyk pdb 'run' crashes when the it's first argument is non-string (2006-04-18) http://python.org/sf/1472251 opened by Kuba Ko??czyk import module with .dll extension (2006-04-18) http://python.org/sf/1472566 opened by svenn 32/64bit pickled Random incompatiblity (2006-04-19) http://python.org/sf/1472695 opened by Peter Maxwell Bug in threadmodule.c:local_traverse (2006-04-18) CLOSED http://python.org/sf/1472710 opened by Collin Winter xml.sax.saxutils.XMLGenerator mangles \r\n\t in attributes (2006-04-19) http://python.org/sf/1472827 opened by Mikhail Gusarov Tix: Subwidget names (2006-04-19) http://python.org/sf/1472877 opened by Matthias Kievernagel shutil.copytree debug message problem (2006-04-19) http://python.org/sf/1472949 opened by Christophe DUMEZ valgrind detects problems in PyObject_Free (2006-04-19) CLOSED http://python.org/sf/1473000 opened by Jaime Torres Amate SimpleXMLRPCServer responds to any path (2006-04-19) http://python.org/sf/1473048 opened by A.M. Kuchling urllib2.Request constructor to urllib.quote the url given (2006-04-20) http://python.org/sf/1473560 opened by Nikos Kouremenos cPickle produces locale-dependent dumps (2006-04-20) http://python.org/sf/1473625 opened by Ivan Vilata i Balaguer TempFile can hang on Windows (2006-04-20) http://python.org/sf/1473760 opened by Tim Peters test test_capi crashed -- thread.error: can't allocate lock (2006-04-21) http://python.org/sf/1473979 opened by shashi Bugs Closed ___________ QNX4.25 port (2006-04-14) http://python.org/sf/1470300 closed by loewis test_ctypes fails on FreeBSD 4.x (2006-04-14) http://python.org/sf/1470353 closed by theller make depend/clean issues w/ ast (2005-11-13) http://python.org/sf/1355883 closed by loewis configure incorrectly adds -OPT:Olimit=0 for icc (2005-03-12) http://python.org/sf/1162001 closed by hoffmanm Mention coercion removal in Misc/NEWS (2006-04-14) http://python.org/sf/1470502 closed by nnorwitz Error in PyGen_NeedsFinalizing() (2006-04-14) http://python.org/sf/1470508 closed by tim_one bdist_wininst preinstall script support is broken in 2.5a1 (2006-04-06) http://python.org/sf/1465834 closed by theller reload(ctypes) leaks references (2006-04-16) http://python.org/sf/1471423 closed by theller Bug in threadmodule.c:local_traverse (2006-04-18) http://python.org/sf/1472710 deleted by collinwinter valgrind detects problems in PyObject_Free (2006-04-19) http://python.org/sf/1473000 closed by nnorwitz New / Reopened RFE __________________ "idna" encoding (drawing unicodedata) necessary in httplib? (2006-04-18) http://python.org/sf/1472176 opened by kxroberto From amaltasb at gmail.com Mon Apr 10 23:10:04 2006 From: amaltasb at gmail.com (amaltasb at gmail.com) Date: 10 Apr 2006 20:10:04 -0700 Subject: writing captcha image file In-Reply-To: <1144723853.566700.151680@z34g2000cwc.googlegroups.com> References: <1144723853.566700.151680@z34g2000cwc.googlegroups.com> Message-ID: <1144725003.989669.273190@t31g2000cwb.googlegroups.com> I get this msg: Traceback (most recent call last): File "/usr/local/apache/cgi-bin/newuser.cgi", line 61, in ? cstatus = im.save(file_name,'JPEG') File "/usr/local/lib/python2.4/PIL/Image.py", line 1299, in save fp = __builtin__.open(fp, "wb") IOError: [Errno 13] Permission denied: '/usr/local/apache/htdocs/captcha/t13uum15a2jgfj2sqg.jpg' From scott.daniels at acm.org Tue Apr 18 18:27:50 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Tue, 18 Apr 2006 15:27:50 -0700 Subject: datetime question In-Reply-To: <1614927.J7V8dXKGb9@jupiter.g2ctech> References: <1614927.J7V8dXKGb9@jupiter.g2ctech> Message-ID: <444564bf$1@nntp0.pdx.net> Jorge Godoy wrote: > Philippe Martin wrote: > >> I need to get the date and time under Windows and Linux but need the >> information visible to the user (cannot find my words) not the sytem >> information (ex: a PC setup on greenwich but the date/time displayed are >> relative to some other place. > > Something like this? > >>>> import datetime >>>> datetime.datetime.now() > ... Just so you (Phillipe) know, you are talking about "local time" vs. UTC. >>> import datetime >>> print datetime.datetime.now() # local 2006-04-18 15:25:03.140000 >>> print datetime.datetime.utcnow() # zulu / utc / gmt 2006-04-18 22:25:13.625000 --Scott David Daniels scott.daniels at acm.org From lucaberto at libero.it Sat Apr 1 09:04:10 2006 From: lucaberto at libero.it (luca72) Date: 1 Apr 2006 06:04:10 -0800 Subject: wx.checklistbox In-Reply-To: <1143822322.589470.241040@z34g2000cwc.googlegroups.com> References: <1143815725.730867.324970@j33g2000cwa.googlegroups.com> <1143817821.621038.205640@g10g2000cwb.googlegroups.com> <1143820847.823668.90720@j33g2000cwa.googlegroups.com> <1143822322.589470.241040@z34g2000cwc.googlegroups.com> Message-ID: <1143900250.243912.309390@v46g2000cwv.googlegroups.com> i have again one simple problem: the script is this: def output(self): global lista2 lista2 = open('/lista2', 'w') iteminlista2 = self.checkListBox2.GetStrings() lista2.writelines(iteminlista2) def input1(self): lista2leggi = open('/lista2', 'r') cd = lista2leggi.readlines() self.checkListBox2.AppendItems(cd) The write file is like: item1item2item3 when i read the and i put the item in the checklistbox , i don't find : item1 item2 item3 but : item1item2item3 How to do for have it like : item1 item2 item3 Regards Luca From binarystar. at binarystar.org Wed Apr 26 01:58:30 2006 From: binarystar. at binarystar.org (*binarystar*) Date: Wed, 26 Apr 2006 15:58:30 +1000 Subject: Introspection Class/Instance Name Message-ID: Hello there, what method would you use to return the name of the class and/or instance introspectively eg. class Bollocks: def __init__( self ): print self.__method_that_returns_class_name__() print self.__method_that_returns_instance_name__() instance_of_bollocks = Bollocks() # Which outputs 'Bollocks' 'instance_of_bollocks' I have been scouring the 2.4 docs ... I am sure it is frustratingly simple thx in advance ** From amaltasb at gmail.com Sun Apr 9 03:35:21 2006 From: amaltasb at gmail.com (amaltasb at gmail.com) Date: 9 Apr 2006 00:35:21 -0700 Subject: Writing files on server through CGI Message-ID: <1144568121.238866.122800@i40g2000cwc.googlegroups.com> I have a CGI script on server which process a form and writes its content on a file like fp = open(fname, 'w') fp.write('Cool list

%s


%s

Its working fine, but will it work if the script recieves thousands of request simultaneously. Can this script writes files simultaneusly or will all the request queued and processed one by one. If that is the case then how can I make this script work so that it can process several requests at a time. Thanks Amaltas From nobody at 127.0.0.1 Wed Apr 26 13:30:54 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 26 Apr 2006 17:30:54 GMT Subject: Counting elements in a list wildcard References: <1145921582.526072.120480@u72g2000cwu.googlegroups.com> <1145953610.077361.320290@y43g2000cwc.googlegroups.com> <444DEEC8.7000001@lexicon.net> <1146045430.686430.65440@t31g2000cwb.googlegroups.com> Message-ID: Iain King wrote: > steven = re.compile("Ste(v|ph|f|ff)(e|a)n") > steven = ["Steven", "Stephen", "Stefen", "Steffen", "Stevan", > "Stephan", "Stefan", "Steffan"] > > I know which I'd rather type. 'Course, if you can use a ready-built > list of names... Oh I agree, I'd rather *type* the former, but I'd rather *read* the latter. :) From fredrik at pythonware.com Tue Apr 11 04:39:56 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 11 Apr 2006 10:39:56 +0200 Subject: About classes and OOP in Python References: <1144678797.749000.155010@t31g2000cwb.googlegroups.com> <1144743716.408970.23840@z34g2000cwc.googlegroups.com> Message-ID: Ben Sizer wrote: > I think it's important not to wrongly confuse 'OOP' with ''data hiding' > or any other aspect you may be familiar with from Java or C++. The > primary concept behind OOP is not buzzwords such as abstraction, > encapsulation, polymorphism, etc etc, but the fact that your program > consists of objects maintaining their own state, working together to > produce the required results, as opposed to the procedural method where > the program consists of functions that operate on a separate data set. +1 QOTW From johnjsal at NOSPAMgmail.com Tue Apr 4 12:45:24 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 04 Apr 2006 16:45:24 GMT Subject: how do you use pickle? In-Reply-To: <1144167350.837406.172430@i39g2000cwa.googlegroups.com> References: <1144167350.837406.172430@i39g2000cwa.googlegroups.com> Message-ID: Pythor wrote: > John Salerno wrote: > >> I'm sorry, but I'm terribly confused. Nothing seems to be working for >> me. I *think* what I need to pickle is an image file, > > SNIP > > Hint: Read the source for that page more carefully. > Hmmm...the source doesn't say much. Is there more to do with the source beyond using it to figure out what 'peak hell' means? From chyf1983929 at 126.com Thu Apr 20 05:11:43 2006 From: chyf1983929 at 126.com (chyf1983929) Date: Thu, 20 Apr 2006 17:11:43 +0800 (CST) Subject: python about mobile game? Message-ID: <4447504F.000153.06981@m61.126.com> Is there any modules about mobile game in python? which l can use it to write mobile game . thank you -------------- next part -------------- An HTML attachment was scrubbed... URL: From nobody at 127.0.0.1 Thu Apr 27 18:03:32 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Thu, 27 Apr 2006 22:03:32 GMT Subject: OOP techniques in Python References: <1146158190.320947.108480@t31g2000cwb.googlegroups.com> <3%84g.4111$B42.3689@dukeread05> Message-ID: Philippe Martin wrote: > I'm not sure I understand what you mean ... I did get a strange new > message from my email client and disabled the signature. Look again at the post I replied to (great-grandparent of this one). It's not your sig quote that was the problem. From ldo at geek-central.gen.new_zealand Mon Apr 10 03:24:03 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 10 Apr 2006 19:24:03 +1200 Subject: how relevant is C today? References: <44381ee4$0$4209$c3e8da3@news.astraweb.com> <871ww7elvu.fsf@ieee.org> <1144541959.611623.25540@i39g2000cwa.googlegroups.com> <44393167$1@nntp0.pdx.net> <443965f2$0$67257$157c6196@dreader2.cybercity.dk> Message-ID: In article <443965f2$0$67257$157c6196 at dreader2.cybercity.dk>, David Rasmussen wrote: >In my everyday work, I am forced to use a C90 only compiler, and >everyday I miss some C++ feature that wouldn't make my program any more >complex, quite the opposite. These are features like "const", no default >extern linkage, more typesafe enums etc. "const" is in C89/C90. As for the others, how about hiding a copy of GCC somewhere, just to use to preflight your code before actually building it with your compulsory broken compiler? :) From jstroud at ucla.edu Wed Apr 12 22:26:22 2006 From: jstroud at ucla.edu (James Stroud) Date: Wed, 12 Apr 2006 19:26:22 -0700 Subject: Iterating command switches from a data file - have a working solution but it seems inefficient In-Reply-To: <443db30a$1@news.eftel.com> References: <123r6925duev9b2@corp.supernews.com> <443db30a$1@news.eftel.com> Message-ID: John Machin wrote: > On 13/04/2006 11:23 AM, James Stroud wrote: >> opt_map = {'m': 'Queue Manager', 's': 'Server', 'p': 'Port', >> 'o': 'Object', 'k': 'Key', 't': 'To', >> 'c': 'Check', 'd': 'Report', 'q': 'Display} >> > > 'Queue Manager' is not suitable for later use as an attribute name. Who said anything about attribute names? I did it this way to show the OP that not every value has to be "select variables which would eventually be included in a class object". Using a dict would be far more attractive than a bunch of "setattr" & "getattr"s later. >> afile = open("filename") >> >> settings = {} >> for aline in afile: >> splitline = aline.split() >> flags, options = splitline[::2], splitline[1::2] >> flags = [f[1] for f in flags] # get rid of pesky "-"s > > > Actually that's getting rid of the first character irrespective of > whether it's "-" or not -- except when there's only one character in > which case it will die in a hole. Who said the "-" was optional? >> for flag, option in zip(flags, options): >> settings[opt_map(flag)] = option >> print "%s = %s" % (opt_map(flag), option) > > > opt_map is a dict; should be opt_map[flag] in above two lines Typos. >> afile.close() >> > > Like Peter said, use optparse -- it handles the no-argument flags, has > error detection, defaults, can be told the type of the flag, already > returns the goodies as attributes of an object, ... Peter's post was up when I responded, but it does not give the OP any ideas about how to write better python code. Note the 4 page if...elif construct. optparse might be logical for vet pythonistas, but if someone is writing code like to OP, it might be better to give him some coding hints at the expense of sophistication. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From thn at mail.utexas.edu Wed Apr 26 21:53:37 2006 From: thn at mail.utexas.edu (Thomas Nelson) Date: 26 Apr 2006 18:53:37 -0700 Subject: print names of dictionaries In-Reply-To: <1146090057.616316.61990@y43g2000cwc.googlegroups.com> References: <1146085818.242086.206290@e56g2000cwe.googlegroups.com> <1146086980.998908.281140@g10g2000cwb.googlegroups.com> <1146090057.616316.61990@y43g2000cwc.googlegroups.com> Message-ID: <1146102817.412502.48070@v46g2000cwv.googlegroups.com> I meant something like def printdict(dictionaries=[(apps,'apps'), (dirs,'dirs'), (sites,'sites')]): for dictionary,name in dictionaries: print name keys = dictionary.keys() keys.sort() for key in keys: print key, ":",dictionary[key] print '\n', It's not really easier than what you did. Instead of making sure every dictionary in the dictionaries argument contains a 'name' key that does what you expect, you must make sure the argument passed in is a list of (dictionary, name) pairs. It's a little better in my personal opinion, because you don't have to modify the dictionaries themselves, and it avoids the problem of 'name' already existing in the dictionary, as described by Scott Daniels. But I suppose that's only one opinion. THN From tzot at sil-tec.gr Mon Apr 10 08:57:15 2006 From: tzot at sil-tec.gr (Christos Georgiou) Date: Mon, 10 Apr 2006 15:57:15 +0300 Subject: Python 3.0 or Python 3000? References: <4439aba9$0$18019$c3e8da3@news.astraweb.com> <1144639927.634478.319420@v46g2000cwv.googlegroups.com> Message-ID: <77lk32hp1gr4m4n0v6d1jbecut3anji8ar@4ax.com> On 9 Apr 2006 20:32:07 -0700, rumours say that "Ray" might have written: >Dennis Lee Bieber wrote: >> Or... just to save "3000" as a "time way down the road"... The next >> major version of Python will be: Python PI (and each build will add >> another digit... "3.1, 3.14, 3.141, ...") > >I like this idea a lot. This way, people ALWAYS know what the next >release's name will be. Who gave the time machine to the Donald Knuth? Have we got infiltrators? Or did he steal it? In other news, the unnamed chief of the PSU has stat From robert.kern at gmail.com Mon Apr 24 12:31:08 2006 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 24 Apr 2006 11:31:08 -0500 Subject: MinGW and Python In-Reply-To: <444C79D7.4060007@v.loewis.de> References: <1145861223.509630.247350@y43g2000cwc.googlegroups.com> <444C79D7.4060007@v.loewis.de> Message-ID: Martin v. L?wis wrote: > Srijit Kumar Bhadra wrote: > >>Is there any specific reason for not using MinGW to build the official >>distribution of Python for Win32? > > What could be the reasons to use MinGW? > > As for reasons not to do that: > - there is no build process available to do that > - people building extensions to Python must be able to do so with > Microsoft C++, since some of these extensions are written using MFC. > - developing Python itself in Visual Studio is quite convenient; in > particular, the debugger works "better" than gdb. - gcc does not optimize particularly well. -- Robert Kern robert.kern at gmail.com "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From peter at engcorp.com Tue Apr 11 06:45:21 2006 From: peter at engcorp.com (Peter Hansen) Date: Tue, 11 Apr 2006 06:45:21 -0400 Subject: updated pre-PEP: The create statement In-Reply-To: <1144741586.861381.190350@z34g2000cwc.googlegroups.com> References: <443a9c60$1_1@news.bluewin.ch> <1144741586.861381.190350@z34g2000cwc.googlegroups.com> Message-ID: Michele Simionato wrote: > Honestly, I don't want the 'create' statement to be used to write XML > in Python. > I think this would be a misuse of the functionality. OTOH I believe > that the main selling point for the 'create' statements is that it make > it easy to implement declarative minilanguages, so I have given an XML > example. To solve the ordering issue one > should change the internals of Python, in such a way to pass an ordered > dict ... That solves "the ordering issue", but not the real issue, which is that XML can have *multiple* elements with the same name (even though ids must be unique, but that's irrelevant to the point here). Attributes on an element are mappings, but elements are (nested) lists of items in XML, not mappings. > You can pull out the example in the official > PEP, if you like. Please do. If this is supposed to have anything to do with namespaces, it has nothing to do with the type of data structures XML is capable of and the presence of this example would only lead some people to think there can't be a good use case for the whole idea if that's the best we can come up with to demonstrate its benefits. -Peter From eddie at holyrood.ed.ac.uk Mon Apr 3 11:12:20 2006 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Mon, 3 Apr 2006 15:12:20 +0000 (UTC) Subject: String pattern matching References: <1143888648.234963.326000@j33g2000cwa.googlegroups.com> Message-ID: "Jim Lewis" writes: >Anyone have experience with string pattern matching? >I need a fast way to match variables to strings. Example: >string - variables >============ >abcaaab - xyz >abca - xy >eeabcac - vxw >x matches abc >y matches a >z matches aab >w maches ac >v maches ee Off topic I know but I've been learning snobol pattern matching recently so I thought I'd give this one a bash. Here is my effort: define('foo(str)') &fullscan = 1 '/abcaaab/abca/eeabcac/' '/' arb $ x arb $ y arb $ z '/' *x *y '/' + arb $ v *x arb $ w '/' *foo(v '/' w '/' x '/' y '/' z) :F(end) foo output = str :(FRETURN) end Good eh? Here's the output: /eeabcac//abca/aab e/eabcac//abca/aab ee/abcac//abca/aab eea/bcac//abca/aab eeab/cac//abca/aab eeabc/ac//abca/aab eeabca/c//abca/aab eeabcac///abca/aab ee/bcac/a/bca/aab eeabc/c/a/bca/aab ee/cac/ab/ca/aab ee/ac/abc/a/aab ee/c/abca//aab Removing empty entries is quite easy: '/abcaaab/abca/eeabcac/' '/' arb $ x arb $ y arb $ z '/' *x *y '/' + arb $ v *x arb $ w '/' *differ(v) *differ(w) *differ(x) + *differ(y) *differ(z) *foo(v '/' w '/' x '/' y '/' z) :F(end) generates: ee/bcac/a/bca/aab eeabc/c/a/bca/aab ee/cac/ab/ca/aab ee/ac/abc/a/aab If I get time I'll try to get this working in Sam Wilmott's Python pattern matching library. What fun! Eddie From antroy at gmail.com Thu Apr 27 04:22:28 2006 From: antroy at gmail.com (Ant) Date: 27 Apr 2006 01:22:28 -0700 Subject: begging for a tree implementation In-Reply-To: <2lq0521052qd9a5tb3k3na8imm3ulrbebb@4ax.com> References: <1146091386.013265.153660@v46g2000cwv.googlegroups.com> <1146107842.659346.178910@t31g2000cwb.googlegroups.com> <2lq0521052qd9a5tb3k3na8imm3ulrbebb@4ax.com> Message-ID: <1146126148.259872.50610@y43g2000cwc.googlegroups.com> Did you not read the first post? > All the nice methods would be appreciated (getLeaves, isLeaf, isRoot, > depthfirst, breadthfirst,...) From finite.automaton at gmail.com Mon Apr 10 14:03:29 2006 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 10 Apr 2006 11:03:29 -0700 Subject: minidom + wxPython woes In-Reply-To: <1144448449.586601.293480@v46g2000cwv.googlegroups.com> References: <1144448449.586601.293480@v46g2000cwv.googlegroups.com> Message-ID: <1144692209.945370.54430@g10g2000cwb.googlegroups.com> I'm hesitant to resort to tricks like "import pyexpat before wx, so that symbols are loaded from the right library". Luckily, I stumbled onto pxdom. It's a pure-python DOM implementation, and switching to it was as easy as this: # import xml.dom.minidom as dom import pxdom as dom From mmanns at gmx.net Thu Apr 13 00:31:42 2006 From: mmanns at gmx.net (Martin Manns) Date: Thu, 13 Apr 2006 04:31:42 GMT Subject: Numpy and cPickle In-Reply-To: References: Message-ID: Robert Kern wrote: > Martin Manns wrote: >> If I cPickle a numpy array under Linux and un-cPickle it under Solaris >> 10, my arrays seem to be transposed. > Transposed? That's odd. There was a byteorder issue with pickles going across > differently-endianed platforms that was fixed in the past few days. Could you > come up with a small bit of code that shows the problem and post it and the > incorrect output to the bug tracker? Sorry, I my ad-hoc small example does not reproduce the error even though the files generated on both platforms differ. I will try to set up the code tomorrow. Thank you though for the fast response Martin From amy.berry at cox.net Tue Apr 11 09:52:59 2006 From: amy.berry at cox.net (ACB) Date: Tue, 11 Apr 2006 06:52:59 -0700 Subject: Saving files from post data via sys.stdin References: Message-ID: <5xO_f.212$Oe2.71@fed1read07> "ACB" wrote in message news:KoE_f.200$Oe2.100 at fed1read07... >I am rewriting an existing PERL script I wrote several months ago. It is a >script that is used as the action for a form containing several type="file" >inputs. The script is run unbuffered and writes the data from sys.stdin to >a file which is stat'ed by another script called asyncornously from >javascript. In the end I am able to make a progress bar for file uploads >via http. > > Anyway, I have printed sys.stdin to a file and looked at it afterward. > This is what is looks like > -----------------------------126591649570 > Content-Disposition: form-data; name="userid" > > myUserid > -----------------------------126591649570 > Content-Disposition: form-data; name="ulimage"; filename="bc12.jpg" > Content-Type: image/jpeg > > binary data of jpeg > -----------------------------126591649570 > Content-Disposition: form-data; name="ulimage"; filename="" > Content-Type: image/jpeg > > -----------------------------126591649570 > Content-Disposition: form-data; name="ulimage"; filename="" > Content-Type: image/jpeg > > > -----------------------------126591649570 > Content-Disposition: form-data; name="sessionid" > > mySessionid > > Normally, I use cgi.FieldStorage() and access the values via calls like > form = cgi.FieldStorage() > sessionid = form["sessionid"].value > > What is the best method for accessing the various variables and their > respective values so I can save the files one at a time? Is there some > class that can take this input and make it easier to deal with? I need to > save each of the ulimage values as individual images and gain access to > the values of sessionid and userid. > > Thanks > Amy > > Any further help is appreciated. : ) From diffuser78 at gmail.com Wed Apr 5 01:59:25 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 4 Apr 2006 22:59:25 -0700 Subject: specialized GUI Message-ID: <1144216765.431476.176270@e56g2000cwe.googlegroups.com> I am new to python. I got a new project where I have to create a GUI and attch my code to it. The GUI should look like vsTASKER www.virtualsim.com I mean GUI lets user create diagram, and my code should read that diagram and run the algorithm. Do you know any other tool like this where I can integrate my code with. Every help is appreciated From ianb at colorstudy.com Fri Apr 28 11:36:55 2006 From: ianb at colorstudy.com (Ian Bicking) Date: 28 Apr 2006 08:36:55 -0700 Subject: Editing a function in-memory and in-place References: <1146115733.082702.106380@t31g2000cwb.googlegroups.com> Message-ID: <1146238615.692349.88070@i40g2000cwc.googlegroups.com> Thanks for the answers, very helpful. I think I'm going to give Peter's hack a try, as it's actually quite close to what I'm trying to do -- I get the source for the new function, then that lets me make the old function become the new one. But I'll probably also use Michael's solution for class editing. Now I just have to figure out how to take in-memory structures and turn them into Python source code. Hmm... that actually leads me back to Michael's solution more, since in that model you are always dealing with source, and if you faithfully reproduce the source then you should more-or-less reproduce the same structures. Hmm... challenging. I guess this is one motivation for languages like Smalltalk to use an image, because they don't have to serialize code as source. Of course, I could use one of those pickle alternatives that knows how to pickle live objects; but that takes the project much further from normal Python. From brian at sweetapp.com Wed Apr 26 09:36:07 2006 From: brian at sweetapp.com (Brian Quinlan) Date: Wed, 26 Apr 2006 15:36:07 +0200 Subject: Importing modules through directory shortcuts on Windows Message-ID: <444F7747.3060201@sweetapp.com> Recently, I became responsible for maintaining some Python code, which was organized as follows: user/pylib ui ... project2/pylib ui ... project3/pylib ui ... python-packages/user => /user/pylib project2 => /project2/pylib project3 => /project3/pylib The idea is that "python-packages" is added to sys.path and then every project can import the library package from every other project. NOTE: I think that this structure is crazy but I'm just the poor maintenance programmer. Anyway, the problem is that Windows does not have a symlink facility to accommodate this (AFAIK) and the Python import mechanism does not resolve shortcuts. Therefore, I wrote a very simple import hook to get around that problem. If you are interested, the code is here: http://www.sweetapp.com/shortcut/shortcutimporter.py BTW, does anyone else think that this functionality should be part of core Python? Cheers, Brian From rpdooling at gmail.com Fri Apr 21 07:15:25 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 21 Apr 2006 04:15:25 -0700 Subject: python-mysql on Windows -- How to? In-Reply-To: <1145602923.653628.222040@u72g2000cwu.googlegroups.com> References: <1145602923.653628.222040@u72g2000cwu.googlegroups.com> Message-ID: <1145618125.010034.273380@e56g2000cwe.googlegroups.com> Chris, I'm no expert, but this keeps coming up and the last several people have had better luck with mxODBC. http://tinyurl.com/fmp3y But if you're set on MySql-Python someone will jump in to help. rick From josecarlos.balderas at gmail.com Wed Apr 12 07:04:48 2006 From: josecarlos.balderas at gmail.com (Jose Carlos Balderas Alberico) Date: Wed, 12 Apr 2006 13:04:48 +0200 Subject: Can't connect to SimpleXMLRPCServer. Help needed. Message-ID: Up till now I've been setting up my server and client in the same machine, using the "localhost" address for everything. Once I've made it work, I need to move my client application to the computer where it'll be run from, and for some reason, I get a socket.error: (111, 'connection refused'). The server is listening on port 8000. I've used the line server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 8000), ....) ##register functions... ... ... server.serve_forever() And the client does the following: host = "XXXX:8000" (where XXXX is the server's IP address) conn = xmlrpclib.connect(host) data = conn.requestData() (requestData is a function previously registered in the server) I've made sure the server is listening on port 8000, since the netstat command says it's listening on port 8000. I've also pinged the server from the client and viceversa and I get an answer. So they can see each other. I've tried looking in google but couldn't find a solution to this problem. Anyone can give me a hand on this? Thank you very much. Jose Carlos. -------------- next part -------------- An HTML attachment was scrubbed... URL: From williams13 at llnl.gov Wed Apr 19 11:41:33 2006 From: williams13 at llnl.gov (Dean N. Williams) Date: Wed, 19 Apr 2006 08:41:33 -0700 Subject: unrecognized command line option "-Wno-long-double" Message-ID: <44465A2D.90900@llnl.gov> Dear Python and Mac Community, I have just successfully built gcc version 4.1.0 for my Mac OS X 10.4.6. gcc -v Using built-in specs. Target: powerpc-apple-darwin8.6.0 Configured with: /usr/local/src/gcc-4.1.0/configure Thread model: posix gcc version 4.1.0 When I try to build Python 2.4.3, I get the following error below: gcc -c -fno-strict-aliasing -no-cpp-precomp -mno-fused-madd -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused-madd -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DPy_BUILD_CORE -o Modules/python.o Modules/python.c gcc: unrecognized option '-no-cpp-precomp' gcc: unrecognized option '-no-cpp-precomp' cc1: error: unrecognized command line option "-Wno-long-double" make: *** [Modules/python.o] Error 1 Python make failed. What is the best solution for this unrecognized command line option? Thanks for your help in advance, Dean From vivainio at gmail.com Tue Apr 11 17:49:04 2006 From: vivainio at gmail.com (Ville Vainio) Date: 11 Apr 2006 14:49:04 -0700 Subject: list.clear() missing?!? References: <1144767680.583085.310160@v46g2000cwv.googlegroups.com> Message-ID: <1144792144.168802.146310@i39g2000cwa.googlegroups.com> John Salerno wrote: > Thanks guys, your explanations are really helpful. I think what had me > confused at first was my understanding of what L[:] does on either side > of the assignment operator. On the left, it just chooses those elements > and edits them in place; on the right, it makes a copy of that list, > right? (Which I guess is still more or less *doing* the same thing, just > for different purposes) Interestingly, if it was just a "clear" method nobody would be confused. From fredrik at pythonware.com Mon Apr 24 12:56:43 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 24 Apr 2006 18:56:43 +0200 Subject: Packing a list of lists with struct.pack() References: <1145895732.963584.231100@j33g2000cwa.googlegroups.com> Message-ID: Panos Laganakos wrote: > I have a list that includes lists of integers, in the form of: > li = [[0, 1, 2], [3, 4, 5], ...] > What can I do to get li as a single list of integers? > > I tried list comprehension in the form of: > [([j for j in i]) for i in li] > > But that doesn't seem to work, any ideas? you have it backwards: a nested list expression is like a nested for loop, but with the innermost expression at the beginning. a for-loop would look like: for i in li: for j in i: ... do something with j ... so the corresponding comprehension is [j for i in li for j in i] which gives you the expected result. when you pass this to pack, you can use a generator expression instead: data = struct.pack("%di" % (len(li)*3), *(j for i in li for j in i)) From fredrik at pythonware.com Sat Apr 1 06:17:34 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 1 Apr 2006 13:17:34 +0200 Subject: python tutorial: popular/informative Python sites ? Message-ID: the "what now?" page in the tutorial http://www.python.org/doc/tut/node14.html lists a couple of relevant web sites for Python users, including: http://www.python.org http://starship.python.net http://www.python.org/pypi the starship link has been there since 1998 or so (Python 1.5), but I don't think the starship is very active these days. but if we were to replace it with something else, what should that be? what sites do pythoneers and pythonistas visit these days? post your suggestions in this thread or on this page: http://pytut.infogami.com/node14.html thanks /F From josecarlos.balderas at gmail.com Wed Apr 12 03:58:07 2006 From: josecarlos.balderas at gmail.com (Jose Carlos Balderas Alberico) Date: Wed, 12 Apr 2006 09:58:07 +0200 Subject: Beginner question. Exceptions Message-ID: Hello. I'm having my way with exceptions in a little program I've done, and I'm wondering... What is a decent way of dealing with them? By a decent way I mean, what should I do when I see that an exception has occurred? I've seen that Python's default action is to print a stack trace. As far as I know, exception handling is a mean of knowing what can go wrong with your program, like anticipating wrongs and treating them. What I'm having trouble understanding is this: if I use a "raise" sentence to raise an exception... shoul I use it inside a "try" block, so I can catch it with an "except" block? If I don't do that, a stack trace will be printed onto the screen... Is that the way it's usually done? Please, help me out, for I'm kind of new to exceptions and I want to know if I get them right. Thanks a lot in advance. Jose Carlos. -------------- next part -------------- An HTML attachment was scrubbed... URL: From finite.automaton at gmail.com Thu Apr 6 01:36:16 2006 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 5 Apr 2006 22:36:16 -0700 Subject: ``pickling'' and ``unpickling'' References: <1144300906.286664.75350@j33g2000cwa.googlegroups.com> Message-ID: <1144301776.147022.120740@i40g2000cwc.googlegroups.com> Pickling is the Python term for serialization. See http://en.wikipedia.org/wiki/Serialization Suppose you want to save a Python object "x" to a file... output_file = open('my_pickle', 'wb') # open a file import pickle pickle.dump(x, output_file) # write x to the file output_file.close() ... and to restore x from the file: input_file = open('my_pickle','rb') x = pickle.load(input_file) input_file.close() From bayerj at in.tum.de Wed Apr 19 13:49:59 2006 From: bayerj at in.tum.de (bayerj) Date: 19 Apr 2006 10:49:59 -0700 Subject: How do you guys print out a binary tree? In-Reply-To: References: <1145343415.809363.116280@i39g2000cwa.googlegroups.com> Message-ID: <1145468999.535850.308330@z34g2000cwc.googlegroups.com> The problem is that you cannot represent a matrix as a tree, due to the fact that there are more than one tree for a matrix. First you have to decide, how you will turn the matrix into a tree. From steve at REMOVETHIScyber.com.au Sun Apr 9 18:42:32 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Mon, 10 Apr 2006 08:42:32 +1000 Subject: Decorators, Identity functions and execution... References: <1144597938.664642.133100@v46g2000cwv.googlegroups.com> Message-ID: On Sun, 09 Apr 2006 08:52:18 -0700, Carl Banks wrote: > it's more important > to respect community standards than to stick to some silly preference > you have. What happens when the community standard is a silly preference? I object to the suggestion that "community standards" (that is, a standard not even designed by a committee, merely evolved by a mob) is necessarily worthy of respect. As it turns out, regarding this particular "silly preference" (community or private), I always remember that communication is the purpose of email (and, believe it or not, Usenet), and the use of tabs in some buggy news readers can cause the failure of communication. Hence I use spaces when posting code. The rest of the time, particularly in my private coding, my preference (whatever it is) is no more or less irrational than the other preference. -- Steven. From tjreedy at udel.edu Thu Apr 6 13:20:27 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 6 Apr 2006 13:20:27 -0400 Subject: pre-PEP: The create statement References: <59Wdnbd8EazRCqnZnZ2dnUVZ_vudnZ2d@comcast.com><1144310059.925361.36780@t31g2000cwb.googlegroups.com> <4435278c_2@news.bluewin.ch> Message-ID: "Azolex" wrote in message news:4435278c_2 at news.bluewin.ch... > I'd advocate for the shortest possible keyword, and - maybe because > English is not my native language - I'd thus prefer "make" if any is > really required. While currently +0 on the proposal, I am +1 on 'make' versus 'create'. Aside from the above, factories don't create things, they make them. Terry Jan Reedy From onurb at xiludom.gro Fri Apr 28 05:29:10 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 28 Apr 2006 11:29:10 +0200 Subject: Get all attributes of a com object In-Reply-To: <1146209689.917251.224530@g10g2000cwb.googlegroups.com> References: <1146151043.933987.145080@t31g2000cwb.googlegroups.com> <4450e4b7$0$21092$626a54ce@news.free.fr> <1146209689.917251.224530@g10g2000cwb.googlegroups.com> Message-ID: <4451e0bd$0$7724$636a55ce@news.free.fr> eicwo01 wrote: > Thanks for your tips. > But dir() and inspect did not really help. Really ? def dump(obj): for name in dir(obj): print getattr(obj, name) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From greg.kujawa at gmail.com Mon Apr 10 09:15:06 2006 From: greg.kujawa at gmail.com (gregarican) Date: 10 Apr 2006 06:15:06 -0700 Subject: how relevant is C today? References: <44381ee4$0$4209$c3e8da3@news.astraweb.com> <44382711.10403@v.loewis.de> <44393fbe$0$19226$c3e8da3@news.astraweb.com> <44398651$0$4206$c3e8da3@news.astraweb.com> <1144632983.039143.203330@u72g2000cwu.googlegroups.com> <443a4e8a$0$21013$626a54ce@news.free.fr> Message-ID: <1144674906.886475.238510@i39g2000cwa.googlegroups.com> bruno wrote: > Err... Even if Lisp is the father of functional programming, it is > definitively not a 'pure' FPL. True. I couldn't referred to something like Haskell as being pure FP. My bad :-) From samantha7395 at hotmail.com Tue Apr 4 11:02:59 2006 From: samantha7395 at hotmail.com (Samantha) Date: Tue, 4 Apr 2006 08:02:59 -0700 Subject: Help with display placement Message-ID: <0v-dnVDsAaY-F6_Z4p2dnA@adelphia.com> I am new to Python and am attempting to write a routine that will display a five game selection for a power ball drawing. I think I have the random drawing set to work ok, but I want to have the dialog box move in the center of my screen. I can't seem to get the code correct to do this. Any help would be appreciated. Thanks, S This is the routine I have. ########################### import random from Tkinter import * root = Tk() frame = Label(root, width=50, height=2, background = 'white', text = 'PowerBall Numbers') frame.pack() def GetNumbers(): numbers = random.sample(xrange(53), 5) numbers.sort() numbers[0] = numbers[0] + 1 numbers[1] = numbers[1] + 1 numbers[2] = numbers[2] + 1 numbers[3] = numbers[3] + 1 numbers[4] = numbers[4] + 1 powerball = random.sample(xrange(42), 1) powerball[0] = powerball[0] + 1 return numbers, powerball y = 0 sp1 = sp2 = sp3 = sp4 = sp5 =' ' w = 0 for x in range(5): y = y + 1 MyNumbers= GetNumbers() x = MyNumbers num1= str(x[0][0]) num2 = str(x[0][1]) num3 = str(x[0][2]) num4 = str(x[0][3]) num5 = str(x[0][4]) pbnum = str(MyNumbers[1][0]) root.title =('Powerball Numbers') w = Label(root, width=50, height=2, background= 'white' , text='Game '+str(y)+': Numbers: '+num1.zfill(2)+' '+num2.zfill(2)+' '+num3.zfill(2)+' '+num4.zfill(2)+' '+num5.zfill(2)+' '+'PowerBall: '+pbnum.zfill(2)) w.pack() root.mainloop() ##################### From fredrik at pythonware.com Tue Apr 4 12:15:21 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 4 Apr 2006 18:15:21 +0200 Subject: how do you use pickle? References: Message-ID: John Salerno wrote: > > but if you insist on using your own Pickler instance, you have to save > > the pickler instance in a variable, and call the dump method on that in- > > stance: > > > > myfile = open(somefilename, "wb") > > mypickler = pickle.Pickler(myfile) > > mypickler.dump(object) > > I'm sorry, but I'm terribly confused. Nothing seems to be working for > me. I *think* what I need to pickle is an image file, but so far I think > all I'm doing is passing the file handle in as the 'object' define "image file". the data in the file, the file name, or some other representation? > I tried it both ways you suggest, but I can't get past the errors. I > keep getting either > > AttributeError: 'module' object has no attribute 'dump' (when I use the > function) did you, by any chance, name your test script "pickle.py" ? From Serge.Orlov at gmail.com Mon Apr 17 05:12:04 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 17 Apr 2006 02:12:04 -0700 Subject: attaching an excel file using MIME in smtp In-Reply-To: References: Message-ID: <1145265124.143627.46220@g10g2000cwb.googlegroups.com> Kun wrote: > does anyone know how to attach an excel file to send out using smtplib > and MIME? There is an example in the python documentation how to send entire content of a directory: http://docs.python.org/lib/node597.html From amy.berry at cox.net Mon Apr 10 22:21:35 2006 From: amy.berry at cox.net (ACB) Date: Mon, 10 Apr 2006 19:21:35 -0700 Subject: Saving files from post data via sys.stdin Message-ID: I am rewriting an existing PERL script I wrote several months ago. It is a script that is used as the action for a form containing several type="file" inputs. The script is run unbuffered and writes the data from sys.stdin to a file which is stat'ed by another script called asyncornously from javascript. In the end I am able to make a progress bar for file uploads via http. Anyway, I have printed sys.stdin to a file and looked at it afterward. This is what is looks like -----------------------------126591649570 Content-Disposition: form-data; name="userid" myUserid -----------------------------126591649570 Content-Disposition: form-data; name="ulimage"; filename="bc12.jpg" Content-Type: image/jpeg binary data of jpeg -----------------------------126591649570 Content-Disposition: form-data; name="ulimage"; filename="" Content-Type: image/jpeg -----------------------------126591649570 Content-Disposition: form-data; name="ulimage"; filename="" Content-Type: image/jpeg -----------------------------126591649570 Content-Disposition: form-data; name="sessionid" mySessionid Normally, I use cgi.FieldStorage() and access the values via calls like form = cgi.FieldStorage() sessionid = form["sessionid"].value What is the best method for accessing the various variables and their respective values so I can save the files one at a time? Is there some class that can take this input and make it easier to deal with? I need to save each of the ulimage values as individual images and gain access to the values of sessionid and userid. Thanks Amy From paddy3118 at netscape.net Sun Apr 9 03:24:31 2006 From: paddy3118 at netscape.net (Paddy) Date: 9 Apr 2006 00:24:31 -0700 Subject: Automated Graph Plotting in Python In-Reply-To: <1144552132.926125.222210@i39g2000cwa.googlegroups.com> References: <1144552132.926125.222210@i39g2000cwa.googlegroups.com> Message-ID: <1144567471.260970.126570@u72g2000cwu.googlegroups.com> Hi, I saw you mentioned gnuplot and did a search on Google of 'gnuplot python-wrapper' which lead me eventually to: http://gnuplot-py.sourceforge.net/ I have not tried it, but if you would try it and report back if it works that might help someone else too. - Cheerio, Paddy. From nogradi at gmail.com Mon Apr 17 08:20:17 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Mon, 17 Apr 2006 14:20:17 +0200 Subject: CGI scripts In-Reply-To: <5f56302b0604170518n405f1aa6uab4c2444a3e4ca40@mail.gmail.com> References: <1145270724.641162.164490@e56g2000cwe.googlegroups.com> <5f56302b0604170518n405f1aa6uab4c2444a3e4ca40@mail.gmail.com> Message-ID: <5f56302b0604170520w1fd197ffr3bb709db548ead5b@mail.gmail.com> > > Can I use Python for CGI scripts. It is telling me to use Perl and I > > don't know any > > > > To be honest I don't really no what CGI scripts are (soz) > > > > I have purchased a domain name of my ISP PIPEX and 100MB space > > > > And I don't know what I can do with it now I just realized that you also mentioned having a 100MB quota, so probably your pages will be served by your ISP. Then the best thing is to ask your ISP if it hosts python or not. From kent at kentsjohnson.com Tue Apr 4 12:09:50 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Tue, 04 Apr 2006 12:09:50 -0400 Subject: scraping nested tables with BeautifulSoup In-Reply-To: <1144165142.767043.70100@g10g2000cwb.googlegroups.com> References: <1144142334.695498.293650@u72g2000cwu.googlegroups.com> <4432753a$1_2@newspeer2.tds.net> <1144165142.767043.70100@g10g2000cwb.googlegroups.com> Message-ID: <443294f6$1_1@newspeer2.tds.net> Gonzillaaa at gmail.com wrote: > Hey Kent, > > thanks for your reply. how did you exactly save the file in firefox? if > I save the file locally I get the same error. The Firefox version, among other things, turns all the funky and tags into comments. Here is a way to do the same thing with BS: import re from urllib import urlopen from BeautifulSoup import BeautifulSoup, BeautifulStoneSoup # This tells BS to turn into which allows it # to do a better job parsing this data fixExclRe = re.compile(r']+)>') BeautifulStoneSoup.PARSER_MASSAGE.append( (fixExclRe, r'') ) data = urlopen('http://www.findaproperty.com/regi0018.html').read() soup = BeautifulSoup(data) priceGuide = soup('table', dict(bgcolor="e0f0f8", border="0", cellpadding="2", cellspacing="2", width="150"))[1] print priceGuide Kent From eric_brunel at despammed.com Thu Apr 27 09:13:11 2006 From: eric_brunel at despammed.com (Eric Brunel) Date: Thu, 27 Apr 2006 15:13:11 +0200 Subject: How to align the text of a Listbox to the right References: <1146130550.583881.149820@g10g2000cwb.googlegroups.com> Message-ID: On 27 Apr 2006 02:35:50 -0700, Leonardo da Vinci wrote: > Greetings gentlemen and ladies, > I have a question: in Tkinter, how to align a Listbox entry (i.e. a > line of text) to the right? In a real Listbox, the answer is simple: you can't. What are you trying to do? Maybe there is another widget more suited to your needs. -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From dananrg at yahoo.com Wed Apr 5 16:44:48 2006 From: dananrg at yahoo.com (dananrg at yahoo.com) Date: 5 Apr 2006 13:44:48 -0700 Subject: Filters like old skool Jive, Fudd, Valspeak... Text transformation in Python In-Reply-To: <4433b3f1$0$24162$636a55ce@news.free.fr> References: <1144237161.700762.75630@e56g2000cwe.googlegroups.com> <4433b3f1$0$24162$636a55ce@news.free.fr> Message-ID: <1144269888.887561.247620@v46g2000cwv.googlegroups.com> bruno at modulix wrote: > There's a Kant generator example in Dive Into Python: > http://diveintopython.org/xml_processing/index.html Thanks Bruno! Perhaps I could modify it to throw in some Hume and Wittgenstein, mix it all up in a syntactic / semantic blender and REALLY confuse people. Word Games indeed. :-) Or throw in stuff by whichever philosopher who wrote a book called "The Meaning of Meaning", to add some metaphoric recursion. And that what be one heck of a Frankenstenian (but only 1 part Wittgensteinian) Robo-philosopher. Dana From aahz at pythoncraft.com Wed Apr 12 09:50:18 2006 From: aahz at pythoncraft.com (Aahz) Date: Wed, 12 Apr 2006 06:50:18 -0700 Subject: REMINDER: BayPIGgies: April 13, 7:30pm (IronPort) Message-ID: <20060412135018.GA13449@panix.com> The next meeting of BayPIGgies will be Thurs, April 13 at 7:30pm at IronPort. This meeting features JJ reviewing "Professional Software Development" with discussion and newbie questions afterward. BayPIGgies meetings alternate between IronPort (San Bruno, California) and Google (Mountain View, California). For more information and directions, see http://baypiggies.net/ Before the meeting, we sometimes meet at 6pm for dinner. Discussion of dinner plans is handled on the BayPIGgies mailing list. Advance notice: We have a speaker for May. We can use speakers for June/July. Please e-mail baypiggies at python.org if you want to suggest an agenda (or volunteer to give a presentation). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "LL YR VWL R BLNG T S" From ptmcg at austin.rr._bogus_.com Thu Apr 13 17:01:33 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Thu, 13 Apr 2006 21:01:33 GMT Subject: Forms with multiple submit buttons vs 'form' objects with single 'submit' methods References: <1144956412.286214.316800@u72g2000cwu.googlegroups.com> Message-ID: wrote in message news:1144956412.286214.316800 at u72g2000cwu.googlegroups.com... > Hi all, > > I'm using pywin to write a script that will commandeer internet > explorer to go to a certain website, where it will navigate menus, post > forms, and eventually retrieve certain data. > > Here's my question: Suppose a form has more than one submit button. > Now the COM 'form' object has a 'submit' method that doesn't take any > arguments, so how do I tell it which button I want to press? > > I'll be *unbelievably* grateful, for the rest of my natural life, to > whomever has the answer to this. > > (Yeah, I realize it's more of a COM question than a Python question. > If you know of a more suitable group, or a website where such questions > are dealth with then by all means redirect me. I'll be exceedingly > grateful, though perhaps not for the rest of my natural life.) > > Neil > Perhaps instead of trying to contort IE to y From bignose+hates-spam at benfinney.id.au Tue Apr 4 18:17:07 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 05 Apr 2006 08:17:07 +1000 Subject: tuple syntax ',' (ending in comma?) References: <1144149532.845574.191690@e56g2000cwe.googlegroups.com> Message-ID: <87d5fxugt8.fsf@benfinney.id.au> "Michael Yanowitz" writes: > I am still relatively new to Python. I am confused by the syntax > for tuples. Well, it's reassuring to know that this is still as confusing for newcomers now as it was when I started. > File "scene.py", line 256, in readData > thread.start_new_thread(read_data_thread, (strDataFilename)) > TypeError: 2nd arg must be a tuple Yes, parentheses are not sufficient (and often are unnecessary) to make a tuple. The important syntax for a tuple is the comma. > The way I fixed this error was I added an extra , (comma) to the > tuple: > thread.start_new_thread(read_data_thread, (strDataFilename,)) That's the correct way to do it, yes. > I am just confused by the syntax. I am used to a comma meaning > that there should be another parameter after the comma and if no > additional parameter the comma would not be necessary. This is a known wart, one that many people would like to see fixed. For more discussion (which will likely be repeated in this thread), see this thread from around this time last year: -- \ "Speech is conveniently located midway between thought and | `\ action, where it often substitutes for both." -- John Andrew | _o__) Holmes, _Wisdom in Small Doses_ | Ben Finney From aleaxit at yahoo.com Mon Apr 3 11:32:08 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 3 Apr 2006 07:32:08 -0800 Subject: "definitive" source on advanced python? References: <1144040231.239622.159630@j33g2000cwa.googlegroups.com> <1hd6vcf.upjvx07fad4bN%aleaxit@yahoo.com> <1144045711.723349.231460@t31g2000cwb.googlegroups.com> Message-ID: <1hd7jcu.1fm6z4hqilmcvN%aleaxit@yahoo.com> vdrab wrote: > Thank you. > > The original question was not meant to sound particularly arrogant, and > as you point out > a book covering ONLY things like metaprogramming would probably be > pretty useless in its own way. There's a niche market for such books -- "Putting Metaclasses to Work", for example, an out-of-print book that's about a funky dialect of C++, did influence the design of Python's new object model, since Guido read it at just the right time. But, the book IS out of print and the language it describes is dead, which are cautionary signs;-). > I have been using python on and off for > about a year or so but still find myself staring at some of the funky > recipes at the aspn cookbook site, not knowing which way is up. > A good reference seems to be hard to come by, hence the question. > Thanks for the link, I will have a look at some of the material. You're welcome! Besides the 2nd edition of the Nutshell, for which you should not hold your breath (it's months away yet), and the presentations on my site, there's a fair amount of material in the 2nd edition of the printed Cookbook -- we put a immense amount of work into selecting, discussing, explaining, *and* shoring up the recipes presented there, most particularly the "black magic" ones (look especially for the two chapters whose introductions Raymond Hettinger wrote, both the introductions and contents are quite instructive). But, the Cookbook is mostly about examples/uses of language and library feaures, not a *reference* to them. Alex From ziga.seilnacht at gmail.com Fri Apr 21 10:32:30 2006 From: ziga.seilnacht at gmail.com (Ziga Seilnacht) Date: 21 Apr 2006 07:32:30 -0700 Subject: are docstrings for variables a bad idea? References: <1145615763.943050.170950@j33g2000cwa.googlegroups.com> <1145626181.891190.31080@i39g2000cwa.googlegroups.com> <1145626471.962583.70670@j33g2000cwa.googlegroups.com> Message-ID: <1145629950.790341.236520@v46g2000cwv.googlegroups.com> jelle wrote: > Hi Michele, > > Thanks for pointing that out, cool! > > I would argue -even- that is too much programming effort. > Like method docstring, variables docstrings should be effortless to > write. I don't know what exactly do you mean with variable docstrings, but if you just want to add docstrings to instance's data attributes, you can use something like this: """ This module is useful for documenting data attributes. Example: >>> class C(object): ... foo = attr('a common attribute in examples') ... bar = attr('this one has a name for nicer errors', 'bar') ... baz = attr('and this one has a default value', default=1) ... def __init__(self, foo=None, bar=None, baz=None): ... if foo is not None: ... self.foo = foo ... if bar is not None: ... self.bar = bar ... if baz is not None: ... self.baz = baz ... >>> C.foo attr(doc='a common attribute in examples', name='', default=NoDefault) >>> C.foo.__doc__ 'a common attribute in examples' >>> C.bar.__doc__ 'this one has a name for nicer errors' >>> C.baz.__doc__ 'and this one has a default value' >>> c = C() >>> c.foo Traceback (most recent call last): ... AttributeError: 'C' object has no attribute '' >>> c.bar Traceback (most recent call last): ... AttributeError: 'C' object has no attribute 'bar' >>> c.baz 1 >>> d = C(1, 2, 3) >>> d.foo 1 >>> d.bar 2 >>> d.baz 3 """ class Marker(object): def __init__(self, representation): self.representation = representation def __repr__(self): return self.representation _NoDefault = Marker('NoDefault') class attr(object): def __init__(self, doc='', name='', default=_NoDefault): self.__doc__ = doc self.name = name self.default = default def __repr__(self): s = "attr(doc=%r, name=%r, default=%r)" return s % (self.__doc__, self.name, self.default) def __get__(self, obj, objtype): if obj is None: return self if self.default is _NoDefault: msg = "%r object has no attribute %r" raise AttributeError(msg % (objtype.__name__, self.name)) return self.default if __name__ == '__main__': import doctest doctest.testmod() From thn at mail.utexas.edu Wed Apr 5 22:46:12 2006 From: thn at mail.utexas.edu (Thomas Nelson) Date: 5 Apr 2006 19:46:12 -0700 Subject: python on Mac In-Reply-To: <1hdc51n.1qgtjne1mduk7gN%aleaxit@yahoo.com> References: <1144284073.446005.53950@t31g2000cwb.googlegroups.com> <1hdc51n.1qgtjne1mduk7gN%aleaxit@yahoo.com> Message-ID: <1144291572.151260.56700@j33g2000cwa.googlegroups.com> Thanks to you both. I downloaded the dmg suggested, and trustingly typed: sudo rm /usr/bin/python sudo ln -s /usr/local/bin/python2.4 /usr/bin/python And now my command line and scripts behave the way I expect. Thanks again. THN From richie at entrian.com Wed Apr 26 11:10:55 2006 From: richie at entrian.com (Richie Hindle) Date: Wed, 26 Apr 2006 16:10:55 +0100 Subject: wxPython and twisted problem In-Reply-To: <539a7fb0604260742l6fabbca5g2f8fe9310d08cce0@mail.gmail.com> References: <539a7fb0604260742l6fabbca5g2f8fe9310d08cce0@mail.gmail.com> Message-ID: [Chris] > [we] already tried posting our problem > on comp.lang.python but we didn't receive a successful reply so I thought I > would try the mailing list. [A bit OT but worth pointing out] The mailing list and the newsgroup gateway to each other - everything sent to one also goes to the other (in theory at least 8-) -- Richie Hindle richie at entrian.com From sschwarzer at sschwarzer.net Tue Apr 11 05:55:53 2006 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Tue, 11 Apr 2006 11:55:53 +0200 Subject: ftp putting information in a variable In-Reply-To: References: Message-ID: <443B7D29.2060001@sschwarzer.net> Hi Arne, On 2006-04-08 12:44, Arne wrote: > I am looking for a way to put ftp returns in a variable. > > My OS is XP and I want to get the owner of a file. So I have to > > connect to ftp. But I am stacked with how I can receive this > information and put it in a variable. you can use a library to handle that. One of them is ftputil ( http://ftputil.sschwarzer.net/ ), which I know because I'm its author. ;-) Surely, there are alternatives. You can search the Python package index at http://www.python.org/pypi . With ftputil, you would do import ftputil host = ftputil.FTPHost(hostname, user, password) # st_uid is used by Python's os.(l)stat, but it's a string here, # not an integer user = host.stat(file_or_dir).st_uid ... host.close() This works only if the output of the FTP LIST command contains the user information (which is often the case). ftputil is pure Python and should work on OS X without problems. If you think that installing/using an additional library is overkill, you can extract the necessary parser code from the file ftp_stat.py or write your own parser. Stefan From carlosperezs at alumnos.uvigo.es Thu Apr 27 08:27:53 2006 From: carlosperezs at alumnos.uvigo.es (carlosperezs at alumnos.uvigo.es) Date: Thu, 27 Apr 2006 14:27:53 +0200 Subject: Doubt with wx.ListCtrl Message-ID: <1146140873.4450b8c93bb70@correoweb.uvigo.es> I have programmed this code: # self ist a panel self.partListCtrlMarks = wx.ListCtrl(self.panel, -1, style = wx.LC_REPORT) self.Bind(wx.EVT_LIST_ITEM_SELECTED,self.OnSelectedItemList,self.partListCtrlMarks) vs.Add(self.partListCtrlMarks, 1, wx.EXPAND | wx.ALL, 4) self.partListCtrlMarks.InsertColumn(0, "Name") self.partListCtrlMarks.InsertColumn(1, "Note") self.partListCtrlMarks.SetColumnWidth(1, 80) later I have this... idx = self.partListCtrlMarks.GetItemCount() self.partListCtrlMarks.InsertStringItem(idx, "Can embestido") self.partListCtrlMarks.SetStringItem(idx, 1, "De como a cabra smbiste o can") With self.partListCtrl.GetItemText(idx) I get only "Can embestido" which is in first column. My doubt is: How can I get the second column text "De como a cabra smbiste o can". --oOo-----------------------------------------------------------------oOo-- Servicio de acceso ? correo electr?nico v?a web da Universidade de Vigo Servicio de acceso al correo electr?nico v?a web de la Universidad de Vigo Servicios Inform?ticos [ http://si.uvigo.es ] Universidade de Vigo [ http://www.uvigo.es ] URL: https://correoweb.uvigo.es From steven.bethard at gmail.com Tue Apr 18 17:52:07 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 18 Apr 2006 15:52:07 -0600 Subject: Updated PEP 359: The make statement In-Reply-To: <_aydnYpYE_rjuNjZRVn-og@comcast.com> References: <_aydnYpYE_rjuNjZRVn-og@comcast.com> Message-ID: Steven Bethard wrote: > I've updated PEP 359 with a bunch of the recent suggestions. The > patch is available at: > http://bugs.python.org/1472459 > and I've pasted the full text below. > > I've tried to be more explicit about the goals -- the make statement > is mostly syntactic sugar for:: > > class : > __metaclass__ = > > > so that you don't have to lie to your readers when you're not actually > creating a class. I've also added some new examples and expanded the > discussion of the old ones to give the statement some better > motivation. And I've expanded the Open Issues discussions to consider > a few alternate keywords and to indicate some of the difficulties in > allowing a ``__make_dict__`` attribute for customizing the dict in > which the block is executed. Guido has pronounced on this PEP: http://mail.python.org/pipermail/python-3000/2006-April/000936.html Consider it dead. =) STeVe From nobody at 127.0.0.1 Wed Apr 26 00:34:53 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 26 Apr 2006 04:34:53 GMT Subject: MinGW and Python References: <1145861223.509630.247350@y43g2000cwc.googlegroups.com> <444C79D7.4060007@v.loewis.de> <1145968025.903148.140700@i39g2000cwa.googlegroups.com> <1heca3f.14i9v2akwb61sN%aleaxit@yahoo.com> <1fs3g.75522$dW3.69605@newssvr21.news.prodigy.com> <1hed99c.v7rg17w0nvzrN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > I assume you mean "compare pybench on Python 2.4.3 compiled under" etc. Yep > Unfortunately, I suspect the ex-officio gcc defenders will only react by > finding yet another quibble (anything to avoid admitting that gcc may > not be as good at optimizing as a _Microsoft_ product -- perish the > thought!), therefore I'm disinclined to invest my scarce free time in > that particular endeavour. No problem. I don't expect anyone to follow through, it was more a suggestion to forestall rampant speculation. :) From enterr at gmail.com Fri Apr 7 22:40:34 2006 From: enterr at gmail.com (Atanas Banov) Date: 7 Apr 2006 19:40:34 -0700 Subject: Characters contain themselves? In-Reply-To: References: Message-ID: <1144464034.756319.233030@z34g2000cwc.googlegroups.com> congratulations for (ostensibly) discovering the Barber's paradox (if the village barber shaves all and only those who don't shave tehmselves, who shaves the barber? http://en.wikipedia.org/wiki/Barber_paradox) in python ! :-D as far as i see it, you complaint is not just that any string X contains itself but that string X can contain another string Y (i.e. object of class string to contain another of class string) - where you understand "contain" as per the operator "in" to be set-theory operator, when in fact the meaning put for strings is instead "has a substring". therefore your grudge is not just with 'a' in 'a' but also with 'a' in 'abcd' here is excerpt from the reference manual: ---------------------------------------- The operators in and not in test for set membership. x in s evaluates to true if x is a member of the set s, and false otherwise. x not in s returns the negation of x in s. The set membership test has traditionally been bound to sequences; an object is a member of a set if the set is a sequence and contains an element equal to that object. However, it is possible for an object to support membership tests without being a sequence. In particular, dictionaries support membership testing as a nicer way of spelling key in dict; other mapping types may follow suit. For the list and tuple types, x in y is true if and only if there exists an index i such that x == y[i] is true. For the Unicode and string types, x in y is true if and only if x is a substring of y. An equivalent test is y.find(x) != -1. Note, x and y need not be the same type; consequently, u'ab' in 'abc' will return True. Empty strings are always considered to be a substring of any other string, so "" in "abc" will return True. ---------------------------------------- it is apparent "in" was overriden for strings for convenience's sake, not to get freaky on the therory of sets. what can you do about it? well, you can check for string type specifically but there are no guarantees in life: someone else can define new type with "in" that behaves like that: say "interval(x,y)", where "interval(x,y) in interval(a,b)" checks if [x,y] is a sub-interval of [a,b] - very intuitive - but there you have the problem again! or you can specifically check if the objects are from a "semanthically supported group" of classes - but that will hamper authomatic extension by introducing new types. - Nas WENDUM Denis 47.76.11 (agent) wrote: > While testing recursive algoritms dealing with generic lists I stumbled > on infinite loops which were triggered by the fact that (at least for my > version of Pyton) characters contain themselves.See session: > > >>> 'a' is 'a' > True > >>> 'a' in 'a' > True > >>> 'a' in ['a'] > True > >>> .... > > Leading to paradoxes and loops objects which contain themselves (and > other kinds of monsters) are killed in set theory with the Axiom of > Foundation:=) > > But let's go back to more earthly matters. I couldn't find any clue in a > python FAQ after having googled with the following "Python strings FAQ" > about why this design choice and how to avoid falling in this trap > without having to litter my code everywhere with tests for stringiness > each time I process a generic list of items. > > Any hints would be appreciated. From markscala at gmail.com Mon Apr 24 12:20:49 2006 From: markscala at gmail.com (markscala at gmail.com) Date: 24 Apr 2006 09:20:49 -0700 Subject: error In-Reply-To: <4b44hbFt29klU1@uni-berlin.de> References: <1145886838.594093.102670@j33g2000cwa.googlegroups.com> <4b44hbFt29klU1@uni-berlin.de> Message-ID: <1145895649.203923.101370@u72g2000cwu.googlegroups.com> thanks for the heads up. I read other posts on this error, but it's unclear to me whether the following will be a problem as well. Suppose I break up my very long module into smaller modules and import them into another module 'main'. Will I get the same error running main if the total number of lines in the smaller modules is > 10k? thanks. From recordus at gmail.com Wed Apr 5 19:16:13 2006 From: recordus at gmail.com (Recoruds) Date: 5 Apr 2006 16:16:13 -0700 Subject: how to convert string In-Reply-To: <1144261976.640631.9280@e56g2000cwe.googlegroups.com> References: <1144261976.640631.9280@e56g2000cwe.googlegroups.com> Message-ID: <1144278973.874578.118730@i40g2000cwc.googlegroups.com> for i in xrange(10): print i, this could be fine. From jzgoda at o2.usun.pl Mon Apr 24 15:41:46 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Mon, 24 Apr 2006 21:41:46 +0200 Subject: Recommended IDE for creating GUI? In-Reply-To: <124idf0362d75dd@corp.supernews.com> References: <124idf0362d75dd@corp.supernews.com> Message-ID: Marty Christion napisa?(a): > What are some good free or inexpensive (<$50) IDE's for learning how to > program and create GUI's for Python? I'm pretty good with the simple > programming aspect of the language, but I'm a little mystified by the world > of GUI's, and the options available in python. Glade is a GUI builder for GTK and PyGTK. Free, cost free, OpenSource, multiplatform. Not as easy as Delphi, but with Python can do wonders. -- Jarek Zgoda http://jpa.berlios.de/ From praveenkumar.117 at gmail.com Thu Apr 6 05:11:25 2006 From: praveenkumar.117 at gmail.com (praveenkumar.117 at gmail.com) Date: 6 Apr 2006 02:11:25 -0700 Subject: How to catch python's STDOUT Message-ID: <1144314684.986767.131650@j33g2000cwa.googlegroups.com> Hi, Can someone help me by suggesting how to capture python's STDOUT. I doesn't want the python's output to get displayed on the screen. From dinov at exchange.microsoft.com Fri Apr 28 14:20:42 2006 From: dinov at exchange.microsoft.com (Dino Viehland) Date: Fri, 28 Apr 2006 11:20:42 -0700 Subject: Undocumented alternate form for %#f ? Message-ID: <4039D552ADAB094BB1EA670F3E96214E02ADDBE6@df-foxhound-msg.exchange.corp.microsoft.com> I'm assuming this is by-design, but it doesn't appear to be documented: >>> '%8.f' % (-1) ' -1' >>> '%#8.f' % (-1) ' -1.' The docs list the alternate forms, but there isn't one listed for f/F. It would seem the alternate form for floating points is truncate & round the floating point value, but always display the . at the end. Is that correct? Do you want to help develop Dynamic languages on CLR? (http://members.microsoft.com/careers/search/details.aspx?JobID=6D4754DE-11F0-45DF-8B78-DC1B43134038) From kelie.feng at gmail.com Fri Apr 14 05:17:50 2006 From: kelie.feng at gmail.com (Kelie) Date: 14 Apr 2006 02:17:50 -0700 Subject: requestion regarding regular expression Message-ID: <1145006270.632156.144790@j33g2000cwa.googlegroups.com> Hello, I'm trying to analyze some autolisp code with python. In the file to be analyzed there are many functions. Each function begins with a "defun" statement. And before that, there may or may not have comment line(s), which begins with ";". My goal is to export each function into separate files, with comments, if there is any. Below is the code that I'm struggling with: [code] path = "C:\\AutoCAD\\LSP\\Sub.lsp" string = file(path, 'r').read() import re pat = "\\;+.+\\n\\(DEFUN" p = re.compile(pat,re.I) iterator = p.finditer(string) spans = [match.span() for match in iterator] for i in range(min(15, len(spans))): print string[spans[i][0]:spans[i][1]] [/code] The code above runs fine. But it only takes care of the situation in which there is exactly one comment line above the "defun" statement. How do I repeat the sub-pattern "\\;+.+\\n" here? For example if I want to repeat this pattern 0 to 10 times, I know "\\;+.+\\n{0:10}\\(DEFUN" does not work. But don't know where to put "{0:10}". As a work around, I tried to use pat = "|".join(["\\;+.+\\n"*i+ "\\(DEFUN" for i in range(11)]), and it turned out to be very slow. Any help? Thank you. Kelie From jhefferon at smcvt.edu Fri Apr 21 17:33:26 2006 From: jhefferon at smcvt.edu (Jim) Date: 21 Apr 2006 14:33:26 -0700 Subject: Read and extract text from pdf In-Reply-To: References: Message-ID: <1145655206.352208.138920@u72g2000cwu.googlegroups.com> There is a pdftotext executable, at least on Linux. From sturlamolden at yahoo.no Tue Apr 25 10:30:36 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 25 Apr 2006 07:30:36 -0700 Subject: Hooking things up in GUI application In-Reply-To: References: <1145965957.073830.320580@y43g2000cwc.googlegroups.com> Message-ID: <1145975436.076511.24020@i40g2000cwc.googlegroups.com> Ryan Ginstrom wrote: > > Behalf Of sturlamolden > > If you use PyGTK (it also runs on Windows), you can design > > the GUI with > > GLADE and then use libglade to import the gui as an xml-resource. > > Yes, I've tried something similar with wxGlade. Nice, but it doesn't seem to > remove the most tedious work -- hooking up handlers (although it does help > here, at the cost of some behind-the-scenes magic), It does, there is just *one* line of code for hooking up all the handlers: win.signal_autoconnect(something) That is one line of code for the entire window, not one line of code for every widget in the window. Even if your window contains 100 widgets (buttons, sliders, menus, etc), this hooks up the handlers for every one of them. You just call .signal_autoconnect once. This single line of code does the job of all the message map macros you would write in MFC, Fox and wxWidgets. signal_autoconnect does what it says, it autoconnects the signal handlers. How can that be tedious? Here is an advice: just be lazy. In particular: * Don't create write a dictionary mannually and feed it to signal_autoconnect. Many tutorials do that. It is silly: it is tedious, it is superfluous bloat, and the job has in fact aldready been done. Write a class instead. Guido has made sure every class has a dictionary. Just make sure you have class methods with names corresponding to the signals. Pass a class reference to signal_autoconnect. * Don't grab references for every widget out of the xml. I've seen done that in many tutorials too. It is silly. Just ask the xml for a reference when you need one. The xml resources will store the widget references for you, you don't need to save them anywhere else. Storing a hundred widget references as class variables is tedious and superfluous work, and does not do anything except bloating and slowing your code. > and getting data into and out of GUI widgets. It does not save you the job of writing the GUI handlers! It saves you the job of coding the GUI (delegate that job to a graphical designer!) and hooking up the handlers. But you still need to *write* the handlers. > That's the kind of boilerplate code that makes GUI > development a pain in my opinion -- the actual GUI design/layout isn't so > bad, especially with the spacer layout concept. At least you get the GUI design out of the rest of your code. The application logic still need to be there. From ldo at geek-central.gen.new_zealand Sat Apr 22 18:24:04 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 23 Apr 2006 10:24:04 +1200 Subject: another question about buffers References: <1145645420.014839.260540@g10g2000cwb.googlegroups.com> <1145711394.139083.275100@i39g2000cwa.googlegroups.com> Message-ID: In article <1145711394.139083.275100 at i39g2000cwa.googlegroups.com>, nephish at xit.net wrote: >i think it may be, Moral: don't use arbitrary values as booleans. From invalidemail at aerojockey.com Wed Apr 26 17:33:00 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 26 Apr 2006 14:33:00 -0700 Subject: A defense for bracket-less code In-Reply-To: <72Q3g.20605$tN3.18334@newssvr27.news.prodigy.net> References: <72Q3g.20605$tN3.18334@newssvr27.news.prodigy.net> Message-ID: <1146087180.746037.171730@i39g2000cwa.googlegroups.com> Edward Elliott wrote: > Stelios Xanthakis wrote: > > Also, I think that perl does that because otherwise code like > > > > if ($x) $y++ if $z; else $z--; > > > > would be even more confusing :) > > With or without braces, that's not legal code. A one-line if can't be > followed by an else. Thus proving the original claim about it being confusing. :) I think he intended it to parse this way: if ($x) { $y++ if $z; } else { $z--; } Carl Banks From nogradi at gmail.com Sun Apr 30 16:12:53 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Sun, 30 Apr 2006 22:12:53 +0200 Subject: setting file permissions on a web server In-Reply-To: <4454f1e1$0$1963$c3e8da3@news.astraweb.com> References: <445449f6$0$9437$c3e8da3@news.astraweb.com> <4454f1e1$0$1963$c3e8da3@news.astraweb.com> Message-ID: <5f56302b0604301312h536165d8sef59039625caf061@mail.gmail.com> > > In short, chmod refers to local files so wherever you run it it will > > refer to files on that machine. You run it simply by typing it in a > > shell as a user who has privilage to perform the operatation, which > > can mean you have to be an owner of the file but if you are root you > > can do it in any case. Depending on your ftp, scp, http or whatever > > method you use to transfer files the file permissions may or may not > > change during the transfer. If permissions are kept intact you can > > chmod on your local machine and then transfer, if they are not then > > you transfer first and chmod on the server. When you transfer files > > from a windows machine to *nix it again depends on the particular > > method you choose how the permissions will be set. > > Thanks, but I'm still a little confused. Since I'm running Windows, I > assume that I can't run the chmod line on my own computer. Correct, chmod is a *nix command. > My web server > uses Unix, but is it possible for me to have access to a command line > for the server? This depends on your arrangements with your web server provider. Perhaps you are allowed to ssh into that machine, perhaps not, you need to ask your provider. In case you can use ssh, then you can log in with putty (an ssh client for windows, grab it from here: http://www.chiark.greenend.org.uk/~sgtatham/putty/) and you will have a command line on the server so you can run chmod there. > I didn't know that was possible for basic web hosting plans (I'm using 1and1 right now). I have absolutely no experience with public web hosting but I guess some might provide ssh-ing possibilities although I imagine most don't. > I suppose I could write a script that would set the permissions of all > the files in a particular folder on my computer to 755, but is there a > Windows equivalent command for chmod to do this? I have next to zero experience with windows but as far as I know windows doesn't have file permissions at all (anyone, please correct me if I'm wrong :)) so in windows land it doesn't make any sense to "change file permissions". Even if it has some sort of a notion of file permissions I wouldn't know how that gets translated into unix. > Or am I stuck having to do it on the server side? I guess so. But that's not a terribly big problem even if you can't use ssh. What I would do is write a script (in python of course :)) that does the file permission changing and run that script over the web. Since this can have serious security implications my strategy would be to place this script somewhere which is not reachable through the web and only relocate it to a web accessible directory when you want to run it over the web, and when you are done, you place it back to its secure location so nobody can reach it. You can find out how to write this script from http://docs.python.org/lib/os-file-dir.html HTH :) From robert.kern at gmail.com Mon Apr 3 21:41:04 2006 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 03 Apr 2006 20:41:04 -0500 Subject: [ANN] markup.py - 1.2 - an HTML/XML generator In-Reply-To: <1144112722.28978.11.camel@kenshin.CASA> References: <5f56302b0604031509r51af902dh2e908561bbf78d44@mail.gmail.com> <1144103244.20245.2.camel@kenshin.CASA> <1144112722.28978.11.camel@kenshin.CASA> Message-ID: Felipe Almeida Lessa wrote: > Em Seg, 2006-04-03 ?s 17:20 -0700, Erik Max Francis escreveu: > >>Felipe Almeida Lessa wrote: >> >> >>>IMHO, it's strange and ugly. Besides, AFAIK everybody uses "cls" or >>>"class_", this is the first place I see "klass", so this breaks >>>consistency, too. But that's just my opinion... >> >>A quick Google Groups search indicates that `klass` is more commonly >>mentioned than `class_`. > > > Well... > > $ pwd > /usr/lib/python2.4/site-packages > $ grep -re klass . | wc -l > 274 > $ grep -re class_ . | wc -l > 897 > $ calc 897 / 274 > ~3.27372262773722627737 > $ cd /tmp > $ svn co http://svn.python.org/projects/python/trunk/ > A trunk/Python > A trunk/Python/codecs.c > A trunk/Python/thread_foobar.h > ... [loads of files] ... > A trunk/pyconfig.h.in > A trunk/install-sh > U trunk > Gerado c?pia de trabalho para revis?o 43612. > $ grep -re klass trunk/ | wc -l > 534 > $ grep -re class_ trunk/ | wc -l > 1720 > $ calc 1720 / 534 > ~3.22097378277153558052 > $ grep -re klass trunk/Lib/ | wc -l > 340 > $ grep -re class_ trunk/Lib/ | wc -l > 1188 > $ calc 1188 / 340 > ~3.49411764705882352941 > > For me that's enough. "class_" is used at least three times more than > "klass". Besides, as Scott pointed out, "class_" is prefered by the > guidelines too. __class__ -- Robert Kern robert.kern at gmail.com "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From mwilson-to at sympatico.ca Thu Apr 13 08:19:44 2006 From: mwilson-to at sympatico.ca (Mel Wilson) Date: Thu, 13 Apr 2006 08:19:44 -0400 Subject: list.clear() missing?!? In-Reply-To: References: <1144767680.583085.310160@v46g2000cwv.googlegroups.com> <1144792144.168802.146310@i39g2000cwa.googlegroups.com> <1144870852.886477.238570@u72g2000cwu.googlegroups.com> Message-ID: Steven D'Aprano wrote: > Convenience and obviousness are important for APIs -- that's why lists > have pop, extend and remove methods. The only difference I can see between > a hypothetical clear and these is that clear can be replaced with a > one-liner, while the others need at least two, e.g. for extend: > > for item in seq: > L.append(item) Both extend and append have one-line slice equivalents, except that the equivalents have to keep referring to the length of the list.. (have to keep finding the len function.) Mel. From johnjsal at NOSPAMgmail.com Wed Apr 5 10:07:55 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 05 Apr 2006 14:07:55 GMT Subject: using range() in for loops In-Reply-To: <_NOYf.356201$ey3.10665089@phobos.telenet-ops.be> References: <443324dc$0$11257$c3e8da3@news.astraweb.com> <_NOYf.356201$ey3.10665089@phobos.telenet-ops.be> Message-ID: <%aQYf.1916$No6.42173@news.tufts.edu> Roel Schroeven wrote: > In many cases loops really are for iterating over sequences; more so > than I realized when using for loops in C or C++. In these cases, > Python's for statement works better than C-style loops. And if you > really need to do something a certain number of times, there's still > range() or xrange() to do it. Yeah, I'm starting to see the distinction now. I think one thing that confused me was that C# had two separate loops for these functionalities, the for loop and the foreach loop (which is equivalent to Python's for). But even when just doing something a number of times (C#'s for, Python's for), it looks much cleaner in Python because you don't have the long, messy three-part for statement. From cygnus at cprogrammer.org Tue Apr 25 23:02:45 2006 From: cygnus at cprogrammer.org (Jonathan Daugherty) Date: Tue, 25 Apr 2006 20:02:45 -0700 Subject: Drawing charts and graphs. Message-ID: <20060426030245.GP7561@vulcan.cprogrammer.org> Hello, I'm looking at a number of chart-drawing libraries and modules for Python and I'd like to know which one people tend to consider the best. I've tried gdchart2 but its interface seems somewhat limited, and pychart looks nice. I'd like to find something that will let me draw graphs similar to those created by RRDtool. Thanks! -- Jonathan Daugherty http://www.parsed.org From Bulkan at gmail.com Tue Apr 25 19:30:06 2006 From: Bulkan at gmail.com (placid) Date: 25 Apr 2006 16:30:06 -0700 Subject: cmd module "busy waiter" ? In-Reply-To: <4a0p42p0g0tuu1iqt0dlggt88b3bl3o19k@4ax.com> References: <1145861391.884637.280020@i39g2000cwa.googlegroups.com> <4a0p42p0g0tuu1iqt0dlggt88b3bl3o19k@4ax.com> Message-ID: <1146007806.488148.308080@j33g2000cwa.googlegroups.com> Dennis Lee Bieber wrote: > On 23 Apr 2006 23:49:51 -0700, "placid" declaimed the > following in comp.lang.python: > > > Just wondering if the cmd module in python uses "busy waiting" for > > "polling" user command input as this is inefficient. > > > Use the Source... > > At least on 2.3.x... > > Last paragraph of the docstring: > > > These interpreters use raw_input; thus, if the readline module is > loaded, > they automatically support Emacs-like command history and editing > features. i dont know Emacs, and im using Windows XP (cant find readline module, only for *nix ), does that mean it still busy waits... > -- > > ============================================================== < > > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > > wulfraed at dm.net | Bestiaria Support Staff < > > ============================================================== < > > Home Page: < > > Overflow Page: < From aleaxit at yahoo.com Mon Apr 3 02:52:57 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 2 Apr 2006 22:52:57 -0800 Subject: "definitive" source on advanced python? References: <1144040231.239622.159630@j33g2000cwa.googlegroups.com> Message-ID: <1hd6vcf.upjvx07fad4bN%aleaxit@yahoo.com> vdrab wrote: > Hi all, > > Is there some sort of coherent source (dead tree format, maybe?) on > some of the more advanced features > of python (decorators, metaclasses, etc)? I'm sort of looking for a > python book that actually gets to the good stuff at some point, without > first spending 6 chapters on how to append ints to a list. I can't seem > to find any. "Python in a Nutshell" covers some advanced features (including both of those you mention, in the 2nd edition due out in a few months) in Chapter 5, but it may not be advanced enough for your desires (since, in Chapter 4, it _does_ cover, inter alia, the list.append method). I do not know of any book that ONLY cover exoterica and just assumes that the reader has complete, thorough and correct understanding of all the basics (some of which are subtler than most people think). Many of my presentations, available at www.aleax.it in PDF form, do focus strictly on some advanced subjects. However, you get just the PDF form of the slides, not the way I normally present the materials (I do not think any of my presentations has been filmed, yet). Alex From cesugden at gmail.com Thu Apr 27 11:03:18 2006 From: cesugden at gmail.com (Chris) Date: 27 Apr 2006 08:03:18 -0700 Subject: finding IP address of computer Message-ID: <1146150198.737288.37640@i40g2000cwc.googlegroups.com> How do I find and print to screen the IP address of the computer my python program is working on? From felipe.lessa at gmail.com Wed Apr 19 20:21:43 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Wed, 19 Apr 2006 21:21:43 -0300 Subject: Method Call in Exception In-Reply-To: <1145490879.789439.18030@t31g2000cwb.googlegroups.com> References: <1145490879.789439.18030@t31g2000cwb.googlegroups.com> Message-ID: <1145492503.4177.6.camel@kenshin.CASA> Em Qua, 2006-04-19 ?s 16:54 -0700, mwt escreveu: > This works when I try it, but I feel vaguely uneasy about putting > method calls in exception blocks. What do you put in exception blocks?! > So tell me, Brave Pythoneers, is this > evil sorcery that I will end up regretting, or is it just plain good > ol' Python magic? IMHO, the exception block in Python is used a lot in places where you could use an if-then-else, like your example that could be written as if internet_available(): [...] #doing some internet stuff else: alternate_method_that_doesnt_need_internet() So yes, I think there's no problem there. -- Felipe. From steve at ferg.org Sun Apr 9 14:31:38 2006 From: steve at ferg.org (Steve) Date: 9 Apr 2006 11:31:38 -0700 Subject: Best Python web-hosting? In-Reply-To: <1144605832.364688.305300@j33g2000cwa.googlegroups.com> References: <1144605832.364688.305300@j33g2000cwa.googlegroups.com> Message-ID: <1144607498.875061.90370@t31g2000cwb.googlegroups.com> http://www.python-hosting.com/ I haven't used them myself, but recent research that I did made them look like good candidates. From wrffruntre at tznvy.pbz.ROT13 Sat Apr 15 22:14:02 2006 From: wrffruntre at tznvy.pbz.ROT13 (Jesse Hager) Date: Sat, 15 Apr 2006 22:14:02 -0400 Subject: How to Convert a string into binary In-Reply-To: References: Message-ID: <1243a31lta57h1a@corp.supernews.com> The short version: def str2bin(s): return ''.join([''.join(['10'[not (m&ord(x))] for m in (128,64,32,16,8,4,2,1)]) for x in s]) Notes: Split into 3 lines for newsgroup post, 3rd line is actually the end of the 2nd. It will run as shown above. Returns digits in MSB order, to return LSB first, reverse the order of the bit weights. (1,2,4,8,16,32,64,128) To support 16-bit Unicode, add powers of two to the bit weights up to 32768. To put a separator between digits for each character put it between first set of empty quote chars. ',' -> '00000000,11111111' To put a separator between digits of the same character, put it between the second set of empty quotes. '.' -> '0.1.0.1.0.1.0.1' This is probably slower than one based on lookup tables like the others are proposing. -- Jesse Hager email = "wrffruntre at tznvy.pbz".decode("rot13") From workbee at gmail.com Sat Apr 8 20:15:57 2006 From: workbee at gmail.com (Enigma Curry) Date: 8 Apr 2006 17:15:57 -0700 Subject: Python based 'Toaster' animation like Gaim or MSN Messenger? In-Reply-To: <1144541410.956974.211730@z34g2000cwc.googlegroups.com> References: <1144541410.956974.211730@z34g2000cwc.googlegroups.com> Message-ID: <1144541757.681382.69990@u72g2000cwu.googlegroups.com> Ok, cool! There's one for wxPython called ToasterBox ( http://wiki.wxpython.org/index.cgi/ToasterBox ) I'm more familiar with pyGTK.. so if anyone knows one based on pyGTK, please let me know! :) Ryan McGuire From wuwei23 at gmail.com Wed Apr 5 22:42:22 2006 From: wuwei23 at gmail.com (alex23) Date: 5 Apr 2006 19:42:22 -0700 Subject: MOO meets Python In-Reply-To: References: Message-ID: <1144291342.367595.176500@v46g2000cwv.googlegroups.com> There's also the unfortunately named POO: http://www.strout.net/python/poo/index.html (Although that page claims it hasn't been updated since '98...) Python has already reminded me of MOO-coding in some key ways: the object model, the core libraries, the minimalism of the language. - alex23 From kent at kentsjohnson.com Tue Apr 18 06:10:31 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Tue, 18 Apr 2006 06:10:31 -0400 Subject: scanning through page and replacing all instances of 00:00:00.00 In-Reply-To: References: Message-ID: <4444bb05_2@newspeer2.tds.net> Kun wrote: > Fredrik Lundh wrote: >> "Kun" wrote: >> >>> I have a python-cgi file that pulls data from an sql database, i am >>> wondering what is the easiest way to remove all instances of >>> '00:00:00.00' in my date column. >>> >>> how would i write a python script to scan the entire page and delete all >>> instances of '00:00:00.00', would i use regular expressions? >> umm. if you're using a database, why not filter out uninteresting dates either >> in the SQL statement, or when you're building the page ? >> >> > because in my sql database, the date is only 'date' (as in yyyy-mm-dd), > only when i extract it with my python-cgi does the date turn into > (yyyy-mm-dd 00:00:00.00), thus i figured the best way to fix this > problem is to parse it after the matter. It sounds like the problem is with the way you format the date for output. Just omit the time. Kent From magnus.weimer at gmail.com Fri Apr 21 09:27:48 2006 From: magnus.weimer at gmail.com (mw) Date: 21 Apr 2006 06:27:48 -0700 Subject: Does wxWindow.MakeModal(True) work for all Windows or just frames? Message-ID: <1145626068.820781.35190@j33g2000cwa.googlegroups.com> I am using wxPython 2.6.3.0 As far as I can tell from the documentation (www.wxpython.org), MakeModal() should work for all windows, but when I do some practical tests, I can only get it to work for frames. Can anyone confirm what the status of this method is. Is it intended to work for all windows or just for frames? If it is intended to work for all windows, does anyone have some sample code to make a window within a frame modal (personally, I want to make a grid modal). /Magnus From felipe.lessa at gmail.com Fri Apr 14 18:58:54 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Fri, 14 Apr 2006 19:58:54 -0300 Subject: Problem involving sets... In-Reply-To: <1145054607.679905.36180@g10g2000cwb.googlegroups.com> References: <1145054607.679905.36180@g10g2000cwb.googlegroups.com> Message-ID: <1145055534.5694.2.camel@kenshin.CASA> Em Sex, 2006-04-14 ?s 15:43 -0700, flamesrock escreveu: > Does anyone have a simple solution???? $ python2.4 Python 2.4.3 (#2, Mar 30 2006, 21:52:26) [GCC 4.0.3 (Debian 4.0.3-1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> l1 = [['c1',1],['c2',2],['c3',4]] >>> l2 = [['c1',1],['c2',2],['c4',4],['c3',3]] >>> print [tuple(x) for x in l1] [('c1', 1), ('c2', 2), ('c3', 4)] >>> print [tuple(x) for x in l2] [('c1', 1), ('c2', 2), ('c4', 4), ('c3', 3)] >>> s1 = frozenset(tuple(x) for x in l1) >>> s2 = frozenset(tuple(x) for x in l2) >>> print s1 frozenset([('c2', 2), ('c1', 1), ('c3', 4)]) >>> print s2 frozenset([('c2', 2), ('c4', 4), ('c3', 3), ('c1', 1)]) >>> print s2-s1 frozenset([('c4', 4), ('c3', 3)]) >>> print [list(x) for x in s2-s1] [['c4', 4], ['c3', 3]] -- Felipe. From cretin at des.alpes.ch Mon Apr 10 07:41:59 2006 From: cretin at des.alpes.ch (Azolex) Date: Mon, 10 Apr 2006 13:41:59 +0200 Subject: Characters contain themselves? In-Reply-To: References: Message-ID: <443a4489$1_1@news.bluewin.ch> WENDUM Denis 47.76.11 (agent) wrote: > > While testing recursive algoritms dealing with generic lists I stumbled > on infinite loops which were triggered by the fact that (at least for my > version of Pyton) characters contain themselves. Note that the empty string is contained in all strings, including itself. >>> bool('') False >>> '' in '' True From brian at rkspeed-rugby.dk Sun Apr 16 06:13:49 2006 From: brian at rkspeed-rugby.dk (Brian Elmegaard) Date: Sun, 16 Apr 2006 12:13:49 +0200 Subject: Upgrading and modules References: <1145023656.353186.114000@z34g2000cwc.googlegroups.com> Message-ID: "BartlebyScrivener" writes: > Are you saying you're on Windows? Yes > http://www.activestate.com/Products/ActivePython/ > It's a one-click, msi install with everything you need for win32, > including IDE etc. I don't it includes every possible module, e.g., py2exe, ctypes, mysqldb, wxpython... -- Brian (remove the sport for mail) http://www.et.web.mek.dtu.dk/Staff/be/be.html http://www.rugbyklubben-speed.dk From fredrik at pythonware.com Sat Apr 15 07:06:59 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 15 Apr 2006 13:06:59 +0200 Subject: list.clear() missing?!? References: <1144767680.583085.310160@v46g2000cwv.googlegroups.com> <89iu32p2or66h7sqig37e8ur4c2rqd2s9h@4ax.com> Message-ID: "Ben C" wrote: > I used to think it assigned with things like integers, because if you > write: > > a = 5 > b = a > b += 1 > print a > > a is still 5. So it looked like a and b stored values and b got a "copy" > of a's value. But this is the wrong interpretation, > > b += 1 > > is really b = b + 1, and rebinds b. almost: "b += obj" is really "b = b.__iadd__(obj)" with "b = b + obj" as a fallback if __iadd__ isn't supported by "b". > If it weren't for the id() function I think the difference between > "variable stores value", "variable stores immutable reference" and > "variable stores copy-on-write reference" would be implementation > detail and never visible to the programmer. except when they are: >>> a = [1, 2, 3] >>> b = a >>> b += [4] >>> a [1, 2, 3, 4] >>> b [1, 2, 3, 4] From johnjsal at NOSPAMgmail.com Tue Apr 11 13:53:03 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 11 Apr 2006 17:53:03 GMT Subject: setting up mod_python handlers on a server? In-Reply-To: References: <1144766317.290453.65920@i39g2000cwa.googlegroups.com> Message-ID: <32S_f.1955$No6.42696@news.tufts.edu> Daniel Nogradi wrote: >>> and I think what you want is: >>> >>> AddHandler mod_python .psp >>> PythonHandler mod_python.psp >> This is what I have in my htaccess file (along with debugging). But >> there is also an option in the control panel to set new handlers and >> extensions on the server, but I'm not sure what to call them, so I've >> been trying several combinations, like: >> >> mod_python .psp #this wasn't there yesterday, but is now >> PythonHandler .psp >> mod_python.psp .psp >> >> You get the idea. I'm not sure if I'm even on the right track by trying >> to add new handlers though. > > Chances are that you will get much more help on the mod_python mailing > list which is at http://modpython.org/ and please send all your apache > directives referring to mod_python that way it should be easier to see > where the problem is. Thanks, I will try that. From g.horvath at gmx.at Sat Apr 15 00:47:30 2006 From: g.horvath at gmx.at (Gregor Horvath) Date: Sat, 15 Apr 2006 06:47:30 +0200 Subject: VB to Python In-Reply-To: References: Message-ID: Aleksandar Cikota schrieb: > Can someone translate the VB code to Python? > > VB code: > > Dim chsr as New DriverHelper.Chooser > chsr.DeviceType = "Telescope" > scopeProgID = chsr.Choose(scopeProgID) > Set scope = CreateObject(scopeProgID) > scope.Connected = True > (untested; late binding): import win32com.client chsr = win32com.client.Dispatch("DriverHelper.Chooser") #you may have to choose the ProdID of the class from the registry here chsr.DeviceType = "Telescope" scopeProgID = chsr.Choose(scopeProgID) scope = win32com.client.Dispatch(scopeProgID) scope.Connected = True -- Mit freundlichen Gr??en, Ing. Gregor Horvath, Industrieberatung & Softwareentwicklung Mobil: +43(0)69910879004 Fax: +43(0)1/25330333931 http://www.gregor-horvath.com -- Mit freundlichen Gr??en, Ing. Gregor Horvath, Industrieberatung & Softwareentwicklung http://www.gregor-horvath.com From __peter__ at web.de Tue Apr 11 11:47:13 2006 From: __peter__ at web.de (Peter Otten) Date: Tue, 11 Apr 2006 17:47:13 +0200 Subject: [OT] Re: a unicode question? References: <1144631034.049820.62550@u72g2000cwu.googlegroups.com> <1144633431.375745.77670@z34g2000cwc.googlegroups.com> <1144636425.117258.258620@t31g2000cwb.googlegroups.com> <1144654497.676432.263170@i39g2000cwa.googlegroups.com> <1144672526.309349.296120@j33g2000cwa.googlegroups.com> Message-ID: John Machin wrote: > ... and yes Peter, info travels faster also from China that it does > from Armenia :-()) Q: Can info travel faster from Armenia than from China? Radio Yerevan: In principle, yes. Just make sure that it doesn't go the other way round the globe or meets some friends on the way... From __peter__ at web.de Sun Apr 16 04:53:09 2006 From: __peter__ at web.de (Peter Otten) Date: Sun, 16 Apr 2006 10:53:09 +0200 Subject: multiple parameters in if statement... References: <1145148440.290181.6340@u72g2000cwu.googlegroups.com> Message-ID: Kun wrote: > mensanator at aol.com wrote: >> Kun wrote: >>> I am trying to make an if-statement that will not do anything and print >>> 'nothing entered' if there is nothing entered in a form. I have the >>> following code that does that, however, now even if I enter something >> >> Yes, but did you enter everything? >> >>> into the form, the code still outputs 'nothing entered'. >> >> The logic doesn't imply "nothing", it implies "not everything". >> The else clause will execute if ANY item is not enetered. >> >>> This violates >>> the if statement and I am wondering what I did wrong. >>> >>> if form.has_key("delete_id") and form["delete_id"].value != "" and >>> form.has_key("delete_date") and form["delete_date"].value != "" and >>> form.has_key("delete_purchasetype") and >>> form["delete_purchasetype"].value != "" and form.has_key("delete_price") >>> and form["delete_price"].value != "" and form.has_key("delete_comment") >>> and form["delete_comment"].value != "": >>> delete_id=form['delete_id'].value >>> delete_date=form['delete_date'].value >>> delete_purchasetype=form['delete_purchasetype'].value >>> delete_price=form['delete_price'].value >>> delete_comment=form['delete_comment'].value >>> else: >>> print "ERROR: Nothing entered!" >>> raise Exception >> > How do I make this so that it only prints 'nothing entered' when none of > the fields are entered? def has_data(form, fields): for field in fields: if form.has_key(field) and form[field] != "": return True return False fields = ["delete_id", "delete_date", "delete_purchasetype", "delete_price", "delete_comment"] if not has_data(form, fields): print "nothing entered" Just testing for if field in form: ... instead of if form.has_key(field) and form[field] != "": ... is probably sufficient if form is a cgi.FieldStorage. Peter From kay.schluehr at gmx.net Thu Apr 6 08:59:22 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 6 Apr 2006 05:59:22 -0700 Subject: pre-PEP: The create statement In-Reply-To: <59Wdnbd8EazRCqnZnZ2dnUVZ_vudnZ2d@comcast.com> References: <59Wdnbd8EazRCqnZnZ2dnUVZ_vudnZ2d@comcast.com> Message-ID: <1144328362.729594.173160@z34g2000cwc.googlegroups.com> Steven Bethard wrote: > Python-Version: 2.6 Have you a rough estimation how many modules will be broken when "create" is introduced as a keyword? From osv at javad.com Tue Apr 11 01:40:50 2006 From: osv at javad.com (Sergei Organov) Date: Tue, 11 Apr 2006 09:40:50 +0400 Subject: Python 3.0 or Python 3000? References: <4439aba9$0$18019$c3e8da3@news.astraweb.com> Message-ID: Dennis Lee Bieber writes: > On Mon, 10 Apr 2006 12:12:58 +0200, Benjamin Niemann > declaimed the following in comp.lang.python: >> >> That's actually the versioning scheme of TeX, currently being at 3.141592 > > My last exposure to TeX was some 15 odd years ago; and even > then it was just rudimentary stuff fed through LaTeX. It's total nonsense as LaTeX is a bunch of macros written in TeX the language. If you meant TeX the interpreter of the TeX the language (a program), then it's total nonsense again, as interpreter is not (usually) fed through anything. Latex the program just loads LaTeX macros into the TeX interpreter before the document to be processed, so one may say LaTeX is fed through TeX, but not vise versa. Anyway, it's unfair to speak of one of the most wonderful pieces of software ever written in such a tone. -- Sergei. From mxchrisp at gmail.com Wed Apr 5 23:23:01 2006 From: mxchrisp at gmail.com (Chris P) Date: Wed, 5 Apr 2006 23:23:01 -0400 Subject: Splitting a string with extra parameters Message-ID: Hello list, I just started using python and I must say I enjoy it very much. I do have an issue in which I hope to get some pointers to. I have a string, which I need to split based on a delimiter. This I know how to do. But what I cannot figure out is, take for example the following: "column 1 data", "column 2 data", "column price $2,020", "column 4 data" when splitting based on a delimiter of "," the above string gets broken up in 5 "columns" instead of 4 due to the "," in the money amount. how can I say: split string on "," delmiter except if between for example " & "? I'm sure there are other python modules out there that deal with csv/delmited strings/files but I need to do this without any additional modules. Any advice is greatly appreciated. Thanks!! -------------- next part -------------- An HTML attachment was scrubbed... URL: From michael at elehack.net Wed Apr 5 16:43:13 2006 From: michael at elehack.net (Michael Ekstrand) Date: Wed, 05 Apr 2006 15:43:13 -0500 Subject: RELEASED Python 2.5 (alpha 1) In-Reply-To: <1144244505.471052.115200@i39g2000cwa.googlegroups.com> References: <200604052248.19094.anthony@python.org> <1144244505.471052.115200@i39g2000cwa.googlegroups.com> Message-ID: <44342BE1.2010508@elehack.net> Michele Simionato wrote: > Michael Ekstrand wrote: >> After reading AMK's survey of what's new in Python 2.5, I am suitably >> impressed. As usual, I can't wait to start using the cool new >> features... extended generators? (mind is currently swimming with the >> question of "can I implement Scheme's call-with-current-continuation >> using extended generators".) > > No. Oh well. I'll try not to think too hard about it then. The day Python (without using Stackless) has true continuations will be a happy day. - Michael -- mouse, n: a device for pointing at the xterm in which you want to type. -- Fortune Visit me on the Web: http://www.elehack.net From cygnus at cprogrammer.org Mon Apr 17 22:42:58 2006 From: cygnus at cprogrammer.org (Jonathan Daugherty) Date: Mon, 17 Apr 2006 19:42:58 -0700 Subject: Missing interfaces in Python... In-Reply-To: <1hdybsi.1g0xk7pmm2m2tN%aleaxit@yahoo.com> References: <1145306373.781129.305840@z34g2000cwc.googlegroups.com> <20060417210541.GV7561@vulcan.cprogrammer.org> <20060417212336.GW7561@vulcan.cprogrammer.org> <1hdybsi.1g0xk7pmm2m2tN%aleaxit@yahoo.com> Message-ID: <20060418024258.GC7561@vulcan.cprogrammer.org> # "parser"...?! If you have an 'Object o', say one just received as an # argument, and cast it to IBlahble, a la # # IBlahble blah = (IBlahble) o; # # ...what can the parser ever say about it? Maybe you didn't read the "I think" in my OP. Anyway, you clearly know more about (or have more recent experience with) Java than I do. -- Jonathan Daugherty http://www.parsed.org From Serge.Orlov at gmail.com Fri Apr 7 19:35:10 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 7 Apr 2006 16:35:10 -0700 Subject: calculating system clock resolution References: <1144434899.840346.220780@z34g2000cwc.googlegroups.com> Message-ID: <1144452910.634097.117310@e56g2000cwe.googlegroups.com> jUrner at arcor.de wrote: > Hello all > > I have the problem of how to calculate the resolution of the system > clock. > Its now two days of head sratching and still there is nothing more than > these few lines on my huge white sheet of paper stiring at me. Lame I > know. > > import time > > t1 = time.time() > while True: > t2 = time.time() > if t2 > t1: > print t1, t2 > # start calculating here > break > > > BTW t1 and t2 print out equal up to the fraction on my machine. What > does > python know that I don't? A pointer to the source lines where this is > implemented > would even be helpfull to clear this out. Can't seem to find it. > > Anyone any ideas? I think you are pretty close: import time def resolution_sample(): t1 = time.time() while True: t2 = time.time() if t2 > t1: return t2 - t1 def timer_resolution(): return min(resolution_sample() for x in xrange(10)) The function above (timer_resolution) is actually pretty dumb. I think the number of samples to take depends on resolution. From fredrik at pythonware.com Wed Apr 26 07:01:42 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 26 Apr 2006 13:01:42 +0200 Subject: Nested Lists Assignment Problem References: <1146039200.264901.317920@j33g2000cwa.googlegroups.com> Message-ID: "Licheng Fang" wrote: >I wanna use nested lists as an array, but here's the problem: > >>>> a = [[0]*3]*3 >>>> a > [[0, 0, 0], [0, 0, 0], [0, 0, 0]] >>>> a[0][0] = 1 >>>> a > [[1, 0, 0], [1, 0, 0], [1, 0, 0]] > > Could anybody please explain to me why three values were change? I'm > bewildered. Thanks! http://pyfaq.infogami.com/how-do-i-create-a-multidimensional-list From bearophileHUGS at lycos.com Tue Apr 11 09:46:59 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 11 Apr 2006 06:46:59 -0700 Subject: Why new Python 2.5 feature "class C()" return old-style class ? In-Reply-To: <443ba5a9$0$14281$626a54ce@news.free.fr> References: <1144752553.305591.88050@j33g2000cwa.googlegroups.com> <1144756774.177225.311120@z34g2000cwc.googlegroups.com> <443ba5a9$0$14281$626a54ce@news.free.fr> Message-ID: <1144763219.936992.219110@g10g2000cwb.googlegroups.com> bruno at modulix>Since the class statement without superclass actually creates an old-style class, I'd expect the "class MyClass():" variant to behave the same.< In Python 3.0 I really hope the class C: pass class C(): pass class C(object): pass will mean the same thing. (So in Python 2.5 the second version can be made to mean the same thing of the third). Bye, bearophile From peter at engcorp.com Tue Apr 11 21:04:46 2006 From: peter at engcorp.com (Peter Hansen) Date: Tue, 11 Apr 2006 21:04:46 -0400 Subject: How to initiate HotSync of Palm device? In-Reply-To: <1144797534.819751.150020@t31g2000cwb.googlegroups.com> References: <1144725904.731539.142760@u72g2000cwu.googlegroups.com> <1144797534.819751.150020@t31g2000cwb.googlegroups.com> Message-ID: dylpkls91 wrote: > I posted a similar question on comp.sys.palmtops.pilot and am waiting > for a response. Thank you for your reply; the acknowledgement is > appreciated. I believe that a possible solution would be to use a > command line option of HotSync Manager, but I am not sure what the > correct option would be. Thanks again! I'm not actually aware of the existence of any PC-side method for initiating a HotSync. My HotSync Manager certainly doesn't show such an option anywhere that I can see. -Peter From swami426 at yahoo.com Wed Apr 5 20:51:11 2006 From: swami426 at yahoo.com (swami426 at yahoo.com) Date: 5 Apr 2006 17:51:11 -0700 Subject: how to convert string In-Reply-To: <1144261976.640631.9280@e56g2000cwe.googlegroups.com> References: <1144261976.640631.9280@e56g2000cwe.googlegroups.com> Message-ID: <1144284671.748880.187060@j33g2000cwa.googlegroups.com> Try this for x in range(10): sys.stdout.write(x) sys.stdout.write(" ") 0 1 2 3 4 5 6 7 8 9 diffuser78 at gmail.com wrote: > I want to print number 0 to 9 in one line like this > 0 1 2 3 4 5 6 7 8 9 > > if I do like this, it prints in different lines > > for i in xrange(10): > print i > > so i tried like this > > str = "" > for i in xrange(10): > str = i + " " > print str > > but i want to know how convert int i to string. > > Every help is appreciate. From sybrenUSE at YOURthirdtower.com.imagination Mon Apr 10 03:58:29 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Mon, 10 Apr 2006 09:58:29 +0200 Subject: wiki engine (just engine) available? References: Message-ID: loguser at almad.net enlightened us with: > Ideal feature set is ReStructureText, some easy way to add custom > commands (to keep my pages integrated in way Trac is doing) and > (ideally) docbook export (althrough I'm ready to write one). What is Trac doing? What kind of commands are you talking about? You can convert reST to XML, so from there it's a small XSLT step to Docbook. There are bound to be XSLT files available for that. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From tomi.lindberg.NO_SPAM at pp.inet.fi.invalid Wed Apr 5 08:36:32 2006 From: tomi.lindberg.NO_SPAM at pp.inet.fi.invalid (Tomi Lindberg) Date: Wed, 05 Apr 2006 12:36:32 GMT Subject: Dice probability problem In-Reply-To: References: Message-ID: Antoon Pardon wrote: > IMO you are making things too complicated and not general > enough. I believe that the above is very likely more than just your opinion :) Programming is just an occasional hobby to me, and I lack both experience and deeper (possibly a good chunk of shallow as well) knowledge on the subject. I'll study the code you posted, and make further questions if something remains unclear afterwards. Thanks, Tomi Lindberg From Serge.Orlov at gmail.com Wed Apr 19 18:06:22 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 19 Apr 2006 15:06:22 -0700 Subject: send pdf or jpg to printer In-Reply-To: References: Message-ID: <1145484382.263112.12100@u72g2000cwu.googlegroups.com> Bell, Kevin wrote: > Does anyone have any suggestions on printing pdf's? These pdf's don't > change much, so if it be more straight forward to convert them to jpgs, > or another format, then that'd be fine too. You didn't say what OS you're using, assuming it's windows: http://tgolden.sc.sabren.com/python/win32_how_do_i/print.html From nicolas.pinto at gmail.com Sat Apr 22 16:19:14 2006 From: nicolas.pinto at gmail.com (nich2o) Date: 22 Apr 2006 13:19:14 -0700 Subject: quick surface plots In-Reply-To: <1145621306.742445.276960@g10g2000cwb.googlegroups.com> References: <1144942298.800990.139160@g10g2000cwb.googlegroups.com> <1145621306.742445.276960@g10g2000cwb.googlegroups.com> Message-ID: <1145737154.579574.115720@v46g2000cwv.googlegroups.com> Did you try mplot3D ? http://www.scipy.org/Wiki/Cookbook/Matplotlib/mplot3D -- N From fabiofz at gmail.com Fri Apr 21 08:10:28 2006 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Fri, 21 Apr 2006 09:10:28 -0300 Subject: How should multiple (related) projects be arranged (structured) and configured so that they can share code, have a related package structure and enable proper unittesting, and ensuring no namespace collisions In-Reply-To: <1145546785.268550.154240@e56g2000cwe.googlegroups.com> References: <1145546785.268550.154240@e56g2000cwe.googlegroups.com> Message-ID: > > > COMMON > src > a.b.c.common > test > a.b.c.common Ok, first thing... it won't work becaus as soon as python finds the first a.b.c.common it will bail on the other... That's the default approach for java, becase it will give you access to module-level things declared as 'default', that otherwise you wouldn't have access (in python all are grown-ups, so that's not necessary) and it won't bail out in the first match. So, in python, you'd probably do something as: test/test.a.b.c.common or create a tests dir as src/a.b.c.common.tests (I guess there are other solutions, but those 2 seem more appealing to me -- coming from a java background). I believe you'd be able to keep that structure and play with the pythonpath if you wanted, but it could be too brittle in the end, and lead to hard-to-discover problems. Cheers, Fabio -------------- next part -------------- An HTML attachment was scrubbed... URL: From chris.cavalaria at free.fr Thu Apr 27 05:42:47 2006 From: chris.cavalaria at free.fr (Christophe) Date: Thu, 27 Apr 2006 11:42:47 +0200 Subject: bug in modulus? In-Reply-To: <1145807918.069455.241510@i40g2000cwc.googlegroups.com> References: <1145807918.069455.241510@i40g2000cwc.googlegroups.com> Message-ID: <4450928c$0$21107$626a54ce@news.free.fr> jantod at gmail.com a ?crit : > I think there might be something wrong with the implementation of > modulus. > > Negative float values close to 0.0 break the identity "0 <= abs(a % b) > < abs(b)". > > print 0.0 % 2.0 # => 0.0 > print -1e-010 % 2.0 # =>1.9999999999 > > which is correct, but: > > print -1e-050 % 2.0 # => 2.0 > print -1e-050 % 2.0 < 2.0 # => False > > This means I can't use modulus to "wrap around" before it reaches a > certain value. I'm using Python 2.4.2 on WindowsXP. > > Thanks > Janto > Consider that -1e-050 % 2.0 = 2.0 - 1e-050 Now, test that : >>> 2.0 - 1e-050 == 2.0 True Floating point numbers just don't have the required precision to represent 2.0 - 1e-050. For your specific problem, if you really want the result to be < 2.0, the the best you can do is admit that floating point operations have errors and return 0.0 when the modulus operation equals 2.0. From lycka at carmen.se Wed Apr 12 05:52:29 2006 From: lycka at carmen.se (Magnus Lycka) Date: Wed, 12 Apr 2006 11:52:29 +0200 Subject: About classes and OOP in Python In-Reply-To: <1144745819.173322.174040@z34g2000cwc.googlegroups.com> References: <1144678797.749000.155010@t31g2000cwb.googlegroups.com> <1144745819.173322.174040@z34g2000cwc.googlegroups.com> Message-ID: Michele Simionato wrote: > Roy Smith wrote: > >> That being said, you can indeed have private data in Python. Just prefix >> your variable names with two underscores (i.e. __foo), and they effectively >> become private. Yes, you can bypass this if you really want to, but then >> again, you can bypass private in C++ too. > > Wrong, _foo is a *private* name (in the sense "don't touch me!"), __foo > on the contrary is a *protected* name ("touch me, touch me, don't worry > I am protected against inheritance!"). > This is a common misconception, I made the error myself in the past. While your wording makes sense, it's probably confusing for anyone with a C++ background, where private roughly means "only accessible within the actual class" and protected roughly means "only accessible within the class and other classes derived from it". From felipe.lessa at gmail.com Sat Apr 8 23:24:01 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Sun, 09 Apr 2006 00:24:01 -0300 Subject: Automated Graph Plotting in Python In-Reply-To: <1144552132.926125.222210@i39g2000cwa.googlegroups.com> References: <1144552132.926125.222210@i39g2000cwa.googlegroups.com> Message-ID: <1144553041.7140.0.camel@kenshin.CASA> Em S?b, 2006-04-08 ?s 20:08 -0700, diffuser78 at gmail.com escreveu: > My python program spits lot of data. I take that data and plot graphs > using OfficeOrg spredsheet. I want to automate this task as this takes > so much of time. I have some questions. You can try ReportLab (www.reportlab.org). Great tool. -- Felipe. From youlei.yuan at gmail.com Tue Apr 25 20:49:02 2006 From: youlei.yuan at gmail.com (=?utf-8?B?6Zu3?=) Date: 25 Apr 2006 17:49:02 -0700 Subject: do while loop Message-ID: <1146012542.166096.78690@g10g2000cwb.googlegroups.com> suggest add do while loop in later version From __peter__ at web.de Thu Apr 27 01:50:18 2006 From: __peter__ at web.de (Peter Otten) Date: Thu, 27 Apr 2006 07:50:18 +0200 Subject: Editing a function in-memory and in-place References: <1146115733.082702.106380@t31g2000cwb.googlegroups.com> Message-ID: Ian Bicking wrote: > I got a puzzler for y'all. I want to allow the editing of functions > in-place. I won't go into the reason (it's for HTConsole -- > http://blog.ianbicking.org/introducing-htconsole.html), except that I > really want to edit it all in-process and in-memory. So I want the > identity of the function to remain the same, even as I edit the body > and hopefully the signature too. > > Well, the reason is that I want to edit any function object, without > having to know who has a reference to the function. This way editing a > function or a method or a property.fget can all be done in the same > way. > > The func_code attributes of functions is writable, but I don't know how > to create the proper code object. Just compiling a new body isn't good > enough. Can you cheat and just assign another known good func_code object? >>> def hello(): print "hello" ... >>> def world(): print "world" ... >>> def use_it(hello=hello, world=world): ... hello() ... world() ... >>> use_it() hello world >>> world.func_code = hello.func_code >>> use_it() hello hello >>> hello, world (, ) Peter From erchamion.beren at gmail.com Wed Apr 5 10:53:35 2006 From: erchamion.beren at gmail.com (erchamion.beren at gmail.com) Date: Wed, 5 Apr 2006 10:53:35 -0400 Subject: save file as utf-8 format Message-ID: <200604051053.35591.orome.the.valar@gmail.com> hi, what should i do to save file as utf-8 encoding. thanks. From brenNOSPAMbarn at NObrenSPAMbarn.net Fri Apr 14 02:42:11 2006 From: brenNOSPAMbarn at NObrenSPAMbarn.net (OKB (not okblacke)) Date: Fri, 14 Apr 2006 06:42:11 +0000 (UTC) Subject: PEP 359: The "make" Statement References: Message-ID: Nicolas Fleury wrote: > I have no idea of the > implementation implications, but it would be nice to have the > capability to override the namespace type to use something else > than dict, so that it can be filled with symbols one statement at a > time. I agree. I have sometimes wanted this ability for classes, so that class definitions could map assignments onto class attributes in some way besides blindly stuffing into a dict. -- --OKB (not okblacke) Brendan Barnwell "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown From brian at rkspeed-rugby.dk Tue Apr 25 06:52:42 2006 From: brian at rkspeed-rugby.dk (Brian Elmegaard) Date: Tue, 25 Apr 2006 12:52:42 +0200 Subject: MinGW and Python References: <1145861223.509630.247350@y43g2000cwc.googlegroups.com> <444C79D7.4060007@v.loewis.de> Message-ID: Robert Kern writes: > If you meant writing extension modules for Python instead of extending > distutils, I thought about extending distutils to make non-python installers. I may have misunderstood the answers I got. http://groups.google.com/group/comp.lang.python/browse_thread/thread/3f721b5a38fbc2d1/7af1aea19aa187b6?lnk=st&q=author%3Aelmegaard+distutils&rnum=1#7af1aea19aa187b6 > mingw for the standard Python distribution. Please see my post in the thread "MS > VC++ Toolkit 2003, where?". Thanks, I will. -- Brian (remove the sport for mail) http://www.et.web.mek.dtu.dk/Staff/be/be.html http://www.rugbyklubben-speed.dk From pmartin at snakecard.com Sat Apr 8 12:53:18 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Sat, 08 Apr 2006 11:53:18 -0500 Subject: Where python looks for path References: Message-ID: <0URZf.65$9c6.30@dukeread11> Hi, I had to move the dlls from pywin32_system32 to where python.exe is. PS: if someone has a great desire to have another library included in the package, let me know. Regards, Philippe Philippe Martin wrote: > Hi, > > I am currently packaging python and a few libraries: PyWin32, PySerial, > PIL, wxPython, HTML generator, numarray for U3 distribution. > > Basically that means that the complete system initially in $path1\host > will be moved dynamically to $path2\at execution. > > > To take PIL as an example, I notice when I launch Idle in a "relative" > manner: I am in $path1\host that $path1\host\Lib\site-packages\PIL is in > the sys.path before I do anything. > > I notice that there is a PIL.pch file in site-packages: > > Q1) is that read by python ? > > > On the other hand, even after appending all I can think of in sys.path, I > still get an error (cannot find module) trying to load win32com.client: it > fails in the win32api import in win32com.client. > > pywin32.pch is there. > > I think all the .dlls are there also, so I'm a bit confused. > > Q2) what should I be looking for ? > > > Also, I seemed to notice in the past that modules (my own) not listed in > any __init__.py where found under Linux but not Windows for which I had to > upgrade my __init__.py. > > > Q3: is that true ? > > > Regards, > > Philippe From john at castleamber.com Sat Apr 29 01:39:09 2006 From: john at castleamber.com (John Bokma) Date: 29 Apr 2006 05:39:09 GMT Subject: (was Re: Xah's Edu Corner: Criticism vs Constructive Criticism) References: <1145992903.834316.198370@u72g2000cwu.googlegroups.com> <4GM3g.3084$TT.1768@twister.nyroc.rr.com> <1146231280.733609.143230@e56g2000cwe.googlegroups.com> <1146276319.504694.218970@v46g2000cwv.googlegroups.com> <1146285809.127897.24070@j33g2000cwa.googlegroups.com> Message-ID: "Tagore Smith" wrote: > Try > sending mail to abuse at (any of my) desmesne(s). You won't get a > response- in fact, no-one will read your mail. Then you come close to being RFC ignorant IMO. Couldn't be bothered to check it out. > I'm not sure that Xah's post was offtopic, and I am not sure how to > determine that objectively. An excessive crosspost is hardly ever on topic. > I am sure that it was excessively > crossposted. I also know that Xah was posting to Usenet a long time > before you, Could be, oldest post I could find of myself: But is this a pissing contest? > and that he will still be posting to Usenet long after you > have given up in disgust, no matter who you complain to. I doubt it. I am still "here" after 14 years. > Crossposting is bad, unless it serves a specific purpose- Xah's post > obviously doesn't. I dont like people reporting on Usenet posters to > their ISPs, but... I can't really complain about that. Crossposting is > not good, without a really good justification. > > But you are complaining about the content of his posts, and harassing > his ISP based on that. Again, learn to read: I reported excessive crossposting, period. > Would you like a Usenet campaign started to disrupt your internet > access? You would be angry if that were done, and justifiably. Last time something like that happened the culprit lost his account. So be my guest. -- John MexIT: http://johnbokma.com/mexit/ personal page: http://johnbokma.com/ Experienced programmer available: http://castleamber.com/ Happy Customers: http://castleamber.com/testimonials.html From invalidemail at aerojockey.com Mon Apr 17 22:24:27 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 17 Apr 2006 19:24:27 -0700 Subject: PEP 359: The "make" Statement References: <1145318176.952461.203240@i39g2000cwa.googlegroups.com> Message-ID: <1145327067.281826.250030@j33g2000cwa.googlegroups.com> Mike Orr wrote: > > I think this PEP is going off the rails. It's primary virtue was that it > was a simpler, clearer way to write: > > class Foo(args): > __metaclass__ = some_metaclass > #... > > And it doesn't even do that. What's wrong with "class Foo: > __metaclass__ = blah"? Two lines of code, and the double underscores > indicate something special is happening. I think you're missing the point somewhat. The real point isn't to make using metaclasses easier; it's to let the useful semantics of the class statement be used for things that aren't classes. Example: I can define the following "metaclass": def PropertyMaker(name,bases,pdict): fget = pdict.get("get",None) fset = pdict.get("set",None) fdel = pdict.get("delete",None) doc = pdict.get("__doc__",None) return property(fget,fset,fdel,doc) Then, I could define a property inside some class definition like this: class some_attribute: __metaclass__ = PropertyMaker def get(self): whatever def set(self,value): whatever But the thing is, if I did that, I'd be lying bastard. I'd be using the class statement and the __metaclass__ property; however, the object I'm creating is not a class (it's a property), and the thing I'm assigning to __metaclass__ is not a metaclass (it's a factory function). With the make statement, I could instead write: make property some_attribute: def get(self): # etc. Then I'm not lying about it, and I'm using a more straightforward syntax. If this proposal were just about metaclasses, I agree that wouldn't be important enough to justify a new statement. Metaclasses aren't too common, and are generally used by experts who don't need the straightforwardness the make statement would provide. But, properties, dicts, and other things could benefit from some of the semantics the class statement, and with the make statement, the average user could take advantage of that without having to worry about all this circumlocative metaclass hackiness. Carl Banks From tim.peters at gmail.com Thu Apr 27 13:28:18 2006 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 27 Apr 2006 13:28:18 -0400 Subject: PyEval_EvalFrame In-Reply-To: <1146157021.547361.185710@y43g2000cwc.googlegroups.com> References: <1146157021.547361.185710@y43g2000cwc.googlegroups.com> Message-ID: <1f7befae0604271028k478f5889he5c933825f54f31e@mail.gmail.com> [bretthall at gmail.com] > I see a C/python program that we're using spending a lot of time in > this function, far more than we think it should. What is it? PyEval_EvalFrame is the heart of the CPython interpreter: it's a very large function that _implements_ the interpreter, marching through the byte codes and executing them. You can't run Python code at all without it. > Thanks in advance! There seems to be nothing (but a bunch of stack > traces) when I google this. It's rarely called directly, but is called indirectly by everything that runs Python code. From onurb at xiludom.gro Wed Apr 5 05:04:11 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 05 Apr 2006 11:04:11 +0200 Subject: Standalone Python functions in UML? In-Reply-To: <1144198593.264275.131480@i39g2000cwa.googlegroups.com> References: <1144145349.186395.44890@z34g2000cwc.googlegroups.com> <1144198593.264275.131480@i39g2000cwa.googlegroups.com> Message-ID: <44338852$0$9464$626a54ce@news.free.fr> Ravi Teja wrote: (snip) > >> And probably Python is too dynamic for UML. That is another reason > rountrip tools aren't there. > > > As you probably already know, UML diagrams are structural and > behavioural (plus interactional with 2.0). Round trip tools only model > structural diagrams. Python is dynamic but only once the program starts > executing :-). Even though Python classes "can" change, they do so only > at runtime Well, you can have a lot of things happening during the import stage. Is this 'runtime' or not ?-) And you can actually *create* (not 'change') classes at runtime too. > So dynamism of Python should not be as > much of an issue. Not so sure about this. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From jstroud at ucla.edu Sat Apr 29 15:55:41 2006 From: jstroud at ucla.edu (James Stroud) Date: Sat, 29 Apr 2006 12:55:41 -0700 Subject: (was Re: Xah's Edu Corner: Criticism vs Constructive Criticism) In-Reply-To: References: Message-ID: bruce wrote: > but you know... > > one could simply hit the delete/skip button when you see a msg you don't > like!!! or email/spam filters... or you can spend more time complaining.. in > life, you gotta' learn to pick your battles... > > peace.. > Bruce: You may want to check your mail reader to make sure it responds to the thread. That would help people to "skip" messages. The thread in question got out of hand a long time ago (even before I jumped in ;), so it would help if related posts replied to the thread--at least thunderbird does not group your post with the thread. I'm guessing other news readers won't either. Also, there is no doubt that you will soon be chastised for "top posting": http://en.wikipedia.org/wiki/Top-posting James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From williams.jasonscott at gmail.com Mon Apr 24 17:51:16 2006 From: williams.jasonscott at gmail.com (williams.jasonscott at gmail.com) Date: 24 Apr 2006 14:51:16 -0700 Subject: C API - tp_getattro and tp_methods In-Reply-To: <3945369.6RQT0EcFBM@news.perlig.de> References: <1145910179.468987.266850@u72g2000cwu.googlegroups.com> <2341353.ZoQ3i2GqUK@news.perlig.de> <1145911852.768851.36030@t31g2000cwb.googlegroups.com> <3945369.6RQT0EcFBM@news.perlig.de> Message-ID: <1145915476.368508.13520@y43g2000cwc.googlegroups.com> Ahhh... The the light clicks on in my head. I see what is happening and both of these are great approaches. Many thanks! From stefan.behnel-n05pAM at web.de Tue Apr 25 08:17:49 2006 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 25 Apr 2006 14:17:49 +0200 Subject: Parsing XML/XSLT In-Reply-To: <1145808564.914308.102620@e56g2000cwe.googlegroups.com> References: <1145808564.914308.102620@e56g2000cwe.googlegroups.com> Message-ID: <444e136e$0$11078$9b4e6d93@newsread4.arcor-online.net> veracon wrote: > I'm looking to use XML and XSLT for templates in a system I'm writing, > however I'm not really sure which parser is the "best". Basically, > which library has the most features, and which is the most supported? lxml arguably has the most features by now, as it is based on libxml2 and libxslt (libexslt support is in SVN) and wraps most of their features into easy-to-use Python APIs. At least lxml's API is also arguably the most supported as it mostly compatible to ElementTree (which made it into Python 2.5). http://codespeak.net/lxml Beware though, I'm somewhat biased as I'm one of the authors. Stefan From a.serrano at vielca.com Thu Apr 6 07:02:55 2006 From: a.serrano at vielca.com (a.serrano at vielca.com) Date: 6 Apr 2006 04:02:55 -0700 Subject: Unicode, command-line and idle Message-ID: <1144321375.901932.161330@v46g2000cwv.googlegroups.com> Hello, the following program prompts the user for a word and tests to see if it is the same as another one. If the user types "espa?a" (note that the word contains an '?'), the program should output "same". This works if I run the code in IDLE but does not if I run it in the windows console. Can someone explain me why this happens and how to get around it? # -*- coding: cp1252 -*- text1 = 'espa?a' text2 = raw_input() if text1 == text2: print 'same' else: print 'not same' From sturlamolden at yahoo.no Thu Apr 27 14:47:11 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 27 Apr 2006 11:47:11 -0700 Subject: MS VC++ Toolkit 2003, where? In-Reply-To: References: <1he8pss.1yk7ug81rv7pw2N%aleaxit@yahoo.com> <1145811839.042394.73260@t31g2000cwb.googlegroups.com> <1he8sbx.dqqp3q10n5thaN%aleaxit@yahoo.com> <1145849491.347970.112150@e56g2000cwe.googlegroups.com> <1he9m4m.9d8okx1x7mxeaN%aleaxit@yahoo.com> <444C784F.3000502@v.loewis.de> <1heag4u.19dksfxrbe14wN%aleaxit@yahoo.com> <444D61F9.4040003@v.loewis.de> Message-ID: <1146163631.327928.79560@v46g2000cwv.googlegroups.com> I believe MinGW can link .lib C libraries files from Visual Studio. But there are no .a for Python24.dll as far as I can tell. From steven.bethard at gmail.com Sat Apr 29 20:04:48 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 29 Apr 2006 18:04:48 -0600 Subject: best way to determine sequence ordering? In-Reply-To: <1146354770.313981.324600@u72g2000cwu.googlegroups.com> References: <70q4g.2006$No6.43783@news.tufts.edu> <1146259620.636600.119710@u72g2000cwu.googlegroups.com> <1146315935.017018.65580@u72g2000cwu.googlegroups.com> <2_idnXXyMIjKbc7ZnZ2dneKdnZydnZ2d@comcast.com> <1146354770.313981.324600@u72g2000cwu.googlegroups.com> Message-ID: nikie wrote: > That's what this thread was all about. Now, I don't really see what you > are trying to say: Are you still trying to convince the OP that he > should write a Python function like one of those you suggested, for > performance reasons? Sure, if it really matters. Code it in C, and you can do better than .index(). But I don't think it really matters. ;-) STeVe From webraviteja at gmail.com Sun Apr 30 03:48:47 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 30 Apr 2006 00:48:47 -0700 Subject: basic python programing In-Reply-To: <1146376141.767029.17850@j73g2000cwa.googlegroups.com> References: <1146376141.767029.17850@j73g2000cwa.googlegroups.com> Message-ID: <1146383327.664894.279250@v46g2000cwv.googlegroups.com> How To Ask Questions The Smart Way http://www.catb.org/~esr/faqs/smart-questions.html From rpdooling at gmail.com Fri Apr 28 11:31:28 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 28 Apr 2006 08:31:28 -0700 Subject: os.startfile() - one or two arguments? In-Reply-To: References: <1146236762.657595.23240@u72g2000cwu.googlegroups.com> Message-ID: <1146238288.379151.94120@g10g2000cwb.googlegroups.com> Whoops! Sorry all. I was using the "in-development" version of the documentation and didn't even realize it. Thank you, Rick From jpierce at junglecreatures.com Thu Apr 13 08:46:00 2006 From: jpierce at junglecreatures.com (jpierce at junglecreatures.com) Date: 13 Apr 2006 05:46:00 -0700 Subject: Python2CPP ? In-Reply-To: <4a4a98FrjdvlU1@uni-berlin.de> References: <4a4a98FrjdvlU1@uni-berlin.de> Message-ID: <1144932360.077594.171670@i39g2000cwa.googlegroups.com> Diez B. Roggisch wrote: > > 1) Curiosity. I would like to see how well the translation goes. > > If there is something that works, it will look awful to the eye. > Code-generators are generally not very idiomatic - they mapping is to > localized to e.g. factorize out a more complex loop to something a > generator might to much better. > > I suggest you take a look at pyrex, a python-like language that bridges > python and C by generating C. > > > 2) Efficiency. It is alot quicker to code something in Python. If I can > > write it in Python and auto-convert it to C++. I would save time > > coding. > > Then let it run in python. > > > 3) Education. I would learn more about Python, C++, their similarities and > > differences. > > I also doubt that. digging into generated, non-idiomatic code won't do much > for you to grasp what is behind Python or C++ as well. Think e.g. of > templating, a major feature in C++ that certainly won't be utilized by a > code-generator that does everything based on python C-structures and their > C-API. > > Regards, > > Diez From pmartin at snakecard.com Wed Apr 26 18:54:35 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Wed, 26 Apr 2006 17:54:35 -0500 Subject: MinGW and Python References: <1145861223.509630.247350@y43g2000cwc.googlegroups.com> <444C79D7.4060007@v.loewis.de> Message-ID: This might relevant. http://www.aceshardware.com/read.jsp?id=153 Philippe Robert Kern wrote: > Martin v. L?wis wrote: >> Srijit Kumar Bhadra wrote: >> >>>Is there any specific reason for not using MinGW to build the official >>>distribution of Python for Win32? >> >> What could be the reasons to use MinGW? >> >> As for reasons not to do that: >> - there is no build process available to do that >> - people building extensions to Python must be able to do so with >> Microsoft C++, since some of these extensions are written using MFC. >> - developing Python itself in Visual Studio is quite convenient; in >> particular, the debugger works "better" than gdb. > > - gcc does not optimize particularly well. > > -- > Robert Kern > robert.kern at gmail.com > > "I have come to believe that the whole world is an enigma, a harmless > enigma > that is made terrible by our own mad attempt to interpret it as though it > had an underlying truth." > -- Umberto Eco From aghazalp at ucla.edu Sun Apr 2 17:35:03 2006 From: aghazalp at ucla.edu (aghazalp) Date: 2 Apr 2006 14:35:03 -0700 Subject: very very basic question In-Reply-To: <44304260.6050104@websafe.com> References: <1144011128.206400.275270@e56g2000cwe.googlegroups.com> <1144011650.148681.173910@t31g2000cwb.googlegroups.com> <1144012531.467476.121760@z34g2000cwc.googlegroups.com> <44304260.6050104@websafe.com> Message-ID: <1144013703.361956.310040@t31g2000cwb.googlegroups.com> WOWWWWWWWW Larry that was very very smart...it works perfectly =) From sudharsh at gmail.com Mon Apr 10 08:40:04 2006 From: sudharsh at gmail.com (sudharsh at gmail.com) Date: 10 Apr 2006 05:40:04 -0700 Subject: PC-104 LINUX 512KB 1MB In-Reply-To: <1144646583.214860.136150@v46g2000cwv.googlegroups.com> References: <1144646583.214860.136150@v46g2000cwv.googlegroups.com> Message-ID: <1144672804.544158.304520@z34g2000cwc.googlegroups.com> err...this is chinese.. From iddw at hotmail.com Fri Apr 21 16:06:35 2006 From: iddw at hotmail.com (Dave Hansen) Date: Fri, 21 Apr 2006 15:06:35 -0500 Subject: how to append to a list twice? References: <4282g.68392$H71.37777@newssvr13.news.prodigy.com> <1145649038.408067.46010@z34g2000cwc.googlegroups.com> Message-ID: <43ei42h8c1ggusi186ve22dimg0udo44sh@4ax.com> On 21 Apr 2006 12:50:38 -0700 in comp.lang.python, callmebill at gmail.com wrote: >I don't get it (the Elliot solution)... How is it that the first value >is repeated once times, and the remaining values are repeated twice >times? Integer division truncates. 200/2 -> 100, 199/2 -> 99, 198/2 -> 99, etc. Regards, -=Dave -- Change is inevitable, progress is not. From john at castleamber.com Fri Apr 28 17:36:11 2006 From: john at castleamber.com (John Bokma) Date: 28 Apr 2006 21:36:11 GMT Subject: Xah's Edu Corner: What Languages to Hate References: <1145992903.834316.198370@u72g2000cwu.googlegroups.com> <1146172923.830732.187130@i40g2000cwc.googlegroups.com> <20060427223335.6c8537e6.alex.buell@munted.org.uk> <1146254391.815629.145130@j33g2000cwa.googlegroups.com> Message-ID: "Kaz Kylheku" wrote: > John Bokma wrote: >> Alex Buell wrote: >> >> > Send your complaints to: >> > abuse at sbcglobal dott net >> > abuse at dreamhost dott com >> >> Yup, done. If he's still with dreamhost he probably is in trouble >> now. If not, next. > > Hahaha, right. Your complaints probably go straight do /dev/null. Do > you think any ISP out there cares about someone cross-posting a little > troll on Usenet, cross-posted to a handful of groups? They have bigger > abuse issues to worry about. I have warned this user that excessive offtopic cross-posting is not allowed, and explained that if he doesn't quit he risks losing his account. If you (or anyone else) notice this in the future, please do not hesitate to submit another report. If you have any questions, please let us know. - Jeff C. - Abuse Coordinator, DreamHost Web Hosting - http://www.dreamhost.com/ > He pisses some of you people off because a lot of his ranting is > approximately on the mark. You have no clue, so much is clear, and guessing doesn't help. > In my home country of Slovakia people say > "Trafena' hus zaga'ga!", which means "It is the goose that is hit > which will honk up". Expect some honking from Xah soon then. -- John MexIT: http://johnbokma.com/mexit/ personal page: http://johnbokma.com/ Experienced programmer available: http://castleamber.com/ Happy Customers: http://castleamber.com/testimonials.html From duane.kaufman at gmail.com Mon Apr 3 00:01:50 2006 From: duane.kaufman at gmail.com (TheSeeker) Date: 2 Apr 2006 21:01:50 -0700 Subject: Problem with wrapping GNU Units Message-ID: <1144036910.180343.33180@e56g2000cwe.googlegroups.com> Hi, As part of a larger project, I am trying to use the GNU Units program to provide unit conversions between quantities. My first iteration, which worked OK, was to simply use units as a command-line app, and capture its output. The larger program however, calls the conversion routine many times, and the overhead of starting units for every call made things too slow. I then re-formulated my use of units to open it using popen2, and do conversions with it through stdin and stdout (Windows XP). This too works OK, at least up to the point I want to stop the program, which is where I am having problems. If I simply try to exit my app, python.exe hangs, and units.exe keeps running, according to the Task Manager. If I try sending Control-D, as the on-line help suggests, the program hangs too. Does anyone have any ideas on how to control this app? Here is some of my code: # Functions for driving GNU Units (if installed) GNU_Units_stdin = None GNU_Units_stdout = None def SetupGNU_Units(): import time, os, sys # Initialization routine to set up pipe to running GNU Units process # Start GNU Units as a child and feed and read through stdin and stdout global GNU_Units_stdin, GNU_Units_stdout CurrentDir = os.getcwd() # Hack to find correct directory if not 'units.exe' in os.listdir(os.getcwd()): UnitsDir = os.path.join(CurrentDir, 'GNU_Units') else: UnitsDir = CurrentDir print "CurrentDir ", CurrentDir os.chdir(UnitsDir) (GNU_Units_stdin, GNU_Units_stdout) = os.popen2('units.exe -f .\units.dat') time.sleep(0.5) print 'First initialization read: ', GNU_Units_stdout.readline() time.sleep(0.5) print 'Second initialization read: ', GNU_Units_stdout.readline() time.sleep(0.5) print 'Units initialization complete.' def ShutdownGNU_Units(): global GNU_Units_stdin, GNU_Units_stdout # From the GNU Units help, to quit the program from the interactive prompt # (which is how we are using it), one needs to feed it Control-D GNU_Units_stdin.write(chr(4)) # ResponseLine1 = GNU_Units_stdout.readline() GNU_Units_stdin = None GNU_Units_stdout = None def ConvertUnits(Value, FromUnitStr, ToUnitStr): import os, sys global GNU_Units_stdin, GNU_Units_stdout # Sanity check on the numerical portion of the input try: dummy=float(Value) except ValueError: raise ConvertUnitsError('ConvertUnits: non-numeric input') return 0 if not GNU_Units_stdin: # Initialize pipes to GNU Units SetupGNU_Units() FromStr = str(Value) FromStr += ' ' + FromUnitStr + '\r' ToStr = ToUnitStr + '\r' GNU_Units_stdin.write(FromStr) GNU_Units_stdin.write(ToStr) ResponseLine1 = GNU_Units_stdout.readline() ResponseLine2 = GNU_Units_stdout.readline() ReadBackLine = GNU_Units_stdout.readline() ReadBackLine2 = GNU_Units_stdout.readline() if 'conformability error' == ReadBackLine.strip(): raise ConvertUnitsError('ConvertUnits: conformability error') AnswerElement = ReadBackLine.strip() return float(AnswerElement.split()[1]) Thanks in advance, Duane From scott.daniels at acm.org Mon Apr 10 12:50:24 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 10 Apr 2006 09:50:24 -0700 Subject: Characters contain themselves? In-Reply-To: References: <1144419901.071235.158590@g10g2000cwb.googlegroups.com> Message-ID: <443a89e6$1@nntp0.pdx.net> WENDUM Denis 47.76.11 (agent) wrote: >... From the answers I've got it seems I'll have to check if I'm > iterating on a string or on another kind of "list".... >>>> import sys >>>> sys.setrecursionlimit(10) >>>> def f(List): > ... try: # assuming List supports iteration > ... new=[f(item) for item in List] > ... except:# if no iteration is possible > ... new=1 > ... return new >>>> f([1, [2,3]]) # f substitutes each non iterable item by 1 (silly >>>> butshows the problem) > [1, [1, 1]] >>>> f([1, [2.3, (5,6,7)]]) > [1, [1, [1, 1, 1]]] >>>> f('bac') > [[[[[[[[1]]]]]]], [[[[[[[1]]]]]]], [[[[[[[1]]]]]]]] >>>> sys.setrecursionlimit(5) >>>> f('bac') > [[[1]], [[1]], [[1]]] >>>> # each item in 'bac' is a character, > ie. a string of length one on wich one can iterate > and so triggers an infinite descent of recursion. I'd rewrite your 'f' as follows: def copier(List): try: # assuming List supports iteration new = [f(item) for item in List] except TypeError: # Non-iterables get replaced return '?' except RuntimeError: # Recursion failures get shown return 'Recursion' return new Note, even if you got your wish and somehow you couldn't have an issue with characters in strings, you would have to deal with this: simple_list = [3.1415] container = [simple_list] simple_list.append(container) Your function (and mine) assumes the argument is a DAG (Directed Acyclic Graph), but there is no such guarantee about data structures in python. --Scott David Daniels scott.daniels at acm.org From n.estner at gmx.de Fri Apr 28 19:39:33 2006 From: n.estner at gmx.de (nikie) Date: 28 Apr 2006 16:39:33 -0700 Subject: best way to determine sequence ordering? References: <70q4g.2006$No6.43783@news.tufts.edu> <1146259620.636600.119710@u72g2000cwu.googlegroups.com> Message-ID: <1146267573.382477.316730@v46g2000cwv.googlegroups.com> I V wrote: > On Fri, 28 Apr 2006 14:27:00 -0700, nikie wrote: > > Steven Bethard wrote: > > > >> >>> L = ['C', 'A', 'D', 'B'] > >> >>> positions = dict((item, i) for i, item in enumerate(L)) > > Do you need the generator expression here? dict(enumerate(L)) should be > equivalent, no? I think the generator is needed to swap the item and the index. dict(enumerate(L)) would yield a dict like {0:'C', 1:'A'...} > > Isn't this bound to be less efficient? I mean, inserting the items into > > a dict is probably O(n log n), which is definitely worse than O(n) for > > searching the list twice. And, of course, it would yield different > > results if 'A' or 'D' are in the list more than once. > > Although presumably the dict method might be quicker if you were comparing > the positions a large number of times. Only if you build the dict once, but called index each and every time, which is comparing apples with oranges... > Incidentally, does python have a built-in to do a binary search on a > sorted list? Obviously it's not too tricky to write one, but it would be > nice if there was one implemented in C. I once read in an algorithm book that it took 10 years from the first binary search publication until a correct version was published, so, it actually is a bit tricky... Better stick to the bisect module. Don't know if it's written in C, though. From larry.bates at websafe.com Fri Apr 21 19:52:44 2006 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 21 Apr 2006 18:52:44 -0500 Subject: Finding Module Dependancies In-Reply-To: <1145657885.389499.232600@t31g2000cwb.googlegroups.com> References: <1145657885.389499.232600@t31g2000cwb.googlegroups.com> Message-ID: mwt wrote: > When I'm rewriting code (cutting and pasting pieces from earlier > modules), is there a quick way to determine if I have imported all the > necessary modules? I am used to working in Java, where the compiler > will tell you if you haven't imported everything, and also Eclipse, > which has the handy "organize imports" feature. This is not the case in > Python, since it's not compiled, of course, and also running it might > not insure you've got all the imports, unless you go through every > possible usage scenario -- which in some cases is quite a few, and > could take a long time. > > So what I'm looking for is a command, like "check dependencies" or > something, which will list all the modules needed for a source module > to run. > If you are an accomplished Eclipse user (I'm not), you should look at the Python plug-in for Eclipse. Remember that Python is so dynamic that you can build dependencies during program execution and import them on-the-fly. So a dependency checker would always be incomplete. You always need to write unit tests. -Larry Bates From martin at v.loewis.de Wed Apr 26 13:15:18 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 26 Apr 2006 19:15:18 +0200 Subject: Query regarding support for IPv6 in python In-Reply-To: References: Message-ID: <444FAAA6.40204@v.loewis.de> Pramod TK wrote: > Is this new function getaddrinfo() of IPv6 is supported in Win32 Extensions > for python. Yes, since Python 2.4 (actually, not in the Win32 extensions, but in the standard Python socket module for Win32). Regards, Martin From me at modelnine.org Thu Apr 27 02:13:01 2006 From: me at modelnine.org (Heiko Wundram) Date: Thu, 27 Apr 2006 08:13:01 +0200 Subject: Query regarding support for IPv6 in python In-Reply-To: References: Message-ID: <200604270813.01239.me@modelnine.org> Am Mittwoch 26 April 2006 17:02 schrieb Pramod TK: > 1. Does python support IPv6? [128 bit IP addresses?] Yes. > 2. Does it support setting of QoS flags? Yes. That's a socket option which you can set just as you would set it using C (at least under Unix, under Windows: no idea). > 3. Does it support tunneling of IPv6 on a IPv4 network? No. That's an OS's job. You could, of course, implement a 6in4-tunnel using TUN interfaces, completely in Python. But I don't think that's what you want to do. And, anyway, your host OS would need IPv6 support for this to work. I wouldn't know how you'd go about implementing this on Windows, though. > 4. If an IPv4 address is given, does it support this on a IPv6 network? Depends on the OS. If the OS supports 6to4, then Python does too (because an IPv4-Adress is simply mapped to an IPv6-Network with a certain notation, look up the documentation for the 2001::-network on Wikipedia, for example). If the OS doesn't, Python doesn't either. This is also an OS job, not a Python job. --- Heiko. From jstroud at ucla.edu Mon Apr 24 22:19:23 2006 From: jstroud at ucla.edu (James Stroud) Date: Mon, 24 Apr 2006 19:19:23 -0700 Subject: Hooking things up in GUI application In-Reply-To: References: Message-ID: Ryan Ginstrom wrote: > Apropos recent threads about GUI editors, coming from a Win32/WTL C++ > background, I actually like the idea of being able to (easily) create GUIs > programmatically. > > But I still see a lot of the same tedium: hooking up events to handlers, and > getting data into and out of dialogs. In C++, this is generally handled > through code generation and/or macros, but IMO these are brittle and ugly. > > So my question: Is there a Pythonic way to make these tedious hookups easier? > > --- > Regards, > Ryan Ginstrom > I'm not sure any python gui has anything similar, but I hear cocoa users raving about something called KVO. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From tprimke at interia.pl Fri Apr 14 02:36:02 2006 From: tprimke at interia.pl (TPJ) Date: 13 Apr 2006 23:36:02 -0700 Subject: A problem with exec statement Message-ID: <1144996562.237621.110500@t31g2000cwb.googlegroups.com> I have the following code: ----------------------------------- def f(): def g(): a = 'a' # marked line 1 exec 'a = "b"' in globals(), locals() print "g: a =", a a = 'A' # marked line 2 exec 'a = "B"' in globals(), locals() print "f: a =", a g() f() ----------------------------------- I don't understand, why its output is: f: a = A g: a = a instead of: f: a = B g: a = b All works as intended, if the marked lines are commented out. I just don't understand, why. (I suppose I don't understand, how the exec statement works, or the way Python handles objects, their names and namespaces...) In my opinion (according to my knowledge about Python), with or without the marked lines commented, the code should work the same. Well - I think I have to learn more about Python... According to my knowledge, the most important are the namespaces: the local ones, in this case. When Python calls the f function, its namespace is created. This namespace contains only the g function. Then the a variable is created (and the "a" name is added to the f function namespace). The next statement is the exec one. Since the statement "knows" the local namespace (obtained from the locals() function), it should replace the value of the a variable in the local namespace with the value of the new string "B". I don't understand, why this is not done. The situation in the g function is similar, the only difference is that the local namespace contains the "a" name, that refers to a different Python object. From vbgunz at gmail.com Fri Apr 28 02:12:08 2006 From: vbgunz at gmail.com (vbgunz) Date: 27 Apr 2006 23:12:08 -0700 Subject: append function problem? References: <1146196184.408569.197960@i40g2000cwc.googlegroups.com> Message-ID: <1146204728.368465.61180@i39g2000cwa.googlegroups.com> seed = [1,2,3] seed.append(4) print seed # [1,2,3,4] many of the list methods are in place methods on a mutable object. In other words, doing the following results in None. seed = [1,2,3] seed = seed.append(4) print seed # None you also just wiped out your list... The append method like many other list methods simply return None. To get the value of an append, append first then access later like so. seed = [1,2,3] seed.append(4) print seed # [1,2,3,4] From istvan.albert at gmail.com Mon Apr 3 16:20:39 2006 From: istvan.albert at gmail.com (Istvan Albert) Date: 3 Apr 2006 13:20:39 -0700 Subject: MOO meets Python In-Reply-To: References: Message-ID: <1144095639.090725.323290@u72g2000cwu.googlegroups.com> Quote from the webpage: "It's a buggy bundle of Python code that, by default, opens interfaces to your computer and makes it insecure." ... just what I was looking for ... From michele.petrazzo at TOGLIunipex.it Thu Apr 6 12:34:44 2006 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Thu, 06 Apr 2006 18:34:44 +0200 Subject: shelve and ".bak .dat .dir" files In-Reply-To: References: <443502c0$0$29101$5fc30a8@news.tiscali.it> Message-ID: <44354322$0$29096$5fc30a8@news.tiscali.it> Sion Arrowsmith wrote: > > This is a documented behaviour of shelve: Sorry, I had read only the: """Open a persistent dictionary. The filename specified is the base filename""" ... :) > I guess this depends on what dbm shelve is built on the documentation > implies it goes through anydbm. I'm not seeing this behaviour on my > Debian 3.1 In my tries, I see that if I use a "simple" script that open, use and save the shelve data, it work without problems, but if I use shelve into my application, I has this behaviour. (and I fail to understand why > it is a problem). > Because: 1) I pass a name that, after, I'll pass to another program and if shelve change the name, the latter can't read it (it doesn't exists!) 2) I can't read those files with shelve! If I try... : >>> shelve.open("test.dat") Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.3/shelve.py", line 231, in open return DbfilenameShelf(filename, flag, protocol, writeback, binary) File "/usr/lib/python2.3/shelve.py", line 212, in __init__ Shelf.__init__(self, anydbm.open(filename, flag), protocol, writeback, binary) File "/usr/lib/python2.3/anydbm.py", line 80, in open raise error, "db type could not be determined" anydbm.error: db type could not be determined And this with all the three types. Thanks, Michele From duncan.booth at invalid.invalid Wed Apr 26 10:29:43 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 26 Apr 2006 14:29:43 GMT Subject: Importing modules through directory shortcuts on Windows References: Message-ID: Brian Quinlan wrote: > Anyway, the problem is that Windows does not have a symlink facility to > accommodate this (AFAIK) and the Python import mechanism does not > resolve shortcuts. Windows does have the equivalent of symlinks provided you are running on NTFS with Windows 2000 or later (Google for 'XP junction'). However, by default the system provides no support for manipulating junction points, so they are only really useful in an environment where you can control the tools on the system, not something you can expect to use on arbitrary systems. From adonisv at DELETETHISTEXTearthlink.net Mon Apr 10 09:14:45 2006 From: adonisv at DELETETHISTEXTearthlink.net (Adonis) Date: Mon, 10 Apr 2006 13:14:45 GMT Subject: "Locate" command in Python In-Reply-To: <1144651800.278586.124560@e56g2000cwe.googlegroups.com> References: <1144633799.467327.15450@i39g2000cwa.googlegroups.com> <5Fj_f.2567$Es3.1608@newsread3.news.atl.earthlink.net> <1144651800.278586.124560@e56g2000cwe.googlegroups.com> Message-ID: <9Ts_f.2665$Es3.2057@newsread3.news.atl.earthlink.net> BartlebyScrivener wrote: > How about one of these that works on Windows XP? I know there's no > files.cache, but I wonder if your script could be combined with another > function that would generate a list of paths on a Windows XP machine. > > Anyway, thanks for the script. > I wrote it on a Windows XP machine. The files.cache is generated when you use the -u option. For example if you saved the script as locate.py first at a command prompt: python locate.py -u this will create the files.cache, it simply walks through your entire hard drive writing all the directories and files it finds along the way. Then doing: python locate.py SomeFileOrDirName will go through the files.cache matching whatever term your looking for if present. Although the rootPath variable is set to the POSIX style path of "/" Python converts it to a proper path. At least thats my assumption as it works fine on my system. Adonis From max at alcyone.com Thu Apr 13 17:00:52 2006 From: max at alcyone.com (Erik Max Francis) Date: Thu, 13 Apr 2006 14:00:52 -0700 Subject: New Karrigel page in Wikipedia In-Reply-To: <1144915559.734587.131140@e56g2000cwe.googlegroups.com> References: <1144867025.095969.92870@e56g2000cwe.googlegroups.com> <1144915559.734587.131140@e56g2000cwe.googlegroups.com> Message-ID: Ben Sizer wrote: > Why is Wikipedia being abused for software promotion and documentation? > Articles on Wikipedia are supposed to be from a neutral point of view > and purely informative, not biased or instructive. Because it's Wikipedia? This kind of garbage is the inevitable result of an "encyclopedia" which anyone can edit. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Sitting in the den and / Looking at the phone as if it owed / Owed me a favor -- Blu Cantrell From lucaberto at libero.it Fri Apr 28 04:55:40 2006 From: lucaberto at libero.it (luca72) Date: 28 Apr 2006 01:55:40 -0700 Subject: Direct acces to db unify on unix sco In-Reply-To: <1146208689.533833.84850@y43g2000cwc.googlegroups.com> References: <1146123680.837469.200940@y43g2000cwc.googlegroups.com> <1146208689.533833.84850@y43g2000cwc.googlegroups.com> Message-ID: <1146214540.673141.186100@v46g2000cwv.googlegroups.com> Thanks Luca From benchline at gmail.com Fri Apr 14 11:32:49 2006 From: benchline at gmail.com (benchline) Date: 14 Apr 2006 08:32:49 -0700 Subject: jpype and zxJDBC In-Reply-To: <443add94$1_2@newspeer2.tds.net> References: <1144511109.359283.140960@z34g2000cwc.googlegroups.com> <1144706301.999452.118940@z34g2000cwc.googlegroups.com> <443add94$1_2@newspeer2.tds.net> Message-ID: <1145028769.546711.167870@t31g2000cwb.googlegroups.com> I haven't compared them, and you may be exacly right. Paul From dakman at gmail.com Wed Apr 19 09:18:11 2006 From: dakman at gmail.com (dakman at gmail.com) Date: 19 Apr 2006 06:18:11 -0700 Subject: Telnet Server Lib In-Reply-To: <1145394277.295466.82410@g10g2000cwb.googlegroups.com> References: <1145394277.295466.82410@g10g2000cwb.googlegroups.com> Message-ID: <1145452691.944727.80570@g10g2000cwb.googlegroups.com> Does anybody have any ideas? From onurb at xiludom.gro Wed Apr 12 04:52:06 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 12 Apr 2006 10:52:06 +0200 Subject: About classes and OOP in Python In-Reply-To: <00rn321nv3oqbjesmqpdl4p0s3tgdj7o2f@4ax.com> References: <1144678797.749000.155010@t31g2000cwb.googlegroups.com> <1144743716.408970.23840@z34g2000cwc.googlegroups.com> <00rn321nv3oqbjesmqpdl4p0s3tgdj7o2f@4ax.com> Message-ID: <443cc001$0$27992$626a54ce@news.free.fr> Casey Hawthorne wrote: >>I think it's important not to wrongly confuse 'OOP' with ''data hiding' >>or any other aspect you may be familiar with from Java or C++. The >>primary concept behind OOP is not buzzwords such as abstraction, >>encapsulation, polymorphism, etc etc, but the fact that your program >>consists of objects maintaining their own state, working together to >>produce the required results, as opposed to the procedural method where >>the program consists of functions that operate on a separate data set. > > > Isn't "inheritance" an important buzzword for OOP? Which kind of inheritance ? subtyping or implementation inheritance ?-) FWIW, subtyping is implicit in dynamically typed languages, so they don't need support for such a mechanism. And implementation inheritance is not much more than a special case of composition/delegation, so it's almost useless in a language that have a good support for delegation (which we have in Python, thanks to __getattr__/__setattr__). -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From rridge at csclub.uwaterloo.ca Fri Apr 28 14:25:34 2006 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: 28 Apr 2006 11:25:34 -0700 Subject: MinGW and Python References: Message-ID: <1146248734.511062.115290@j73g2000cwa.googlegroups.com> Ross Ridge write: > No one is working on removing MinGW's depency on MSVCRT.DLL. Ames Andreas wrote: > There is certainly work underway to ease the use of msvcrXX in > mingw built binaries. Danny makes it pretty clear in the message you refered that he's not working on that. > 2) legal issues: redistribution of msvcrXX ... > No. 2 could be a show-stopper. You'd have to point people who don't already have it to Microsoft's download site. This wouldn't be ideal, but then Python already points Windows users to Microsoft's download site if they don't have MSI already installed. > There remains one technical issue that isn't a killer but would > be inconvenient, IMHO: Can pywin32 be made working with a > mingw-python (I'm quite sure it can't be made building on it)? I don't why it couldn't. It works with old versions of Python that use MSVCRT.DLL. I think that having current versions of Python also linked MSVCRT.DLL, whether compiled with MinGW or MSVC 6, 7 or 8, could be over all be a better solution than using a CRT DLL specific to one version of Microsoft's compiler. It would make it possible to build extentions with any version of MSVC, instead of just the one that Python was built with. Ross Ridge From s99999999s2003 at yahoo.com Thu Apr 6 06:16:14 2006 From: s99999999s2003 at yahoo.com (s99999999s2003 at yahoo.com) Date: 6 Apr 2006 03:16:14 -0700 Subject: how to touch a file Message-ID: <1144318574.250269.104320@j33g2000cwa.googlegroups.com> hi i have a dir that contains directories with names and spaces in between example rootdir | ----> ABC DEF A | ---> BDD SD N I wanted to touch a file with the same name as the directories inside each directory rootdir | ----> ABC DEF A |-------> ABC DEF A-dummy | ---> BDD SD N |-------> BDD SD N-dummy heres the code : for d in os.walk(rootdir): (dirpath, dirnames, filenames) = d for dir in [dirpath]: if not os.path.exists( os.path.join(dir,"-dummy") ): f = open( os.path.join(dir,"-dummy") , "w").write("") but i got only "-dummy" as the filename in each directory How can i deal with spaces in this case? or is there some wrong things i do in the code? thanks for any help. From juanernestof at hotmail.com Thu Apr 27 20:44:11 2006 From: juanernestof at hotmail.com (JUAN ERNESTO FLORES BELTRAN) Date: Fri, 28 Apr 2006 00:44:11 +0000 Subject: [pygtk] Advanced Treeview Filtering Trouble In-Reply-To: <44512445.4060300@moeraki.com> Message-ID: Thanks a lot!!!!! it did work!! :) From bencvt at gmail.com Mon Apr 24 22:24:11 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 24 Apr 2006 19:24:11 -0700 Subject: Multiple hierarchie and method overloading In-Reply-To: References: Message-ID: <1145931851.526941.231680@v46g2000cwv.googlegroups.com> Philippe Martin wrote: > I have something like this: > > Class A: > def A_Func(self, p_param): > ..... > Class B: > def A_Func(self): > ..... > > Class C (A,B): > A.__init__(self) > B.__init__(self) > > ..... > > self.A_Func() #HERE I GET AN EXCEPTION "... takes at least 2 arguments (1 > given). > > > I renamed A_Func(self) to fix that ... but is there a cleaner way around ? When using multiple inheritence, the order of the base classes matters! E.g.: class A(object): def f(self): print 'in A.f()' class B(object): def f(self): print 'in B.f()' class X(A, B): pass class Y(B, A): pass >>> x = X() >>> x.f() in A.f() >>> y = Y() >>> y.f() in B.f() If you want to call B.f() instead of A.f() for an X instance, you can either rename B.f() like you've done, or do this: >>> B.f(x) in B.f() --Ben From cretin at des.alpes.ch Wed Apr 5 20:01:09 2006 From: cretin at des.alpes.ch (Azolex) Date: Thu, 06 Apr 2006 02:01:09 +0200 Subject: Counting all permutations of a substring In-Reply-To: <1144271242.858677.124490@t31g2000cwb.googlegroups.com> References: <1144271242.858677.124490@t31g2000cwb.googlegroups.com> Message-ID: <44345a50$1_2@news.bluewin.ch> [counting all (possibly overlapping) occurences of a substring in a string] def count_subs(s,subs,pos=0) : pos = 1+s.find(subs,pos) return pos and 1+count_subs(s,subs,pos) or equivalently def count_subs(s,subs) pos,cnt = 0,0 while True : pos = 1+s.find(subs,pos) if not pos : return cnt cnt += 1 or even (using the helper functions of my last post in the "small challenge" thread) def count_subs(s,subs) : cnt = 0 for pos1 in echoback(1+s.find(subs,pos) for pos in itially(0)) : if not pos1 : return cnt cnt += 1 (I've minimally tested only the first version) From steve at REMOVETHIScyber.com.au Tue Apr 11 21:32:51 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Wed, 12 Apr 2006 11:32:51 +1000 Subject: list.clear() missing?!? References: <1144767680.583085.310160@v46g2000cwv.googlegroups.com> <1144792144.168802.146310@i39g2000cwa.googlegroups.com> Message-ID: On Tue, 11 Apr 2006 14:49:04 -0700, Ville Vainio wrote: > John Salerno wrote: > >> Thanks guys, your explanations are really helpful. I think what had me >> confused at first was my understanding of what L[:] does on either side >> of the assignment operator. On the left, it just chooses those elements >> and edits them in place; on the right, it makes a copy of that list, >> right? (Which I guess is still more or less *doing* the same thing, just >> for different purposes) > > Interestingly, if it was just a "clear" method nobody would be confused. Even more importantly, you could say help(list.clear) and learn something useful, instead of trying help(del) and getting a syntax error. >>> help(del) File "", line 1 help(del) ^ SyntaxError: invalid syntax I know Python isn't a purely OOP language, but in my opinion using statements like del should be avoided when there is an easy and natural OO way of doing it. Something like name.del() which means "delete the reference to name in name's namespace" feels wrong, and may not even be possible with Python's object model, so del name is a natural way to do it. But name.clear() meaning "mutate the object referenced by name to the empty state" is a very natural candidate for a method, and I don't understand why lists shouldn't have it. For lists, it would be natural to have a hypothetical clear() method accept an index or slice as an argument, so that these are equivalent: del L[:] <=> L.clear() del L[n] <=> L.clear(n) del L[a:b] <=> L.clear(slice(a, b)) # untested reference implementation: class ClearableList(list): def clear(self, obj=None): if obj is None: obj = slice(0, len(self)) if isinstance(obj, int): self.__delitem__(obj) elif isinstance(obj, slice): self.__delslice__(obj.start, obj.stop) else: raise TypeError -- Steven. From michaeltaft at gmail.com Fri Apr 21 20:21:43 2006 From: michaeltaft at gmail.com (mwt) Date: 21 Apr 2006 17:21:43 -0700 Subject: Finding Module Dependancies In-Reply-To: <444971D3.6010104@lexicon.net> References: <1145657885.389499.232600@t31g2000cwb.googlegroups.com> <444971D3.6010104@lexicon.net> Message-ID: <1145665303.788362.183390@i40g2000cwc.googlegroups.com> John Machin wrote: > > This is called "testing". Yes, it could take a long time. Thanks for the clarification. ;) Actually, I've done hellish amounts of testing on these code pieces, which is why I don't want to have to do it all over again just to check the imports. > > Consider pychecker and pylint. I haven't tried pylint, but pychecker > does what you want and a whole lot more: > > C:\junk>type miss_import.py > # need to import re, but forgot > def my_isdigit(s): > return bool(re.match(r"\d+", s)) > > C:\junk>pychecker miss_import > > C:\junk>c:\python24\python.exe > c:\python24\Lib\site-packages\pychecker\checker.py miss_import > Processing miss_import... > > Warnings... > > miss_import.py:3: No global (re) found > > C:\junk> That sounds really useful. I'll check it out. Thanks! From roy at panix.com Wed Apr 19 10:18:42 2006 From: roy at panix.com (Roy Smith) Date: Wed, 19 Apr 2006 14:18:42 +0000 (UTC) Subject: Missing interfaces in Python... References: <1145306373.781129.305840@z34g2000cwc.googlegroups.com> <1he0aen.324fes1th8n52N%aleaxit@yahoo.com> <1he14gl.z8faxb1ifoa5aN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: >Roy Smith wrote: > ... >> > A class asserting, e.g., "implements IPainter", doesn't thereby risk >> > being accidentally misused where an IGunslinger is required (OTOH, >> > implementing >1 of these IS a bother, but that's sort of inevitable). >> >> I suppose, but all you've really done is move the problem to a different >> namespace. Which IPainter did you have in mind? The one that has to do >> with people who apply oils to canvas, or the one that has to do with ropes >> that are used to tie up rowboats? > >In Java's excellent naming convention for modules, there's no ambiguity: >I specifically requested it.aleax.artists.IPainter, or else specifically >requested com.panix.roy.boating.IPainter -- nothing stops any language >with a structured namespace for modules from using that convention. This is true. This is one of the things Java does well. From spamspam at spam.eggs Wed Apr 5 17:14:03 2006 From: spamspam at spam.eggs (Ben C) Date: 5 Apr 2006 21:14:03 GMT Subject: how to convert string References: <1144261976.640631.9280@e56g2000cwe.googlegroups.com> <443417e7$1@nntp0.pdx.net> Message-ID: On 2006-04-05, Scott David Daniels wrote: > Ben C wrote: >> ... But this puts an extra space on the end (so did the print i, >> version above). > Actually, no (the trailing-comma prints do a funny dance). > Check it out: [...] You're right, I tried it! Thanks for that. Useful, although I hope Python doesn't turn into a "do what I mean" language... From timothy.williams at nvl.army.mil Tue Apr 11 14:39:12 2006 From: timothy.williams at nvl.army.mil (timw.googlepost) Date: 11 Apr 2006 11:39:12 -0700 Subject: installing pyodbc Message-ID: <1144780752.914805.304260@u72g2000cwu.googlegroups.com> I just downloaded the pyodbc source to try and install on my Linux FC3 box. I see that there is a setup.py file, but when I try to do a 'python setup.py build' (or just 'python setup.py') I get Traceback (most recent call last): File "setup.py", line 27, in ? revision = latest_revision('.') File "setup.py", line 25, in latest_revision return int(output) ValueError: invalid literal for int(): exported The README.txt doesn't really say anything about how to install, exept that the easiest way is to use the Windows installer. That's fine for Windows, but what about Linux? Thanks for any help. From ishtar2020 at hotmail.com Tue Apr 4 14:39:19 2006 From: ishtar2020 at hotmail.com (ishtar2020) Date: 4 Apr 2006 11:39:19 -0700 Subject: Strange problem when running python code Message-ID: <1144175959.412184.187110@g10g2000cwb.googlegroups.com> Hi everybody I've been writing my very first application in Python and everything is running smoothly, except for a strange problem that pops up every once in a while. I'm sure is the kind of newbie thing every seasoned programmer knows. Sometimes a receive strange Syntax Errors from parts of code that worked perfectly minutes ago. What's even more puzzling is that those errors are pointed to another part of the module when I do some random, innofensive changes in the code (like inserting a line or deleting some comments). Sometimes those changes are enough to make the error dissapear. Could it be that python has found a real error but is failing to tell me where it is? From python at cgcreator.com Fri Apr 14 02:30:39 2006 From: python at cgcreator.com (python at cgcreator.com) Date: Fri, 14 Apr 2006 02:30:39 -0400 (EDT) Subject: wx.DC problem Message-ID: <2880.59.167.41.140.1144996239.squirrel@wm0> I?m trying to create a way to pass the wx.dc object between multiple object, and its mostly working I can get two different panels to draw to the same DC but when I scale the window out it looks like the 2nd panel is getting blocked by something, im not sure if its a OnPaint problem or Maybe something with me hiding the second panel. Please help me out here thanks Attached is my two python scripts that im using use the test.py to test the PaintPanel script.. -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: PaintPanel.py URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: test.py URL: From felipe.lessa at gmail.com Tue Apr 11 10:16:02 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Tue, 11 Apr 2006 11:16:02 -0300 Subject: Why new Python 2.5 feature "class C()" return old-style class ? In-Reply-To: <1144763398.243329.231380@g10g2000cwb.googlegroups.com> References: <1144752553.305591.88050@j33g2000cwa.googlegroups.com> <1144756774.177225.311120@z34g2000cwc.googlegroups.com> <443ba5a9$0$14281$626a54ce@news.free.fr> <1144763398.243329.231380@g10g2000cwb.googlegroups.com> Message-ID: <1144764962.4227.11.camel@kenshin.CASA> Em Ter, 2006-04-11 ?s 06:49 -0700, looping escreveu: > But in an other hand, > I believe that new-style class are faster to instanciate (maybe I'm > wrong...). $ python2.4 -m timeit -s 'class x: pass' 'x()' 1000000 loops, best of 3: 0.435 usec per loop $ python2.4 -m timeit -s 'class x(object): pass' 'x()' 1000000 loops, best of 3: 0.316 usec per loop -- Felipe. From moishyyehuda at gmail.com Tue Apr 25 11:15:29 2006 From: moishyyehuda at gmail.com (Moishy Gluck) Date: Tue, 25 Apr 2006 08:15:29 -0700 Subject: How do I open a mysql database with python Message-ID: <187d38240604250815u447c47f8p148ddc6a38615082@mail.gmail.com> How do I open a mysql database with python. I nead a module that is compatible with windows, and will be on any regular server I singup with. if you could give me some documentation on the module that would be good also. Thanks From usidoesit at yahoo.com Tue Apr 25 09:30:14 2006 From: usidoesit at yahoo.com (RK) Date: 25 Apr 2006 06:30:14 -0700 Subject: python application ideas. In-Reply-To: References: Message-ID: <1145971814.148633.145220@v46g2000cwv.googlegroups.com> I need a python source code diagrammer that actually works out-of-the-box to explore all the code already written out there. something like SmallWorlds was to java before they got rid of it. From cncprgr at aim.com Mon Apr 10 16:16:12 2006 From: cncprgr at aim.com (dc) Date: 10 Apr 2006 13:16:12 -0700 Subject: newbie: Need Help Moving Data from Kirbybase to Gadfly References: <1144683061.069346.297680@v46g2000cwv.googlegroups.com> Message-ID: <1144700172.451352.44840@g10g2000cwb.googlegroups.com> I have muddle through this and gotten my script to work. Corrected code attached. # get global modules for python import os import sys #get database manager module from kirbybase import KirbyBase, KBError # open a database, embedded db = KirbyBase() result=db.select('test2.tbl', ['recno'],['*'], returnType='object') # open Gadfly database for storing data import gadfly connection = gadfly.gadfly("subscription", "pvfd_sql") #connection.startup("subscription", "pvfd_sql") cursor = connection.cursor() # Insert all records into SQL Database for record in result: ln=str(record.lastname).strip("'") fn=str(record.firstname).strip("'") ci=str(record.city).strip("'") st=str(record.state).strip("'") ad=str(record.address).strip("'") zi=str(record.zip).strip("'") ph=str(record.phone).strip("'") sql = "INSERT INTO addresslist (lastname, firstname,CITY, STATE, ADDRESS, ZIPCODE, PHONE) VALUES(?,?,?,?,?,?,?)" cursor.execute(sql,(ln, fn, ci, st, ad, zi, ph)) print "adding..." connection.commit() connection.close #------------------------------------------------------------------------------ # End of Script #------------------------------------------------------------------------------ From reedobrien at gmail.com Sat Apr 1 10:32:10 2006 From: reedobrien at gmail.com (reedobrien at gmail.com) Date: 1 Apr 2006 07:32:10 -0800 Subject: Python 2.5 licensing: stop this change In-Reply-To: References: Message-ID: <1143905530.340222.75910@g10g2000cwb.googlegroups.com> That isn't in the published 2.5 License. http://docs.python.org/dev/ref/node110.html Thanks for the scare.. ~r From garylinux at gmail.com Fri Apr 14 13:39:07 2006 From: garylinux at gmail.com (garylinux at gmail.com) Date: 14 Apr 2006 10:39:07 -0700 Subject: Python editing with emacs/wordstar key bindings. References: Message-ID: <1145036347.591993.112550@j33g2000cwa.googlegroups.com> This is new to me. I did not know that emacs HAD a word star mode..... I may have to look at emacs again (last time was 1995). I am still looking for a python editor I like. Yes I used to write asm code in wordstar in nondocument mode. And yes all of the old dos editors used the wordstar keys. Everything by Borland used them. Because of this I still use the 'joe' editor when I am on the command line and cooledit(with wstar like bindings) on X. I like the features on other editors but I need my wstar keys. From sdavies6 at nyc.rr.com Sat Apr 8 20:16:02 2006 From: sdavies6 at nyc.rr.com (sdavies6) Date: Sun, 09 Apr 2006 00:16:02 GMT Subject: Do I Need This? References: <1PSZf.18681$cY3.16958@news-wrt-01.rdc-nyc.rr.com> <1144519521.433149.162030@z34g2000cwc.googlegroups.com> Message-ID: <6nYZf.20110$cY3.9813@news-wrt-01.rdc-nyc.rr.com> "Paul Boddie" wrote in message news:1144519521.433149.162030 at z34g2000cwc.googlegroups.com... > sdavies6 wrote: >> I have no idea how this got onto my month old HP computer; I must have >> downloaded something which uses it. It seems I have a folder and >> subfolders >> equaling about 29 MB, called PYTHON 22. The subfolders are "DLLs," >> "Lib," >> "libs," "Scripts," and, "td." I am not a programmer, so I'm wondering if >> I >> can safely remove this. > > See this page for some advice: > > http://www.python.org/doc/faq/installed/ > > Paul > Thank you very much. Right on point. I'm just gonna leave it there; can't hurt anything. Steven From auch-ich-m at g-kein-spam.com Mon Apr 24 17:28:08 2006 From: auch-ich-m at g-kein-spam.com (=?UTF-8?B?QW5kcsOp?= Malo) Date: Mon, 24 Apr 2006 23:28:08 +0200 Subject: C API - tp_getattro and tp_methods References: <1145910179.468987.266850@u72g2000cwu.googlegroups.com> <2341353.ZoQ3i2GqUK@news.perlig.de> <1145911852.768851.36030@t31g2000cwb.googlegroups.com> Message-ID: <3945369.6RQT0EcFBM@news.perlig.de> * williams.jasonscott at gmail.com wrote: >> tp_getattro is like defining __getattribute__, i.e. it gets called on >> every attribute read access. You can use PyObject_GenericGetAttr inside >> the function to find predefined attributes before applying your own >> rules. > > Thanks for the reply. I see and was afraid of that, I don't have a > predefinded list of attributes. I want to get them from the C library > as needed. Is there another way I should be accessing the data from my > C lib since it isn't known at compile time? Well, methods *are* predefined attributes (which just happen to be callable and bound to the instance). You can use PyObject_GenericGetAttr like this: static PyObject * mytype_getattro(mytypeobject *self, PyObject *name) { PyObject *tmp; if (!(tmp = PyObject_GenericGetAttr((PyObject *)self, name))) { if (!PyErr_ExceptionMatches(PyExc_AttributeError)) return NULL; PyErr_Clear(); } else return tmp; /* your code */ } - or - explicitly define __getattr__ in tp_methods (instead of tp_getattro), which only gets called on unknown attributes then. nd -- die (eval q-qq:Just Another Perl Hacker :-) # Andr? Malo, # From jdhunter at ace.bsd.uchicago.edu Mon Apr 3 14:35:38 2006 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Mon, 03 Apr 2006 13:35:38 -0500 Subject: can I get the index number in for x in y loop? References: <1144078372.411795.21570@i39g2000cwa.googlegroups.com> <1144078792.350510.57870@i39g2000cwa.googlegroups.com> <1144079271.758144.92070@v46g2000cwv.googlegroups.com> <44314f92$1@nntp0.pdx.net> Message-ID: <87r74ese11.fsf@peds-pc311.bsd.uchicago.edu> >>>>> "Scott" == Scott David Daniels writes: Scott> I cannot find the distance in meters between Paris and Scott> London with: for i in range(10): print i Works for me def range(x): yield '332.8 km' for i in range(10): print i ...may not be considered best practice, though JDH From jjl at pobox.com Thu Apr 20 18:20:31 2006 From: jjl at pobox.com (John J. Lee) Date: 20 Apr 2006 22:20:31 +0000 Subject: send cookie on request with urllib2 References: <1145539129.322307.77220@z34g2000cwc.googlegroups.com> <4447ffcb$1_2@newspeer2.tds.net> Message-ID: <87lktzx51s.fsf@pobox.com> Kent Johnson writes: > itay_k wrote: > > Hi, > > > > I dont understand why this is so complicated, just to add one line of > > cookie header on the GET request. > > > > This is my unworking code: > > import time > > import Cookie > > import cookielib, urllib2 > > > > c= cookielib.Cookie(1,"Name","Tom", 80,False, "itay", False, False, > > "d:\\asddd",False, False,time.time()+1000,False,None,None,None) > > ^^^^ path is the server path to which the cookie applies. Try '/'. """ "No," scolded Yoda. "Do, or do not. There is no try." """ (there, a Star Wars quote -- I guess there's truly no hope of ever erasing my geek status now!-) Why guess? Why not log in (using Python) and see what the cookie actually is? Once you've actually done that, there's nothing to stop you storing it as a Cookie constructor call. I know I certainly don't remember all the *truly horrendous* detail of what *exactly* all those parameters mean :-) The Cookie object, as is documented, is merely a struct object and it is easy to construct incorrect and even self-inconsistent Cookie objects; CookieJar has all the knowledge about constructing cookies -- and allows use of that knowledge through .make_cookies() and .load()/.revert(). John From webraviteja at gmail.com Tue Apr 4 20:56:33 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 4 Apr 2006 17:56:33 -0700 Subject: Standalone Python functions in UML? In-Reply-To: References: <1144145349.186395.44890@z34g2000cwc.googlegroups.com> Message-ID: <1144198593.264275.131480@i39g2000cwa.googlegroups.com> > So, function could be a utility class method. If there are no better ways. What I mean is <> is the formal notation for a class in which global functions are aggregated. It's not a hack. Python is not alone here. Most OO languages aside Java and Smalltalk have functions outside classes and UML accomodates though not encourages free functions. > Well, maybe SOL (Semantic Object Language) could also be quite beneficial in some cases. At least, it depends with whom to communicate design ideas and what level of formality to maintain. I don't know what Semantic Object Language is. One important requirement of choosing communication notations is that they should be sufficiently popular that everyone understands. Kind of beats the purpose if you are the only person who knows it. I got 146 hits on Google for "Semantic Object Language" and UML. Too few for me to care. If it is a deserving notation, hopefully that will change in the future. > Also, my argument that Python is quite good at communicating design ideas is supported by the fact that Python developers do not use UML (or other modelling tools/languages) as often as say Java programmers, nor feel the need to. I guess you and I mean VERY different things when we say "Design Ideas". You seem to imply pseudo code. I mean overall archetecture. I think Python devs will use UML tools if there are good ones available. I know I would. I could really use a round trip class and package diagram editor now. > And probably Python is too dynamic for UML. That is another reason rountrip tools aren't there. As you probably already know, UML diagrams are structural and behavioural (plus interactional with 2.0). Round trip tools only model structural diagrams. Python is dynamic but only once the program starts executing :-). Even though Python classes "can" change, they do so only at runtime ( wouldn't it be scary if they decided to change as code when you are not looking :-) ). So dynamism of Python should not be as much of an issue. I think the reason we don't have good UML round trip tools for Python is primarily a market issue rather than a language issue. If Python gets the same market share as Java, it will surely get all these tools and more. From fulvio at pc.jaring.my Thu Apr 13 08:36:11 2006 From: fulvio at pc.jaring.my (Fulvio) Date: Thu, 13 Apr 2006 20:36:11 +0800 Subject: Figure out month number from month abbrievation In-Reply-To: References: <1144873227.982973.18720@i40g2000cwc.googlegroups.com> <200604131911.40313.fulvio@pc.jaring.my> Message-ID: <200604132036.11218.fulvio@pc.jaring.my> Alle 20:16, gioved? 13 aprile 2006, Fredrik Lundh ha scritto: > >>> locale.setlocale(locale.LC_ALL, "it_IT") > > 'it_IT' Thank you Great & kind explanation F From albert at compuscan.co.za Mon Apr 3 07:59:53 2006 From: albert at compuscan.co.za (Albert Leibbrandt) Date: Mon, 03 Apr 2006 13:59:53 +0200 Subject: GIS Message-ID: <44310E39.4090801@compuscan.co.za> Hi I need to get myself familiarised with GIS, specifically postgis for postgres. Can anyone give some advice, or some docs that start at the beginning. I've tried the postgis mailing list but it does not seem as if that list is very active. Perhaps you guys know of gis packages for python? Thanks Albert From g.brandl-nospam at gmx.net Wed Apr 12 13:02:26 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Wed, 12 Apr 2006 19:02:26 +0200 Subject: list.clear() missing?!? In-Reply-To: References: <1144767680.583085.310160@v46g2000cwv.googlegroups.com> <1144792144.168802.146310@i39g2000cwa.googlegroups.com> Message-ID: John Salerno wrote: > Steven Bethard wrote: > >> I think these are all good reasons for adding a clear method, but being >> that it has been so hotly contended in the past, I don't think it will >> get added without a PEP. Anyone out there willing to take out the best >> examples from this thread and turn it into a PEP? > > What are the usual arguments against adding it? That there should be one obvious way to do it. Yes, I know that it can be debated whether "del x[:]" is obvious, and fortunately I'm not the one to decide . Georg From rpdooling at gmail.com Tue Apr 11 14:39:43 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 11 Apr 2006 11:39:43 -0700 Subject: Searching python-list and MySQL In-Reply-To: References: Message-ID: <1144780783.657674.302880@v46g2000cwv.googlegroups.com> Oh, sorry, Richard, and to answer your question about Python and MySql, try searching on mxODBC, or better, search on "mxODBC Holden" as Steve Holden seems to answer every question on sql and Python. Hope that helps. rick From john at castleamber.com Sat Apr 29 16:14:02 2006 From: john at castleamber.com (John Bokma) Date: 29 Apr 2006 20:14:02 GMT Subject: Xah's Edu Corner: What Languages to Hate References: <1145992903.834316.198370@u72g2000cwu.googlegroups.com> <1146172923.830732.187130@i40g2000cwc.googlegroups.com> <20060427223335.6c8537e6.alex.buell@munted.org.uk> <1146254391.815629.145130@j33g2000cwa.googlegroups.com> <4453c6d2$0$4502$9b4e6d93@newsread2.arcor-online.net> Message-ID: Timo Stamm wrote: > I just wrote to the abuse department at dreamhost, telling them that > your accusations are highly exaggerated. I included Xah's post, on which they based their reply. Maybe use your weekend to do some research? -- John MexIT: http://johnbokma.com/mexit/ personal page: http://johnbokma.com/ Experienced programmer available: http://castleamber.com/ Happy Customers: http://castleamber.com/testimonials.html From mandelin at cs.berkeley.edu Tue Apr 4 17:19:23 2006 From: mandelin at cs.berkeley.edu (Dave Mandelin) Date: 4 Apr 2006 14:19:23 -0700 Subject: Dice probability problem References: Message-ID: <1144185563.778283.173220@v46g2000cwv.googlegroups.com> That looks reasonable. The operation you are implementing is known as 'convolution' and is equivalent to multiplying polynomials. It would be a little more general if you had the input 'die' be a sequence of the count for each outcome, so d6 would be [1]*6 (or [0]+[1]*6 if you prefer). That would allow allow you to represent unfair dice and also to add not just a die to a distribution, but to add any two distributions, so you can play tricks like computing 16d6 as (d6)*2*2*2*2. (The code above is a convolution that restricts the second distribution 'die' to have only 0 and 1 coefficients.) The general convolution can be implemented much like what you have, except that you need another multiplication (to account for the fact that the coefficient is not always 0 or 1). My not particularly efficient implementation: def vsum(seq1, seq2): return [ a + b for a, b in zip(seq1, seq2) ] def vmul(s, seq): return [ s * a for a in seq ] # Convolve 2 sequences # equivalent to adding 2 probabililty distributions def conv(seq1, seq2): n = (len(seq1) + len(seq2) -1) ans = [ 0 ] * n for i, v in enumerate(seq2): vec = [ 0 ] * i + vmul(v, seq1) + [ 0 ] * (n - i - len(seq1)) ans = vsum(ans, vec) return ans # Convolve a sequence n times with itself # equivalent to multiplying distribution by n def nconv(n, seq): ans = seq for i in range(n-1): ans = conv(ans, seq) return ans print nconv(3, [ 1 ] * 6) print nconv(3, [ 1.0/6 ] * 6) print nconv(2, [ .5, .3, .2 ]) [1, 3, 6, 10, 15, 21, 25, 27, 27, 25, 21, 15, 10, 6, 3, 1] [0.0046296296296296294, 0.013888888888888888, 0.027777777777777776, 0.046296296296296294, 0.069444444444444448, 0.097222222222222238, 0.11574074074074074, 0.125, 0.125, 0.11574074074074073, 0.097222222222222224, 0.069444444444444448, 0.046296296296296294, 0.027777777777777776, 0.013888888888888888, 0.0046296296296296294] [0.25, 0.29999999999999999, 0.29000000000000004, 0.12, 0.040000000000000008] From nnorwitz at gmail.com Thu Apr 20 03:32:56 2006 From: nnorwitz at gmail.com (Neal Norwitz) Date: Thu, 20 Apr 2006 00:32:56 -0700 Subject: Python Software Foundation seeks mentors and students for Google Summer of Code Message-ID: This spring and summer, Google will again provide stipends for students (18+, undergraduate thru PhD programs) to write new open-source code. The Python Software Foundation (PSF) http://www.python.org/psf/ will again act as a sponsoring organization in Google's Summer of Code, matching mentors and projects benefiting Python and Python users. Projects can include work on the core Python language, programmer utilities, libraries, packages, frameworks related to Python, or other Python implementations like Jython, PyPy, or IronPython. Please add your project ideas to the existing set at http://wiki.python.org/moin/SummerOfCode Mentoring instructions are also on this page. The deadline is soon, so please sign up as a mentor early. If you are a student considering a project, you should start deciding now. Feel free to ask questions on python-dev at python.org The main page for the Summer of Code is http://code.google.com/summerofcode.html At the bottom are links to StudentFAQ, MentorFAQ, and TermsOfService. The first two have the timeline. Note that student applications are due between May 1, 17:00 PST and May 8, 17:00 PST. People interested in mentoring a student though PSF are encouraged to contact me, Neal Norwitz at nnorwitz at gmail.com. People unknown to Guido or myself should find a couple of people known within the Python community who are willing to act as references. Feel free to contact me if you have any questions. I look forward to meeting many new mentors and students. Let's improve Python! Cheers, n From martin at v.loewis.de Sun Apr 2 13:19:18 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 02 Apr 2006 19:19:18 +0200 Subject: print() in Python 3000 return value? In-Reply-To: <1143997643.857261.186430@i40g2000cwc.googlegroups.com> References: <1143997643.857261.186430@i40g2000cwc.googlegroups.com> Message-ID: <44300797$0$28451$9b622d9e@news.freenet.de> James Thiele wrote: > I noticed in PEP 3000 that print will become a function. The PEP > references a thread where Guido explains this decision. The thread does > not specify what the function will return. Has this been decided? My intuition is that it should be a procedure (i.e. returning None). What do you want it to return? Regards, Martin From akraps at gmail.com Fri Apr 21 05:37:42 2006 From: akraps at gmail.com (akrapus) Date: 21 Apr 2006 02:37:42 -0700 Subject: threading, how to? Message-ID: <1145612262.485501.262300@i40g2000cwc.googlegroups.com> Hi, I am trying to understand how to use threading in Python. I get threading as a concept, but not the implementation. In order to start threading, do you call it as a separate function, which will then be applied to the rest of the code (functions) or do you open threading in each function. This all can probably be answered by 'How python threads different functions'? Hope if somebody can drop me a few lines. I've been trying with different tutorials, but still do not understand. Cheers, Stevan From johnjsal at NOSPAMgmail.com Thu Apr 6 17:25:11 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 06 Apr 2006 21:25:11 GMT Subject: good style guides for python-style documentation ? In-Reply-To: References: Message-ID: Fredrik Lundh wrote: > (reposted from doc-sig, which seems to be mostly dead > these days). > > over at the pytut wiki, "carndt" asked: > > Are there any guidelines about conventions concerning > punctuation, text styles and language style (e.g. how > to address the reader)? > > any suggestions from this list ? Just for fun one day, I extracted what I thought were the main points from the PEP and made a website for it: http://www.johnjsal.devisland.net/styleguide.html From sudharsh at gmail.com Sat Apr 8 12:37:56 2006 From: sudharsh at gmail.com (sudharsh at gmail.com) Date: 8 Apr 2006 09:37:56 -0700 Subject: Documentation for Tkinter/Tix In-Reply-To: References: Message-ID: <1144514276.746130.80330@z34g2000cwc.googlegroups.com> wesley's core python programming (i m havin the old one) has a good chaper on Tkinter. From lucaberto at libero.it Sat Apr 1 15:14:06 2006 From: lucaberto at libero.it (luca72) Date: 1 Apr 2006 12:14:06 -0800 Subject: wx.checklistbox In-Reply-To: References: <1143815725.730867.324970@j33g2000cwa.googlegroups.com> <1143900250.243912.309390@v46g2000cwv.googlegroups.com> Message-ID: <1143922446.596030.299380@i40g2000cwc.googlegroups.com> Thank Fredrik I try and then i will inform you Luca From tim at pollenation.net Wed Apr 5 04:42:19 2006 From: tim at pollenation.net (Tim Parkin) Date: Wed, 05 Apr 2006 09:42:19 +0100 Subject: "The World's Most Maintainable Programming Language" In-Reply-To: <44331897$0$12009$c3e8da3@news.astraweb.com> References: <44331897$0$12009$c3e8da3@news.astraweb.com> Message-ID: <443382EB.8040500@pollenation.net> John Salerno wrote: > There is an article on oreilly.net's OnLamp site called "The World's > Most Maintainable Programming Language" > (http://www.oreillynet.com/onlamp/blog/2006/03/the_worlds_most_maintainable_p.html). > > > It's not about a specific language, but about the qualities that would > make up the title language (learnability, consistency, simplicity, > power, enforcing good programming practices). I thought this might be of > interest to some of you, and I thought I'd point out the two places > where Python was mentioned: It's interesting to see a slightly different take on type checking.. "In the real world it is an error to put five pounds of potatoes in a ten pound sack" "The same might be true of computer games, where a type checker so careful that it might refuse to allow an operation where a 180-pound character can carry 10,000 gold pieces might actually remove the aspect of fun from the game." Isn't this data validation and if it is, should the compiler be checking this? Tim Parkin From mrbmahoney at gmail.com Fri Apr 21 14:02:40 2006 From: mrbmahoney at gmail.com (B Mahoney) Date: 21 Apr 2006 11:02:40 -0700 Subject: Property In Python References: <1145607499.712267.178120@j33g2000cwa.googlegroups.com> Message-ID: <1145642560.250255.143140@u72g2000cwu.googlegroups.com> I started with the "How-To Guide for Descriptors" by Raymond Hettinger http://users.rcn.com/python/download/Descriptor.htm It is one of several docs on the "New-style Classes" page at python.org http://www.python.org/doc/newstyle/ From rpdooling at gmail.com Mon Apr 10 11:07:02 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 10 Apr 2006 08:07:02 -0700 Subject: can't pass command-line arguments In-Reply-To: References: <1144676885.317592.21780@e56g2000cwe.googlegroups.com> Message-ID: <1144681621.999659.78880@z34g2000cwc.googlegroups.com> >> print "running",__file__ Well, I tried to let this die because I just KNEW I was going to look like an idiot before it was over. It's the .pyc versus the .py file. Obviously I don't understand how that works yet. The .pyc file lags behind the .py file? So when I run cbfindfiles.py I'm running the .py version and when I run cbfindfiles it's running the .pyc version which is not the same between edits. No need to explain. I'll go read up on how that .pyc file is generated. Sorry for the trouble. Rick From johnjsal at NOSPAMgmail.com Wed Apr 5 15:16:31 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 05 Apr 2006 19:16:31 GMT Subject: PIL question about crop method In-Reply-To: <49ii6rFoffn9U1@uni-berlin.de> References: <49ii6rFoffn9U1@uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > Alternatively you can see it as boundary lines, in the order left, top, > right, bottom. > > (10, 20, 30, 100) So in the above, from where are the numbers being counted? 10 is ten pixels from the left border of the image? 20 is twenty pixels from the top border? But is 30 thirty pixels from the left or the right border of the image? And is 100 one hundred pixels from the top or bottom? From michaeltaft at gmail.com Fri Apr 21 20:30:18 2006 From: michaeltaft at gmail.com (mwt) Date: 21 Apr 2006 17:30:18 -0700 Subject: Finding Module Dependancies In-Reply-To: <1145665303.788362.183390@i40g2000cwc.googlegroups.com> References: <1145657885.389499.232600@t31g2000cwb.googlegroups.com> <444971D3.6010104@lexicon.net> <1145665303.788362.183390@i40g2000cwc.googlegroups.com> Message-ID: <1145665818.173363.223020@i40g2000cwc.googlegroups.com> Wow! Just ran pychecker on a couple of modules. I'm blown away by how much information I'm getting. Thanks again! From rpdooling at gmail.com Tue Apr 18 09:38:13 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 18 Apr 2006 06:38:13 -0700 Subject: Ironpython book? In-Reply-To: <4ak7gpFo52lsU1@uni-berlin.de> References: <1145329406.419299.12780@i40g2000cwc.googlegroups.com> <1hdyh5s.1ithyei4n7ucmN%aleaxit@yahoo.com> <1145334081.117264.75050@u72g2000cwu.googlegroups.com> <1hdykd6.1ubb4c1jh6mfmN%aleaxit@yahoo.com> <1145342633.307500.235390@v46g2000cwv.googlegroups.com> <4ak7gpFo52lsU1@uni-berlin.de> Message-ID: <1145367493.212255.77470@i39g2000cwa.googlegroups.com> >> I can't comment on this in general, but on the CCC (Chaos Communication >> Congress, a Hacker-con) last year the notebook-distribution was like this: Now THAT sounds like a fun event for a journalist to cover! I'll have to look into that one. Thanks rick From sjmachin at lexicon.net Tue Apr 4 08:23:31 2006 From: sjmachin at lexicon.net (John Machin) Date: 4 Apr 2006 05:23:31 -0700 Subject: Convertion of Unicode to ASCII NIGHTMARE In-Reply-To: <1144150561.389856.302670@v46g2000cwv.googlegroups.com> References: <1144079830.734516.8390@z34g2000cwc.googlegroups.com> <1144081137.137744.253790@i39g2000cwa.googlegroups.com> <34b9g3-ku8.ln1@home.rogerbinns.com> <1144150561.389856.302670@v46g2000cwv.googlegroups.com> Message-ID: <1144153411.671614.115700@e56g2000cwe.googlegroups.com> "Thus you lose data, but thats just dandy with me.": Please reconsider this attitude, before you perpetrate a nonsense or even a disaster. Wrt your last para: 1. Roger didn't say "ignore" -- he said "won't accept" (a major difference). 2. The ASCII code comprises 128 characters, *NOT* 256. 3. What Roger means is: given a Python 8-bit string and no other information, you don't have a clue what the encoding is. Most codes of interest these days have the ASCII code (or a mild perversion thereof) in the first 128 positions, but it's anyones guess what the writer of the string had in mind with the next 128. From peter at engcorp.com Wed Apr 12 20:30:30 2006 From: peter at engcorp.com (Peter Hansen) Date: Wed, 12 Apr 2006 20:30:30 -0400 Subject: list.clear() missing?!? In-Reply-To: References: <1144767680.583085.310160@v46g2000cwv.googlegroups.com> <1144870852.886477.238570@u72g2000cwu.googlegroups.com> Message-ID: Alan Morgan wrote: > Right. I was wondering what would happen in this case: > > s=[1,2,3] > t=s > s.clear() > t # [] or [1,2,3]?? > > If you know your basic python it is "obvious" what would happen > if you do s=[] or s[:]=[] instead of s.clear() and I guess it is > equally "obvious" which one s.clear() must mimic. I'm still not > used to dealing with mutable lists. If you know your basic python :-), you know that s[:] = [] is doing the only thing that s.clear() could possibly do, which is changing the contents of the list which has the name "s" bound to it (and which might have other names bound to it, just like any object in Python). It *cannot* be doing the same as "s=[]" which does not operate on the list but creates an entirely new one and rebinds the name "s" to it. The only possible answer for your question above is "t is s" and "t == []" because you haven't rebound the names. -Peter From invalidemail at aerojockey.com Thu Apr 6 01:44:08 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 5 Apr 2006 22:44:08 -0700 Subject: pre-PEP: The create statement References: <59Wdnbd8EazRCqnZnZ2dnUVZ_vudnZ2d@comcast.com> Message-ID: <1144302248.639529.161700@j33g2000cwa.googlegroups.com> Steven Bethard wrote: > This PEP proposes a generalization of the class-declaration syntax, > the ``create`` statement. The proposed syntax and semantics parallel > the syntax for class definition, and so:: > > create : > > > is translated into the assignment:: > > = ("", , ) > > where ```` is the dict created by executing ````. > The PEP is based on a suggestion [1]_ from Michele Simionato on the > python-dev list. And who needs a class statement after that? create type A: That's probably even more readable than class A, if not as familiar. My biggest concern with this is the special arguments of the caller. It breaks my heart that we couldn't do something like this: create dict keymap: A = 1 B = 2 And it'll probably confuse people as well. We ought to keep that in mind. > Of course, properties are only one of the many possible uses of the > create statement. The create statement is useful in essentially any > situation where a name is associated with a namespace. So, for > example, sub-modules could be created as simply as:: > > create module mod: > "This creates a sub-module named mod with an f1 function" > > def f1(): > ... Let's not do this, really. A module should be one-to-one with a file, and you should be able to import any module. Having in-line modules complicates everything. And it becomes a misnomer. So, please, let's get a better example. If you must, call it a scope or namespace. > Remove the create keyword > ------------------------- > > It might be possible to remove the create keyword so that such > statements would begin with the callable being called, e.g.: > > module mod: > def f1(): > ... > def f2(): > ... > > interface C(...): > ... I don't like it. It seems to violate the spirit of the pronouncement on programmable syntax. I presume if it passes then "class" would become a regular symbol and a synonym of "type". Overall, it seems like an idea worth considering. In fact, I'd be in favor of phasing out "class" in favor of "create type" in the interests of there being only one obvious way to do it. (Obviously not before Python 3000, though. The thing is, because the usage of "class" varies so little, updating code to use "create type" would be pretty automatic). Carl Banks From ivoras at __-fer.hr-__ Wed Apr 19 19:42:13 2006 From: ivoras at __-fer.hr-__ (Ivan Voras) Date: Thu, 20 Apr 2006 01:42:13 +0200 Subject: Simple DAV server? In-Reply-To: References: Message-ID: robert wrote: > > thanks, that's exactly to the point: > > python server.py 8080 mydavrootfolder Thanks for the patch, I assume it's free to incorporate it into the original archive? Also, see my reply to "Kyler Laird"... From jzgoda at o2.usun.pl Mon Apr 24 14:49:31 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Mon, 24 Apr 2006 20:49:31 +0200 Subject: i18n hell In-Reply-To: References: <1145853400.436212.26190@u72g2000cwu.googlegroups.com> <1145864322.901596.122290@i40g2000cwc.googlegroups.com> Message-ID: Martin Blais napisa?(a): > See > http://furius.ca/antiorm/ for something simple that works well. I'd like to know what is this module/library good for *before* I start downloading it. "Almost like ORM but not exactly" is rather vague term and can denote anything. Is it dishwasher? Or microwave oven? BTW, I don't have any problems without character encodings since I started using unicode objects internally in my programs. Database is the same kind of data source, as regular files, sockets or ttys -- you have to know client encoding before you start receiving data. Then decode it to unicode and you are fine. -- Jarek Zgoda http://jpa.berlios.de/ From bignose+hates-spam at benfinney.id.au Thu Apr 6 08:16:05 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 06 Apr 2006 22:16:05 +1000 Subject: Simple string formatting question References: <4434DCEC.4080308@REMOVEMEcyber.com.au> Message-ID: <87zmiyucfu.fsf@benfinney.id.au> "Steven D'Aprano" writes: > I have a sinking feeling I'm missing something really, really > simple. "Oh no, everyone in the galaxy gets that, that's perfectly natural paranoia." > I'm looking for a format string similar to '%.3f' except that > trailing zeroes are not included. Can;t be done, to my knowledge. You specify a particular precision, and the number will be formatted at that precision. This matches the 'printf' behaviour that inspired string formatting operations. If your brute-force approach works, stick to that until you have a reason to look for something better. -- \ "I have an answering machine in my car. It says, 'I'm home now. | `\ But leave a message and I'll call when I'm out.'" -- Steven | _o__) Wright | Ben Finney From antroy at gmail.com Fri Apr 21 06:30:55 2006 From: antroy at gmail.com (Ant) Date: 21 Apr 2006 03:30:55 -0700 Subject: proposed Python logo In-Reply-To: <1145585399.871299.31900@t31g2000cwb.googlegroups.com> References: <1145585399.871299.31900@t31g2000cwb.googlegroups.com> Message-ID: <1145615455.477800.74730@i39g2000cwa.googlegroups.com> Sorry dude, but it looks like a hairdryer! Imagine it at 16x16 pixels or smaller, and it'll look like little more than a circle with two sticks. The current image scales well. I think that the current logo is fine. Much more professional than the old image. The + formation is positive enough, and it has a yin-yang feel to it which to me conjures up the image of balance, not divisiveness. JM2PW From gabriel.becedillas at gmail.com Tue Apr 25 15:10:41 2006 From: gabriel.becedillas at gmail.com (gabriel.becedillas at gmail.com) Date: 25 Apr 2006 12:10:41 -0700 Subject: PyThreadState_SetAsyncExc and native extensions Message-ID: <1145992241.659509.4000@j33g2000cwa.googlegroups.com> Does anyone know if PyThreadState_SetAsyncExc stops a thread while its inside a native extension ? I'm trying to stop a testing script that boils down to this: while True: print "aaa" native_extension_call() print "bbb" Using PyThreadState_SetAsyncExc the module doesn't stop but if I add more print statements to increase the chance that PyThreadState_SetAsyncExc is called when the module is executing Python code, the module stops. From peter at engcorp.com Wed Apr 12 13:28:59 2006 From: peter at engcorp.com (Peter Hansen) Date: Wed, 12 Apr 2006 13:28:59 -0400 Subject: list.clear() missing?!? In-Reply-To: References: <1144767680.583085.310160@v46g2000cwv.googlegroups.com> <1144792144.168802.146310@i39g2000cwa.googlegroups.com> Message-ID: John Salerno wrote: > Steven Bethard wrote: >>I think these are all good reasons for adding a clear method, but being >>that it has been so hotly contended in the past, I don't think it will >>get added without a PEP. Anyone out there willing to take out the best >>examples from this thread and turn it into a PEP? > > What are the usual arguments against adding it? I think one is that it's very rare to need it. Most of the time, just rebinding the name to a new empty list is easier, and possibly faster. The main problem with that approach is that in multithreaded code that can be a source of subtle bugs. On the other hand, most things can be a source of subtle bugs in multithreaded code, so maybe that's not a good reason to add clear(). Saving us time answering the question repeatedly (and trying to justify the current state of affairs) might be justification enough... -Peter From gh at ghaering.de Wed Apr 26 10:20:15 2006 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 26 Apr 2006 16:20:15 +0200 Subject: blob problems in pysqlite In-Reply-To: <1146059708.820551.7250@i39g2000cwa.googlegroups.com> References: <1146059708.820551.7250@i39g2000cwa.googlegroups.com> Message-ID: <444F819F.9000804@ghaering.de> aldonnelley at gmail.com wrote: > Hi there. > > I'm a long-time lurker and (I think) first time poster. > Only relatively new to python, and I'm trying to get pysqlite to work > with binary data, and having a tough time of it. [...] It seems to me that you're using pysqlite correctly. Where exactly is the problem? Is the fetchall() not delivering what you think it should? If so, please explain what exactly it yields, and what you expect it to yield. -- Gerhard From dadapapa at googlemail.com Mon Apr 24 10:16:55 2006 From: dadapapa at googlemail.com (harold) Date: 24 Apr 2006 07:16:55 -0700 Subject: Subclass str: where is the problem? In-Reply-To: <1145886773.533093.65420@t31g2000cwb.googlegroups.com> References: <1145882577.827728.54960@j33g2000cwa.googlegroups.com> <1145883907.466748.325610@t31g2000cwb.googlegroups.com> <1145886773.533093.65420@t31g2000cwb.googlegroups.com> Message-ID: <1145888215.516117.255770@t31g2000cwb.googlegroups.com> Hi Pascal, Indeed, the example you show work corrctly. But in the code you posted before, you wonder about the behavior of these lines: > m = MyObject() > m.id > '' > type(m.id) > So what happens when you provide the empty string '' to your and-or construct? value = '' value = type(value) is type('') and Upper(value) or value As you can easily check, bool('') resolves to False. Thus, your line becomes: value = False and False or value Python first evaluates the and expression, which resolves to False. The or expression evaluates the second argument and returns that one as the result if and only if the first one evaluates to False, which is the case here. So the result of False or value is value. You can check that >>> value is (False or value) True so, in you code, the empty string gets indeed assign as value again. Be carefull with the condition/and/or chain! You must be 110% sure, that the desired return value in case of condition==True can never evaluate to False! - harold - From nobody at 127.0.0.1 Tue Apr 25 17:33:14 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Tue, 25 Apr 2006 21:33:14 GMT Subject: MinGW and Python References: <1145861223.509630.247350@y43g2000cwc.googlegroups.com> <444C79D7.4060007@v.loewis.de> <444DC62B.7000702@v.loewis.de> <1145985979.369429.114040@i39g2000cwa.googlegroups.com> <1145996649.514911.99880@g10g2000cwb.googlegroups.com> Message-ID: sturlamolden wrote: > Edward Elliott wrote: >> Couldn't you compile the msvc-python code under gcc/mingw? > > Yes I could, but I cannot compile the code under msvc for comparison. I > only have MinGW. If build the mingw binary then someone else has to > build the msvc binary for comparison. Then we could do pybenches on the > same computer. Sorry, I didn't mean you personally, I meant "you" in the general sense. > Uh .. I actually think it could be an EULA violation to publish mingw > vs. msvc benchmarks without permission from Microsoft. I don't want to > part of anything illegal or have M$ lawyers breathing down my back. If > we are going to do this, then we must do it properly and get the > permissions we need. Why, because of a "no benchmarks" clause in the EULA? First, I'm fairly certain that clause is uneforceable. Second, it's not worth MS's time to come after you. Third, even if they did, they'd have an incredibly tough time showing that any harm occured from your actions, leaving them with no recovery. Fourth, if it somehow came to that, you'd have organizations like the EFF lining up at your door to take the case gratis. I'm assuming US law here. Not saying you should do it, just that the risk in my opinion is extremely low. I am a law student, but this is not legal advice. From rridge at csclub.uwaterloo.ca Thu Apr 27 14:50:56 2006 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: 27 Apr 2006 11:50:56 -0700 Subject: MinGW and Python References: <1145861223.509630.247350@y43g2000cwc.googlegroups.com> <444C79D7.4060007@v.loewis.de> <444DC62B.7000702@v.loewis.de> <1145985979.369429.114040@i39g2000cwa.googlegroups.com> <1145995815.818582.166230@y43g2000cwc.googlegroups.com> <444FA85B.7010104@v.loewis.de> <1146088651.980286.97220@j33g2000cwa.googlegroups.com> <44505e03$0$13138$9b622d9e@news.freenet.de> <1146139371.544074.172700@g10g2000cwb.googlegroups.com> Message-ID: <1146163856.519720.254030@u72g2000cwu.googlegroups.com> sturlamolden wrote: > Cygwin executables are native windows ".exe files" just like MinGW > executables. They are built by the same compiler, a port of GCC to 32 > bit Windows originally written by Mumit Khan. No, Cygwin executables are built using a different port of GCC, the Cygwin port of GCC. The two ports are very similar, but the Cygwin port is a Cygwin application. That means, for example, it uses Cygwin pathnames instead of the standard Win32 pathnames that MinGW uses. Ross Ridge From DavidRushby at gmail.com Wed Apr 5 21:27:04 2006 From: DavidRushby at gmail.com (David Rushby) Date: 5 Apr 2006 18:27:04 -0700 Subject: IMPORTANT 2.5 API changes for C Extension Modules References: <1144219456.668201.201620@g10g2000cwb.googlegroups.com> Message-ID: <1144286824.765801.320360@z34g2000cwc.googlegroups.com> Thank you for taking the time to pull the relevant links together and make this post, Neal. From L.Plant.98 at cantab.net Thu Apr 20 04:06:28 2006 From: L.Plant.98 at cantab.net (Luke Plant) Date: 20 Apr 2006 01:06:28 -0700 Subject: Help! Identical code doesn't work in Wing IDE but does in Komodo. In-Reply-To: <1145519650.863418.274800@v46g2000cwv.googlegroups.com> References: <1145519650.863418.274800@v46g2000cwv.googlegroups.com> Message-ID: <1145520388.162227.169750@g10g2000cwb.googlegroups.com> > With the exact same line of code in Komodo I get the correct output > which is "Sample Feed" > > Any idea what's wrong? My guess would be different PYTHONPATHs. Try this on each: >>> import sys >>> print sys.path They might even be using different python versions - but both of these are just guesses. Luke From peter.maas at somewhere.com Tue Apr 18 15:11:36 2006 From: peter.maas at somewhere.com (Peter Maas) Date: Tue, 18 Apr 2006 21:11:36 +0200 Subject: Missing interfaces in Python... In-Reply-To: References: <1145306373.781129.305840@z34g2000cwc.googlegroups.com> <20060417210541.GV7561@vulcan.cprogrammer.org> Message-ID: Fredrik Lundh schrieb: > Jonathan Daugherty wrote_ > >> # In Python, you would simply call the functions you need. No need to >> # make things that rigidly defined. >> >> Except when you need to handle exceptions when those methods don't >> exist. I think interfaces can definitely be useful. > > so with interfaces, missing methods will suddenly appear out of thin > air ? He probably means that with interfaces one could test compliance with the interface as a whole instead of testing each member and each signature as a single piece. Peter Maas, Aachen From grflanagan at yahoo.co.uk Fri Apr 21 12:17:49 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 21 Apr 2006 09:17:49 -0700 Subject: how to append to a list twice? In-Reply-To: <1145632430.282522.102090@v46g2000cwv.googlegroups.com> References: <1145632430.282522.102090@v46g2000cwv.googlegroups.com> Message-ID: <1145636269.440949.197670@j33g2000cwa.googlegroups.com> Gerard Flanagan wrote: > John Salerno wrote: > > If I want to create a list of the form [100, 99, 99, 98, 98, 97, 97...] > > (where each item is repeated twice after the first one), how might I do > > that most efficiently? > > series = [100] > > for i in range(1,10): > series.extend([100-i]*2) > > print series > > [100, 99, 99, 98, 98, 97, 97, 96, 96, 95, 95, 94, 94, 93, 93, 92, 92, > 91, 91] Alternative: --------------------------------------------------------- series = [100] r = xrange(99,90,-1) for L in ( [a1,a2] for a1,a2 in zip( r, r ) ): series.extend(L) print series out: [100, 99, 99, 98, 98, 97, 97, 96, 96, 95, 95, 94, 94, 93, 93, 92, 92, 91, 91] --------------------------------------------------------- series = ['a'] r = 'bcdefgh' for L in ( [a1,a2] for a1,a2 in zip( r, r ) ): series.extend(L) print series out: ['a', 'b', 'b', 'c', 'c', 'd', 'd', 'e', 'e', 'f', 'f', 'g', 'g', 'h', 'h'] --------------------------------------------------------- Gerard From ataanis at gmail.com Mon Apr 24 10:01:58 2006 From: ataanis at gmail.com (ataanis at gmail.com) Date: 24 Apr 2006 07:01:58 -0700 Subject: MySql -Python question In-Reply-To: <9doo42hquanqru36173frhmk1nj4kb8848@4ax.com> References: <1145852748.327176.69080@j33g2000cwa.googlegroups.com> <9doo42hquanqru36173frhmk1nj4kb8848@4ax.com> Message-ID: <1145887318.445312.67130@e56g2000cwe.googlegroups.com> both of your suggestions don't work, that's kind of what I was trying the whole time From wahab at chemie.uni-halle.de Sat Apr 8 17:20:03 2006 From: wahab at chemie.uni-halle.de (Mirco Wahab) Date: Sat, 08 Apr 2006 23:20:03 +0200 Subject: how relevant is C today? In-Reply-To: <44381ee4$0$4209$c3e8da3@news.astraweb.com> References: <44381ee4$0$4209$c3e8da3@news.astraweb.com> Message-ID: Hi John > Because of my 'novice-ness' in programming, I had always thought that C > was replaced by C++ and wasn't really used anymore today. I know that's > not the case at all now, but I'm still curious how much C is used > anymore in programming today, and what purpose it serves. There is a whole spectrum of 'mixing' between features of C ans C++ used today in the industry and thats o.k. if it just works. You cal write plain C in a C++ environment, mix some C++ features to your otherwise plain C and so on - as you like. You can't compare C/C++'industrial use w/Python's in todays Software production - there is no match. A recent 580+ people survey (O'Reilly) brought up the following: http://www.onlamp.com/pub/a/onlamp/2005/12/02/onlamp_survey_results.html?page=2 "The Dice" (find tech jobs) has offerings (last 7 days, U.S. + unrestricted) for: *SQL 14,322 C/C++ 11,968 Java 10,143 ... Perl 3,332 PHP 730 *Python* 503 Fortran 119 Ruby 108 open*gl 66 That is what the industry looks for. You understand the ratios? > ... Is it used for > actual application programming, or is its use more for something like > extending Python? Would it help for a newbie to learn C for any reason? It is used for almost everything, from - Programming the Python Language itself, - Programming the Perl Language itself, - Programming the PHP language and others, to - complete Applications, as you said. It *is* somehow 'wordy' (especially C), but don't underestimate its power in the hands of a master ;-) There is a huge amount of highly functional libraries for almost everything too. Regards, M. From grante at visi.com Fri Apr 21 14:10:47 2006 From: grante at visi.com (Grant Edwards) Date: Fri, 21 Apr 2006 18:10:47 -0000 Subject: proposed Python logo References: <1145585399.871299.31900@t31g2000cwb.googlegroups.com> <1145628079.749480.191190@g10g2000cwb.googlegroups.com> <124hqel51rur33b@corp.supernews.com> <1145640106.269556.276060@u72g2000cwu.googlegroups.com> Message-ID: <124i8176of81331@corp.supernews.com> On 2006-04-21, Michael Tobis wrote: > (The main thing I dislike about Python is that the documentation is too > sketchy. Well, Monty Python was a pretty sketchy show... [sorry] > The best snake-and-language logos I have seen are the Twisted-Matrix > one and the PyCon one. Sincy Python wasn't named after the snake, why the insistence on using a snake in the logo? > But I think my idea can be developed too. I think the colon as > snake-eyes thing is a big win. We would think affectionately > of the snake every time we type the unnecessary colon. I think something Monty Python related would be better. How about a nice can of spam? I doubt our friends in Austin would like that idea. OTOH, there is a Monty Python "spam, spam, spam, spam" display in the spam museum (which is actually much more interesting than you might think). -- Grant Edwards grante Yow! ... Um...Um... at visi.com From ivan at ivan-herman.net Sat Apr 1 04:54:16 2006 From: ivan at ivan-herman.net (Ivan Herman) Date: Sat, 01 Apr 2006 11:54:16 +0200 Subject: Python 2.5 licensing: stop this change In-Reply-To: <1143881699.232542.224960@j33g2000cwa.googlegroups.com> References: <1143881699.232542.224960@j33g2000cwa.googlegroups.com> Message-ID: <442e4dc6$0$62914$dbd49001@news.euronet.nl> I would certainly look at *all details* of the announcement, including the second line from the top which gives the date:-) Ivan Caleb Hattingh wrote: > WAIT- > > Did I just get caught by an April Fools Joke? > > I have a nasty feeling about this :)) > > C > From rpdooling at gmail.com Wed Apr 26 18:20:57 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 26 Apr 2006 15:20:57 -0700 Subject: print names of dictionaries In-Reply-To: <1146086980.998908.281140@g10g2000cwb.googlegroups.com> References: <1146085818.242086.206290@e56g2000cwe.googlegroups.com> <1146086980.998908.281140@g10g2000cwb.googlegroups.com> Message-ID: <1146090057.616316.61990@y43g2000cwc.googlegroups.com> >> Of course, the easiest way is just to use a tuple (dict,string). I don't mean to be obtuse, but I'm not getting this one either. Is it easier than what I did? Thx, rick From ginstrom at tree.odn.ne.jp Thu Apr 6 06:15:31 2006 From: ginstrom at tree.odn.ne.jp (Ryan Ginstrom) Date: Thu, 6 Apr 2006 19:15:31 +0900 Subject: Using PythonWin32 to copy text to Windoze Clipboard for Unix-stylerandom .sig rotator? In-Reply-To: <1144317354.546106.167500@v46g2000cwv.googlegroups.com> Message-ID: <002e01c65963$0c9c44c0$030ba8c0@RYAN> > On > Behalf Of dananrg at yahoo.com > I want to write a Python script that, when launched, will choose a > random .sig (from a list of about 30 cool ones I've devised), > and store > the .sig text in the Windows Clipboard, so I can then paste > it into any > Windows application. You might try looking into wxPython.wx.wxTheClipboard However, unless this is soley for your own use, I would suggest you try a different method. In my experience, users get annoyed when their clipboard contents are stepped on. One general, if messy, solution is to use pywinauto to type the text in directly. Another (much more ambitious) project would be to create a private clipboard, save the current clipboard contents there, and then swap them back in when you are done. Regards, Ryan --- Ryan Ginstrom From johnjsal at NOSPAMgmail.com Tue Apr 4 21:02:09 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 04 Apr 2006 21:02:09 -0400 Subject: "The World's Most Maintainable Programming Language" Message-ID: <44331897$0$12009$c3e8da3@news.astraweb.com> There is an article on oreilly.net's OnLamp site called "The World's Most Maintainable Programming Language" (http://www.oreillynet.com/onlamp/blog/2006/03/the_worlds_most_maintainable_p.html). It's not about a specific language, but about the qualities that would make up the title language (learnability, consistency, simplicity, power, enforcing good programming practices). I thought this might be of interest to some of you, and I thought I'd point out the two places where Python was mentioned: from Part 4, Power: "Of course (second point), a language that requires users to extend it to be productive has already failed, unless it can enforce that there is one obvious solution to any problem and autonomously subsume the first working solution into the core language or library. Python is a good example of this practice. There is a strong polycultural subcommunity in the world of free and open source, and the members of this group consider the lack of competing projects in Python (one XML parser, one logging library, one networking toolkit) to be counterintuitive and even counter to the goal of language progress. They?re wrong; this is actually a strong force for cohesion in the language and community, where the correct answer to a novice?s question of ?How can I parse XML??, ?How can I publish a database-driven web site??, or even ?How can I integrate the legacy system of an acquired company from a different industry with our existing legacy system?? (to prove that this principle does not only apply to small or toy problems) is usually ?Someone else has already implemented the correct solution to that problem ? it is part of the standard library.?" from Part 5, Enforcing Good Programming Practices: "Having a comprehensive standard library helps alleviate this problem to some degree for many languages. Consider how PHP and Java have both avoided the trouble of conflicting addons by aggressively integrating new features into the language. (Of course, Python has done a similar job through a rigorous set of community procedures, but that?s difficult ? though not impossible ? to emulate in a parser and compiler.)" From aleaxit at yahoo.com Fri Apr 21 00:00:59 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 20 Apr 2006 21:00:59 -0700 Subject: perspective on ruby References: <1145555339.316764.123210@i39g2000cwa.googlegroups.com> Message-ID: <1he41sz.r7aasv1oo5lfN%aleaxit@yahoo.com> Edward Elliott wrote: ... > course in C++ doesn't cut it, the curriculum should either use different > languages fitted to each task or emphasize a single language with broad > abilities (picking the best programming model for each task). Java is The only "single language" I could see fitting that role is Mozart, deliberately designed to be SUPER-multi-paradigm -- not even Lisp and Scheme (the only real competition) can compare. While Mozart appears cool, I really think that a wider variety of languages would help -- some machine code (possibly abstract a la Mixal), C (a must, *SO* much is written in it!), at least one of C++, D, or ObjectiveC, either Scheme or Lisp, either *ML or Haskell, either Python or Ruby, and at least one "OOP-only" language such as Java, C#, Eiffel, or Smalltalk. For a tipycal CS bachelor course, a set of over half a dozen languages might be overkill, admittedly (particularly because these are just the "general purpose" languages -- you no doubt also want to present XML and friends, possibly XSLT, definitely SQL, and several other *special*-purpose language classes, too....!!!); too much time would end up devoted to semirelevant syntax differences... > Note that I'm talking about teaching languages. Outside the classroom my > choices would be completely different. Absolutely, I'm thinking about CS courses specifically -- for science and engineering courses, I'd have much different sets (yes, Virginia, there ARE fields where you still absolutely need to know Fortran!-), for humanities and soft-sciences other ones yet, and the real world is a different (and frightening;-) sort of place!-) Alex From duncan.booth at invalid.invalid Tue Apr 11 10:43:05 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 11 Apr 2006 14:43:05 GMT Subject: Why new Python 2.5 feature "class C()" return old-style class ? References: <1144752553.305591.88050@j33g2000cwa.googlegroups.com> <1144756774.177225.311120@z34g2000cwc.googlegroups.com> <443ba5a9$0$14281$626a54ce@news.free.fr> <1144763398.243329.231380@g10g2000cwb.googlegroups.com> <443bbdbe$0$15517$626a54ce@news.free.fr> Message-ID: bruno at modulix wrote: >> cause is bother me to >> type "(object)" when I don't need their features. > > Please repeat this 101 times each morning: > "thou shall not use old-style classes for they are deprecated". It's a pity though that Python still uses old-style classes internally, even for some things which are brand new: >>> from __future__ import with_statement >>> type(with_statement) (yes, I know that the _Feature class isn't actually new, just this particular instance of it.) From felipe.lessa at gmail.com Sun Apr 2 09:08:00 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Sun, 02 Apr 2006 10:08:00 -0300 Subject: Exception handling....dumb question? In-Reply-To: <1143982411.571726@isa.mirotel.net> References: <1143849093.457940.294150@g10g2000cwb.googlegroups.com> <1143982411.571726@isa.mirotel.net> Message-ID: <1143983280.4221.7.camel@kenshin.CASA> Em Dom, 2006-04-02 ?s 15:54 +0300, Flexx escreveu: > Ben Finney writes: > > This allows all other exceptions to propogate back through the call > > stack. > > import sys, logging > try: > foo = 12/0 > except: > e = str(sys.exc_value) > print "You *knew* this was going to happen: '%s'" % (e) > logging.error(e) The point (I think) Ben was trying to show is that you should not hide exceptions from the caller's code unless you expected that exception. For example: def percentage(now, total): """Returns the percentage of now in total.""" return now * 100.0 / total Very simple. What if I do "percentage(1, 0)"? The code expected me to be clever enough to know that you can't make a percentage when the total is zero, so it lets the exception pass by to my code (like: "it's your problem, not mine!"): >>> percentage(1, 0) Traceback (most recent call last): File "", line 1, in ? File "", line 3, in percentage ZeroDivisionError: float division But if your function is being used on a context where total can be zero and it has a meaning, for example, returning -1, then _in_this_case_ you should catch the exception: def percentage(now, total): """Returns the percentage of now in total. If total is zero, then return -1. """ try: return now * 100.0 / total except ZeroDivisionError: return -1 >>> percentage(1, 0) -1 But this function won't catch exceptions if you don't give it numbers: >>> percentage(None, 1) Traceback (most recent call last): File "", line 1, in ? File "", line 7, in percentage TypeError: unsupported operand type(s) for *: 'NoneType' and 'float' But this is also a problem on the caller's code! You should *not* hide it from him! But if None is valid in the context of your code, then... well, you get the point! =) HTH, -- Felipe. From ivoras at __-fer.hr-__ Wed Apr 19 19:45:47 2006 From: ivoras at __-fer.hr-__ (Ivan Voras) Date: Thu, 20 Apr 2006 01:45:47 +0200 Subject: Simple DAV server? In-Reply-To: References: Message-ID: Kyler Laird wrote: > I added the ability to create and delete collections (directories), > delete members (files), authenticate users, and run per-user setuid/ > setgid. It works well with Cadaver but I'm waiting for some MS users > to report how it works under Windows. > > The only thing on my list right now is to make it report the times for > collections (directories). Already it's looking like a nice solution > for my needs. And it was *so* much easier to hack than Apache. Thank you for such a nice response :) If you or anybory else (robert?) is interested, I can set up a SourceForge project for it so patches & contribution can be easily managed? From arne.meissner at gmx.de Wed Apr 12 12:05:11 2006 From: arne.meissner at gmx.de (Arne) Date: Wed, 12 Apr 2006 18:05:11 +0200 Subject: ftp connection and commands (directroy size, etc) Message-ID: Hello everybody! I am working on Windows XP and I want to do the following: 1. Connecting to a server using ftp 2. Getting the directory structure and the size of each directory in the root 3. Getting the owner of a file All these steps I want to do with python. What I already have is: 1. Connecting to ftp import ftplib ftp = ftplib.FTP('host') ftp.login(') directory = '/' ftp.cwd(directory) linelist = [] ftp.retrlines('LIST', linelist.append) ftp.close() 2. Getting the directory structure and the size of each directory in the root But I am don't know how to send commands to ftp and capturing the result If have tried: a = [] a=ftp.sendcmd('Dir') By trying to get the directory with 'dir', I am getting an Error 500 result. Furthermore I don't know how to get the directory size. Even I don't know the best command for it. 3. Getting the owner of a file Can I get the owner for one file? I know with the LIST you get them all. Please be so kind and post a little bit of a solution code Thank you very much! Arne From ndbecker2 at gmail.com Wed Apr 19 10:06:10 2006 From: ndbecker2 at gmail.com (Neal Becker) Date: Wed, 19 Apr 2006 10:06:10 -0400 Subject: Missing interfaces in Python... References: <1145306373.781129.305840@z34g2000cwc.googlegroups.com> Message-ID: redefined.horizons at gmail.com wrote: > I'm coming from a Java background, so please don't stone me... > > I see that Python is missing "interfaces". The concept of an interface > is a key to good programming design in Java, but I've read that they > aren't really necessary in Python. I am wondering what technique I can > use in Python to get the same benefits to a program design that I would > get with interfaces in Java. > > For example, if I want to have a program with a Car object, and a Bus > object. I want both of these objects to present a common group of > methods that can be used by Mechanic objects, but slightly different > methods that can be used by Driver objects. > > In Java I would accomplish this by defining an IFixable interface that > would be implemented by both the Car and Bus objects. Mechanic objects > would work with any object implementing this interface. > > How would I approach this problem in Python? I think I would use an > abstract class instead of an interface for IFixable, since Python > supports multiple inheritance, but I'm not sure this is correct. > > Thanks for any suggestions. > I see various answers that Python doesn't need interfaces. OTOH, there are responses that some large Python apps have implemented them (e.g., zope). Does anyone have an explanation of why these large systems felt they needed to implement interfaces? From a at bc.de Sun Apr 16 00:29:35 2006 From: a at bc.de (Mr. M) Date: Sun, 16 Apr 2006 00:29:35 -0400 Subject: Numpy and cPickle In-Reply-To: References: Message-ID: Martin Manns wrote: > Robert Kern wrote: >> Martin Manns wrote: > >>> If I cPickle a numpy array under Linux and un-cPickle it under Solaris >>> 10, my arrays seem to be transposed. >> Transposed? That's odd. There was a byteorder issue with pickles going across >> differently-endianed platforms that was fixed in the past few days. Could you >> come up with a small bit of code that shows the problem and post it and the >> incorrect output to the bug tracker? > > Sorry, I my ad-hoc small example does not reproduce the error even > though the files generated on both platforms differ. I will try to set > up the code tomorrow. Somehow, the bug does not show up any more. I believe it was due to the numpy version that is fetched by cPickle. Is there any way to control (or even determine), which library version cPickle grabs for unpickling a numpy array (numpy, scipy, etc)? From iainking at gmail.com Tue Apr 25 04:26:50 2006 From: iainking at gmail.com (Iain King) Date: 25 Apr 2006 01:26:50 -0700 Subject: Counting elements in a list wildcard In-Reply-To: <1145921582.526072.120480@u72g2000cwu.googlegroups.com> References: <1145921582.526072.120480@u72g2000cwu.googlegroups.com> Message-ID: <1145953610.077361.320290@y43g2000cwc.googlegroups.com> hawkesed wrote: > If I have a list, say of names. And I want to count all the people > named, say, Susie, but I don't care exactly how they spell it (ie, > Susy, Susi, Susie all work.) how would I do this? Set up a regular > expression inside the count? Is there a wildcard variable I can use? > Here is the code for the non-fuzzy way: > lstNames.count("Susie") > Any ideas? Is this something you wouldn't expect count to do? > Thanks y'all from a newbie. > Ed Dare I suggest using REs? This looks like something they'de be good for: import re def countMatches(names, namePattern): count = 0 for name in names: if namePattern.match(name): count += 1 return count susie = re.compile("Su(s|z)(i|ie|y)") print countMatches(["John", "Suzy", "Peter", "Steven", "Susie", "Susi"], susie) some other patters: iain = re.compile("(Ia(i)?n|Eoin)") steven = re.compile("Ste(v|ph|f)(e|a)n") john = re.compile("Jo(h)?n") Iain From kruhftREMOVE at gmail.com Thu Apr 13 13:53:11 2006 From: kruhftREMOVE at gmail.com (Burton Samograd) Date: 13 Apr 2006 11:53:11 -0600 Subject: function prototyping? Message-ID: <87hd4x1hx4.fsf@gmail.com> Hi, Is there any way to 'prototype' functions in python, as you would in C? Would that be what the 'global' keyword is for, or is there a more elegant or 'pythonic' way of doing forward references? -- burton samograd kruhft .at. gmail kruhft.blogspot.com www.myspace.com/kruhft metashell.blogspot.com From roger.miller at nova-sol.com Fri Apr 28 16:51:50 2006 From: roger.miller at nova-sol.com (Roger Miller) Date: 28 Apr 2006 13:51:50 -0700 Subject: Add file to zip, or replace file in zip In-Reply-To: <1146226281.040805.252450@j33g2000cwa.googlegroups.com> References: <1146226281.040805.252450@j33g2000cwa.googlegroups.com> Message-ID: <1146257509.963417.250250@g10g2000cwb.googlegroups.com> First note that zipfile is a plain Python module, so reading Python.../Lib/zipfile.py will reveal all its secrets. I don't think it is possible to replace archive members using the module. You could copy all the files into a new zip file, replacing the ones you want to change as you go. But it might be easier just to use os.system() or something similar to run an external zip program. From nogradi at gmail.com Sun Apr 30 11:41:18 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Sun, 30 Apr 2006 17:41:18 +0200 Subject: Converting tuple to String In-Reply-To: <1146411167.835198.19230@e56g2000cwe.googlegroups.com> References: <1146411167.835198.19230@e56g2000cwe.googlegroups.com> Message-ID: <5f56302b0604300841x7aa7687ey4a348d47ff609e0a@mail.gmail.com> > Is their a command to convert a tuple to string? e.g. > > xyz = "Hello", "There" > print xyz > > Is their any way of getting print to see xyz as being one string i.e. > "Hello There" rather than "Hello" and "There", despite "Hello" and > "There" being, in reality, seperate? Try one_big_string = ''.join( xyz ) print one_big_string Hope this helps. From deets at nospam.web.de Fri Apr 21 06:50:46 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 21 Apr 2006 12:50:46 +0200 Subject: threading, how to? References: <1145612262.485501.262300@i40g2000cwc.googlegroups.com> <1145616278.477085.101860@v46g2000cwv.googlegroups.com> Message-ID: <4arro7Fu848rU1@uni-berlin.de> akrapus wrote: > Thanks for reply. > > So would it be implemented as follows: > > Func 1 > Func 2 > Func 3 > > Thread for Func 1 > Thread for Func 2 > Thread for Func 3 Could be, but the you woul most probably subclass threading.Thread and override the run-method. However, often it is done like this: def some_threaded_function(): while though_shalt_work(): do_work() for i in xrange(THRAD_NUM): t = threading.Thread(target=some_threaded_function) t.start() Diez From deets at nospam.web.de Mon Apr 3 09:51:39 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 03 Apr 2006 15:51:39 +0200 Subject: GIS References: <44310E39.4090801@compuscan.co.za> Message-ID: <49cno0Fo28agU1@uni-berlin.de> I need to create a sphere with a certain size. I have x and y > coordinates which I then need to calculated the distances between. > I use postgresql, that is why I am looking at postgis. > > If anybody knows of any documentation (except for what is on the postgis > homepage) please let me know as I seam to have problems with the > installation, postgres does not recognize the functions although the > functions exist. That is a question to ask on the postgis mailing list. And I can't see any postings of you there so far... I can tell you that I have successfully installed postigis with PG 8.0 and 8.1 - under a debian system. Just by following the available documentation. Diez From claudio.grondi at freenet.de Wed Apr 26 12:31:10 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Wed, 26 Apr 2006 18:31:10 +0200 Subject: I have problems with creating the classic game Wumpus. the file: http://esnips.c In-Reply-To: <1146061532.208523.145370@g10g2000cwb.googlegroups.com> References: <1146061532.208523.145370@g10g2000cwb.googlegroups.com> Message-ID: Ben Sizer wrote: > connyledin wrote: > >>Im trying to create a version of the game Wumpus. Mine is called >>Belzebub. But im STUCK! And its due tuesday 2 maj. Im panicing! Can >>some one help me?? >>here is the file: >>http://esnips.com/webfolder/b71bfe95-d363-4dd3-bfad-39999a9e36d0 >> >>What i have the biggest problems with now is between line 8 and 23. > > > Perhaps you could post those lines so we get an idea of what's going > wrong. You also really need to explain what exactly you are hoping to > achieve, and in what way it isn't working. I don't think anybody is > likely to give you a full solution because that would defeat the > object. > I have trouble to get rid of the impression, that the (hidden from direct detection) goal of the original posting is some kind of promotion. Claudio From michele.simionato at gmail.com Tue Apr 11 05:43:00 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 11 Apr 2006 02:43:00 -0700 Subject: updated pre-PEP: The create statement In-Reply-To: References: <443a9c60$1_1@news.bluewin.ch> Message-ID: <1144741861.753019.288680@g10g2000cwb.googlegroups.com> Steven Bethard wrote: > Azolex wrote: > > Steven Bethard wrote: > >> and named, nested hierarchies like XML documents could be created > >> like:: > >> > >> create ETobject html: > >> "This statement would generate an ElementTree object" > >> > >> create ETobject head: > >> "generate the head" > >> ... > >> > >> create ETobject body: > >> "generate the body" > >> ... > > > > I think this is is a most important eventual use-case, and would like to > > see it better worked out - or else declared outside the scope of the > > proposed statement. As far as I can see, this does not cut it, since xml > > and html allow /sequencial repetition/ of tags and the results of the > > statement suites are passed as unordered namespaces/dicts. > > Good point. The code above would only work if you didn't care about the > order of elements. I'm half inclined to pull the example, but the > original was due to Michele Simionato, and I haven't quite convinced > myself yet that you couldn't hack it to have ETObject append to an > internal list somehow to keep order. Michele? Did you have a plan for > how this would work? > > STeVe Honestly, I don't want the 'create' statement to be used to write XML in Python. I think this would be a misuse of the functionality. OTOH I believe that the main selling point for the 'create' statements is that it make it easy to implement declarative minilanguages, so I have given an XML example. To solve the ordering issue one should change the internals of Python, in such a way to pass an ordered dict to the 'create' statement instead of an usual dictionary. I think the main use case for 'create' would be in things like object-relational-mappers, not in XML generation. You can pull out the example in the official PEP, if you like. It was just matter for thought. Michele Simionato From greg.kujawa at gmail.com Sun Apr 2 09:17:35 2006 From: greg.kujawa at gmail.com (gregarican) Date: 2 Apr 2006 06:17:35 -0700 Subject: Is pwm Python MegaWidgets viable? References: <499rh1Fnh7voU1@individual.net> Message-ID: <1143983854.954254.221080@i40g2000cwc.googlegroups.com> Paul Watson wrote: > Does pwm run well on Python 2.4? The last release appears to be in > 2003. The Manning discussion forum is dead. > > Is there a better path to learning and producing tkInter apps? > > > Has there been any discussion of wxPython becoming part of the base > Python distro? A requirement here is to not require download/install of > anything other than the Python release. I can't vouch for Python 2.4, but I used the PMW library pretty extensively for an app that is based on Python 2.3. Tkinker itself offers most of the basic widgets that any Tk implementation does, and there's an online guide (can't recall the URL right now) to Tkinter that is great for an introduction tutorial. PMW is an add-on to Tkinter that is useful if there are specific widgets that you need that basic Tkinter doesn't provide and you don't feel like creating them from scratch. Just because it doesn't have a new release in the past couple of years doesn't mean that it's truly a dead project. Perhaps it's stabilized and there haven't been overwhelming requests for adding any new items to it. Using PMW won't help you learn Tkinter any quicker in any event. Just icing on the cake :-) From tim.peters at gmail.com Sun Apr 9 22:15:15 2006 From: tim.peters at gmail.com (Tim Peters) Date: Sun, 9 Apr 2006 22:15:15 -0400 Subject: Python 3.0 or Python 3000? In-Reply-To: <4439aba9$0$18019$c3e8da3@news.astraweb.com> References: <4439aba9$0$18019$c3e8da3@news.astraweb.com> Message-ID: <1f7befae0604091915l1984a47pae2443cb948a75c@mail.gmail.com> [John Salerno] > Is 'Python 3000' just a code name for version 3.0, or will it really be > called that when it's released? The smart money is on changing the name to Ecstasy, to leverage marketing publicity from the hallucinogenic club drug of the same name. "class" will be renamed to "rave", and the license will be changed to prohibit use by people with bipolar disorder. Either that, or the name will be Python 3.0. From ivan.zuzak at fer.hr Fri Apr 7 12:59:11 2006 From: ivan.zuzak at fer.hr (Ivan Zuzak) Date: Fri, 07 Apr 2006 18:59:11 +0200 Subject: Calling Web Services from Python Message-ID: Hello, My Python application calls web services available on the Internet. The web service being called is defined through application user input. The Python built-in library allows access to web services using HTTP protocol, which is not acceptible - generating SOAP messages for arbitrary web services is something i wish to avoid. I need a package/tool that generates web service proxies that will do all the low-level HTTP work. (Someting like the WSDL.EXE tool in .NET Framework) The ZSI and SOAPy packages [1] that i found (should) have those functionalities but either have a bug (SOAPy) or either do not work for arbitrary web services (ZSI). I tried the ZSI wsdl2py script on a wsdl of one of my services, and the script crashes. I suppose the wsdl was "too hard" for the script to parse. Are there any other packages that utilize generation of web service proxies that are compatible with SOAP & WSDL standards? Thank you, ivan zuzak [1] - http://pywebsvcs.sourceforge.net/ From fredrik at pythonware.com Fri Apr 28 04:19:32 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 28 Apr 2006 10:19:32 +0200 Subject: Why not BDWGC? References: <1146194093.309243.314490@y43g2000cwc.googlegroups.com> Message-ID: LuciferLeo at gmail.com wrote: > I've heard that the reason why python uses reference counting rather > than tracing collector is because python cannot determine the root set > for its various C extensions. > But provided that BDWGC(full name: Boehm-Demers-Weiser conservative > garbage collector) is conservative --- can be used for C, and > opensourced, why python not adopt it as its gcmodule? google has the answer: http://groups.google.com/groups?q=Boehm-Demers+Python From brianlum at gmail.com Fri Apr 14 07:01:11 2006 From: brianlum at gmail.com (brianlum at gmail.com) Date: 14 Apr 2006 04:01:11 -0700 Subject: Future Warning with Negative Int Message-ID: <1145012470.947175.73340@i39g2000cwa.googlegroups.com> Hi, If I try to print a negative integer as a hexadecimal, I get the following error: FutureWarning: %u/%o/%x/%X of negative int will return a signed string in Python 2.4 and up For example: >>> print "%X" % -1 __main__:1: FutureWarning: %u/%o/%x/%X of negative int will return a signed string in Python 2.4 and up FFFFFFFF Does that mean that in the future it will say -1 or -FFFFFFFF? Also, how do I suppress this warning? Thanks, Brian From tzot at sil-tec.gr Wed Apr 12 17:46:18 2006 From: tzot at sil-tec.gr (Christos Georgiou) Date: Thu, 13 Apr 2006 00:46:18 +0300 Subject: symbolic links, aliases, cls clear References: <1143672131.167324.36920@i39g2000cwa.googlegroups.com> <1144844223.094969.82870@t31g2000cwb.googlegroups.com> <87r7430x2t.fld@apaflo.com> <4a53skFr812lU1@individual.net> <9p20h3-sfc.ln1@xword.teksavvy.com> Message-ID: <3isq329vv0hopvhkfsu80vi8ncm0li0b1v@4ax.com> On Wed, 12 Apr 2006 15:59:05 -0400, rumours say that "Chris F.A. Johnson" might have written: >>> I still have a system which does not have tput. >> >> And that justifies everything else. Of course. > > If I want to write portable scripts, then yes, it does. Well, either port your system out of the window or port tput.c to your system and then start writing "portable" scripts. tput is part of the POSIX 1003.1 standard, and guess what the 'P' stands for in POSIX. If you insist, I will retort to using Terry Pratchett references. -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From kylotan at gmail.com Wed Apr 19 08:39:59 2006 From: kylotan at gmail.com (Ben Sizer) Date: 19 Apr 2006 05:39:59 -0700 Subject: How protect proprietary Python code? (bytecode obfuscation?, what better?) In-Reply-To: <4444c777$0$9453$626a54ce@news.free.fr> References: <1145293384.791678.14450@v46g2000cwv.googlegroups.com> <4444c777$0$9453$626a54ce@news.free.fr> Message-ID: <1145450399.254863.234380@i40g2000cwc.googlegroups.com> bruno at modulix wrote: > seberino at spawar.navy.mil wrote: > > I suppose another idea is to rewrite entire Python app in C if compiled > > C code > > is harder to decompile. > > Do you really think "native" code is harder to reverse-engineer than > Python's byte-code ? Yes, until there's a native code equivalent of "import dis" that telepathically contacts the original programmer to obtain variable names that aren't in the executable. -- Ben Sizer From fulvio at pc.jaring.my Thu Apr 13 07:02:14 2006 From: fulvio at pc.jaring.my (Fulvio) Date: Thu, 13 Apr 2006 19:02:14 +0800 Subject: ftp connection and commands (directroy size, etc) In-Reply-To: References: Message-ID: <200604131902.14532.fulvio@pc.jaring.my> Alle 00:05, gioved? 13 aprile 2006, Arne ha scritto: > a=ftp.sendcmd('Dir') > By trying to get the directory with 'dir' Are you sure that the command 'dir" is understood via ftp? IF I'm not wrong would be 'ls' o list. But since I don't have such psckage on my system, it's recommended you read the manual of that or read here: http://www.cs.colostate.edu/helpdocs/ftp.html Which is the result of google search of "ftp command list" (no quote). F From andre.roberge at gmail.com Fri Apr 28 20:43:59 2006 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 28 Apr 2006 17:43:59 -0700 Subject: Using a browser as a GUI: which Python package Message-ID: <1146267821.057699.29270@g10g2000cwb.googlegroups.com> First, an apology: I realise that I don't know enough about what I am asking to make sure to use the proper language to phrase my question. I would like to use a browser (e.g. Firefox) as a simple GUI "framework". Note that this is to be done on a single user machine, so the question of sandboxing is not really relevant here. The simplest application I would like to start with would be one with two "windows" (within a browser window) and a single button. One window would be used as a Python code editor; the other as an output window. On clicking on the button, the code in the editor window would be run by Python with the result appearing in the output window. [A more advanced, future version, would be to have Python create some graphical code (e.g. SVG) that could be passed to the browser to be displayed within the output window.] Ideally, I would prefer a Python-based solution only. My ultimate goal would be to port the main features of two wxPython-based apps I wrote (rur-ple and Lightning Compiler, both found at https://sourceforge.net/project/showfiles.php?group_id=125834) within a standard browser. Any help/pointers would be appreciated. Andr? From osv at javad.com Fri Apr 14 05:14:56 2006 From: osv at javad.com (Sergei Organov) Date: Fri, 14 Apr 2006 13:14:56 +0400 Subject: Python editing with emacs/wordstar key bindings. References: <1144887253.027194.198750@i39g2000cwa.googlegroups.com> <1144949128.068372.129600@t31g2000cwb.googlegroups.com> <1144992497.402792.153560@t31g2000cwb.googlegroups.com> Message-ID: "BartlebyScrivener" writes: > Yes, but for some reason, I get more and better help here with Python > than on xemacs. Or maybe I've just had bad luck. Something like the > following just leaves me scratching my head. I'm on Windows XP and > never compiled anything that I know of. I'd rather pay $30 and have > the editor work. Well, I'd pay too, but my experience is that no editor *always* works for me, and ability to fix it (or fine-tune for my own needs) is indeed essential for me. To the extreme that I'd rather learn some lisp to be able to (and besides lisp being fun to learn) ;) That said, I do think (X)emacs is not very suitable for casual user, but it starts to pay back for investments put into it pretty soon. BTW, what you've cited below sounds just like messed/broken Emacs installation (maybe installing one version on top of another, or mixing Emacs and XEmacs installations, or borrowing some files from separate archives -- difficult to say exactly), as you normally don't need to compile anything. Not to mention the fact that Windows is rather new platform for emacsen, so quite a few OS-specific issues could well be unresolved or simply be buggy indeed. Well, I think we should better stop this as an OT anyway. -- Sergei. > > "BartlebyScrivener" writes: >> I tried searching on this but I don't see exactly my error message. >> When I open a php file for editing, I get: "file mode specification >> error: (void-function run-mode-hooks)" > >> What line do I need to add to my .init file to make this stop? > > You are using .elc files compiled with a different version of Emacs. > Recompile them. > > -- > http://mail.python.org/mailman/listinfo/python-list From williams.jasonscott at gmail.com Wed Apr 19 12:45:42 2006 From: williams.jasonscott at gmail.com (williams.jasonscott at gmail.com) Date: 19 Apr 2006 09:45:42 -0700 Subject: C API - Conversions from PyInt or PyFloat to a char * Message-ID: <1145465141.985789.139010@e56g2000cwe.googlegroups.com> Hi, I'm looking at the C API and wanting to know a good way to convert Python numeric types to native c types. For strings I've been using PyString_AsString(v) and thats great, but I would like to do the same for ints and floats. I have found PyFloat_AsString in the source but it seems to be undocumented and some of the comments make me think that I shouldn't use it but I've given it a go anyhow. It is defined in floatobject.h as: PyAPI_FUNC(void) PyFloat_AsString(char*, PyFloatObject *v); and also: PyAPI_FUNC(void) PyFloat_AsReprString(char*, PyFloatObject *v); And I have a few questions: Should I use these calls? And the comment that I am concerned about from floatobject.c is: 315 /* XXX PyFloat_AsString and PyFloat_AsReprString should be deprecated: 316 XXX they pass a char buffer without passing a length. 317 */ OK so what the caller can manage the buf len, but is there something else I should be concerned about? If these types of calls are the way to go, is there a call for int? And how should I convert a PyObject to a PyFloatObject? If this isn't a good approach, what is? thanks, ~jason From zdwang at xinces.com Sun Apr 9 22:33:45 2006 From: zdwang at xinces.com (zdwang at xinces.com) Date: 9 Apr 2006 19:33:45 -0700 Subject: a unicode question? In-Reply-To: <1144633431.375745.77670@z34g2000cwc.googlegroups.com> References: <1144631034.049820.62550@u72g2000cwu.googlegroups.com> <1144633431.375745.77670@z34g2000cwc.googlegroups.com> Message-ID: <1144636425.117258.258620@t31g2000cwb.googlegroups.com> Mr. John Machin This question come form the flow codes. I use the PyXml to build a DOM tree. from xml.dom.ext.reader import HtmlLib doc = HtmlLib.FromHtmlUrl('http://stock.business.sohu.com/q/nbcg.php?code=600028') title_elem = doc.documentElement.getElementsByTagName("TITLE")[0] title_string = title_elem.firstChild.data print title_string # the title_string is unicode, but it is not "latin1" code, so I wantto change it. From onurb at xiludom.gro Mon Apr 24 07:16:30 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Mon, 24 Apr 2006 13:16:30 +0200 Subject: Looking for resources for making the jump from Java to Python easier and more productive In-Reply-To: References: <1145691651.385835.298600@u72g2000cwu.googlegroups.com> Message-ID: <444cb3e1$0$21091$626a54ce@news.free.fr> Lawrence D'Oliveiro wrote: > In article <1145691651.385835.298600 at u72g2000cwu.googlegroups.com>, > "ToddLMorgan" wrote: > > >>I'm looking for the common types of mistakes that say a Java/C# or >>even C++ developer may commonly make. > > > Using subclassing when you don't have to. For instance, you might have a > Java method which takes an argument of type java.io.OutputStream to > which it writes. You might translate this to a Python method to which > you are careful to only pass instances of subclasses of file objects. > But in fact there is no necessity for this: you are free to pass any > object which has appropriate members. > > I suppose this is an instance of the more general rule: "using OO when > you don't have to". Lawrence, I'm afraid you're confusing OO with "statically-typed class-based". FWIW, dynamic typing is part of OO since Smalltalk. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From __peter__ at web.de Tue Apr 11 12:16:22 2006 From: __peter__ at web.de (Peter Otten) Date: Tue, 11 Apr 2006 18:16:22 +0200 Subject: [OT] Re: challenging (?) metaclass problem References: <1144656384.077748.229010@u72g2000cwu.googlegroups.com> <1144742649.335274.279800@e56g2000cwe.googlegroups.com> Message-ID: alainpoint at yahoo.fr wrote: > I don't know if you noticed but i changed my mind and removed the post No, I didn't. It seems to be kept in the cache of my newsreader. > as i realised that people seemed to have much more interest in how > relevant c code still is than in solving an interesting problem. Oh the defeatism. The chance that you might get an answer is a perfect reason to ask. That you might get no answer is no reason not to. > I only speak French and Dutch and my knowledge of Belgium's third > official language (German) is only passive. Otherwise i would have > posted on the german newsgroup (the French newsgroup does not seem to > be so interesting and there are no belgian or dutch newsgroups either). > Anyway, thank you for accepting the challenge. I'll try out your code > and get back if i have any problem. I don't think you are more likely to get an answer on the national newsgroups. Python addicts frequent groups in both English and vernacular. > Viele dank. Gern geschehen. Peter From rridge at csclub.uwaterloo.ca Tue Apr 25 18:57:39 2006 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: 25 Apr 2006 15:57:39 -0700 Subject: MS VC++ Toolkit 2003, where? References: <1he8pss.1yk7ug81rv7pw2N%aleaxit@yahoo.com> <1145811839.042394.73260@t31g2000cwb.googlegroups.com> <1he8sbx.dqqp3q10n5thaN%aleaxit@yahoo.com> <1145849491.347970.112150@e56g2000cwe.googlegroups.com> <1he9m4m.9d8okx1x7mxeaN%aleaxit@yahoo.com> <444C784F.3000502@v.loewis.de> <1heag4u.19dksfxrbe14wN%aleaxit@yahoo.com> <444E7747.7090101@v.loewis.de> Message-ID: <1146005859.457486.232940@i39g2000cwa.googlegroups.com> Martin v. L?wis wrote: > Right. MingW (GNU ld) was (apparently) changed to support that shortly > after I started including libpython24.a files with the Windows > distributions. A bug in binutils support for short import library records was fixed about year ago. You need to use MinGW binutils 2.16.91 or newer if you want to link with any of the ".lib" files included with Python 2.4. Ross Ridge From g.brandl-nospam at gmx.net Wed Apr 12 16:23:39 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Wed, 12 Apr 2006 22:23:39 +0200 Subject: just one more question about the python challenge In-Reply-To: References: <%2a%f.1965$No6.42797@news.tufts.edu> Message-ID: John Salerno wrote: > Fredrik Lundh wrote: >> John Salerno wrote: >> >>>> At the second, don't rename the file, rename the URL. >>> Do you mean rename the URL *aside from* the file name? >> >> no, the URL you got when you followed georg's instructions will give you >> some data that you need to manipulate before you can see what it is. to >> figure out how to manipulate it, study the *first* image carefully. what >> is the person on that page doing? > > Thanks Fredrik. I think my problem lies in not knowing what the 'data' > is I need to move on to the next step of the puzzle. I now have 3 > images, along with gfx file. The images are perfect images, so there are chances there's no additional data hidden in them. The gfx file, however, isn't viewable yet. Hint, hint ;) Georg From tim.hochberg at ieee.org Mon Apr 10 15:10:22 2006 From: tim.hochberg at ieee.org (Tim Hochberg) Date: Mon, 10 Apr 2006 12:10:22 -0700 Subject: unboundlocalerror with cgi module In-Reply-To: <443aa178$1_1@newspeer2.tds.net> References: <1282490.JcRWy2CgMu@teancum> <443aa178$1_1@newspeer2.tds.net> Message-ID: Kent Johnson wrote: > David Bear wrote: > >>I'm attempting to use the cgi module with code like this: >> >>import cgi >>fo = cgi.FieldStorage() >># form field names are in the form if 'name:part' >>keys = fo.keys() >>for i in keys: >> try: >> item,value=i.split(':') >> except NameError, UnboundLocalError: >> print "exception..." >> item,value=(None,None) >>return(item,value) >> >>However, the except block does not seem to catch the exception and an >>unboundlocalerror is thrown anyway. What am I missing? >> > > I don't know why you would get an UnboundLocalError from the above code, > but the correct syntax is > except (NameError, UnboundLocalError): One possibility is that there are no keys. Then the loop finishes without ever setting item or values. This would give an unbound local error. I assume that the OP would have noticed that in the traceback, but perhaps he missed it. OT, using i for the field namelike that makes my head hurt. Perhaps "for fieldname in fo.keys():" would be in order instead. Regards, -tim > > Your code is binding the actual exception to the name "UnboundLocalError" > > Kent From rschroev_nospam_ml at fastmail.fm Thu Apr 13 05:58:34 2006 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Thu, 13 Apr 2006 09:58:34 GMT Subject: just one more question about the python challenge In-Reply-To: References: <%2a%f.1965$No6.42797@news.tufts.edu> Message-ID: John Salerno schreef: > Fredrik Lundh wrote: >> John Salerno wrote: >> >>>> At the second, don't rename the file, rename the URL. >>> Do you mean rename the URL *aside from* the file name? >> no, the URL you got when you followed georg's instructions will give you >> some data that you need to manipulate before you can see what it is. to >> figure out how to manipulate it, study the *first* image carefully. what >> is the person on that page doing? > > Thanks Fredrik. I think my problem lies in not knowing what the 'data' > is I need to move on to the next step of the puzzle. I now have 3 > images, along with gfx file. I know shuffling/unshuffling has something > to do with the puzzle, but I haven't figure out what yet. Am I wrong to > think that this is another PIL puzzle? As others have said, you don't need PIL for this one. You need to have a look at the data of the gfx file itself (you can do that with some simple Python code, though I find it easier to use a hex editor). Focus on the start of the data at first. Compare the patterns in the data with the data at the start of other image files (JPG, PNG, GIF). From another view of how you need to manipulate the bytes, look at what the dealer is doing with the cards. Count how many piles he's using. And I guess you'll be happy to know that puzzle 13 doesn't have anything to do with images :) -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From Gonzillaaa at gmail.com Tue Apr 4 11:39:02 2006 From: Gonzillaaa at gmail.com (Gonzillaaa at gmail.com) Date: 4 Apr 2006 08:39:02 -0700 Subject: scraping nested tables with BeautifulSoup In-Reply-To: <4432753a$1_2@newspeer2.tds.net> References: <1144142334.695498.293650@u72g2000cwu.googlegroups.com> <4432753a$1_2@newspeer2.tds.net> Message-ID: <1144165142.767043.70100@g10g2000cwb.googlegroups.com> Hey Kent, thanks for your reply. how did you exactly save the file in firefox? if I save the file locally I get the same error. print len(soup('table')) gives me 4 instead 25 From onurb at xiludom.gro Mon Apr 10 05:58:10 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Mon, 10 Apr 2006 11:58:10 +0200 Subject: [Newbie] Referring to a global variable inside a function In-Reply-To: References: Message-ID: <443a2c7b$0$27989$626a54ce@news.free.fr> Ernesto Garc?a Garc?a wrote: > Hi experts, > > I've built a class for parsing a user-defined list of files and matching > lines with a user-defined list of regular expressions. It looks like this: > (snip code) > > But then, when I try to use my class using actions with "memory" it will > fail: > > > import LineMatcher > > global count > count = 0 > > def line_action(line, match_dictionary): > count = count + 1 (snip) > > > The error is: > (snip) > UnboundLocalError: local variable 'count' referenced before assignment > > > How would you do this? FWIW, I would *not* use a global. class LineAction(object): def __init__(self): self.count = 0 def __call__(self, line, match_dictionary): self.count +=1 line_action = LineAction() line_matcher = LineMatcher.LineMatcher() line_matcher.add_files('*') line_matcher.add_action(r'(?P.*)', line_action) line_matcher.go() HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From rpdooling at gmail.com Tue Apr 18 19:01:11 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 18 Apr 2006 16:01:11 -0700 Subject: indirect import of standard module In-Reply-To: References: <1145386200.076643.253740@u72g2000cwu.googlegroups.com> <1145393476.931506.9650@e56g2000cwe.googlegroups.com> Message-ID: <1145401271.166891.86660@t31g2000cwb.googlegroups.com> >> More accurately, it *does* import it twice, into two separate >> namespaces; If it's in two different namespaces, how can they have the same id number? rick From pmartin at snakecard.com Fri Apr 14 13:25:16 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Fri, 14 Apr 2006 12:25:16 -0500 Subject: Passing a packed C structure to a c module References: <3OP%f.811$9c6.333@dukeread11> <443fcb63$0$3177$9b622d9e@news.freenet.de> <443fd8f2$0$470$9b622d9e@news.freenet.de> Message-ID: Well, The call actually is an IOCtl: depending on the control code, the structure has a different format. Although the number of control codes/structures is finite, it would make the wrapper function fairly large. You seem to think that building the structure from python would be a mistake: why is that ? PS: the wrapper also has to work under multiple OSs Regards, Philippe "Martin v. L?wis" wrote: > Philippe Martin wrote: >> It's a pretty big structure: painfull to pass each item as a param. > > So how else would you like to pass them? Define the API you want, > and then just implement it. It still shouldn't require to define > the layout in Python. > > Regards, > Martin From jjl at pobox.com Tue Apr 11 15:46:09 2006 From: jjl at pobox.com (John J. Lee) Date: 11 Apr 2006 19:46:09 +0000 Subject: pre-PEP: The create statement References: <59Wdnbd8EazRCqnZnZ2dnUVZ_vudnZ2d@comcast.com> <1144328362.729594.173160@z34g2000cwc.googlegroups.com> <13B*uLudr@news.chiark.greenend.org.uk> <1144335440.387962.250960@u72g2000cwu.googlegroups.com> Message-ID: <87psjn99q6.fsf@pobox.com> "Michele Simionato" writes: [...] > This agrees with my scan (except I also found an occurrence of 'create' > in Tkinter). > BTW, I would be curious to see the script you are using for the > scanning. Are you > using tokenize too? In am quite fond of the tokenize module ;) Having seen Sion's (non-existent) script, how about posting yours? I regularly grep for things in Python code, and it hadn't occurred to me that I could instead use module tokenize. Module tokenize looks pretty simple, but would be nice to see some code that has already been used. John From duncan.booth at invalid.invalid Tue Apr 11 08:19:08 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 11 Apr 2006 12:19:08 GMT Subject: Help - strange behaviour from python list References: Message-ID: Sean Hammond wrote: > class Area: > def __init__(self, occupants = []): > self.occupants = occupants > ... > I must be making some really stupid mistake, but this just doesn't > look like the list behaviour I would expect. What's going on here? Whenever you use the default value for occupants in the constructor you reuse the same list. Don't use mutable objects as default values: def __init__(self, occupants=None): if occupants is None: self.occupants = [] else: self.occupants = occupants From dbickett at gmail.com Sun Apr 2 13:15:17 2006 From: dbickett at gmail.com (Daniel Bickett) Date: 2 Apr 2006 10:15:17 -0700 Subject: python tutorial: popular/informative Python sites ? In-Reply-To: <1143903028.749385.261340@i40g2000cwc.googlegroups.com> References: <1143903028.749385.261340@i40g2000cwc.googlegroups.com> Message-ID: <1143998116.995540.218880@i40g2000cwc.googlegroups.com> I read c.l.py and (the Unofficial) Planet Python (and that's it), so perhaps that's an appropriate suggestion: http://www.planetpython.org/ (From the Starship: "If you want to join the crew, we only require your PSA membership....") -- Daniel Bickett dbickett at gmail dot com http://heureusement.org/ From rpdooling at gmail.com Mon Apr 10 10:16:16 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 10 Apr 2006 07:16:16 -0700 Subject: "Locate" command in Python In-Reply-To: <9Ts_f.2665$Es3.2057@newsread3.news.atl.earthlink.net> References: <1144633799.467327.15450@i39g2000cwa.googlegroups.com> <5Fj_f.2567$Es3.1608@newsread3.news.atl.earthlink.net> <1144651800.278586.124560@e56g2000cwe.googlegroups.com> <9Ts_f.2665$Es3.2057@newsread3.news.atl.earthlink.net> Message-ID: <1144678576.470023.255360@i39g2000cwa.googlegroups.com> Adonis, Cool! I'm on it. Thanks again. rpd From nobody at 127.0.0.1 Sat Apr 29 20:07:12 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Sun, 30 Apr 2006 00:07:12 GMT Subject: best way to determine sequence ordering? References: <70q4g.2006$No6.43783@news.tufts.edu> <1146259620.636600.119710@u72g2000cwu.googlegroups.com> <1146315935.017018.65580@u72g2000cwu.googlegroups.com> <2_idnXXyMIjKbc7ZnZ2dneKdnZydnZ2d@comcast.com> Message-ID: Steven Bethard wrote: > Ok, lets get comparable functions by writing them both in Python: First of all, your functions aren't quite comparable. The first index takes the value to locate as a variable, while the second has both values hard-coded as literals. Changing the second one to index2(L, a, b) makes a slight but not significant difference in the timings. Secondly, the lists you tested with are artificially short. As you increase the size of the list, the difference lessens to unimportance: $ python -m timeit -s "import temp; L = ['x'] * 500 + ['C', 'A', 'D', 'B']" "a, d = temp.index2(L,'A','D'); a < d" 1000 loops, best of 3: 227 usec per loop $ python -m timeit -s "import temp; L = ['x'] * 500 + ['C', 'A', 'D', 'B']" "a = temp.index1(L, 'A'); d = temp.index1(L, 'D'); a < d" 1000 loops, best of 3: 236 usec per loop Third, the target values are very close together in those lists. If there's a large difference in their positions, then the "two-in-one-pass" algorithm becomes much slower: $ python -m timeit -s "import temp; L = ['C','A'] + ['x'] * 500 + ['D', 'B']" "a = temp.index1(L, 'A'); d = temp.index1(L, 'D'); a < d" 10000 loops, best of 3: 120 usec per loop $ python -m timeit -s "import temp; L = ['C','A'] + ['x'] * 500 + ['D', 'B']" "a, d = temp.index2(L,'A','D'); a < d" 1000 loops, best of 3: 267 usec per loop Remember kids: 1. Numbers can show anything 2. Know your data set 3. Premature optimizations are evil From dave at pythonapocrypha.com Fri Apr 14 14:32:50 2006 From: dave at pythonapocrypha.com (Dave Brueck) Date: Fri, 14 Apr 2006 12:32:50 -0600 Subject: Writing backwards compatible code In-Reply-To: References: Message-ID: <443FEAD2.8050408@pythonapocrypha.com> Steven D'Aprano wrote: > I came across an interesting (as in the Chinese curse) problem today. I > had to modify a piece of code using generator expressions written with > Python 2.4 in mind to run under version 2.3, but I wanted the code to > continue to use the generator expression if possible. [snip] > What techniques do others use? About the only reliable one I know of is to not use syntax from the newer version, period, if the code needs to run on old versions. Your example was pretty straightforward, but unless the use case is always that simple it's too easy to have two separate versions of the code to maintain, and there's no way to enforce that changes/fixes to one will be duplicated in the other. So... if you have to take the time to make one that works with the older version, you might as well just use it exclusively. -Dave From sjmachin at lexicon.net Wed Apr 12 17:10:58 2006 From: sjmachin at lexicon.net (John Machin) Date: Thu, 13 Apr 2006 07:10:58 +1000 Subject: Figure out month number from month abbrievation In-Reply-To: References: <1144873227.982973.18720@i40g2000cwc.googlegroups.com> Message-ID: <443d6cf7$1@news.eftel.com> On 13/04/2006 7:02 AM, John Salerno wrote: > Bill wrote: > >> def month_number(monthabbr): >> """Return the month number for monthabbr; e.g. "Jan" -> 1.""" >> for index, day in enumerate(calendar.month_abbr): >> if day == monthabbr: >> return index >> >> which works well enough but isn't very clever. I'm pretty new to >> Python; what am I missing here? >> Thanks -- Bill. > > I'm curious, does that really work, or is there a problem with the first > index being 0? Or is that avoided somehow? Yes, No, Yes. You can answer such questions yourself very easily, e.g. in this case: >>> import calendar >>> calendar.month_abbr >>> list(calendar.month_abbr) ['', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] From duncan.booth at invalid.invalid Fri Apr 21 08:07:00 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 21 Apr 2006 12:07:00 GMT Subject: Joining stdout & stderr of subprocess ? References: Message-ID: robert wrote: > > when I run a command > > myapp 2>&1 > [ I guess you meant to say here that the stdout, stderr output was interleaved ] > > yet: > > #!python > print os.popen("myapp 2>&1").read() > > the stderr stuff comes all after the stdout stuff. > How can I get ahold of all the out and err joined synchronously in the > order, it is created ? > I think what is happening here is that in the first case the output is to a terminal, so myapp doesn't buffer its output. In the second case the output isn't going to a terminal so myapp is buffering it and only produces output when the buffer is full. Probably there isn't sufficient stderr output to force any out until myapp terminates, so you get it all at the end. Probably the only way to get the output interleaved is to change myapp so that it doesn't buffer its output or so it sends all of its output to a single stream. From peter at engcorp.com Mon Apr 3 07:45:02 2006 From: peter at engcorp.com (Peter Hansen) Date: Mon, 03 Apr 2006 07:45:02 -0400 Subject: Oserror: [Errno 20] In-Reply-To: References: Message-ID: k r fry wrote: > Hi, I am new to this list and also programming with python. > > I have an error: oserror [errno 20] not a directory "katiescint.py" Please always post complete tracebacks, and without manually reentering the data. In most cases you'll save us and you lots of time and guessing. > The piece of code causing the problem is: > [code] > > for subdir in os.listdir(DATADIR): #loop through list of > strings > > file=FITS.Read(DATADIR+'/'+subdir+'/flux.fits') #opens > flux.fits file and reads os.listdir() returns a list of all files and directories inside the directory specified (DATADIR), so you can't assume that "subdir" is always going to be a directory. Use os.path.isdir() to confirm that it is and ignore those items for which that function returns False. -Peter From robert.kern at gmail.com Sun Apr 16 06:26:55 2006 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 16 Apr 2006 05:26:55 -0500 Subject: Help with python output redirection In-Reply-To: References: <1145059153.392141.145360@u72g2000cwu.googlegroups.com><1145111789.969239.270260@i40g2000cwc.googlegroups.com> Message-ID: Fredrik Lundh wrote: > Steven D'Aprano wrote: > >>So, let me say firstly that I wish the following code to be put into >>the public domain > > so you're taking the work by others ("for m in x", "print m", and so on) > and think that by posting it to usenet as if you wrote it yourself, you > can release it into the public domain ? I don't think there's a judge in the world that would think those few characters are copyrightable by themselves. -- Robert Kern robert.kern at gmail.com "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From johnjsal at NOSPAMgmail.com Sun Apr 9 01:24:57 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sun, 09 Apr 2006 01:24:57 -0400 Subject: how to make a generator use the last yielded value when it regains control In-Reply-To: <1144539432.798755.102520@v46g2000cwv.googlegroups.com> References: <4435cde3$0$11677$c3e8da3@news.astraweb.com> <1144383206.576767.192570@g10g2000cwb.googlegroups.com> <4435e96d$0$17970$c3e8da3@news.astraweb.com> <44384257$0$11362$c3e8da3@news.astraweb.com> <1144539432.798755.102520@v46g2000cwv.googlegroups.com> Message-ID: <44389c36$0$4520$c3e8da3@news.astraweb.com> Gerard Flanagan wrote: > John Salerno wrote: > >> Michael Spencer wrote: >> >>> itertools.groupby makes this very straightforward: >> I was considering this function, but then it seemed like it was only >> used for determing consecutive numbers like 1, 2, 3 -- not consecutive >> equivalent numbers like 1, 1, 1. But is that not right? > > > data = [1, 1, 1, 2, 2, 3, 4, 4, 3, 2, 2, 1, 1, 2, 2,4, 2, 2] > > from itertools import groupby > > > for k, g in groupby( data ): > print k, list(g) > > 1 [1, 1, 1] > 2 [2, 2] > 3 [3] > 4 [4, 4] > 3 [3] > 2 [2, 2] > 1 [1, 1] > 2 [2, 2] > 4 [4] > 2 [2, 2] > > for k, g in groupby( data, lambda x: x<2 ): > print k, list(g) > > True [1, 1, 1] > False [2, 2, 3, 4, 4, 3, 2, 2] > True [1, 1] > False [2, 2, 4, 2, 2] > > Gerard > Interesting. After following along with the doc example, it seemed like I had to do complicated stuff with the keys parameter, and I kind of lost track of it all. From bob at greschke.com Sat Apr 1 13:57:16 2006 From: bob at greschke.com (Bob Greschke) Date: Sat, 1 Apr 2006 11:57:16 -0700 Subject: PIL ImageDraw line not long enough References: Message-ID: "Fredrik Lundh" wrote in message news:mailman.3914.1143785974.27775.python-list at python.org... > Bob Greschke wrote: > >> I have to extend the vertical line to y+8, instead of y+7 to get the line >> segment to be drawn long enough. This is on Linux, Solaris, 2.x versions >> of >> Python, 1.1.5 version of PIL, and on Windows with the latest of >> everything. >> Am I missing a setting somewhere? > > I recently got another bug reported that talked about the same thing, so > it's probably a bug in 1.1.5 that nobody has noticed before. > > (as nikie mentions, the low-level line segment drawer avoids drawing over- > lapping points, but the "line" wrapper should add the last pixel) > > Hey! It's not ME for once. :) It seems to only happen with lines that have a vertical-ness to them (straight up-down or diagonal). It doesn't seem to happen when the line segment is just horizontal. These are the characters that I am drawing www.greschke.com/unlinked/images/graphs.png It works really well. Thanks! Bob From sjmachin at lexicon.net Sun Apr 16 18:34:14 2006 From: sjmachin at lexicon.net (John Machin) Date: Mon, 17 Apr 2006 08:34:14 +1000 Subject: Help for a complete newbie In-Reply-To: <1145197346.128929.37880@e56g2000cwe.googlegroups.com> References: <7xY%f.1245$kz3.903@twister.nyroc.rr.com> <1145197346.128929.37880@e56g2000cwe.googlegroups.com> Message-ID: <4442C666.7040906@lexicon.net> On 17/04/2006 12:22 AM, fatal.serpent top-posted: > There was an extra space before ready. Space? Strange. Both Google groups & my newsreader display it as 8 spaces. I could have sworn it was a tab. From petr at tpc.cz Fri Apr 28 13:35:13 2006 From: petr at tpc.cz (Petr Jakes) Date: 28 Apr 2006 10:35:13 -0700 Subject: Using Databases in Python In-Reply-To: <1146240240.440044.258710@g10g2000cwb.googlegroups.com> References: <1146237635.087759.312210@y43g2000cwc.googlegroups.com> <1146240240.440044.258710@g10g2000cwb.googlegroups.com> Message-ID: <1146245713.252291.284930@y43g2000cwc.googlegroups.com> I have got Steven's book of course (it is excellent IMHO). I was just thinking some new approaches can be found in the tutorial. Petr Jakes From rrr at ronadam.com Tue Apr 25 03:08:28 2006 From: rrr at ronadam.com (Ron Adam) Date: Tue, 25 Apr 2006 02:08:28 -0500 Subject: MS VC++ Toolkit 2003, where? In-Reply-To: <1hebbjg.3027zmej4xlrN%aleaxit@yahoo.com> References: <1he8pss.1yk7ug81rv7pw2N%aleaxit@yahoo.com> <1145811839.042394.73260@t31g2000cwb.googlegroups.com> <1he8sbx.dqqp3q10n5thaN%aleaxit@yahoo.com> <1145849491.347970.112150@e56g2000cwe.googlegroups.com> <1he9m4m.9d8okx1x7mxeaN%aleaxit@yahoo.com> <444C7896.9040104@v.loewis.de> <1heagzk.1pzfash1awhj3eN%aleaxit@yahoo.com> <1hebbjg.3027zmej4xlrN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Ron Adam wrote: > ... >> I still get the following with the tinyurl link: >> >> ~~~ >> The download you requested is unavailable. If you continue to see this >> message when trying to access this download, go to the "Search for a >> Download" area on the Download Center home page. >> ~~~ >> >> >> Pasting the above tinyurl into firefox results in the following link. >> >> http://www.microsoft.com/downloads/details.aspx?familyid=272BE09D-40BB-4&d >> isplaylang=en >> >> Which appears to still be truncated. :-/ > > True, but here's the kicker: using the full URL, which I just dblchecked > from Rushby's original message as being (enclosing in <...>)...: Yes, I tried the full url also, but was hoping I did something wrong. Sigh... guess not. > 49FD-9CB0-4BFA122FA91B&displaylang=en> > > NOW gives me the same error page too. When Rushby suggested it > yesterday I immediately used it, and it allowed me to download the > Toolkit 2003 just fine -- so, I guess Microsoft must have killed that > possibility shortly thereafter (who said they can't move fast?-). > > As of now, I don't know any more of a URL that's usable to download > this, therefore:-( And with a new version of windows due at the end of this year, it's likely those who upgrade to Vista, will also need to upgrade to visual studio 2005 or later. I've seen this pattern before. :-/ Ron From steve at hastings.org Sat Apr 1 03:38:08 2006 From: steve at hastings.org (Steve R. Hastings) Date: Sat, 01 Apr 2006 00:38:08 -0800 Subject: any() and all() on empty list? References: <7x3bh1x0ym.fsf@ruckus.brouhaha.com> <42qWf.18211$uX5.7574@tornado.texas.rr.com> <7xzmj9u1di.fsf@ruckus.brouhaha.com> <85tWf.2748$Aa1.1605@dukeread05> <7xy7ytmtk2.fsf@ruckus.brouhaha.com> <7xpsk2f8ab.fsf@ruckus.brouhaha.com> Message-ID: On Sat, 01 Apr 2006 02:06:29 -0600, Ron Adam wrote: > true_count, count = countall(S), len(S) Unfortunately, this does not solve the problem. An iterator yields its values only once. If you have an iterator "itr", you cannot do all(itr) and then do len(itr). Whichever one you do first will run the iterator to exhaustion. This is why my proposed truecount() returns a tuple, with the length and the count of true values. Suppose you wanted, for some reason, to know how many lines in a file start with a vowel: vowels = frozenset("aeiouAEIOU") f = open("a_file.txt") # note that f is an iterator true_count, count = truecount(line[0] in vowels for line in f) print "%d lines in file; %d start with a vowel" % (count, true_count) Because f is an iterator, we only get one pass through the values of the file. Because truecount() returns a tuple with two values, one pass is enough. -- Steve R. Hastings "Vita est" steve at hastings.org http://www.blarg.net/~steveha From duncan.booth at invalid.invalid Wed Apr 26 06:22:28 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 26 Apr 2006 10:22:28 GMT Subject: OOP / language design question References: <1145961248.794496.80220@j33g2000cwa.googlegroups.com> <1145963311.348482.15080@i40g2000cwc.googlegroups.com> <444e0dec$0$27071$626a54ce@news.free.fr> <444e38e9$0$29686$636a55ce@news.free.fr> <1hedc5l.toeunc1twg6bsN%aleaxit@yahoo.com> <444f3f6f$0$27980$626a54ce@news.free.fr> Message-ID: bruno at modulix wrote: > It's *already* split : __new__ construct the object, __init__ > initialize it. > >> That's why I would go for the 2-phase construction: > > But that's already what you have. Very good point. >> after the first phase >> you have an object which is fully initialised, just not yet >> used/connected/running. For example httplib.HTTPConnection does this: >> you construct the object with a host and port, but the actual >> connection is triggered by a separate object. > > If you look at file objects, they do try and open the file at init > time. Is a net or db connection that different ? Well, yes, since the whole point is that we are discussing overriding methods and I bet you haven't subclassed Python file objects recently. For network or database connections you do want to supply your own handlers for things like authentication. From brian at rkspeed-rugby.dk Mon Apr 24 16:22:14 2006 From: brian at rkspeed-rugby.dk (Brian Elmegaard) Date: Mon, 24 Apr 2006 22:22:14 +0200 Subject: MinGW and Python References: <1145861223.509630.247350@y43g2000cwc.googlegroups.com> <444C79D7.4060007@v.loewis.de> Message-ID: Robert Kern writes: > - gcc does not optimize particularly well. But well enough for other platforms. -- Brian (remove the sport for mail) http://www.et.web.mek.dtu.dk/Staff/be/be.html http://www.rugbyklubben-speed.dk From kotlinski at gmail.com Thu Apr 6 16:03:21 2006 From: kotlinski at gmail.com (Johan Kotlinski) Date: 6 Apr 2006 13:03:21 -0700 Subject: standard library audio/image support Message-ID: <1144353801.160479.87580@e56g2000cwe.googlegroups.com> Hi there! I spent the afternoon making a simple graphics-to-audio converter.. I was surprised to find that the AIFF parser/writer is in the standard library, but that I had to go to some external library for opening and manipulating a JPG file. How come audio is deemed more important for the standard library than imaging? Regards, Johan From peter at engcorp.com Sat Apr 1 15:21:08 2006 From: peter at engcorp.com (Peter Hansen) Date: Sat, 01 Apr 2006 15:21:08 -0500 Subject: Scatter/gather on sockets? In-Reply-To: References: Message-ID: Roy Smith wrote: > I've got a bunch of strings in a list: > > vector = [] > vector.append ("foo") > vector.append ("bar") > vector.append ("baz") > > I want to send all of them out a socket in a single send() call, so > they end up in a single packet (assuming the MTU is large enough). I > can do: > > mySocket.send ("".join (vector)) > > but that involves creating an intermediate string. Is there a more > efficient way, that doesn't involve that extra data copy? Two possible answers that I can see: A. No, the send call is implemented in C and requires a single buffer with the entire piece of data that will be sent. Ultimately this gets passed down to the NIC hardware in some fashion, so there's certainly no hope of using something like a generator to send it in pieces. B. Don't bother trying, because even if the MTU is large enough there is absolutely no guarantee that the packet will stay intact all the way through the network anyway (even if you use sendall() instead of send()). So fixing your design not to require this appears to be the only viable solution. -Peter From rurpy at yahoo.com Tue Apr 4 18:18:27 2006 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 4 Apr 2006 15:18:27 -0700 Subject: Doc suggestions In-Reply-To: <1144014432.869077.318440@i40g2000cwc.googlegroups.com> References: <1142964085.356976.166620@t31g2000cwb.googlegroups.com> <1143762250.537475.115420@t31g2000cwb.googlegroups.com> <1144014432.869077.318440@i40g2000cwc.googlegroups.com> Message-ID: <1144189107.589430.89050@v46g2000cwv.googlegroups.com> wrote in message > Here is a 30000' view. I posted about a clear > (admittedly very minor) doc problem 8 days ago. > Since then there have been 30+ postings in this > thread. Insults and bad feelings have flown. > Two people setup wikis and uploaded the tutorial. > I don't know how many people have visited or made > changes. After all that I look at the current > 2.5 docs, and what do I see? The same, trivial, > problem is still there. > > Am I the only one who sees something wrong with > this picture? I have not seen any responses to this so maybe I am the only one. Or has Fredrik Lundh's vitriolic postings intimidated this entire group into silence? [snipped...a proposal that would hopefully improve the documentation and process.] No comments on this either. I wonder why? ...It is a lousy or unworkable idea. ...Fredrik doesn't like it. ...It did not come from an insider. ...The docs for introducing people to Python and getting them to an intermediate level are already ok. Any further improvement would erode the status of the existing experts and is thus undersireable. ...Same as above but would reduce the ability of experts to make money writing commercial books. From swordedotcom at hotmail.com Sun Apr 23 01:35:16 2006 From: swordedotcom at hotmail.com (swordedotcom) Date: 22 Apr 2006 22:35:16 -0700 Subject: Job title: $300 flat for job in perl, cgi, Visual Basic/Asp.Net, whatever online project Message-ID: <1145770516.045756.126440@j33g2000cwa.googlegroups.com> Posted: April 22, 2006 Job title: $300 flat for job in perl, cgi, Visual Basic/Asp.Net, whatever online project Company name: Sworde.com Location: United States, Colorado, Glenwood Springs Pay rate: 300.00 flat for job Travel: 0% Length of employment: Until job done Hours: Flexible Onsite: no Description: I'll pay $300 flat for completed job. 1. Visit our site, look around-test and propose SEO to improve Asbestos Cancer visitors coming to our site cheaper. We care currently paying CPC using Yahoo. 2. http://Sworde.com, We use Google Adsense Links-We need another method of detecting when visitors click our links. Currently, if you click our links-many of these clickthrus are not showing up in Google reports. 3. Propose SEO to help more 'mesothelioma' visitors find our site? We're currently using yahoo CPC. 4. The usual account login with password reminder (like this site). 5. Database tracking all inbound URLs/referred URLs 6. Main display page for site is URL containing a large frame. 7. Make sure to leave a contact name and phone number, best hours to reach you. please contact me at fokx at hotmail.com URL for more information: http://www.sworde.com/ From david.rasmussen at gmx.net Tue Apr 11 02:48:55 2006 From: david.rasmussen at gmx.net (David Rasmussen) Date: Tue, 11 Apr 2006 08:48:55 +0200 Subject: wxStyledTextCtrl - Dead? In-Reply-To: <1144702358.186240.161950@e56g2000cwe.googlegroups.com> References: <4438efbb$0$60784$157c6196@dreader1.cybercity.dk> <1144702358.186240.161950@e56g2000cwe.googlegroups.com> Message-ID: <443b5144$0$67257$157c6196@dreader2.cybercity.dk> Dave Mandelin wrote: > I don't know the answers to 1 and 2, but from the demo I know that the > answer to 3 is wx.stc.StyledTextControl. > > As for 4, I guess it depends on what you want to do. StyledTextControl > looked pretty scary to me, and for my application I mainly needed to > display styled text, not edit it, so I embedded a web browser window > and used HTML+CSS (and even a little JavaScript now). That worked quite > nicely. > > If you need to edit the text as well, then I don't know. The rich edit > control (TextCtrl with style wx.TE_RICH2) is one option, but it is not > particularly nice to use. > I am trying to make a programmer's editor (and later a full IDE), and I want things like syntax highlighting etc. I could of course roll my own fancy editing control, but if STC could solve my problem and is flexible enough, then I'll use that for now :) /David From johnjsal at NOSPAMgmail.com Sat Apr 1 16:57:30 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sat, 01 Apr 2006 16:57:30 -0500 Subject: running IDLE from another program? In-Reply-To: <442eef26_1@newspeer2.tds.net> References: <442d7a45$1_2@newspeer2.tds.net> <442dba0f$0$11191$c3e8da3@news.astraweb.com> <442e0913$1_3@newspeer2.tds.net> <442e1333$0$2459$c3e8da3@news.astraweb.com> <442e6011_3@newspeer2.tds.net> <442ee151$0$9423$c3e8da3@news.astraweb.com> <442eef26_1@newspeer2.tds.net> Message-ID: <442ef875$0$9425$c3e8da3@news.astraweb.com> Kent Johnson wrote: > The working directory must be wrong. Try calling Python directly with > full paths: > > C:\Python24\pythonw C:\Python24\Lib\idlelib\idle.pyw -r C:\path\to\myprog.py Perfect! Thank you so much! I put this line in the command line field, and I left "working directory" empty because I'm not sure what goes there. Should it be the main python directory, or the directory of the file being run? Either way, it seems to work without a working directory. Thanks again! From no-spam at no-spam-no-spam.com Thu Apr 20 06:52:40 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Thu, 20 Apr 2006 12:52:40 +0200 Subject: Simple DAV server? In-Reply-To: References: Message-ID: Ivan Voras wrote: > robert wrote: > >> >> thanks, that's exactly to the point: >> >> python server.py 8080 mydavrootfolder > > > Thanks for the patch, I assume it's free to incorporate it into the > original archive? yes, of course > Also, see my reply to "Kyler Laird"... maybe thats a good idea to put it on sf.net to boil out all bugs. Yet I like it in that simple default manner, maybe switch on those additional creation functions with commandline switches (or config class instance passed to run..(config=None) ) robert From homeusenet2 at brianhv.org Thu Apr 6 22:17:12 2006 From: homeusenet2 at brianhv.org (Brian Victor) Date: Fri, 07 Apr 2006 02:17:12 GMT Subject: OpenGL on Intel Mac Message-ID: I am attempting to build PyOpenGL on my Intel iMac. The transcript of the build failure is here: http://brianhv.org/temp/pyopengl-build.log I'm using the universal MacPython 2.4.3 and PyOpenGL-2.0.1.09. The highlight of the build log is: /System/Library/Frameworks/Kernel.framework/Headers/sys/stat.h:225: error: field 'st_atimespec' has incomplete type /System/Library/Frameworks/Kernel.framework/Headers/sys/stat.h:226: error: field 'st_mtimespec' has incomplete type /System/Library/Frameworks/Kernel.framework/Headers/sys/stat.h:227: error: field 'st_ctimespec' has incomplete type Anyone have tips on how to fix this? -- Brian From aleaxit at yahoo.com Mon Apr 17 22:14:19 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 17 Apr 2006 19:14:19 -0700 Subject: Missing interfaces in Python... References: <1145306373.781129.305840@z34g2000cwc.googlegroups.com> <20060417210541.GV7561@vulcan.cprogrammer.org> <20060417212336.GW7561@vulcan.cprogrammer.org> Message-ID: <1hdybsi.1g0xk7pmm2m2tN%aleaxit@yahoo.com> Jonathan Daugherty wrote: > # enforced by whom, at what point ? > > In the case of Java, I think the JVM enforces interface implementation > (probably at the parser level). "parser"...?! If you have an 'Object o', say one just received as an argument, and cast it to IBlahble, a la IBlahble blah = (IBlahble) o; ...what can the parser ever say about it? It's clearly up to the runtime system to "enforce" whatever -- raising the appropriate exception if the "actual" (leafmost) class of o does not in fact implement IBlahble (Java doesn't _really_ do compile-time static typing: it just forces you to violate the "Don't Repeat Yourself" cardinal rule by redundantly repeating types, as above, but then in general it checks things at runtime anyway!). Alex From roy at panix.com Mon Apr 24 13:45:47 2006 From: roy at panix.com (Roy Smith) Date: Mon, 24 Apr 2006 17:45:47 +0000 (UTC) Subject: need a thread to keep a socket connection alive? References: <1145718638.526525.235090@i39g2000cwa.googlegroups.com> <1145891966.658138.31310@i40g2000cwc.googlegroups.com> <1145900352.203424.105890@i40g2000cwc.googlegroups.com> Message-ID: wrote: >elif len(msg) == (34): # length of request for ping > ping the server This seems really dangerous. You are obviously writing to some already defined (and hopefully, documented) protocol. What does the protocol spec say about ping request messages? I would be very surprised if the spec says that a ping request is defined as any message which is 34 bytes long. More likely, it says something like, "A ping request is defined by the command code being set to 5" or something like that. That's what you should be testing, not the length of the message. From tim.peters at gmail.com Tue Apr 25 00:46:37 2006 From: tim.peters at gmail.com (Tim Peters) Date: Tue, 25 Apr 2006 00:46:37 -0400 Subject: Probability Problem In-Reply-To: <18C1AAF8-C6A6-4FBE-A310-6320D063D5FD@curi.us> References: <1hebf8p.1sb844li5y2g3N%aleaxit@yahoo.com> <18C1AAF8-C6A6-4FBE-A310-6320D063D5FD@curi.us> Message-ID: <1f7befae0604242146s69e6ec61j1d1cd6d6afad5d1c@mail.gmail.com> [Alex Martelli] >> ... >> You can compute the requested answer exactly with no random number >> generation whatsoever: compute the probability of each result from >> 0 to 1000, then sum the probabilities of entries that are exactly 390 >> apart. [Elliot Temple] > That was the plan, but how do I get the probability of any given > result? As the link you gave suggests, the number of ways to get a given sum s is the coefficient of x**s in (1 + x + x**2 + ... +x**100)**10. Divide that by 101**10 to compute the probability of getting sum s. > (in a reasonable amount of time) > > BTW I'm not in a math course, just curious. Computing exact results is probably too hard for "just curious". This little Python program computes the exact number of ways to get each sum in 0 .. 1000 quickly (fraction of a second on my box): """ def mul(p1, p2): result = [0] * (len(p1) + len(p2) - 1) for i, x1 in enumerate(p1): for j, x2 in enumerate(p2): result[i+j] += x1 * x2 while result and result[-1] == 0: del result[-1] return result base = [1] * 101 result = [1] for dummy in range(10): result = mul(result, base) assert len(result) == 1001 assert sum(result) == 101**10 """ Then result[s] is the exact number of ways to get sum s, for each s in range(1001). Figuring out why that works is the "probably too hard for 'just curious'" part. If you want to pursue that, it's a straightforward implementation of fully multiplying out: (1 + x + x**2 + ... +x**100)**10 A polynomial here is represented by a list L of coefficients, where L[i] is the coefficient of x**i. `mul()` implements polynomial multiplication using this format. For example, >>> mul([1, 1], [-1, 1]) [-1, 0, 1] or, IOW, (x+1)*(x-1) = (x**2 - 1). From greg.kujawa at gmail.com Sun Apr 9 21:36:23 2006 From: greg.kujawa at gmail.com (gregarican) Date: 9 Apr 2006 18:36:23 -0700 Subject: how relevant is C today? References: <44381ee4$0$4209$c3e8da3@news.astraweb.com> <44382711.10403@v.loewis.de> <44393fbe$0$19226$c3e8da3@news.astraweb.com> <44398651$0$4206$c3e8da3@news.astraweb.com> Message-ID: <1144632983.039143.203330@u72g2000cwu.googlegroups.com> Here are a few languages I recommend most programmers should at least have a peek at: 1) Smalltalk - The original object oriented programming language. Influenced anything from Mac/Windows GUI to Java language. Terse, clean syntax. IDE rolled into an operating system rolled into a set of core libraries. 2) Lisp - Along with FORTRAN, one of the oldest programming languages still in use. Pure functional programming model that is extensible and has many derivatives. Great for mathematical purposes. Easy to learn if you can get past all of the nested parenthesis :-) 3) C - The "Latin" of modern programming languages. Used in low level tasks (e.g. - hardware drivers) as well as larger projects (e.g. - operating systems and other programming languages). Logcal, explicit flow albeit a bit wordy. I have worked in C and Smalltalk for awhile now and just starting to pickup Lisp. Knowing different languages can help you approach problems with a fresh perspective. I prefer to code in Ruby and Python but can use these languages a certain way given the angles I have picked up elsewhere... From cfriedl at bigpond.net.au Thu Apr 20 06:51:45 2006 From: cfriedl at bigpond.net.au (bwaha) Date: Thu, 20 Apr 2006 10:51:45 GMT Subject: charting References: <87zmigheo9.fsf@localhost.localdomain> Message-ID: <5JJ1g.11173$vy1.10960@news-server.bigpond.net.au> "Gary Wessle" wrote in message news:87zmigheo9.fsf at localhost.localdomain... > Dear python users > > I am just wondering if python is the language to use to build a custom > charting package which is live updated from live data stream coming > through a socket. as well as dynamically execute data analysis code > on the data being fed. I have been looking at SpecTix. > > thank you can't help much with the details but have you checked out the matplotlib library? http://matplotlib.sourceforge.net/ Its an excellent python plotting library. As I recall there's a sample to do with realtime updating of data from an ECG. As for whether python is the language to use ... fwiw ... if you're a programmer then it is a no brainer to use, has a wealth of library support and has a fantastic community to help you out ... and if your not a programmer .... need I say more. bwaha From __peter__ at web.de Sat Apr 15 03:59:55 2006 From: __peter__ at web.de (Peter Otten) Date: Sat, 15 Apr 2006 09:59:55 +0200 Subject: A problem with exec statement References: <1144996562.237621.110500@t31g2000cwb.googlegroups.com> <1145011226.598914.163290@j33g2000cwa.googlegroups.com> Message-ID: TPJ wrote: >> (...) Even allowing for the >> difficulties you've already experienced, it's nearly always better in >> practical cases to use assignment to the keys of a dictionary. Then no >> exec is required, and you have direct control over your own namespace. > > Well... Is this a sugestion, that instead of messing up with the exec > statements used to modify local namespaces I should use dictionaries? > > Perhaps you're right. In fact, the problem, that I'm trying to solve is > as follows: > > def funcA(): > > def funcB(): > ... > var1, var2, var3, ..., varN = ( None, ) * N > t = ( (regexp1, 'var1'), (regexp2, 'var2'), ..., (regexpN, 'varN') > ) > for regexp, var_name in t: > match = regexp.match( some_string ) > if match != None: > # now the *magic* exec statement comes... > exec var_name + ' = match.groups()[0]' in globals(), locals() > return var1, var2, var3, ..., varN > > ... > k1, k2, k3, ..., kN = funcB() > My problem is more complicated, that the presented example. In general, > my problem is: how to create a local variable by executing the Python > code, that isn't known at the moment of writing the program? In another > words: I have to create a local variable, whose name will be known at > the runtime, in a nested function. > > Is it possible, or have I to use dictionaries, instead of exec > statement used to modify local namespaces? There is a mismatch between your example code and the problem description you are giving. The example can easily be rewritten without nested scopes and exec: # of course untested def funcB(some_string): for r in [regexp1, regexp2, regexp3, ..., regexpN]: match = r.match(some_string) if match: yield match.group(1) else: yield None def funcA(): k1, k2, k3, ..., kN = funcB(some_string) The uniform ki variable names are an indication that you may be able to simplify this even further. I'm therefore confident that rewriting your real code without exec will be more rewarding than digging deeper into the quirks of exec (which admittedly I find puzzling, too). Peter PS: Here is another gem showing that my original assertion that inside a function locals() is always a copy is wrong: >>> def f(): ... locals()["a"] = 42 ... print a ... >>> f() Traceback (most recent call last): File "", line 1, in ? File "", line 3, in f NameError: global name 'a' is not defined >>> def f(): ... locals()["a"] = 42 ... print a ... if False: exec "" ... >>> f() 42 From sysfault at zetafunc.net Sat Apr 1 15:21:45 2006 From: sysfault at zetafunc.net (Anthony Greene) Date: Sat, 01 Apr 2006 15:21:45 -0500 Subject: Scatter/gather on sockets? References: Message-ID: On Sat, 01 Apr 2006 14:56:02 -0500, Roy Smith wrote: > I've got a bunch of strings in a list: > > vector = [] > vector.append ("foo") > vector.append ("bar") > vector.append ("baz") > > I want to send all of them out a socket in a single send() call, so > they end up in a single packet (assuming the MTU is large enough). I > can do: > > mySocket.send ("".join (vector)) > > but that involves creating an intermediate string. Is there a more > efficient way, that doesn't involve that extra data copy? Is sendall() what you're looking for? -- A wise man knows he knows nothing. From johnjsal at NOSPAMgmail.com Thu Apr 20 10:15:10 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 20 Apr 2006 14:15:10 GMT Subject: Ironpython book? In-Reply-To: <1he21p0.qn90u0znmn47N%aleaxit@yahoo.com> References: <1145329406.419299.12780@i40g2000cwc.googlegroups.com> <1he15xj.1dy2h0vzbebqmN%aleaxit@yahoo.com> <1he18dm.e64uky1urr3n0N%aleaxit@yahoo.com> <1he21p0.qn90u0znmn47N%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Oh, OK -- I thought you DID refer to the old research project!!! > > Yeah, the terms "Python.NET" and "Python _for_ .NET" have sometimes been > used interchangeably in the past, that's true. Confusing...! Heh heh, well it's still my fault for not knowing what I'm talking about! :) From jstroud at ucla.edu Mon Apr 10 22:50:10 2006 From: jstroud at ucla.edu (James Stroud) Date: Mon, 10 Apr 2006 19:50:10 -0700 Subject: Saving files from post data via sys.stdin In-Reply-To: References: Message-ID: ACB wrote: > I am rewriting an existing PERL script I wrote several months ago. It is a > script that is used as the action for a form containing several type="file" > inputs. The script is run unbuffered and writes the data from sys.stdin to > a file which is stat'ed by another script called asyncornously from > javascript. In the end I am able to make a progress bar for file uploads > via http. > > Anyway, I have printed sys.stdin to a file and looked at it afterward. This > is what is looks like > -----------------------------126591649570 > Content-Disposition: form-data; name="userid" > > myUserid > -----------------------------126591649570 > Content-Disposition: form-data; name="ulimage"; filename="bc12.jpg" > Content-Type: image/jpeg > > binary data of jpeg > -----------------------------126591649570 > Content-Disposition: form-data; name="ulimage"; filename="" > Content-Type: image/jpeg > > -----------------------------126591649570 > Content-Disposition: form-data; name="ulimage"; filename="" > Content-Type: image/jpeg > > > -----------------------------126591649570 > Content-Disposition: form-data; name="sessionid" > > mySessionid > > Normally, I use cgi.FieldStorage() and access the values via calls like > form = cgi.FieldStorage() > sessionid = form["sessionid"].value > > What is the best method for accessing the various variables and their > respective values so I can save the files one at a time? Maybe loop over form's keys... form = cgi.FieldStorage() for k in form.keys(): do_something_with(form, k) > Is there some > class that can take this input and make it easier to deal with? A dictionary. I need to > save each of the ulimage values as individual images and gain access to the > values of sessionid and userid. > > Thanks > Amy > images = get_images_from_pickle_or_something() form = cgi.FieldStorage() if not images.has_key(form['ulimage']): an_image = image_constructor(form['ulimage']) images[form['ulimage']] = an_image else: an_image = images[form['ulimage']] for k in form.keys(): do_something_with(an_image, form[k]) James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From kylotan at gmail.com Wed Apr 5 04:26:27 2006 From: kylotan at gmail.com (Ben Sizer) Date: 5 Apr 2006 01:26:27 -0700 Subject: using range() in for loops In-Reply-To: <443324dc$0$11257$c3e8da3@news.astraweb.com> References: <443324dc$0$11257$c3e8da3@news.astraweb.com> Message-ID: <1144225586.880005.176990@e56g2000cwe.googlegroups.com> John Salerno wrote: > The reason for this distinction comes from the fact that I read a lot > how using range and for is somewhat discouraged, because it doesn't > really use a for loop for it's true purpose. So my question is, is this > just a Python-oriented opinion about for loops, or is it a general idea? The use of range in for loops is not discouraged, just the unnecessary use of it. In many languages, you were forced to use range - or size, or length, or count, etc - because the only practical method of iteration was to use successive indices into the array or other collection, stopping when the indexes run out. Most loops operate on some sort of structure in this way. In Python, you can iterate directly over the structure instead, so you no longer have to worry about keeping track of the current index, comparing it to the maximum index, or collecting the right object from the structure according to its index. Python just gives you the next object until there are none left. As a result, for most looping tasks, you have no need to use range or an equivalent. > Also, what if you *do* need to just do something a set number of times. > Is this okay, or does it mean you are approaching the problem > incorrectly? Do you really need to do something "a number of times"? If so, range (or xrange) is perfect for the job. More often though, you need to do something "once for every ", so put your 'whatevers' in a list and iterate over that. -- Ben Sizer From boyee118 at gmail.com Tue Apr 11 22:17:28 2006 From: boyee118 at gmail.com (boyeestudio) Date: Wed, 12 Apr 2006 10:17:28 +0800 Subject: I meet problems while using the py2exe,Please help me! Message-ID: I want build a python source to .exe file. I use the py2exe and the script file I wrote as below: from distutils.core import setup import py2exe setup(windows=["main.py"], name='palaver', description="palaver is a p2p software", version='0.05', ) it build rightly,But when I run the executable file, a problem have turn out: Traceback (most recent call last): File "main.py", line 20, in ? File "gtkFE\__init__.pyc", line 18, in ? File "gtkFE\gtkDialogs.pyc", line 17, in ? File "gtk\__init__.pyc", line 45, in ? File "gtk\_gtk.pyc", line 12, in ? File "gtk\_gtk.pyc", line 10, in __load ImportError: No module named cairo. The cairo module have been installed in my computer.And I can run my program from the python file. What is wrong with this problem,Please help me,a lot of thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From Bulkan at gmail.com Thu Apr 27 21:09:23 2006 From: Bulkan at gmail.com (placid) Date: 27 Apr 2006 18:09:23 -0700 Subject: Converstion In-Reply-To: <1146181848.615239.281200@j33g2000cwa.googlegroups.com> References: <1146181848.615239.281200@j33g2000cwa.googlegroups.com> Message-ID: <1146186563.335621.167940@e56g2000cwe.googlegroups.com> Chris wrote: > In a program I'm writing I have a problem where a bit of text sent over > a network arrives at my server. If the person who sent the text made a > mistake typing the word and pressed backspace the backspace code is > included in the word for example hello is hel\x08lo. The \x08 is the > backspace key. How do I convert this string to a normal string (without > the \x08). If I print it to screen it appears normal, "hello" but if I > store it in a list it appears as hel\x08lo. inefficient way, use split ("\x08") then recombine the splitted elements, or iterate thorough the list and create a new string, but dont add the backspace character From sturlamolden at yahoo.no Thu Apr 27 07:21:33 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 27 Apr 2006 04:21:33 -0700 Subject: MinGW and Python In-Reply-To: <44505b1a$0$5432$9b622d9e@news.freenet.de> References: <1145861223.509630.247350@y43g2000cwc.googlegroups.com> <444C79D7.4060007@v.loewis.de> <444DC62B.7000702@v.loewis.de> <1145985979.369429.114040@i39g2000cwa.googlegroups.com> <444e7d85$0$12131$9b622d9e@news.freenet.de> <1145999256.027851.132780@y43g2000cwc.googlegroups.com> <444FA782.6040503@v.loewis.de> <1146087513.773086.64370@u72g2000cwu.googlegroups.com> <44505b1a$0$5432$9b622d9e@news.freenet.de> Message-ID: <1146136893.465726.192230@v46g2000cwv.googlegroups.com> Martin v. L?wis wrote: > That's not how I read it. To me, it says: it can be used by other > parts of Windows itself (i.e. system-level components), but it is not > intended to be used by third-party applications (such as Python), > as these are not system-level components. That is correct. And it is the reson why the MinGW team is working on removing the dependency on this CRT. I From nghoffma at gmail.com Tue Apr 11 22:41:25 2006 From: nghoffma at gmail.com (nghoffma) Date: 11 Apr 2006 19:41:25 -0700 Subject: Sorting a list of objects by multiple attributes In-Reply-To: <1144778370.969987.67080@i40g2000cwc.googlegroups.com> References: <1144718377.331845.56390@z34g2000cwc.googlegroups.com> <1144718963.906712.131510@t31g2000cwb.googlegroups.com> <1144732269.462038.250550@i40g2000cwc.googlegroups.com> <1144778370.969987.67080@i40g2000cwc.googlegroups.com> Message-ID: <1144809685.300217.145140@u72g2000cwu.googlegroups.com> I'm sure my avoidance of lambdas as due as much to laziness as adherence to principle. This is a good opportunity to learn about them. I suggested the above because it wasn't obvious to me how one would pass the arbitrary set of attributes to the lambda expression (and I envisioned them being specified as strings in this case, since the set of attributes will be coming from a web form). So what about the following (attrgetter aside)? attrs = 'attr1 attr2 attr3'.split() L.sort(key=lambda i: [getattr(i,a) for a in attrs]) -Noah From fredrik at pythonware.com Thu Apr 6 06:26:54 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 6 Apr 2006 12:26:54 +0200 Subject: how to create file with spaces References: <1144318680.674373.111220@j33g2000cwa.googlegroups.com> Message-ID: s99999999s2003 at yahoo.com wrote: > I wanted to touch a file with the same name as the directories inside > each directory > > rootdir > | ----> ABC DEF A > |-------> ABC DEF A-dummy > | ---> BDD SD N > |-------> BDD SD N-dummy > > heres the code : > for d in os.walk(rootdir): > (dirpath, dirnames, filenames) = d > for dir in [dirpath]: > if not os.path.exists( os.path.join(dir,"-dummy") ): > f = open( os.path.join(dir,"-dummy") , > "w").write("") > > but i got only "-dummy" as the filename in each directory os.path.join joins path elements, so that's entirely expected. try filename = dirpath + "-dummy" if not os.path.isfile(filename): open(filename, "w").close() instead. or if you want to "touch" the file even if it already exists, just do open(dirpath + "-dummy", "w").close() (to only touch a file if it exists, you can use os.utime(filename, None) instead) From spamspam at spam.eggs Fri Apr 21 15:56:01 2006 From: spamspam at spam.eggs (Ben C) Date: 21 Apr 2006 19:56:01 GMT Subject: lambda References: <1145642409.389741.39680@g10g2000cwb.googlegroups.com> Message-ID: On 2006-04-21, Ben C wrote: > On 2006-04-21, rubbishemail at web.de wrote: >> Hello, >> >> I need your help understanding lambda (and doing it a better way >> without). >> >> f = lambda x : x*x >> [...] >> # the idea is now to give the definition of the multiplication of >> functions and integers >> # (f * c)(xx) := f(x)*c >> [lambda xx: f(xx)*y for y in range(1,5)][0](1) >> # returns 4 >> # I would expect 1*x*x = 1 > > If you change the 5 in range(1,5) to a 10, this returns 9. > > So it looks like each of the lambda xx : f(xx) * y is getting the last > value of y. > > I can do this for example: > > f = lambda x : x * x > fns = [lambda xx: f(xx)*y for y in range(1,10)] > for fn in fns: > print fn(1) > > And I get 9 printed out 9 times. > > It does seem a bit surprising, but I suppose if you think about it > there's only one "y"-- the one in the outer scope. This one variable is > bound 9 times, to a new value each time. > > What one would need for it to work would be for each of the functions to > have a variable in its own scope. But you can't, as far as I know, > create local variables in functions defined with lambda. Having said that, I attempted to confirm this using def rather than lambda, and encountered something I cannot explain at all-- it appears that the functions are getting redefined whenever they are called, to effect a kind of "dynamic scoping" behaviour. I would appreciate any explanation anyone can give of this: fns = [] for y in range(2): def fn(): yy = y # exactly the same with yy = int(y) print "defining fn that returns", yy return yy print "Appending at", y print fn, fn() fns.append(fn) print "OK" for fn in fns: print "Calling", fn print fn, fn() y = 10 for fn in fns: print "Calling", fn print fn, fn() The output: Appending at 0 defining fn that returns 0 0 Appending at 1 defining fn that returns 1 1 OK Calling defining fn that returns 1 1 Calling defining fn that returns 1 1 Calling defining fn that returns 10 10 Calling defining fn that returns 10 10 From nico at netsys.co.za Wed Apr 12 06:01:02 2006 From: nico at netsys.co.za (Nico Kruger) Date: Wed, 12 Apr 2006 12:01:02 +0200 Subject: Problem with spawning an external process In-Reply-To: <5f56302b0604120253u2705a0fdo837a981d9930a635@mail.gmail.com> References: <1144834050.3376.35.camel@notamc2.snetsys.co.za> <1144834879.3376.39.camel@notamc2.snetsys.co.za> <5f56302b0604120253u2705a0fdo837a981d9930a635@mail.gmail.com> Message-ID: <1144836062.3376.42.camel@notamc2.snetsys.co.za> Daniel, thanks for your input. What version of the JDK/JRE and Python are you using? On Wed, 2006-04-12 at 11:53, Daniel Nogradi wrote: > > > I want to execute a command (in this case, and it seems to be > > > significant, a Java program) in a thread in Python. When I execute the > > > java binary in the main python thread, everything runs correctly. But > > > when I try and execute java in a thread, java segfaults. I am using > > > Python 2.3.3 and trying to run the java binary from the 1.4.2 SDK from > > > Sun. > > > Here is the output that I get on my machine: > > > [nico@ script]$ python testcrash2.py > > > In main thread > > > > > > PID: 32107 signal: 0 return code: 1 > > > In Thread > > > PID: 32116 signal: 11 return code: 0 > > > Your code works fine here both in the main and the new thread. Here is > the output: > > In main thread > > PID: 5990 signal: 0 return code: 1 > In Thread > > Waiting...PID: 5999 signal: 0 return code: 1 > ...Finished > > So I guess the problem is somewhere else. -- Regards, Nico. -- NetSys International (Pty) Ltd. Tel : +27 12 349 2056 Fax : +27 12 349 2757 Web : http://www.netsys.co.za P.O. Box 35798, Menlo Park, 0102, South Africa ---- The information contained in this communication is confidential and may be legally privileged. It is solely for use of the individual or entity to whom is addressed and others authorised to receive it. If you are not the intended recipient you are hereby notified that any disclosure, copying, distribution or taking of any action in reliance on the contents of this information is strictly prohibited and may be unlawful. This Message has been scanned for viruses and dangerous content by the NetSys International Mail Scanner and is believed to be clean. From ndbecker2 at gmail.com Mon Apr 10 08:59:37 2006 From: ndbecker2 at gmail.com (Neal Becker) Date: Mon, 10 Apr 2006 08:59:37 -0400 Subject: Automated Graph Plotting in Python References: <1144552132.926125.222210@i39g2000cwa.googlegroups.com> <1144553041.7140.0.camel@kenshin.CASA> Message-ID: Felipe Almeida Lessa wrote: > Em S?b, 2006-04-08 ?s 20:08 -0700, diffuser78 at gmail.com escreveu: >> My python program spits lot of data. I take that data and plot graphs >> using OfficeOrg spredsheet. I want to automate this task as this takes >> so much of time. I have some questions. > > You can try ReportLab (www.reportlab.org). Great tool. > xmgrace if you have Motif. Easy enough to pipe your python output to it. From alexci at gmx.net Thu Apr 13 14:43:40 2006 From: alexci at gmx.net (Aleksandar Cikota) Date: Thu, 13 Apr 2006 20:43:40 +0200 (Central European Daylight Time) Subject: BSTR Message-ID: <443E9BDC.000007.02772@CIKOTA-TM4U7QQ2> Hi all, I'm beginner in Python and need help. I'm writing software for a robotic telescope. For CCD camera control we use MaxIm DL (Diffraction Limited). I have a problem with CCDCamera.SaveImage. Error message: > File "S:MaxImmaxim.py", line 19, in ? > CCDCamera.SaveImage('C:/1.fit') > File "C:ProgrammePython24Libsite- > packageswin32comclientdynamic.py", line 491, in __getattr__ > raise pythoncom.com_error, details > com_error: (-2147352567, 'Ausnahmefehler aufgetreten.', > (65535, 'MaxIm DL 4', 'Invalid Input', None, 0, 0), None) Here is the answer that we recieved from Diffraction Limited: --------- For CCDCamera.SaveImage, 'Invalid Input' is reported only if the argument is not of an acceptable type. As you are probably aware from looking at the type library, the filename argument is declared as a variant. What the type library doesn't tell you is that the variant must be either a BSTR (unicode string with header) or a reference to a BSTR. Specifically, the 'vt' member of the VARIANT must be either VT_BSTR or VT_BSTR|VT_BYREF. Does python provide any way of influencing how arguments for COM methods are created? If so, you may be able to get this to work. It may be as simple as assigning the string to a variable name instead of passing it as a literal, or perhaps there's something equivalent to a C++ cast operator or a VB 'type' function (CInt, CStr, etc.). This problem is likely to affect any MaxIm DL automation method that takes a string as an argument. --------- The question is, how to convert a String in a BSTR (unicodestring with header)? For your prompt reply, I say thank you in advance. Best regards, Aleksandar Cikota -------------- next part -------------- An HTML attachment was scrubbed... URL: From paul at boddie.org.uk Sun Apr 23 14:31:58 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 23 Apr 2006 11:31:58 -0700 Subject: Parsing XML/XSLT References: <1145808564.914308.102620@e56g2000cwe.googlegroups.com> Message-ID: <1145817118.868746.4240@v46g2000cwv.googlegroups.com> veracon wrote: > > I'm looking to use XML and XSLT for templates in a system I'm writing, > however I'm not really sure which parser is the "best". Basically, > which library has the most features, and which is the most supported? I use (my own) libxml2dom [1] and XSLTools [2] to respectively parse XML documents and perform XSL transformations on those documents, both solutions employing the widely deployed libxml2 [3] and libxslt [4] libraries. Alternatively, lxml [5] provides parsing and transformation APIs based on the same underlying technologies. > A guide I saw mentioned importing xml.xslt, however it appears the xml > module/package contains pretty much nothing - xml.xslt outputs an > exception, No module named xslt. You could inquire on the XML-SIG mailing list [6] about the status of XSLT in PyXML or in 4Suite, one or both of which being the origin of the xml.xslt package. Paul [1] http://www.python.org/pypi/libxml2dom [2] http://www.python.org/pypi/XSLTools [3] http://www.xmlsoft.org/ [4] http://xmlsoft.org/XSLT/ [5] http://codespeak.net/lxml/ [6] http://mail.python.org/mailman/listinfo/xml-sig/ From enterr at gmail.com Fri Apr 7 23:11:38 2006 From: enterr at gmail.com (Atanas Banov) Date: 7 Apr 2006 20:11:38 -0700 Subject: Python equivalent of Perl-ISAPI? In-Reply-To: <1143069351.101735.301070@z34g2000cwc.googlegroups.com> References: <1142657781.197131.222440@g10g2000cwb.googlegroups.com> <1142790625.227356.48830@i40g2000cwc.googlegroups.com> <1142865756.452672.57930@v46g2000cwv.googlegroups.com> <1142877087.441903.240840@v46g2000cwv.googlegroups.com> <1142878315.504465.191490@z34g2000cwc.googlegroups.com> <1142893860.425691.127640@v46g2000cwv.googlegroups.com> <1142919357.858590.37800@g10g2000cwb.googlegroups.com> <1143069351.101735.301070@z34g2000cwc.googlegroups.com> Message-ID: <1144465897.936288.152710@i40g2000cwc.googlegroups.com> it is your loss as well (so, 2 losses and 1 win). you comparing perl-ex with python-cgi is unfair, to say the least. let's count: 1. you ditched python ASP, because you dont know how it may port on linux (even if it's supported on apache and you probably never, ever, will have to do the said port). 2. you ditched mod_python, because it's for apache and not for IIS. 3. you picked perl-ex, because... it works fast on IIS, even if it doesnt work on apache or linux. hard to speak about fairness here. besides i guess your tests are based on dummy script pages, which do nothing and the real pages which interface with DB and equipment, will spend 10 times more time doing real work, say 1500ms. now tell me what is the difference between 1.514 sec and 1.786 sec wait time? and even if that were not the case, what is the diffrence for a user between 0.014 and 0.286 seconds? part of a blink of the eye?! - nas > Din't find anything more and no further replies > here so here is a quick timing I did... > Perl-Ex: 0.014 sec/page > Perl-ISAPI: 0.168 sec/page > Perl-cgi: 0.187 sec/page > Python-cgi: 0.286 sec/page > > I can't ignore the 20X better performance of > Perl-Ex vs Python, so I guess this is a loss > for Python and a win for Perl. From rrr at ronadam.com Fri Apr 7 21:29:52 2006 From: rrr at ronadam.com (Ron Adam) Date: Fri, 07 Apr 2006 20:29:52 -0500 Subject: Appending Elements in Element Tree Message-ID: In my program I have a lot of statements that append elements, but sometimes I don't want to append the element so it requres an if statement to check it, and that requires assigning the returned element from a function to a name or calling the funtion twice. e = ET.Element('name') e.append(get_subelement(obj)) # but raises an exception on None This works, but I have a lot of appends. sube = get_element(obj) if sube is None: e.append(sube) Now if Elements worked more like lists I could extend an element. alist = [] alist.extend([]) # returns orginal list With strings. s = '' s += '' # returns original string (or copy) So is there an identity operation with Element Tree elements that I can use to avoid putting a lot of if and or try statements around appending elements? I could wrap the append and do it this way... def eappend(e1, e2): if e2 is None: return e1 e1.append(e2) return e1 Then do... e = eappend(e, get_element(obj)) # Append if not None. But maybe there's a better way? Ron From nephish at xit.net Wed Apr 19 01:02:11 2006 From: nephish at xit.net (nephish at xit.net) Date: 18 Apr 2006 22:02:11 -0700 Subject: freakin out over C++ module in python In-Reply-To: References: <1145324978.877495.12580@i40g2000cwc.googlegroups.com> Message-ID: <1145422931.445215.112930@j33g2000cwa.googlegroups.com> pyconstruct looks cool. i dont know if the classes are using the plain berkely-ish code. i couldn't find anything in it that pointed to send() recv(), & such. i found other stuff like SetSocketOpt() and so on like this : long CClientSocket::ConnectToServer(LPCTSTR serverAddr, UINT port) { BOOL socketOption = TRUE; const int rcvBuffsize = 64 *1024; const int sendBuffsize = 64*1024; if ( !Create() ) return ERR_SOCKET_CREATE; int intvalue = sizeof(int); if(!( SetSockOpt(SO_DONTROUTE,&socketOption,sizeof(BOOL),SOL_SOCKET) && SetSockOpt(SO_RCVBUF,&rcvBuffsize,sizeof(int),SOL_SOCKET) && SetSockOpt(SO_SNDBUF,&sendBuffsize,sizeof(int),SOL_SOCKET) && SetSockOpt(TCP_NODELAY,&socketOption,sizeof(BOOL),SOL_SOCKET) && SetSockOpt(SO_KEEPALIVE,&socketOption,sizeof(BOOL),SOL_SOCKET))) return ERR_SOCKET_CREATE; i looked around for some of these and found most references to UDP. I guess its also a windows specific thing too. thanks for the tips gents.... From akameswaran at gmail.com Tue Apr 4 16:54:36 2006 From: akameswaran at gmail.com (akameswaran at gmail.com) Date: 4 Apr 2006 13:54:36 -0700 Subject: xml element tree to html problem In-Reply-To: References: Message-ID: <1144184076.283856.115320@i39g2000cwa.googlegroups.com> Frederick, I didn't know about cElementTree before, wow - this is a lot nicer than PyyXML - and a whole lot faster. Almost makes my comments about dealing with the xml as text, completely pointless. From james.wondrasek at gmail.com Mon Apr 3 19:52:19 2006 From: james.wondrasek at gmail.com (james.wondrasek at gmail.com) Date: 3 Apr 2006 16:52:19 -0700 Subject: How to debug python code? In-Reply-To: <1143782330.199836.221880@v46g2000cwv.googlegroups.com> References: <1143782330.199836.221880@v46g2000cwv.googlegroups.com> Message-ID: <1144108339.014356.173300@i39g2000cwa.googlegroups.com> I don't have an example, but what I do is insert: import pdb pdb.set_trace() before the code that I think is causing the problem (or that the traceback barfed at). Then hit 'l' (lowercase L) to get a list of the code which is being executed. Use 'p' to look at variables. eg p some_local Use 'n' to execute the current line of code (doesn't follow method or function calls) Use 's' to step through code, including following function and method calls. Finally, 'c' to continue execution as normal. There are other options, but that should get you started. And look at the article linked elsewhere in this thread. pdb - because fencing off Alaska is too damn slow, binary search or not. jtm From brent.chambers at gmail.com Tue Apr 25 15:05:58 2006 From: brent.chambers at gmail.com (brent.chambers at gmail.com) Date: 25 Apr 2006 12:05:58 -0700 Subject: python application ideas. In-Reply-To: References: Message-ID: <1145991958.280017.110250@e56g2000cwe.googlegroups.com> Thats the best way to go about it. Python I find is fun because you can just play with the interpreter throwing commands at it and really just working with syntax and usually POC ideas. The most useful ideas usually just come to you. I recieved a pretty barebones MP3 player from my sister for my birthday. I didnt have anything on the lines of file management or playlist management software whatsoever, so I decided to write some custom software (in Tkinter btw) to quickly and efficiently move around songs and playlists with it's basic removable drive format. Its all in what you need, and what you need a 'solution' for. Try not to think of 'ideas' per se, try to think of problems that need solutions. From peter at engcorp.com Tue Apr 11 08:39:25 2006 From: peter at engcorp.com (Peter Hansen) Date: Tue, 11 Apr 2006 08:39:25 -0400 Subject: Why new Python 2.5 feature "class C()" return old-style class ? In-Reply-To: <1144756774.177225.311120@z34g2000cwc.googlegroups.com> References: <1144752553.305591.88050@j33g2000cwa.googlegroups.com> <1144756774.177225.311120@z34g2000cwc.googlegroups.com> Message-ID: looping wrote: > But I think that if we make "class C():" a synonym of "class > C(object):", it will save lot of keystrokes ;-) Saving keystrokes has only rarely influenced Python's design, thankfully. If you read "import this", you'll see "explicit is better than implicit", and interpreting in this case one would have to say that so long as both old and new-style classes exist, making "class():" equivalent to "class(object):" would be doing something very implicit, and potentially very confusing. Leaving things just as they are would be a better choice. -Peter From gaz082 at gmail.com Fri Apr 21 15:14:52 2006 From: gaz082 at gmail.com (Gaz) Date: 21 Apr 2006 12:14:52 -0700 Subject: Pythonesque interface. In-Reply-To: <4asnngFuuc27U1@uni-berlin.de> References: <1145639147.524042.260220@z34g2000cwc.googlegroups.com> <4asil8FuicdvU1@uni-berlin.de> <1145640417.247970.116480@v46g2000cwv.googlegroups.com> <1145641052.645436.255950@g10g2000cwb.googlegroups.com> <4asnngFuuc27U1@uni-berlin.de> Message-ID: <1145646891.962006.277420@e56g2000cwe.googlegroups.com> Yeah, probably i'll be ending doing the front end in Flash and the back end in Python. From johnny at johnnydebris.net Fri Apr 21 02:52:19 2006 From: johnny at johnnydebris.net (Johnny deBris) Date: Fri, 21 Apr 2006 08:52:19 +0200 Subject: How can I call a python method from the XML-RPC client in Java? In-Reply-To: <1145557883.584164.97830@t31g2000cwb.googlegroups.com> References: <1145557883.584164.97830@t31g2000cwb.googlegroups.com> Message-ID: <124h0981jkg0j11@corp.supernews.com> evelyne0510 at gmail.com wrote: > Hi all, > I have created a XML-RPC model (with server and client) written in > Java. > I want to call the methods in another XML-RPC model written in > Python. > I know that in Java, I can use like > "xmlrpc_client.excute("handler_name.method", param)" to call the > methods in my xml-rpc server written in java. > But how can I call the methods in Python? I cannot creat a handler > in my Python XML-RPC server..... > Not sure what you mean by 'creating a handler in your Python RPC server', but if you just want to use the Python XMLRPC library to make a call to an XMLRPC server, there's an example in the documentation: http://docs.python.org/lib/xmlrpc-client-example.html Hope that helps. Cheers, Guido From johnjsal at NOSPAMgmail.com Tue Apr 11 13:56:53 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 11 Apr 2006 17:56:53 GMT Subject: list.clear() missing?!? In-Reply-To: References: <1144767680.583085.310160@v46g2000cwv.googlegroups.com> Message-ID: Steven Bethard wrote: > lst[:] = [] > lst = [] What's the difference here? From panos.laganakos at gmail.com Sun Apr 23 19:27:51 2006 From: panos.laganakos at gmail.com (Panos Laganakos) Date: 23 Apr 2006 16:27:51 -0700 Subject: Passing data attributes as method parameters Message-ID: <1145834871.667658.201550@u72g2000cwu.googlegroups.com> Hello, I'd like to know how its possible to pass a data attribute as a method parameter. Something in the form of: class MyClass: def __init__(self): self.a = 10 self.b = '20' def my_method(self, param1=self.a, param2=self.b): pass Seems to produce a NameError of 'self' not being defined. From maria.kgn at gmail.com Sun Apr 16 09:51:35 2006 From: maria.kgn at gmail.com (MK) Date: 16 Apr 2006 06:51:35 -0700 Subject: sort in Excel In-Reply-To: <1145181954.770416.157470@v46g2000cwv.googlegroups.com> References: <1145181954.770416.157470@v46g2000cwv.googlegroups.com> Message-ID: <1145195495.602541.196220@i40g2000cwc.googlegroups.com> u do it like this: from win32com.client import Dispatch xlApp = Dispatch("Excel.Application") xlApp.Workbooks.Open("D:\python\sortme.csv") xlApp.Range("A1:C100").Sort(Key1=xlApp.Range("B1"), Order1=2) xlApp.ActiveWorkbook.Close(SaveChanges=1) xlApp.Quit() del xlApp From DMagazine at 163.com Wed Apr 5 01:03:39 2006 From: DMagazine at 163.com (magazine) Date: Wed, 5 Apr 2006 13:03:39 +0800 Subject: FW: [psf] #286: Py_Initialize faliure if the python24.lib build with vc8 Message-ID: <44335348.1B3FA7.19994> -----Original Message----- From: Steve Holden [mailto:steve at holdenweb.com] Sent: 2006?4?4? 20:00 To: DMagazine at 163.com Cc: tim at pollenation.net Subject: Re: [psf] #286: Py_Initialize faliure if the python24.lib build with vc8 psf wrote: > #286: Py_Initialize faliure if the python24.lib build with vc8 > -------------------------------+-------------------------------------------- > Reporter: DMagazine at 163.com | Owner: somebody > Type: defect | Status: new > Priority: normal | Milestone: > Component: apacheconf | Version: > Severity: normal | Keywords: > -------------------------------+-------------------------------------------- > I tried embeded python2.4.3 in my project, to get the python24_d.lib, I > had to compile the source with vs2005, that's ok. but in my project,when > call Py_Initialize, it pop a "Debug Assertion Failed!" dialog. The reason > like that install sigal callback function failed. > Please note that the TRAC system into which you entered this problem description is solely for tracking issues with the web site, and you will therefore not receive any other response. Please consider submitting your problem to comp.lang.python, also available as python-list at python.org, if you require an answer to your questions. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd www.holdenweb.com Love me, love my blog holdenweb.blogspot.com From steve at REMOVETHIScyber.com.au Sat Apr 15 22:06:26 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 16 Apr 2006 12:06:26 +1000 Subject: multiple parameters in if statement References: Message-ID: On Sat, 15 Apr 2006 20:28:47 -0400, Kun wrote: > I am trying to make an if-statement that will not do anything and print > 'nothing entered' if there is nothing entered in a form. I have the > following code that does that, however, now even if I enter something > into the form, the code still outputs 'nothing entered'. This violates > the if statement and I am wondering what I did wrong. > > if form.has_key("delete_id") and form["delete_id"].value != "" and > form.has_key("delete_date") and form["delete_date"].value != "" and > form.has_key("delete_purchasetype") and > form["delete_purchasetype"].value != "" and form.has_key("delete_price") > and form["delete_price"].value != "" and form.has_key("delete_comment") > and form["delete_comment"].value != "": > delete_id=form['delete_id'].value > delete_date=form['delete_date'].value > delete_purchasetype=form['delete_purchasetype'].value > delete_price=form['delete_price'].value > delete_comment=form['delete_comment'].value > else: > print "ERROR: Nothing entered!" > raise Exception That's rather, um, unfortunate looking code. Instead of making lots of tests like this: if form.has_key(key) and form[key].value != "" ... you might find it useful to create a helper function: def get(form, key): if form.has_key(key): return form[key].value else: return "" Now you don't need to test for existence and non-emptiness, because missing values will be empty. You just use it like this: if get(form, key) != "" and ... Using the get helper function, your test becomes much simpler: if get(form, "delete_id") != "" and get(form, "delete_date") != "" \ and get(form, "delete_purchasetype") != "" and \ get(form, "delete_price") != "" and get(form, "delete_comment") != "": do_something() else: raise ValueError("nothing entered") But that's still too complicated. In Python, every object can be tested by if...else directly. Strings are all True, except for the empty string, which is False. As an experiment, try this: if "something": print "Something is not nothing." else: print "Empty string." if "": print "Something is not nothing" else: print "Empty string." So your if...else test becomes simpler: if get(form, "delete_id") and get(form, "delete_date") and \ get(form, "delete_purchasetype") and get(form, "delete_price") and \ get(form, "delete_comment"): do_something() else: raise ValueError("nothing entered") Now your test checks that every field is non-empty, and if so, calls do_something(), otherwise it raises an error. But in fact, that gets the logic backwards. You want to raise an error only if every field is empty. So your test becomes: if get(form, "delete_id") or get(form, "delete_date") or \ get(form, "delete_purchasetype") or get(form, "delete_price") or \ get(form, "delete_comment"): do_something() else: raise ValueError("nothing entered") -- Steven. From anton.vredegoor at gmail.com Wed Apr 26 10:49:23 2006 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Wed, 26 Apr 2006 16:49:23 +0200 Subject: not quite 1252 In-Reply-To: References: <444f5e6b$1@usenet.zapto.org> Message-ID: <444f8781@usenet.zapto.org> Fredrik Lundh wrote: > Anton Vredegoor wrote: > >> I'm trying to import text from an open office document (save as .sxw and >> read the data from content.xml inside the sxw-archive using >> elementtree and such tools). >> >> The encoding that gives me the least problems seems to be cp1252, >> however it's not completely perfect because there are still characters >> in it like \93 or \94. Has anyone handled this before? > > this might help: > > http://effbot.org/zone/unicode-gremlins.htm Thanks a lot! The code below not only made the strange chars go away, but it also fixed the xml-parsing errors ... Maybe it's useful to someone else too, use at own risk though. Anton from gremlins import kill_gremlins from zipfile import ZipFile, ZIP_DEFLATED def repair(infn,outfn): zin = ZipFile(infn, 'r', ZIP_DEFLATED) zout = ZipFile(outfn, 'w', ZIP_DEFLATED) for x in zin.namelist(): data = zin.read(x) if x == 'contents.xml': zout.writestr(x,kill_gremlins(data).encode('cp1252')) else: zout.writestr(x,data) zout.close() def test(): infn = "xxxx.sxw" outfn = 'dg.sxw' repair(infn,outfn) if __name__=='__main__': test() From tjreedy at udel.edu Tue Apr 11 21:17:20 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 11 Apr 2006 21:17:20 -0400 Subject: RIIA in Python 2.5 alpha: "with... as" References: <178359972.20060411145606@sinn.ru> Message-ID: "Alexander Myodov" wrote in message news:178359972.20060411145606 at sinn.ru... > Hello, > for k in a1: > pass > print "k: %s" % k > where "k" lives long after the actual need in it was lost, There are occasions, especially when one breaks out of the loop, when keeping k bound *is* useful. If a1 generates big resources that you want the last one of freed, or if having k still bound just bothers you, del k > and even list comprehensions: > b1 = [l for l in a1] > print "l: %s" % l This will go away in 3.0. For now, del l if you wish. Terry Jan Reedy From olanglois at quazal.com Tue Apr 11 14:30:22 2006 From: olanglois at quazal.com (Olivier Langlois) Date: Tue, 11 Apr 2006 14:30:22 -0400 Subject: Memory limit to dict? Message-ID: <400BDC416E2A0042AA35DF3919BB8A5123A0EF@mail.mtl.proksim.com> With 32 bits address space, you have exactly 4GB. Of course out of that 4GB, the OS reserves some of that space for itself. So I think that 2GB of available memory for a user process is good approximation. However, on top of that, you need to account for space overhead that Python and the OS heap management will generate. I have written an article discussing memory allocation overhead: http://www3.sympatico.ca/olanglois/CFixAlloc.html It is for C++ but I believe that concepts still apply for Python users and could give the original poster a better understanding about the problem he is facing. I have kept thinking about the original problem and I now believe that the only solution if he wants to store 3.6GB of data in a Python script is to recompile Python in 64 bits. I do not know if this is something that someone has already done successfully... Olivier Langlois http://www.quazal.com > -----Original Message----- > From: python-list-bounces+olanglois=quazal.com at python.org [mailto:python- > list-bounces+olanglois=quazal.com at python.org] On Behalf Of Burton Samograd > Sent: April 11, 2006 2:10 PM > To: python-list at python.org > Subject: Re: Memory limit to dict? > > Peter Beattie writes: > > > > I've no idea how far the Windows task manager's resource monitor can be > > trusted -- probably not as far as I could throw a heavy-set St Bernard > > --, but it seems to stop roughly when that monitor records a swap file > > size of 2.2 GB. > > Not being a windows expert at all, but I would assume with 32 bit > windows each process in the system can have an address space of ~2 > gigs. In linux the process address space is split in half, bottom 2 > gigs for OS mappings, top for the process, so it looks like you might > just be hitting the maximum allowed address space mapping. > > You should partition your data into hierarchial modules and let python > do the swapping for you...although you have 16 gigs (I have to put a > holy crap after that!) you will always run into process limits, at > least until true 64 bit os's are in vouge. > > -- > burton samograd kruhft .at. gmail > kruhft.blogspot.com www.myspace.com/kruhft metashell.blogspot.com > -- > http://mail.python.org/mailman/listinfo/python-list From goldfita at signalsguru.net Wed Apr 5 16:54:16 2006 From: goldfita at signalsguru.net (Todd) Date: 5 Apr 2006 13:54:16 -0700 Subject: efficiency of range() and xrange() in for loops In-Reply-To: References: Message-ID: <1144270456.419435.15400@i39g2000cwa.googlegroups.com> Steve R. Hastings wrote: > When you compile the expression > > for i in range(1000): > pass > > does Python make an iterator for range(), and then generate the values > on the fly? Or does Python actually allocate the list [0, 1, 2, ..., 999] > and then step through it? I ran an experiment on this a while back. I thought it generated a list. But the results turned out to be surprising. Take this with a grain of salt. I'm not completely sure I did what I meant to do. But it looks like however you do it, it works out about the same. http://www.signalsguru.net/articles/pyloops/pyloops.html From "thulben\" at (none) Sun Apr 2 14:47:16 2006 From: "thulben\" at (none) (none) Date: Sun, 02 Apr 2006 13:47:16 -0500 Subject: Assignment in a while? Message-ID: <123071lnngm15da@corp.supernews.com> Hi all, First, let me preface this by the fact that I'm completely new to the language, but not to programming in general. I'm trying to get my feet wet with something near and dear to my heart: database programming. Here's what I've got: import pgdb; dbh = pgdb.connect(database = 'test') sth = dbh.cursor() sth.execute("SELECT * FROM capitals") #while 1: #results = sth.fetchone() #if results == None: #break #print results while results = sth.fetchone(): print results If I try to run the above code, I get a SyntaxError indicating that I can't do an assignment in the while loop. I found a way around this (see the commented out while loop), but it seems hackish. Assignment within a while loop seems like a pretty standard thing, so I'm just curious what I'm missing. Thanks in advance, Ben From tomerfiliba at gmail.com Mon Apr 24 13:21:43 2006 From: tomerfiliba at gmail.com (gangesmaster) Date: 24 Apr 2006 10:21:43 -0700 Subject: threads and sys.exit() In-Reply-To: <4b4fdaFv61niU1@uni-berlin.de> References: <1145897992.091952.326970@e56g2000cwe.googlegroups.com> <4b4fdaFv61niU1@uni-berlin.de> Message-ID: <1145899303.174911.80770@u72g2000cwu.googlegroups.com> >>> import threading >>> t=threading.Thread(target=sys.exit) >>> t.setDaemon(True) >>> t.start() >>> ? From tjreedy at udel.edu Thu Apr 27 14:57:37 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 27 Apr 2006 14:57:37 -0400 Subject: String Exceptions (PEP 352) References: Message-ID: "Thomas Guettler" wrote in message news:pan.2006.04.27.14.18.41.758387 at thomas-guettler.de... >I like python because it is compatible to old versions. Python 3 will be a new and mostly improved dialect of Python. Some 2.x code will run unchanged. Much will not. Transition tools will be written. > That's way I think string exceptions should not be deprecated. > Is it too late to change this? Yes. > Way not make this line raise "..." > behave like this: raise Exception("...") Part of the motivation for 3.0 is to remove duplication and *simply* the language (= easier to learn), parser, compiler, and interpreter. Terry Jan Reedy From me+python at modelnine.org Thu Apr 13 13:25:00 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Thu, 13 Apr 2006 19:25:00 +0200 Subject: Can't see the forest for the trees - when reading file, only processing first line In-Reply-To: <123t1kbige4ok93@corp.supernews.com> References: <123t1kbige4ok93@corp.supernews.com> Message-ID: <200604131925.01067.me+python@modelnine.org> Am Donnerstag 13 April 2006 19:12 schrieb News: > The use_file() function should be returning each file line. How do you think it should do that? There's a return line statement in the function which breaks function execution right after having read the first line. Rethink your logic... --- Heiko. From barmar at alum.mit.edu Thu Apr 13 00:43:02 2006 From: barmar at alum.mit.edu (Barry Margolin) Date: Thu, 13 Apr 2006 00:43:02 -0400 Subject: symbolic links, aliases, cls clear References: <1143672131.167324.36920@i39g2000cwa.googlegroups.com> <1144844223.094969.82870@t31g2000cwb.googlegroups.com> <87r7430x2t.fld@apaflo.com> <4a53skFr812lU1@individual.net> <9p20h3-sfc.ln1@xword.teksavvy.com> <3isq329vv0hopvhkfsu80vi8ncm0li0b1v@4ax.com> Message-ID: In article , "Chris F.A. Johnson" wrote: > In fact, my scripts are portable to other terminal types by use > of files for each terminal, generated with tput. Using a > different terminal is as easy as ". /usr/share/term-sh/$TERM" or > something similar. I generated a lot of files a few years ago, > but I have never had any call for them, so I'd have to hunt for > them. So you've essentially reinvented the whole termcap/terminfo mechanism? -- Barry Margolin, barmar at alum.mit.edu Arlington, MA *** PLEASE post questions in newsgroups, not directly to me *** *** PLEASE don't copy me on replies, I'll read them in the group *** From johnjsal at NOSPAMgmail.com Tue Apr 4 11:25:30 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 04 Apr 2006 15:25:30 GMT Subject: how do you use pickle? Message-ID: Here's what I have: import pickle data = open(r'C:\pickle_data.txt', 'w') image = open(r'C:\peakhell.jpg') pickle.Pickler(data) data.dump(image) data.close() image.close() First off, I'm not sure the second line is the way to do that. But my main problem is I don't know how to define the steps when pickling an object. How do you first create the object? Does it return a value? I tried: pickler = pickle.Pickler(data) pickle.Pickler(data) Then I tried: pickler.dump(image) data.dump(image) Basically, I'm just confused about all the syntax involved. Which objects do I operate on, and when? I can't find these answers in the documentation or in the interactive help, because I don't see any examples. Furthermore, I get this error every time: Traceback (most recent call last): File "C:\Documents and Settings\jsaler01.TUFTS\My Documents\Python24\myscripts\challenges\pickle.py", line 3, in -toplevel- import pickle File "C:\Documents and Settings\jsaler01.TUFTS\My Documents\Python24\myscripts\challenges\pickle.py", line 7, in -toplevel- pickle.Pickler(data) AttributeError: 'module' object has no attribute 'Pickler' So that makes me really confused, because I must have the syntax totally wrong if it can't even get past the initial creation of a pickler object. From noreply at nospam.winwaed.com Sun Apr 16 18:04:21 2006 From: noreply at nospam.winwaed.com (Richard Marsden) Date: Sun, 16 Apr 2006 17:04:21 -0500 Subject: Python certification/training In-Reply-To: References: <1145193231.657614.275950@v46g2000cwv.googlegroups.com> <1145205741.731529.84530@u72g2000cwu.googlegroups.com> Message-ID: Aahz wrote: > Then may I suggest that you subscribe to the tutor list? That will give > you a good place to ask questions; as you learn Python, answering other > people's questions will give you a good way to hone your own knowledge. Which is? :-) Richard (who might also be interested - in the tutor list, not the certification) -- Richard Marsden Winwaed Software Technology, http://www.winwaed.com http://www.mapping-tools.com for MapPoint tools and add-ins Pre-Order MapPoint 2006 now: http://www.mapping-tools.com/mappoint2006 From kent at kentsjohnson.com Thu Apr 20 09:46:53 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Thu, 20 Apr 2006 09:46:53 -0400 Subject: Method Call in Exception In-Reply-To: <1145498149.790387.289670@v46g2000cwv.googlegroups.com> References: <1145490879.789439.18030@t31g2000cwb.googlegroups.com> <1145498149.790387.289670@v46g2000cwv.googlegroups.com> Message-ID: <444790ae$1_2@newspeer2.tds.net> Carl Banks wrote: > mwt wrote: >> In my latest attempt at some Python code, I've been tempted to write >> something in the form of: >> >> try: >> [...] #doing some internet stuff >> except IOError: >> alternate_method_that_doesnt_need_internet() >> >> This works when I try it, but I feel vaguely uneasy about putting >> method calls in exception blocks. So tell me, Brave Pythoneers, is this >> evil sorcery that I will end up regretting, or is it just plain good >> ol' Python magic? > > It's ok. In fact a lot of Pythonistas recommend this way over the > alternative, even when you don't have to. For example, a lot of people > recommend this: > > try: > name = record.name > except AttributeError: > name = "Freddy" > > instead of this: > > if hasattr(record,"name"): > name = record.name > else: > name = "Freddy" or maybe name = getattr(record, 'name', 'Freddy') Kent From khemkaamit at gmail.com Tue Apr 4 05:46:42 2006 From: khemkaamit at gmail.com (Amit Khemka) Date: Tue, 4 Apr 2006 15:16:42 +0530 Subject: Does anyone know where is the Berkeley XML Database documentation for its Python API? In-Reply-To: <1144139665.722247.213390@j33g2000cwa.googlegroups.com> References: <1144139665.722247.213390@j33g2000cwa.googlegroups.com> Message-ID: <1360b7230604040246i7d5b9917qd1371531fb2eff7e@mail.gmail.com> There are no official/un-official documentation for bdbxml python api AFAIK !!! If you want some examples look in "dbxml/examples/python/", directory in your dbxml installation. Though for most part the python api closely follows the C++/Java api (look: http://www.dbxml.com/docs/programmer.html ) for details. You may also find http://blog.gmane.org/gmane.comp.db.dbxml.general useful. cheers, amit. On 4 Apr 2006 01:34:25 -0700, Sullivan WxPyQtKinter wrote: > I have been looking for python API documentation of BDBXML for quite a > few days but I could not find it. Anyone has any idea where it is? Or > if there is not such a thing at all, how could I get started? > > In addition, in the previous posts I have seen some grumble about > python API's lack of XMLexception and some basic programming and > debugging elements for project engineering. Are they added or fixed in > the lastest version of BSBXML? > > > Thank you for help. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- ---- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. From tzot at sil-tec.gr Sat Apr 8 03:34:07 2006 From: tzot at sil-tec.gr (Christos Georgiou) Date: Sat, 08 Apr 2006 10:34:07 +0300 Subject: "The World's Most Maintainable Programming Language" References: <44362cbe$1_3@news.bluewin.ch> Message-ID: On Fri, 07 Apr 2006 11:11:14 +0200, rumours say that Azolex might have written: >> At-least Pythetic isn't a word (yet). >> > >:))) "now that's quite pythetic !" Well, "pythetic" could become a synonym to "un-pythonic". -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From g.brandl-nospam at gmx.net Wed Apr 12 02:53:47 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Wed, 12 Apr 2006 08:53:47 +0200 Subject: Best way to emulate ordered dictionary (like in PHP)? In-Reply-To: <1144822651.449335.128970@v46g2000cwv.googlegroups.com> References: <1144822651.449335.128970@v46g2000cwv.googlegroups.com> Message-ID: pyGuy wrote: > I am dealing with user profiles, which are simply a set of field-value > pairs. I've tried to many things to list, but for one, I tried creating > a wrapper class which inherits the dictionary and overrides the > iterator. Unfortunately I don't understand iterators enough to get this > working and before I waste any more time trying I figured I should > check wether there is a better way. I have run into a similar problem > once, and I resolved it by creating a wrapper class for the 'list' > class which overides the get_item method, checks for string parameter, > then accesses the appropriate item via a lookup 'list' contained within > the class which maps the string parameter to the index number (eh, it > just doesn't seem practical though). Now, I'e never used PHP, but > apparently, it's dictionaries retain the order in which the items are > entered and regurgitates them in that order when you iterate over them. > That is exactly what I want, but can't seem to get in Python. Any help? If you search Google for OrderedDict, you get more than enough code snippets. There's also one in the Python Cookbook, at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/438823 HTH, Georg From steve at holdenweb.com Tue Apr 11 07:37:23 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 11 Apr 2006 07:37:23 -0400 Subject: Compleated Begginers Guide. Now What? In-Reply-To: References: <1144497870.999295.162450@i39g2000cwa.googlegroups.com> Message-ID: James Stroud wrote: > Mirco Wahab wrote: > >>Jay wrote: >>Malchick, you cracked your veshchs to classes, which is >>not that gloopy. So rabbit on them and add class methods >>that sloosh on beeing called and do the proper veshchs >>to the gulliwuts of their classes. > > > Brillig! > > But neither helpful nor sympathetic. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd www.holdenweb.com Love me, love my blog holdenweb.blogspot.com From bencvt at gmail.com Sat Apr 8 00:41:20 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 7 Apr 2006 21:41:20 -0700 Subject: very strange problem in 2.4 In-Reply-To: <2tCdnYMo5LbIkqrZnZ2dnUVZ_u2dnZ2d@comcast.com> References: <1144454473.488240.271200@t31g2000cwb.googlegroups.com> <2tCdnYMo5LbIkqrZnZ2dnUVZ_u2dnZ2d@comcast.com> Message-ID: <1144471280.411044.174300@i39g2000cwa.googlegroups.com> John Zenger wrote: > Your list probably contains several references to the same object, > instead of several different objects. This happens often when you use a > technique like: > > list = [ object ] * 100 This is most likely what's going on. To the OP: please post the relevant code, including how you create mylist and the definitions of change_var_a and return_var_a. I suspect you're doing something like this: >>> \ class C(object): def __init__(self, x): self.x = x def __repr__(self): return 'C(%r)' % self.x >>> mylist = [C(0)]*3 + [C(1)]*3 >>> mylist [C(0), C(0), C(0), C(1), C(1), C(1)] >>> mylist[0].x = 2 [C(2), C(2), C(2), C(1), C(1), C(1)] When you should do something like: >>> mylist = [C(0) for i in range(3)] + [C(1) for i in range(3)] [C(0), C(0), C(0), C(1), C(1), C(1)] >>> mylist[0].x = 2 [C(2), C(0), C(0), C(1), C(1), C(1)] --Ben From vinjvinj at gmail.com Wed Apr 19 22:11:12 2006 From: vinjvinj at gmail.com (vj) Date: 19 Apr 2006 19:11:12 -0700 Subject: Pyrex installation on windows XP: step-by-step guide In-Reply-To: <1145449777.731155.181600@i40g2000cwc.googlegroups.com> References: <1145449777.731155.181600@i40g2000cwc.googlegroups.com> Message-ID: <1145499072.584917.126420@t31g2000cwb.googlegroups.com> Can you use the stock python build or do you have to build python from scratch with mingw to use pyrex modules built with mingw? From pmartin at snakecard.com Wed Apr 26 17:26:00 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Wed, 26 Apr 2006 16:26:00 -0500 Subject: wxpython warnings References: <1146054739.094951.278490@e56g2000cwe.googlegroups.com> Message-ID: Hi, This is an answer I got from the wxPython NG: """ If it is a wxLog message (I think it is) then you can temporarily disable log messages by creating an instance of wx.LogNull. ?Or you can do something like set the log target to some other object than the default wx.LogGui, or set the log level to a higher level so those messages are not logged. """ Regards, Philippe Iain King wrote: > I have a wxpython program that displays TIF images. Sometimes it will > encounter a tag the tiff loader cant handle. Rather than silently > ignoring it, it pops up a window: > > Python Warning > unknown field with tag blah blah > > I don't want it to do this, but I can't work out how to turn it off. > Anyone know? > > Iain From petr at tpc.cz Fri Apr 28 11:20:35 2006 From: petr at tpc.cz (Petr Jakes) Date: 28 Apr 2006 08:20:35 -0700 Subject: Using Databases in Python Message-ID: <1146237635.087759.312210@y43g2000cwc.googlegroups.com> I would like to know if anybody can point me to the site, where it is possible to find the tutorial "Using Databases in Python" which is mentioned by Steve Holden here: http://tinyurl.com/ectj8 Thanks Petr Jakes From deets at nospam.web.de Wed Apr 19 09:27:15 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 19 Apr 2006 15:27:15 +0200 Subject: Telnet Server Lib References: <1145394277.295466.82410@g10g2000cwb.googlegroups.com> Message-ID: <4ams64Ftsn5rU1@uni-berlin.de> dakman at gmail.com wrote: > I have been working on a project for some time now, that has various > types of admistrating including a CGI web interface, In a previous > version I implemented a Psuedo-Telnet Server if you will, bassicly all > it did was print text to the client, and expect back data, it did not > work with any of the protocol needless to say it was a mess, instead of > programming my own library for the project (Which is a whole nother > project.) Knowing that writing your own telent server is serious > buisness, I have tried googling this and found nothing of relevancy. Do > any of you know of or used any library for telnet servers? Look at twisted. Might do what you want. Diez From peter at engcorp.com Mon Apr 3 17:30:44 2006 From: peter at engcorp.com (Peter Hansen) Date: Mon, 03 Apr 2006 17:30:44 -0400 Subject: MOO meets Python In-Reply-To: <1144095639.090725.323290@u72g2000cwu.googlegroups.com> References: <1144095639.090725.323290@u72g2000cwu.googlegroups.com> Message-ID: Istvan Albert wrote: > Quote from the webpage: "It's a buggy bundle of Python code that, by > default, opens interfaces to your computer and makes it insecure." So it's a way of using Python to emulate the Windows operating system, for people stuck using Linux? > ... just what I was looking for ... :-) -Peter From leonardodiserpierodavinci at gmail.com Fri Apr 28 04:28:16 2006 From: leonardodiserpierodavinci at gmail.com (Leonardo da Vinci) Date: 28 Apr 2006 01:28:16 -0700 Subject: How to align the text of a Listbox to the right In-Reply-To: References: Message-ID: <1146212895.904335.66490@v46g2000cwv.googlegroups.com> Sori Schwimmer ha scritto: > For a listbox, I would give a width and go with string > formatting. In your case, I guess that what I'll do is > to limit the width to something acceptable, and show > only the tail of the line. Yes, this is exactly what I wanted to do. Do you know a way to accomplish that? Because Eric Brunel said it is impossible on a Listbox. Thanks to everybody, L From cfriedl at bigpond.net.au Sun Apr 16 05:12:01 2006 From: cfriedl at bigpond.net.au (bwaha) Date: Sun, 16 Apr 2006 09:12:01 GMT Subject: py2exe problem References: <1145134511.975204.232650@g10g2000cwb.googlegroups.com> Message-ID: "Serge Orlov" wrote in message news:1145134511.975204.232650 at g10g2000cwb.googlegroups.com... > bwaha wrote: > > First time trying to create an executable with py2exe. I have a small > > program which makes use of python23 (2.3.5?), wxpython ('2.6.2.1'), > > matplotlib ('0.83.2'), win32com (latest?), Numeric ('23.7') on Windows XP & > > Win2000. The program runs without problem but as an exe it doesn't even get > > to showing the GUI. > > Do you have more than one wxwindows installed? Check you site-packages. > Do you follow documentation > http://wiki.wxpython.org/index.cgi/MultiVersionInstalls ? Seems like > py2exe picks wrong wxwindows. Insert printing of wx.VERSION and > wx.PlatformInfo and try to run it packaged and non-packaged. > > Serge > Thanks for the suggestion, but I definitely have only one version installed. In fact I uninstalled it and installed an earlier version (2.5.5.1) to see if it was specifically wxPython related. No change. From finite.automaton at gmail.com Fri Apr 7 00:11:35 2006 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 6 Apr 2006 21:11:35 -0700 Subject: how to make a generator use the last yielded value when it regains control References: <4435cde3$0$11677$c3e8da3@news.astraweb.com> <4435cf91$0$11698$c3e8da3@news.astraweb.com> Message-ID: <1144383095.892099.289690@u72g2000cwu.googlegroups.com> The generator in your original post /does/ rebind seed, but only on the last iteration of the loop. You'll need to wrap that loop in another loop if you want the generator to yield more than once. As for "communicating" with a generator --- e.g. telling it to stop --- this might be done by passing some kind of mutable argument to the generator and then changing the value of that mutable object. However, it's not a very elegant solution, and in this case there's not really any reason to do it. Instead, if you want the generator to stop, just stop asking it to yield: for number in morris_sequence_generator(seed): if it_is_time_to_stop(): break And: - No need to convert str(seed) to a list! Strings are indexable. - Instead of using "try...except IndexError" to detect the end of the loop, just change the loop to range(len(seed) - 1) and do the yield after the loop finishes. - Use xrange instead of range. range is evil. Bonus points: Write the generator to work on a seed which is an iterable of unknown length. Super bonus points: Print the Nth element in the sequence without holding more than N groups of {digit, number of occurences} of state information. You'll need to do this if you want to get very far: According to Wikipedia, the 70th term of the look-and-say sequence has 179,691,598 digits. From nico at netsys.co.za Wed Apr 12 05:41:19 2006 From: nico at netsys.co.za (Nico Kruger) Date: Wed, 12 Apr 2006 11:41:19 +0200 Subject: Problem with spawning an external process In-Reply-To: <1144834050.3376.35.camel@notamc2.snetsys.co.za> References: <1144834050.3376.35.camel@notamc2.snetsys.co.za> Message-ID: <1144834879.3376.39.camel@notamc2.snetsys.co.za> Apologies, this is on a Fedora Core 2 system. On Wed, 2006-04-12 at 11:27, Nico Kruger wrote: > I want to execute a command (in this case, and it seems to be > significant, a Java program) in a thread in Python. When I execute the > java binary in the main python thread, everything runs correctly. But > when I try and execute java in a thread, java segfaults. I am using > Python 2.3.3 and trying to run the java binary from the 1.4.2 SDK from > Sun. > > I have tried executing some arbitrary C program that I wrote, and it > works fine in the main thread and the started thread. The problem seems > to be specific to the Java binary. > > Here is the example code: > > --- START CODE --- > import os > import popen2 > import time > import select > import threading > > # Change these to suit your system > PATH = '/home/nico/j2sdk1.4.2/bin/java' > #PATH = '/home/nico/j2sdk1.4.2/bin/java -invalid_arg' > > def get_ret(status): > signal = status & 0xff > if signal == 0: > retcode = status >> 8 > else: > retcode = 0 > return signal,retcode > > print "In main thread" > # Using spawn > pid = os.spawnl(os.P_NOWAIT,PATH,PATH) > ret = os.waitpid(pid,0) > print "PID: %i signal: %i return code: %i" % > (ret[0],get_ret(ret[1])[0],get_ret(ret[1])[1]) > > class TestThread(threading.Thread): > def run(self): > # Using spawn > pid = os.spawnl(os.P_NOWAIT,PATH,PATH) > ret = os.waitpid(pid,0) > print "PID: %i signal: %i return code: %i" % > (ret[0],get_ret(ret[1])[0],get_ret(ret[1])[1]) > > print "In Thread" > TestThread().start() > > print "Waiting..." > time.sleep(2) > print "...Finished" > ---- END CODE ---- > > Here is the output that I get on my machine: > [nico@ script]$ python testcrash2.py > In main thread > > PID: 32107 signal: 0 return code: 1 > In Thread > PID: 32116 signal: 11 return code: 0 > > > You will notice that in the main thread, the program executes correctly > (return code 1, signal 0). When the command is executed in the thread, > it segfaults (signal 11). The second PATH= line calls Java with an > invalid argument. In this case, it does not crash in the thread. > > I have tried a fork() and then os.execv in the thread as well, and get > the same behaviour. > > I would appreciate it if someone with both Java and Python could try and > run this sample and report back. Any suggestions would be welcome, as > this is quite the showstopper for me at the moment. I am sure I am > missing something totally obvious... > > Thanks in advance, > Nico. > -- NetSys International (Pty) Ltd. Tel : +27 12 349 2056 Fax : +27 12 349 2757 Web : http://www.netsys.co.za P.O. Box 35798, Menlo Park, 0102, South Africa ---- The information contained in this communication is confidential and may be legally privileged. It is solely for use of the individual or entity to whom is addressed and others authorised to receive it. If you are not the intended recipient you are hereby notified that any disclosure, copying, distribution or taking of any action in reliance on the contents of this information is strictly prohibited and may be unlawful. This Message has been scanned for viruses and dangerous content by the NetSys International Mail Scanner and is believed to be clean. From maria.kgn at gmail.com Sun Apr 16 06:04:00 2006 From: maria.kgn at gmail.com (MK) Date: 16 Apr 2006 03:04:00 -0700 Subject: sort in Excel Message-ID: <1145181840.806114.92720@z34g2000cwc.googlegroups.com> Hello, Does anyone knows how can I From me+python at modelnine.org Sun Apr 16 15:50:34 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Sun, 16 Apr 2006 21:50:34 +0200 Subject: Using Python To Create An Encrypted Container In-Reply-To: References: <7x7j5p8sj3.fsf@ruckus.brouhaha.com> Message-ID: <200604162150.34777.me+python@modelnine.org> Am Sonntag 16 April 2006 19:11 schrieb Michael Sperlle: > The only other thing I can think of is making it non-readable for anyone > except root, but have the feeling that's not too secure. Huh? If you don't trust your operating system to correctly validate file-permissions for you (on a server, on a client system which can be booted by others than you or from which the physical harddisk can be extracted the security implications are completely different), you're in absolutely no position to even want encryption, because any malicious user can replace your encryption code with code of his own, so that it's easily breakable by him. Of course there are temporary local priviledge escalations (in some applications, or even in the kernel of your operating system), but if you rely on the operating system to keep your encryption code secure, you might as well rely on the operating system to keep your data secure, because that's basically the same thing. --- Heiko. From alexci at web.de Mon Apr 17 18:35:42 2006 From: alexci at web.de (Aleksandar Cikota) Date: Tue, 18 Apr 2006 00:35:42 +0200 Subject: Threading problem References: Message-ID: Thank You, but now it cannot open a file, but it should work... Here the error message: >>> Exception in thread Thread-1: Traceback (most recent call last): File "C:\Program Files\Python\lib\threading.py", line 442, in __bootstrap self.run() File "G:\Robot teleskop\VRT\test\test2.py", line 25, in run Document.OpenFile('F:/Images/VRT/'+name) File "C:\Program Files\Python\Lib\site-packages\win32com\client\dynamic.py", line 496, in __getattr__ raise AttributeError, "%s.%s" % (self._username_, attr) AttributeError: MaxIm.Document.OpenFile And here the Code: import win32com.client import time import os import threading Document = win32com.client.Dispatch('MaxIm.Document') Application = win32com.client.Dispatch('MaxIm.Application') p = win32com.client.dynamic.Dispatch('PinPoint.Plate') class TestThread (threading.Thread): def run (self): path_to_watch = "F:/Images/VRT/" before = dict ([(f, None) for f in os.listdir (path_to_watch)]) while 1: time.sleep(2) after2 = dict ([(f, None) for f in os.listdir (path_to_watch)]) added = [f for f in after2 if not f in before] if added: name= ' ,'.join (added) if str(name[-3:])=='fit': Document.OpenFile('F:/Images/VRT/'+name) Document.SaveFile('F:/Images/VRT/'+ str(name[0:-4])+'.jpg', 6, 1024,2) Application.CloseAll() try: p.AttachFITS('F:/Images/VRT/'+name) p.ArcsecPerPixelHoriz = -1.7 p.ArcsecPerPixelVert = -1.7 p.MaxMatchResidual = 1.0 p.FitOrder = 3 p.CentroidAlgorithm = 0 p.RightAscension = p.TargetRightAscension p.Declination = p.TargetDeclination p.Catalog = 0 # GSC p.CatalogPath = 'F:/' p.ProjectionType = 1 # p.Solve() p.DetachFITS() pRA = p.RightAscension pDec = p.Declination print pRA print pDec except: p.DetachFITS() print 'Error' before = after2 TestThread().start() "raise AttributeError, "%s.%s" % (self._username_, attr)", what does it mean? For your prompt reply, I say thank you in advance. Best regards, Aleksandar "Faber" wrote in message news:OQT0g.86761$A83.2055356 at twister1.libero.it... > Aleksandar Cikota wrote: > >> How to integrate the Code-part in the main programm, so that the >> mainprogramm works? >> >> Code: >> >> import win32com.client >> import time >> import os >> import threading >> >> Document = win32com.client.Dispatch('MaxIm.Document') >> Application = win32com.client.Dispatch('MaxIm.Application') >> p = win32com.client.dynamic.Dispatch('PinPoint.Plate') >> >> class TestThread ( threading.Thread ): >> path_to_watch = "F:/Images/VRT/" > > def run(self): > # Put the following code in the run method > >> before = dict ([(f, None) for f in os.listdir (path_to_watch)]) >> while 1: > > [cut] > >> TestThread().start() > > This should work > > -- > Faber > http://faberbox.com/ > http://smarking.com/ > > The man who trades freedom for security does not deserve nor will he ever > receive either. -- Benjamin Franklin From sanaltacir at gmail.com Sun Apr 16 10:45:43 2006 From: sanaltacir at gmail.com (=?iso-8859-1?B?bWVtbPxr?=) Date: 16 Apr 2006 07:45:43 -0700 Subject: vote Message-ID: <1145198743.096449.95630@t31g2000cwb.googlegroups.com> http://www.hemalhemsat.com/main/auctiondetail/437717/diger/mezarlariniza_muhendis_eli_degsin.php From podi.ex at gmail.com Fri Apr 14 00:47:25 2006 From: podi.ex at gmail.com (Podi) Date: 13 Apr 2006 21:47:25 -0700 Subject: How to create a single executable console application? In-Reply-To: <1144689721.446219.300610@i39g2000cwa.googlegroups.com> References: <1144689721.446219.300610@i39g2000cwa.googlegroups.com> Message-ID: <1144982462.669609.318150@u72g2000cwu.googlegroups.com> Alright, pythoneers, here is what I have found from http://wiki.wxpython.org/index.cgi/CreatingStandaloneExecutables. This is much easier than the py2exe + nullsoft combo :) Cheers! The mcillian installer development is discontinued. mirror: http://davidf.sjsoft.com/mirrors/mcmillan-inc/installer_dnld.html Continued development(not tested yet): http://pyinstaller.hpcf.upr.edu/cgi-bin/trac.cgi This works on Win32. Unzip the Installer in a directory of your choice, and cd there. Configure the Installer by running: python Configure.py Python must be in your PATH for this to work, if it's not, type from the command prompt: PATH=%PATH%;c:\python23 where c:\python23 must be replaced with the root of your python installation. Then, assuming the source code is app.py (placed in c:\source): python Makespec.py --upx --onefile --noconsole c:\source\app.py python Build.py app\app.spec Replace 'app' everywhere above with your application name. You will end up with app\app.exe under the Installer dir.This is a one file .exe containing all the application. If you don't want a one-file build, suppress the option --onefile above. If you don't have upx installed (or don't want to use it), suppress the option --upx above. The option --noconsole is needed to produce a windows gui application, instead of a console one (so the command shell won't pop up when you run the application). From spiralx at gmail.com Sat Apr 8 15:26:11 2006 From: spiralx at gmail.com (James) Date: Sat, 8 Apr 2006 20:26:11 +0100 Subject: Programming Tutorial for absolute beginners In-Reply-To: <1144522414.501828.159550@i40g2000cwc.googlegroups.com> References: <1144439148.751062.16590@t31g2000cwb.googlegroups.com> <1144444872.962395.3310@z34g2000cwc.googlegroups.com> <1144446605.916499.24470@i39g2000cwa.googlegroups.com> <4437c7cd$0$11330$636a55ce@news.free.fr> <1144511666.148953.212510@v46g2000cwv.googlegroups.com> <4437f1bd$0$11642$c3e8da3@news.astraweb.com> <1144522414.501828.159550@i40g2000cwc.googlegroups.com> Message-ID: <7ee3dcd80604081226t311ea9cbh15f6caa3f89fe381@mail.gmail.com> If you're serious about this being a real introduction for someone who knows nothing, then you might want to start off by explaining what a programming language is (and why there are more than one) and then what a standard library is - perhaps explain it in terms of a large set of tools you can use straight away? James On 8 Apr 2006 11:53:34 -0700, Clodoaldo Pinto wrote: > John Salerno wrote: > > Clodoaldo Pinto wrote: > > > > > "Python is a remarkably powerful dynamic programming language that is > > > used in a wide variety of application domains. Python is often compared > > > to Tcl, Perl, Ruby, Scheme or Java. Some of its key distinguishing > > > features include:..." > > > > I'd be careful with that definition for newbies though. There's nothing > > more frustrating (as a newbie myself) when Python (or anything else) is > > compared to something as a way to explain it, yet I have no idea what > > the other things are either! A programming newbie won't know about, and > > maybe won't even have heard of, those other languages. > > Good point. I used the Python site front page definition without the > object oriented thing. > > Regars, Clodoaldo > > -- > http://mail.python.org/mailman/listinfo/python-list > From rpdooling at gmail.com Sun Apr 16 03:59:24 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 16 Apr 2006 00:59:24 -0700 Subject: keyboard command to break out of infinite loop? Message-ID: <1145174364.436843.26660@e56g2000cwe.googlegroups.com> Running Python on Win XP. When running commands with the interpreter, if you get stuck in a while loop, is there a keyboard command to break out of it? Or is the only way out a triple-finger salute and End Task? rd From osv at javad.com Thu Apr 20 04:59:16 2006 From: osv at javad.com (Sergei Organov) Date: Thu, 20 Apr 2006 12:59:16 +0400 Subject: Conditions vs Events References: <4446C03D.7020303@mvista.com> Message-ID: "Carl J. Van Arsdall" writes: > Le Monde De Python, > > I've been working a lot with python threads from the threading module. > Specifically, when is it better to use a condition object vs an event > object? Condition is the universal primitive for waiting for some condition to occur (and for signalling the condition), where particular "condition" is defined by your program and not by the primitive itself. Event, on the other hand, is rather specialized object that allows for, well, what is written in its documentation, and I fail to see how it could be used for waiting for an arbitrary condition reliably, especially when multiple threads can change the condition. Maybe it's indeed safe in the current Python implementation utilizing GIL, I don't know, but I'd avoid to use event to be on the safe side anyway. Overall, everything you can do using event you can do using condition as well (as you can easily implement your own "event" using condition), but not vise versa, I'm afraid. > It seems to me that, at least superficially, I can just about use these > two mechanisms interchangeably. No, in general I don't think you can use event for every purpose for which condition is appropriate. > The only real difference I can see is that I can call isSet() on an > event in the case that an event is triggered before wait() is called. > Are there any differences? Well, these two things are so different that I'd instead ask for similarities, not for differences. The only similarity I see is existence of wait() method, but even then the semantics of this method is very different on event and on condition, e.g., condition.wait() never returns immediately. BTW, in the case of condition, you not only can, but should check your own condition before you enter wait, and you should do it in a loop, otherwise you'll most probably have racy program (e.g., see example at ). Obviously, nobody prevents you from checking your own condition whenever you wish, and this check is somewhat similar to calling isSet() on an event. > Also, does calling wait reset some type of "notify" in a condition > object like it does in an event object? No, condition object in this respect is stateless, and notify() never affects those threads that aren't in the wait queue of the condition at the moment of "notify" call, i.e., unlike event, condition has no "memory", so there is nothing inside to be reset by the wait(). However, as far as I can see, event.wait() doesn't change internal state of the event either. BTW, that's drastically different from how "events" (called also "signals") work in many of real-time systems, and this may confuse those who are used to different behavior. -- Sergei. From do_not_use_this_email at hotmail.com Wed Apr 19 15:03:16 2006 From: do_not_use_this_email at hotmail.com (rx) Date: Wed, 19 Apr 2006 21:03:16 +0200 Subject: multiline comments References: <1381517.XiSu08VAzt@jupiter.g2ctech> <1164308.fsspVXKdt2@jupiter.g2ctech> <44467cb4$0$4820$ba624c82@nntp02.dk.telia.net> <1296658.ifSUO08S9I@jupiter.g2ctech> Message-ID: <44468977$0$12401$ba624c82@nntp02.dk.telia.net> "Jorge Godoy" wrote in message news:1296658.ifSUO08S9I at jupiter.g2ctech... > rx wrote: > >> I have commented out a lot of C++ code and miss the block feature in >> python more than I missed the nested comments in C++. >> Besides nothing really strange happened. >> Sometimes you just need to dissable some of the code temporarly as >> quickly >> as possible, and I like that it is not higlighted any more, since I will >> not look into it before I dissable the comment. > > This is how I do it: select the lines I want to comment and ask Emacs to > comment that region. It is the same command and method for "n" different > languages and I don't care if there is multiline comment support or not. > It is really as fast as inserting /* and ending with */ (in fact, I type > less than to achieve that since I only use three keys, counting the > Ctrl-Space to start the block). It would be much nicer to have it in the language since there are many editors and many ways to do what you do (it would also make it more easy to make a editor). Besides it could be done with two keys if that really important - but I doubt it. But in a way you are also right if you use more than a few languages in the same editor, but then again the editor would still be able to do the commenting if you prefered that. I don't understand the problem - why should comments (and I hope you believe there should be a one line comment at least) be restricted to one line. It doesn't work that way for if, while, for. From fuzzyman at gmail.com Fri Apr 7 18:09:50 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 7 Apr 2006 15:09:50 -0700 Subject: mod_python + apache + winxp => nogo In-Reply-To: <1144445910.877992.80210@v46g2000cwv.googlegroups.com> References: <1144445910.877992.80210@v46g2000cwv.googlegroups.com> Message-ID: <1144447790.070964.295880@g10g2000cwb.googlegroups.com> cyberco wrote: > And I thought this would be trivial...getting mod_python to run within > apache on windows XP. > > ============= > mod_python 3.2.8 > apache 2.0.55 > python2.4 > winxp > ============= > > After adding: > "LoadModule python_module modules/mod_python.so" > I'm no expert - having never tried that combination (but I have heard of it and you should try the mod_python mailing list). However, if IIRC then a '.so' file is a UNIX type library file. (Possibly the equivalent of a dll on windows). This sounds awry to me. Fuzzyman http://www.voidspace.org.uk/python/index.shtml > to apache's httpd.conf, apache refuses to start, saying: > "cannot load c://mod_python.so into server: the specified module > could not be found" > > 'mod_python.so' is in the modules folder under apache, though. > > I've searched everywhere, but could not find a solution. Anybody here > that has been successful in getting this combo to work? From grflanagan at yahoo.co.uk Sat Apr 8 19:37:12 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 8 Apr 2006 16:37:12 -0700 Subject: how to make a generator use the last yielded value when it regains control References: <4435cde3$0$11677$c3e8da3@news.astraweb.com> <1144383206.576767.192570@g10g2000cwb.googlegroups.com> <4435e96d$0$17970$c3e8da3@news.astraweb.com> <44384257$0$11362$c3e8da3@news.astraweb.com> Message-ID: <1144539432.798755.102520@v46g2000cwv.googlegroups.com> John Salerno wrote: > Michael Spencer wrote: > > > itertools.groupby makes this very straightforward: > > I was considering this function, but then it seemed like it was only > used for determing consecutive numbers like 1, 2, 3 -- not consecutive > equivalent numbers like 1, 1, 1. But is that not right? data = [1, 1, 1, 2, 2, 3, 4, 4, 3, 2, 2, 1, 1, 2, 2,4, 2, 2] from itertools import groupby for k, g in groupby( data ): print k, list(g) 1 [1, 1, 1] 2 [2, 2] 3 [3] 4 [4, 4] 3 [3] 2 [2, 2] 1 [1, 1] 2 [2, 2] 4 [4] 2 [2, 2] for k, g in groupby( data, lambda x: x<2 ): print k, list(g) True [1, 1, 1] False [2, 2, 3, 4, 4, 3, 2, 2] True [1, 1] False [2, 2, 4, 2, 2] Gerard From tim.peters at gmail.com Fri Apr 14 11:34:42 2006 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 14 Apr 2006 11:34:42 -0400 Subject: Loop with float increments (frange)? In-Reply-To: References: <1145020298.842177.97830@e56g2000cwe.googlegroups.com> Message-ID: <1f7befae0604140834i709e510dg1cae0dd6b7b26440@mail.gmail.com> [forum at anton.e4ward.com] >> what's the standard way for a "for" loop with float increments? [Dan Sommers] > Use a while loop instead: > > f = initial_value > while f <= final_value: > process(f) > f = f + increment > > Note that there is no general guarantee that f will actually be > final_value; see also . There's no guarantee that the `while` loop will execute "the expected" number of times either, and it's generally a Bad Idea to do "f += increment" inside the loop: the value of f suffers an additional rounding error on each iteration that way, potentially making it drift away from "the expected" value more & more as the loop goes on. Standard careful numeric practice is this way: n = compute the number of iterations you want to make in total for i in xrange(n): process(initial_value + i * increment) Then each value computed suffers a total of only two rounding errors (one for the multiply, one for the add), independent of how large `n` may be, and doesn't get worse as the loop goes on. From kylotan at gmail.com Fri Apr 21 04:40:32 2006 From: kylotan at gmail.com (Ben Sizer) Date: 21 Apr 2006 01:40:32 -0700 Subject: Strategy Design Pattern In-Reply-To: <1145597529.217734.25600@g10g2000cwb.googlegroups.com> References: <1145597529.217734.25600@g10g2000cwb.googlegroups.com> Message-ID: <1145608832.611013.173250@v46g2000cwv.googlegroups.com> Daniel Santa Cruz wrote: > Well, I've gotten stuck with my first go at OO patterns with Python. I > guess it goes without say that some of the stuff that are taken for > granted in most of the books (ie. Interfaces, Abstract classes) don't > really apply to Python per say, but the idea behind the patterns can be > extracted out still. In the original "Design Patterns" book, the authors pointed out that although patterns are generally language-agnostic, the need for formalised patterns to achieve a given goal is not. One example is inheritance - if you're programming in C then you'd need a formal pattern to model inheritance effectively, but in many other languages it's built in. It may be the case that Python gives you the tools to make some other patterns effectively redundant. > In the specific case of the Strategy pattern, I > think the goal is to abstract out of the class an algorithm that can > then be reused by some of the inherited classes. This way we don't > repeat ourselves. Maybe I got this all wrong... The goal is to allow an object to have a certain behaviour which uses an algorithm you can change by changing the object that performs that algorithm. It essentially means you can change the algorithm later without changing the object. In Python, this is quite simple - decide upon an interface that the algorithm should provide, and then assign an object that implements that interface to your object. The object will then pass its data to the interface methods on whichever algorithm object it's been given. > To aid commenters... we can use the example used in "Head First Design > Patterns". I've implemented this simple patter in Java and .NET... now > in python. I can't draw UML here, so I'll try to pseudo talk what the > example has: > > Abstract Base Class: Duck > + FlyBehavior _fly > + swim() > + fly() -> calls _fly.fly() > > Interface: FlyBehavior > + fly() > > Concrete Interface FlyHigh (implements FlyBehavior): > + fly() > > Concrete Class Duck1 (Inherits Duck): > + Constructor: _fly = new FlyHigh() In this example, you can just assign a FlyHigh function to your Duck1 - no Duck or FlyBehavior classes needed. The pattern is almost pointless in situations like this when your language allows you to quickly and easily assign functions between objects. However if, as is common, you need more than 1 function in the interface, you can put them in an object and assign that. class FlyHigh(object): def TakeOff(self, bird): print "take off to fly high" def Land(self, bird): print "land from flying high" class FlyLow(object): def TakeOff(self, bird): print "take off to fly low" def Land(self, bird): print "land from flying low" class Duck(object): def __init__(self, flyingBehavior): self.flyBehavior = flyingBehavior def TakeOff(self): self.flyBehavior.TakeOff(self) def Land(self): self.flyBehavior.Land(self) lowFlyingDuck = Duck(FlyLow()) highFlyingDuck = Duck(FlyHigh()) Note that I don't claim the above code is necessarily optimal (or even correct!) but it should show that half of the Strategy pattern boilerplate is unnecessary in Python. You can even use certain Python tricks to automatically delegate calls on Duck to the behavior classes without typing those out individually, for example. -- Ben Sizer From rrrn at yahoo.com Sat Apr 1 14:14:27 2006 From: rrrn at yahoo.com (Butternut squash) Date: Sat, 01 Apr 2006 19:14:27 GMT Subject: wxpython in action book Message-ID: any recommendations? any opinions? I want to learn to program in python and need a gui reference. I'll be updating various mysql tables. I have most of the code ready to roll by using a command line. I need put some lipstick on my project. pyQT seems viable but there is not really a good reference and tutorial so now I'm considering wxPython and saw this book and I'm wanting to know if if's even worth spending my $40 on. Thanks. From jstroud at ucla.edu Sat Apr 8 17:30:26 2006 From: jstroud at ucla.edu (James Stroud) Date: Sat, 08 Apr 2006 14:30:26 -0700 Subject: Compleated Begginers Guide. Now What? In-Reply-To: References: <1144497870.999295.162450@i39g2000cwa.googlegroups.com> Message-ID: Mirco Wahab wrote: > Jay wrote: > Malchick, you cracked your veshchs to classes, which is > not that gloopy. So rabbit on them and add class methods > that sloosh on beeing called and do the proper veshchs > to the gulliwuts of their classes. Brillig! -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From steve at hastings.org Wed Apr 5 18:46:12 2006 From: steve at hastings.org (Steve R. Hastings) Date: Wed, 05 Apr 2006 15:46:12 -0700 Subject: efficiency of range() and xrange() in for loops References: Message-ID: On Wed, 05 Apr 2006 22:09:29 +0000, Giovanni Bajo wrote: > [...] you assume that the only use-case of range() is within a for-loop. No, I do not assume any such thing. I have not suggested that range() should be changed to always return an iterator. I wondered if the Python compiler could, as a special case, turn: for i in range(n) into compiled code equivalent to for i in itr where "itr" is a lightweight iterator that returns the same values as iter(range(n)). iter(range(n)) will still allocate a list of n integers, and then produce an iterator over that list, so I did not mean to suggest that for would simply call iter() when you use "for i in range". I apologize if my writing was unclear. -- Steve R. Hastings "Vita est" steve at hastings.org http://www.blarg.net/~steveha From enterr at gmail.com Sun Apr 2 17:24:25 2006 From: enterr at gmail.com (Atanas Banov) Date: 2 Apr 2006 14:24:25 -0700 Subject: print() in Python 3000 return value? In-Reply-To: <1143997643.857261.186430@i40g2000cwc.googlegroups.com> References: <1143997643.857261.186430@i40g2000cwc.googlegroups.com> Message-ID: <1144013065.865889.76690@e56g2000cwe.googlegroups.com> James Thiele wrote: > I noticed in PEP 3000 that print will become a function. The PEP > references a thread where Guido explains this decision. The thread does > not specify what the function will return. Has this been decided? reading the discussion, the arguments are about "print" as of now being a syntactic construc, an operator without apparent reason. all that is proposed is to tuck it as a function/procedure, i.e. use parenthesis and be able to redefine with a simple def print(...) if you think about it, the pythonic way is for print to return None. we use it for the side effect (stdout output) From luismgz at gmail.com Sun Apr 23 22:07:43 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 23 Apr 2006 19:07:43 -0700 Subject: Recommended IDE for creating GUI? In-Reply-To: <124idf0362d75dd@corp.supernews.com> References: <124idf0362d75dd@corp.supernews.com> Message-ID: <1145844463.477153.238570@g10g2000cwb.googlegroups.com> Check PythonCard: http://pythoncard.sourceforge.net From me at privacy.net Sat Apr 8 15:19:28 2006 From: me at privacy.net (Dan Sommers) Date: Sat, 08 Apr 2006 15:19:28 -0400 Subject: How to determine if a line of python code is a continuation of the line above it References: <1144520644.233293.81050@u72g2000cwu.googlegroups.com> Message-ID: On 8 Apr 2006 11:24:04 -0700, "Sandra-24" wrote: > I'm not sure how complex this is, I've been brainstorming a little, and > I've come up with: ["This" meaning how to determine if a line of python code is a continuation of the line above it.] > If the previous line ended with a comma or a \ (before an optional > comment) A line ending with a comma does *not* indicate a single statement spread out over two lines: a = 1, print a, a = [ ] None of those lines is a continuation of the line above it. > That's easy to cover with a regex > But that doesn't cover everything ... I think you'll end up having to parse the code in its entirety to do this correctly. Consider triple quoted strings and multiple uses of parenthesis, both of which can be nested arbitrarily, including inside each other, and arbitrarily nested delimeters are beyond the ability of regexen. Is this merely an academic exercise, or is there a larger purpose for wanting this information? Regards, Dan -- Dan Sommers "I wish people would die in alphabetical order." -- My wife, the genealogist From brandon.mcginty at gmail.com Mon Apr 3 22:42:09 2006 From: brandon.mcginty at gmail.com (brandon.mcginty at gmail.com) Date: Mon, 3 Apr 2006 19:42:09 -0700 Subject: Python and microsoft outlook-using com, can I interact with msoutlook? Message-ID: <00d901c65791$6053d8e0$6400a8c0@D1FWTS61> Hi All, I know that Microsoft Exchange has a com interface, CDO, but I can't seem to find one for Microsoft outlook. does anyone have code snippets for using msoutlook and python, or suggestions? I have looked on Google, and tried some code, but nothing has worked. I'm using outlook XP, and any info y'all have is greatly appreciated. Thanks, Brandon mcginty ---------- Feel free to contact me for technical support, or just to chat; I always have time to talk and help, and an open ear. Email:Brandon.mcginty at gmail.com Skype:brandon.mcginty Msn:brandon_mcginty at hotmail.com Aim:brandonmcginty (Not currently available.) Cell:4802025790 (Weekends and nights only, please.) "Kindness is a language that the deaf can hear and the blind can see." Mark Twain -- No virus found in this outgoing message. Checked by AVG Free Edition. Version: 7.1.385 / Virus Database: 268.3.4/299 - Release Date: 3/31/2006 From michaeltaft at gmail.com Wed Apr 19 20:42:01 2006 From: michaeltaft at gmail.com (mwt) Date: 19 Apr 2006 17:42:01 -0700 Subject: Method Call in Exception In-Reply-To: References: <1145490879.789439.18030@t31g2000cwb.googlegroups.com> Message-ID: <1145493721.743646.287500@i39g2000cwa.googlegroups.com> Felipe Almeida Lessa wrote: > Em Qua, 2006-04-19 ?s 16:54 -0700, mwt escreveu: > > This works when I try it, but I feel vaguely uneasy about putting > > method calls in exception blocks. > > What do you put in exception blocks?! Usually I just print an error message. > > > > So tell me, Brave Pythoneers, is this > > evil sorcery that I will end up regretting, or is it just plain good > > ol' Python magic? > > IMHO, the exception block in Python is used a lot in places where you > could use an if-then-else, like your example that could be written as > > if internet_available(): > [...] #doing some internet stuff > else: > alternate_method_that_doesnt_need_internet() > > So yes, I think there's no problem there. > Normally I don't like to use exception blocks to do condition-statement stuff. At least that is how my Java training has programmed me. But in this case, the condition is whether the internet connection is working or not, and I don't see any other way to do it. And furthermore, I don't know if the exceptions-as-logic is a no-no in Python. Hence the question. From steven.bethard at gmail.com Sat Apr 29 19:01:44 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 29 Apr 2006 17:01:44 -0600 Subject: best way to determine sequence ordering? In-Reply-To: <1146315935.017018.65580@u72g2000cwu.googlegroups.com> References: <70q4g.2006$No6.43783@news.tufts.edu> <1146259620.636600.119710@u72g2000cwu.googlegroups.com> <1146315935.017018.65580@u72g2000cwu.googlegroups.com> Message-ID: <2_idnXXyMIjKbc7ZnZ2dneKdnZydnZ2d@comcast.com> nikie wrote: > Steven Bethard wrote: > >> nikie wrote: >>> Steven Bethard wrote: >>> >>>> John Salerno wrote: >>>>> If I want to make a list of four items, e.g. L = ['C', 'A', 'D', 'B'], >>>>> and then figure out if a certain element precedes another element, what >>>>> would be the best way to do that? >>>>> >>>>> Looking at the built-in list functions, I thought I could do something >>>>> like: >>>>> >>>>> if L.index('A') < L.index('D'): >>>>> # do some stuff >>>> This is probably a pretty reasonable approach as long as you're not too >>>> worried about efficiency. It scans the list twice though, so if you >>>> start doing this with really big lists, it might be better to do >>>> something like: >>> On average, it'll only have go through half the list twice, as it can >>> break as soon as it finds the item it searches for. Don't think you can >>> get any more efficient than that. >> Sure you can: >> >> a_index = None >> d_index = None >> for i, item in enumerate(L): >> if item == 'A': >> a_index = i >> elif item == 'D': >> d_index = i >> if a_index is not None and d_index is not None: >> break >> >> if a_index < d_index: >> # do some stuff >> >> That goes through exactly the minimum number of elements. But it's >> probably slower than two .index() calls since .index() is coded in C. >> But timeit and see if you're interested. > > On my PC, calling index twice is 5 times faster. > > But let's just pretend for a moment Python code was compiled and > optimized as well as C code. Ok, lets get comparable functions by writing them both in Python: ----- temp.py ----- def index(L, item): for i, x in enumerate(L): if x == item: return i return -1 def a_d_index(L): a_index = None d_index = None for i, item in enumerate(L): if item == 'A': a_index = i elif item == 'D': d_index = i if a_index is not None and d_index is not None: break return a_index, d_index ------------------- $ python -m timeit -s "import temp; L = ['C', 'A', 'D', 'B']" "a = temp.index(L, 'A'); d = temp.index(L, 'D'); a < d" 100000 loops, best of 3: 5.73 usec per loop $ python -m timeit -s "import temp; L = ['C', 'A', 'D', 'B']" "a, d = temp.a_d_index(L); a < d" 100000 loops, best of 3: 3.75 usec per loop The a_d_index() function is definitely faster. I understand your point about comparison time, but in this case we're just comparing one element strings, so it's not so horrible. Sure, if you used strings that are more complicated to compare (or worse yet, you used your own custom objects with __cmp__ methods) you could provoke the kind of behavior you're looking for. But in this particular case, there really is some substantial overhead to Python's iterator protocol, and you can't just ignore that. Of course the moral of the story (as is the moral of all such threads) is that if you're really interested in speeding things up you need to start timing things. STeVe From gene.tani at gmail.com Mon Apr 24 12:44:14 2006 From: gene.tani at gmail.com (gene tani) Date: 24 Apr 2006 09:44:14 -0700 Subject: Looking for resources for making the jump from Java to Python easier and more productive In-Reply-To: <1145743795.214905.79560@i39g2000cwa.googlegroups.com> References: <1145691651.385835.298600@u72g2000cwu.googlegroups.com> <1145743795.214905.79560@i39g2000cwa.googlegroups.com> Message-ID: <1145897054.138600.158710@i40g2000cwc.googlegroups.com> Ant wrote: > Take a look at the newgroup archives over the last week or two - there > seem to have been a glut of people coming from Java to Python and > asking the same sort of questions. There were some links to a bunch of > Python 'gotcha' pages which will be useful. > Here's a few gotchas which i would like to drop into the python wiki, but I couldn't find an appropriate place. Maybe the Intermediate Conundrums page? Anyway, if OP take the time to flip through these, it'll speed the learning, I hope. http://www.ferg.org/projects/python_gotchas.html http://zephyrfalcon.org/labs/python_pitfalls.html http://zephyrfalcon.org/labs/beginners_mistakes.html http://www.python.org/doc/faq/ http://wiki.python.org/moin/Intermediate_Conundrums http://diveintopython.org/appendix/abstracts.html http://diveintopython.org/appendix/tips.html http://blog.ianbicking.org/my-python-4k.html http://www.onlamp.com/pub/a/python/2004/02/05/learn_python.html http://www.norvig.com/python-iaq.html http://www.faqts.com/knowledge_base/index.phtml/fid/245 http://amk.ca/python/writing/warts http://c2.com/cgi/wiki?PythonProblems From redefined.horizons at gmail.com Thu Apr 27 15:26:28 2006 From: redefined.horizons at gmail.com (redefined.horizons at gmail.com) Date: 27 Apr 2006 12:26:28 -0700 Subject: Protocols for Python? Message-ID: <1146165988.887502.243810@v46g2000cwv.googlegroups.com> I think I have reached an important moment in my growth as a Python Developer. I realize now why interfaces aren't really necessary in Python. :] Still, I'm designing an application that I want to be extendable by third-party developers. I'd like to have some sort of documentation about what behavior is required by the components that can be added to extend the application. I'd thought I might try documenting these behaviors as "protocols" instead of creating abstract classes with no method implementations. I stumbled across PyProtocols, but I don't think it is what I am looking for. I don't want to "implement" a form of interfaces in the python language, just document the required behavior for certain objects in my application for other developers. Is there a standard way to document protocols in Python? Of should I come up with something tailored to my needs. Thanks, Scott Huey From claird at lairds.us Thu Apr 6 16:08:02 2006 From: claird at lairds.us (Cameron Laird) Date: Thu, 06 Apr 2006 20:08:02 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Apr 4) References: <1144171316.283001.151290@i39g2000cwa.googlegroups.com> Message-ID: In article <1144171316.283001.151290 at i39g2000cwa.googlegroups.com>, gene tani wrote: > >Peter Otten wrote: >> The old Python "To-Do List" now lives principally in a >> SourceForge reincarnation. >> http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse >> http://python.sourceforge.net/peps/pep-0042.html >> > >Thanks, very nice summary. > >One thing, the peps moved: >http://www.python.org/dev/peps/pep-0042/ > Thanks for the correction--and thanks to those who relocated this part of Pythonia away from well-meaning-but-oh-so-fallible SFistan. From spamspam at spam.eggs Tue Apr 11 16:12:38 2006 From: spamspam at spam.eggs (Ben C) Date: 11 Apr 2006 20:12:38 GMT Subject: RegExp question References: <1144781090.622493.252460@t31g2000cwb.googlegroups.com> <1144783001.905105.305220@z34g2000cwc.googlegroups.com> Message-ID: On 2006-04-11, Michael McGarry wrote: > Tim, > > for some reason that does not seem to do the trick. > > I am testing it with grep. (i.e., grep -e '(and|or|xor)\s*#' myfile) Try with grep -P, which means use perl-compatible regexes as opposed to POSIX ones. I only know for sure that -P exists for GNU grep. I assumed it was a Python question! Unless you're testing your Python regex with grep, not realizing they're different. Perl and Python regexes are (mostly?) the same. I usually grep -P because I know Python regexes better than any other ones. From http Fri Apr 14 14:35:31 2006 From: http (Paul Rubin) Date: 14 Apr 2006 11:35:31 -0700 Subject: Writing backwards compatible code References: Message-ID: <7xwtdsknt8.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > What techniques do others use? I'd just write the generator with a yield statement. The generator expression does the same thing more concisely, I think. From kent at kentsjohnson.com Tue Apr 18 12:19:21 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Tue, 18 Apr 2006 12:19:21 -0400 Subject: A 'Box' Function In-Reply-To: <1145321497.261653.62130@g10g2000cwb.googlegroups.com> References: <1145321497.261653.62130@g10g2000cwb.googlegroups.com> Message-ID: <44451175$1_2@newspeer2.tds.net> mikelaskey at gmail.com wrote: > Hey guys. > > I should warn you, first off, that I'm relatively new to Python. > Basically, what I'm trying to do is create a word-wrapping function > with the added complication that it add a character at the beginning > and end of each line, so that it encloses the text in a sort of 'box': > > ---------------- > | Like this | > ---------------- > > The word-wrapping function I'm working with is similar to the one given > here: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/148061 > > Does anyone have any ideas on how it could be modified? Am I > approaching it the right way? Thanks a bunch! Rather than rewriting wrap(), I would suggest wrapping it with a new function, wrap_box(), that adds the header, line endings and trailer to the lines returned from wrap(). Kent From paolopantaleo at gmail.com Mon Apr 24 16:07:26 2006 From: paolopantaleo at gmail.com (Paolo Pantaleo) Date: Mon, 24 Apr 2006 22:07:26 +0200 Subject: test assignmet problem In-Reply-To: <6oM2g.27487$ZB1.20568@tornado.texas.rr.com> References: <6oM2g.27487$ZB1.20568@tornado.texas.rr.com> Message-ID: <83e8215e0604241307l2d4c1f03i4dd76a65f89656f6@mail.gmail.com> 2006/4/23, Paul McGuire : > > "Paolo Pantaleo" wrote in message > news:mailman.4903.1145802299.27775.python-list at python.org... > So I tried this > > if(not (attr=global_re.match(line)) ): > break > > it says invalid syntax [on the =] > ... because this syntax is not valid ... > > so it is not possible to do test and assignment in C style? > ... no it's not, see > http://www.python.org/doc/faq/general/#why-can-t-i-use-an-assignment-in-an-expression > > how can I write this otherwise? > ... is this so bad?... > > attr=global_re.match(line) > if not attr: > break > > ... or, since you don't seem to be doing much with attr, you could just do > > if not global_re.match(line): > break > > ... and get rid of all those distracting ()'s! > > > -- > http://mail.python.org/mailman/listinfo/python-list > Thnx for the help, actually the problme is not solved i have [well I want to do...] something like: if a=b(): do stuff with a else if a=c(): do stuff with b else: do other stuff well, two solutions are a1=b() a2=c() if a1: do stuff with a1 else if a2: do stuff with a2 else: do other stuff the other is if b(): a=b() do stuff with a else if c(): a=c() do stuff with b else: do other stuff Even if none is exactly the same about: * the number of times the b() and c() functions are executed * the final value of a I think the right one is: a=b() if a: do stuff with a else: a=c() if a=c(): do stuff with b else: do other stuff PAolo -- if you have a minute to spend please visit my photogrphy site: http://mypic.co.nr From dragan.bajcic at gmail.com Sun Apr 16 08:08:16 2006 From: dragan.bajcic at gmail.com (kodi) Date: 16 Apr 2006 05:08:16 -0700 Subject: keyboard command to break out of infinite loop? In-Reply-To: <1145174364.436843.26660@e56g2000cwe.googlegroups.com> References: <1145174364.436843.26660@e56g2000cwe.googlegroups.com> Message-ID: <1145189296.491399.83350@i40g2000cwc.googlegroups.com> BartlebyScrivener wrote: > Running Python on Win XP. > > When running commands with the interpreter, if you get stuck in a while > loop, is there a keyboard command to break out of it? > > Or is the only way out a triple-finger salute and End Task? > > rd ctrl+c or ctrl+c+enter From grante at visi.com Sat Apr 8 23:18:48 2006 From: grante at visi.com (Grant Edwards) Date: Sun, 09 Apr 2006 03:18:48 -0000 Subject: how relevant is C today? References: <44381ee4$0$4209$c3e8da3@news.astraweb.com> <44382711.10403@v.loewis.de> Message-ID: <123gv8oh4lamb7c@corp.supernews.com> On 2006-04-08, Martin v. L?wis wrote: > As for *learning* the languages: never learn a language > without a specific inducement. That's silly. Learning (weather a computer language, a natural language, or anything else) is never a bad thing. The more languages you know, the more you understand about languages in general. Learning languages is like any other skill: the more you do it, the better you get at it. > If you know you are going to write a Python extension, an > Apache module, or a Linux kernel module in the near future, > start learning C today. If you don't know what you want to use > it for, learning it might be a waste of time, as you won't > know what to look for if you don't have a specific project in > mind. Geeze, when I think of all the things I've "wasted my time" learning. -- Grant Edwards grante Yow! Kids, don't gross me at off... "Adventures with visi.com MENTAL HYGIENE" can be carried too FAR! From finite.automaton at gmail.com Mon Apr 10 13:33:30 2006 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 10 Apr 2006 10:33:30 -0700 Subject: how to make a generator use the last yielded value when it regains control In-Reply-To: References: <4435cde3$0$11677$c3e8da3@news.astraweb.com> <1144390994.551650.31490@v46g2000cwv.googlegroups.com> <443a40e0$1_1@news.bluewin.ch> <1144688740.056988.183640@u72g2000cwu.googlegroups.com> Message-ID: <1144690410.506715.256660@i40g2000cwc.googlegroups.com> In general, you're right - if speed is a concern, loops should be used instead of recursion in Python when possible. In this case, the recursive overhead is insignificant compared to the expense of iterating over the sequence at every iteration. By the time there are 70 stack frames of recursion (i.e. not much), the sequence is more than 170 million elements long. From fredrik at pythonware.com Sat Apr 1 03:05:37 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 1 Apr 2006 10:05:37 +0200 Subject: a question on re References: <1143873454.705410.125300@u72g2000cwu.googlegroups.com> Message-ID: eight02645999 at yahoo.com wrote > i tried to search 2 patterns > > pat1 = re.compile("blah") > pat2 = re.compile("blah2") > > > if i do > if re.findall(pat1,something) and re.findall(pat2,something): > do something > > if does not work > > but when i do a nest if, > > if re.findall(pat1,something) : > if re.findall(pat2,something): > do something > > it works.. > > please advise on why the first code doesnt work. is this the actual code you were using ? and the actual patterns ? what's in "something" ? From peter at engcorp.com Mon Apr 3 21:39:51 2006 From: peter at engcorp.com (Peter Hansen) Date: Mon, 03 Apr 2006 21:39:51 -0400 Subject: [ANN] markup.py - 1.2 - an HTML/XML generator In-Reply-To: <1144112722.28978.11.camel@kenshin.CASA> References: <5f56302b0604031509r51af902dh2e908561bbf78d44@mail.gmail.com> <1144103244.20245.2.camel@kenshin.CASA> <1144112722.28978.11.camel@kenshin.CASA> Message-ID: Felipe Almeida Lessa wrote: > $ pwd > /usr/lib/python2.4/site-packages > $ grep -re klass . | wc -l > 274 > $ grep -re class_ . | wc -l > 897 How many of those "class_" instances are really just substrings of "__class__" and "class_name" and such? On my machine, I see a handful in the standard library, and _none_ in site-packages (which has only 1709 .py files, mind you). > For me that's enough. "class_" is used at least three times more than > "klass". Besides, as Scott pointed out, "class_" is prefered by the > guidelines too. Actually what he posted explicitly states that "cls" is preferred. Following that it says that one should considering appending _ if the name conflicts with a keyword (and one can assume it means "for all keywords other than class"). >>`cls`, at least, is more commonly used within >>Python itself (e.g., classmethods). > > Yes. cls wouldn't be a good choice. But class_ is. Or maybe even > css_class. But klass isn't. As has been pointed out, klass has a fairly established tradition of use. (I happen to agree with the PEP and use "cls" exclusively for such things, and do agree that "klass" is crude.) -Peter From cesugden at gmail.com Wed Apr 26 10:42:14 2006 From: cesugden at gmail.com (chris sugden) Date: Wed, 26 Apr 2006 15:42:14 +0100 Subject: wxPython and twisted problem Message-ID: <539a7fb0604260742l6fabbca5g2f8fe9310d08cce0@mail.gmail.com> Hi, I'm a university student creating a python Chat server and client using twisted. The server works great. However I'm trying to create the client with a gui using wxpython and twisted. The code for the client is attached bellow. I'm working with a partner and he already tried posting our problem on comp.lang.python but we didn't receive a successful reply so I thought I would try the mailing list. Here's the problem: I can get my client to connect to my server, but can't get it to disconnect or send messages to the server. I am getting the following error when I click on the 'Disconnect' button - AttributeError: 'NoneType' object has no attribute 'loseConnection' I have attached the code for the client below this. We are both fairly new to Python so would appreciate any help anyone can offer. Thanks, Chris & Peter client.py ---------- from wxPython.wx import * import wx from twisted.internet import wxreactor wxreactor.install() from twisted.internet import reactor from twisted.internet.protocol import Protocol, ClientCreator class imApp(wxApp, Protocol): def buildMe(self): frame = wx.Frame(None, title="IM Client", size=(800, 550)) bkg = wx.Panel(frame) global ipAdd global portNo global messages global newMsg ipAddLab = wx.StaticText(bkg, -1, 'IP Address: ') ipAdd = wx.TextCtrl(bkg) ipAdd.SetToolTipString('Please enter the server IP address here.') spacer1 = wx.StaticText(bkg, -1, ' ') portNoLab = wx.StaticText(bkg, -1, 'Port No: ') portNo = wx.TextCtrl(bkg) portNo.SetToolTipString('Please enter the port number the server is using here.') spacer2 = wx.StaticText(bkg, -1, ' ') connectButton = wx.Button(bkg, label='Connect') connectButton.SetToolTipString('Click this button to connect to the server.') connectButton.Bind(wx.EVT_BUTTON, self.connectMe) disconnectButton = wx.Button(bkg, label='Disconnect') disconnectButton.SetToolTipString('Click this button to disconnect from the server.') disconnectButton.Bind(wx.EVT_BUTTON, self.disconnectMe) messages = wx.TextCtrl(bkg, style=(wx.TE_MULTILINE | wx.HSCROLL)) newMsg = wx.TextCtrl(bkg) sendButton = wx.Button(bkg, label='Send') sendButton.SetToolTipString('Click this button to send a message to the server.') sendButton.Bind(wx.EVT_BUTTON, self.sendMe) hbox1 = wx.BoxSizer() hbox1.Add(ipAddLab, proportion=0, flag=wx.EXPAND) hbox1.Add(ipAdd, proportion=0, flag=wx.EXPAND) hbox1.Add(spacer1, proportion=0, flag=wx.EXPAND) hbox1.Add(portNoLab, proportion=0, flag=wx.EXPAND) hbox1.Add(portNo, proportion=0, flag=wx.EXPAND) hbox1.Add(spacer2, proportion=0, flag=wx.EXPAND) hbox1.Add(connectButton, proportion=0, flag=wx.LEFT, border=5) hbox1.Add(disconnectButton, proportion=0, flag=wx.LEFT, border=5) hbox2 = wx.BoxSizer() hbox2.Add(newMsg, proportion=1, flag=wx.EXPAND | wx.LEFT | wx.LEFT | wx.LEFT, border=5) hbox2.Add(sendButton, proportion=0, flag=wx.LEFT, border=5) vbox = wx.BoxSizer(wx.VERTICAL) vbox.Add(hbox1, proportion=0, flag=wx.EXPAND | wx.ALL, border=5) vbox.Add(messages, proportion=1, flag=wx.EXPAND | wx.LEFT | wx.LEFT | wx.LEFT, border=5) vbox.Add(hbox2, proportion=1, flag=wx.EXPAND | wx.ALL, border=5) bkg.SetSizer(vbox) ipAdd.WriteText('localhost') portNo.WriteText('1234') frame.Show(true) return true def sendMe(self, e): msg = newMsg.GetValue() + '\n' messages.WriteText(msg) newMsg.SetValue('') def disconnectMe(self, e): messages.WriteText('Disconnecting from server...\n') self.transport.loseConnection() def connectMe(self, e): messages.WriteText('Connecting to server...\n') c = ClientCreator(reactor, imApp) ip = str(ipAdd.GetValue()) port = int(portNo.GetValue()) c.connectTCP(ip, port) def mainProg(): app = imApp(0) app.buildMe() reactor.registerWxApp(app) reactor.run() if __name__ == '__main__': mainProg() -------------- next part -------------- An HTML attachment was scrubbed... URL: From my_email_is_posted_on_my_website at munged.invalid Thu Apr 27 17:38:51 2006 From: my_email_is_posted_on_my_website at munged.invalid (Roedy Green) Date: Thu, 27 Apr 2006 21:38:51 GMT Subject: Xah's Edu Corner: What Languages to Hate References: <1145992903.834316.198370@u72g2000cwu.googlegroups.com> <1146172923.830732.187130@i40g2000cwc.googlegroups.com> Message-ID: On 27 Apr 2006 14:22:03 -0700, "Xah Lee" wrote, quoted or indirectly quoted someone who said : >What Languages to Hate Come, if you are as experienced as you claim you know that comp.lang.java.advocacy is the home of language wars and commentary on them, not comp.lang.java.programmer. It is one thing for a topic to drift but quite another to deliberately post your initial message in the wrong place. -- Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching. From robert.kern at gmail.com Tue Apr 25 18:23:07 2006 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 25 Apr 2006 17:23:07 -0500 Subject: MinGW and Python In-Reply-To: References: <1145861223.509630.247350@y43g2000cwc.googlegroups.com> <444C79D7.4060007@v.loewis.de> <444DC62B.7000702@v.loewis.de> <1145985979.369429.114040@i39g2000cwa.googlegroups.com> <444e7d85$0$12131$9b622d9e@news.freenet.de> <1145999256.027851.132780@y43g2000cwc.googlegroups.com> Message-ID: Edward Elliott wrote: > Ross Ridge wrote: > >>MSVCRT.DLL ... It's not >>exactly "endorsed", Microsoft would rather you use it's current >>compiler and runtime, but it is the standard "official" Windows system >>C library. > > Does it comply with the ANSI C89 standard? I'm still not seeing why mingw > can't just link python to it. It can. -- Robert Kern robert.kern at gmail.com "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From shearichard at gmail.com Tue Apr 25 21:39:42 2006 From: shearichard at gmail.com (shearichard at gmail.com) Date: 25 Apr 2006 18:39:42 -0700 Subject: MySQLdb "begin()" - References: <1145973021.073264.262180@i39g2000cwa.googlegroups.com> Message-ID: <1146015582.079160.114380@y43g2000cwc.googlegroups.com> Thanks for your advice. In fact subsquent to posting I started using ... conn.autocommit = False ... as a synonm for ... conn.begin() ... and as you say that does the job. (Sorry i should have said it's not practicable to turn off autocommit always [or rather it may be but I'm not about to shake the boat to that extent just now ;-] As to what I was reading yes it's here ... http://www.devshed.com/index2.php?option=content&task=view&id=210&pop=1&page=0&hide_js=1 ... or more succinctly ... http://tinyurl.com/s6yd2 ... page down to ... "connection.begin() - start a transaction" ... that article refers to version 0.92 of MySQLdb so clearly it was either wrong then or for some weird reason the method has been dropped. thanks again. richard. From greg.kujawa at gmail.com Sun Apr 30 13:48:50 2006 From: greg.kujawa at gmail.com (gregarican) Date: 30 Apr 2006 10:48:50 -0700 Subject: basic python programing References: <1146376141.767029.17850@j73g2000cwa.googlegroups.com> <1146383327.664894.279250@v46g2000cwv.googlegroups.com> Message-ID: <1146419329.959290.69870@j73g2000cwa.googlegroups.com> Ravi Teja wrote: > How To Ask Questions The Smart Way > http://www.catb.org/~esr/faqs/smart-questions.html Actual the parent post on the thread wasn't asking a question. They were making a somewhat puzzling dangling statement. "here we discuss the most basic concepts about python" Where is _here__? The comp.lang.python newsgroup? In the poster's head? These are but a sampling of my own stoopid questions. From micklee74 at hotmail.com Thu Apr 20 22:29:57 2006 From: micklee74 at hotmail.com (micklee74 at hotmail.com) Date: 20 Apr 2006 19:29:57 -0700 Subject: a subprocess qns Message-ID: <1145586597.202944.125920@j33g2000cwa.googlegroups.com> hi i wanted to start execute a command and put it in the background. i am using Unix. Usually i start this command using something like this : "/path/somecmd &" with the "&" to put it to background. i looked at the subprocess module docs and came across this statement Replacing os.spawn* ------------------- P_NOWAIT example: pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg") ==> pid = Popen(["/bin/mycmd", "myarg"]).pid Can i ask if P_NOWAIT means the same as "&" ?? so if it is, then this statement pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg") will put mycmd into background and return to the caller...? thanks From sandravandale at yahoo.com Sat Apr 8 14:24:04 2006 From: sandravandale at yahoo.com (Sandra-24) Date: 8 Apr 2006 11:24:04 -0700 Subject: How to determine if a line of python code is a continuation of the line above it Message-ID: <1144520644.233293.81050@u72g2000cwu.googlegroups.com> I'm not sure how complex this is, I've been brainstorming a little, and I've come up with: If the previous line ended with a comma or a \ (before an optional comment) That's easy to cover with a regex But that doesn't cover everything, because this is legal: l = [ 1, 2, 3 ] and with dictionaries and tuples as well. Not sure how I would check for that programmatically yet. Is there any others I'm missing? Thanks, -Sandra From wuwei23 at gmail.com Tue Apr 25 21:14:09 2006 From: wuwei23 at gmail.com (alex23) Date: 25 Apr 2006 18:14:09 -0700 Subject: python application ideas. References: Message-ID: <1146014049.232648.243810@e56g2000cwe.googlegroups.com> Anthony Greene wrote: > Hello, I know this isn't really a python centric question, but I'm seeking > help from my fellow python programmers. I've been learning python for the > past year and a half, and I still haven't written anything substantial nor > have I found an existing project which blows my hair back. The Ubuntu project offers bounties for adding needed functionality to their distro, a lot of which is provided through python: http://www.ubuntu.com/community/bounties https://wiki.ubuntu.com/IdeaPool Nothing like Ca$h Prize$ to get that hair ruffled :) - alex23 From wahab at chemie.uni-halle.de Sun Apr 9 14:25:58 2006 From: wahab at chemie.uni-halle.de (Mirco Wahab) Date: Sun, 09 Apr 2006 20:25:58 +0200 Subject: how relevant is C today? In-Reply-To: <44393fbe$0$19226$c3e8da3@news.astraweb.com> References: <44381ee4$0$4209$c3e8da3@news.astraweb.com> <44382711.10403@v.loewis.de> <44393fbe$0$19226$c3e8da3@news.astraweb.com> Message-ID: Hi John > It's just that I obessively like to learn new things, > and I keep moving on to new subjects once I've 'learned' > something well enough. Ha! So learn 'Perl' then - you'll never ever get over this point ... ;-)) And if you, against all odds, think you master it now - zongggg, a new Perl Version with completely new syntax shows up ... > I know Python well enough, but for no real reason, so I think I'm > going to stick with it and keep using it, because it's fun. At which level in the 'python challenge' did you get stuck - and why? Regards M. From randomtalk at gmail.com Thu Apr 27 23:49:44 2006 From: randomtalk at gmail.com (randomtalk at gmail.com) Date: 27 Apr 2006 20:49:44 -0700 Subject: append function problem? Message-ID: <1146196184.408569.197960@i40g2000cwc.googlegroups.com> hello, recently i tried to use list.append() function in seemingly logical ways, however, i cannot get it to work, here is the test code: >>> seed = [2, 3, 4, 5] >>> next = 7 >>> seed1 = seed.append(next) >>> seed1 >>> print(str(seed1)) None >>> def test(lst): ... print(str(lst)) ... >>> test(seed.append(next)) None I'm using Activestate python (latest) on win xp sp2.. I'm not sure why seed1 and the function doesn't recognize the list.. If anyone can point out where i'm going wrong would be much appreciated! Thanks in advance! From sjmaster at gmail.com Tue Apr 11 14:58:29 2006 From: sjmaster at gmail.com (Steve M) Date: 11 Apr 2006 11:58:29 -0700 Subject: Memory limit to dict? In-Reply-To: <4a289fFr0sufU1@uni-berlin.de> References: <4a289fFr0sufU1@uni-berlin.de> Message-ID: <1144781909.327422.7280@j33g2000cwa.googlegroups.com> An alternative is to use ZODB. For example, you could use the BTree class for the outermost layers of the nested dict, and a regular dict for the innermost layer. If broken up properly, you can store apparently unlimited amount of data with reasonable performance. Just remember not to iterate over the entire collection of objects without aborting the transaction regularly. From hitesh287 at gmail.com Mon Apr 24 18:27:56 2006 From: hitesh287 at gmail.com (Hitesh Joshi) Date: 24 Apr 2006 15:27:56 -0700 Subject: What am I doing wrong here References: <1145916134.764210.235250@t31g2000cwb.googlegroups.com> Message-ID: <1145917676.746433.167870@u72g2000cwu.googlegroups.com> ok here is the deal... I figured out how to pass the variable but now messages are not popping up on the windows screen if I use this method: import os Computerlist = ['PC1', 'PC2', 'PC3', 'PC4', 'PC5'] for ComputerName in Computerlist: print ComputerName s = "net send %s" % ComputerName os.system('s "Message"') From ishtar2020 at hotmail.com Tue Apr 4 15:01:12 2006 From: ishtar2020 at hotmail.com (ishtar2020) Date: 4 Apr 2006 12:01:12 -0700 Subject: Strange problem when running python code In-Reply-To: <9bzYf.1903$No6.42196@news.tufts.edu> References: <1144175959.412184.187110@g10g2000cwb.googlegroups.com> <9bzYf.1903$No6.42196@news.tufts.edu> Message-ID: <1144177272.939450.134720@e56g2000cwe.googlegroups.com> I must add, when the python interpreter displays the traceback, with the line that is producing the error, it doesn't look like the one I got in the code. This is the line where the interpreter finds the error if text.list[i].toString() in limits:list)): <- Here is where the error is found, but this line is not on my file SyntaxError: invalid syntax And this is the line I got on the file, looks like the interpreter is mixing the second sentence with the end of the first one: for i in range(self.initialPositionl+1,len(text.list)): if text.list[i].toString() in limits: self.finalPosition=i break It's quite puzzling. And if I change some lousy thing, like inserting a newline between the sentences, the interpreter will find another error somewhere else, even when that part of the code was working flawlessly in previous runs From pythor at gmail.com Sun Apr 9 00:17:32 2006 From: pythor at gmail.com (Pythor) Date: 8 Apr 2006 21:17:32 -0700 Subject: More pythonic circle? In-Reply-To: <1144553845.240153.285040@e56g2000cwe.googlegroups.com> References: <1144544696.577777.239130@e56g2000cwe.googlegroups.com> <1144553845.240153.285040@e56g2000cwe.googlegroups.com> Message-ID: <1144556252.610261.218840@u72g2000cwu.googlegroups.com> John Machin wrote: > OTTOMH, in a rush to go out: never mind Pythonic, following apply to > any language: > (1) accuracy: (a) sue me if I'm wrong, but I think you need range(dx+1) > so that the dx pixel is filled in Hmm. I think you're right. Thanks. > (b) a few more digits after 0.71 > might be useful Sine of 45 degrees is actually .707... I rounded up, since I was using <=. Figured that would make it clear. > (2) efficiency: seems that range(dy, dx+1) would save some wear & tear > on the circuitry :-) It took me a few minutes to figure out waht you meant here. This will certainly help reduce the repeated coordinates. Thanks, again. > (3) legibility: there's no prize for the script with the absolutely > minimum number of space characters :-) True. I assume your saying I should make cx,cy,dx, and dy better names. I probably will. Up to now I was just playing around with this, and not really expecting anyone else to read it. > I think I've got an article on better Bresenham somewhere in the > archives; will dig it out later. I'd definitely appreciate it. In fact, I'm trying to find a decent sphere version, and getting nowhere with google. I tried to figure it out on my own, and ended up with 48 coordinates for each valid test. I'm not sure if that's right. Lee From steven.bethard at gmail.com Mon Apr 10 22:43:19 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 10 Apr 2006 20:43:19 -0600 Subject: updated pre-PEP: The create statement In-Reply-To: <443a9c60$1_1@news.bluewin.ch> References: <443a9c60$1_1@news.bluewin.ch> Message-ID: Azolex wrote: > Steven Bethard wrote: >> and named, nested hierarchies like XML documents could be created >> like:: >> >> create ETobject html: >> "This statement would generate an ElementTree object" >> >> create ETobject head: >> "generate the head" >> ... >> >> create ETobject body: >> "generate the body" >> ... > > I think this is is a most important eventual use-case, and would like to > see it better worked out - or else declared outside the scope of the > proposed statement. As far as I can see, this does not cut it, since xml > and html allow /sequencial repetition/ of tags and the results of the > statement suites are passed as unordered namespaces/dicts. Good point. The code above would only work if you didn't care about the order of elements. I'm half inclined to pull the example, but the original was due to Michele Simionato, and I haven't quite convinced myself yet that you couldn't hack it to have ETObject append to an internal list somehow to keep order. Michele? Did you have a plan for how this would work? STeVe From rpdooling at gmail.com Fri Apr 21 08:31:40 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 21 Apr 2006 05:31:40 -0700 Subject: proposed Python logo In-Reply-To: References: <1145615455.477800.74730@i39g2000cwa.googlegroups.com> Message-ID: <1145622700.893069.70780@g10g2000cwb.googlegroups.com> No matter what you do, "Python" is going to sum up the image of a powerful snake. I suppose you could change the name to "Monty," if you wanted more humor and more of a reference to Monty Python, or maybe "Bring Out Your Dead." Personally I like the snake associations and the notion that you're joining a cult where everybody speaks in Parseltongue. http://en.wikipedia.org/wiki/Priori_Incantatem#Speaking_parseltongue rd From max at alcyone.com Tue Apr 18 21:16:04 2006 From: max at alcyone.com (Erik Max Francis) Date: Tue, 18 Apr 2006 18:16:04 -0700 Subject: test for None In-Reply-To: <1145409010.709268.14770@j33g2000cwa.googlegroups.com> References: <1145409010.709268.14770@j33g2000cwa.googlegroups.com> Message-ID: BartlebyScrivener wrote: > How do you test for a function that returns nothing, and why doesn't > this work? Shouldn't X have to be either None or not? > >>>>x = None >>>> for x in []: > ... if x is None: > ... print "X is None" > ... else: > ... print "X is not None" > ... No, because you're iterating over an empty list, which does nothing: >>> for x in []: print 'hi' ... >>> -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis The doors of Heaven and Hell are adjacent and identical. -- Nikos Kazantzakis From rob at digital-crocus.com Fri Apr 7 12:27:24 2006 From: rob at digital-crocus.com (Robin Haswell) Date: Fri, 07 Apr 2006 17:27:24 +0100 Subject: UnicodeDecodeError help please? Message-ID: Okay I'm getting really frustrated with Python's Unicode handling, I'm trying everything I can think of an I can't escape Unicode(En|De)codeError no matter what I try. Could someone explain to me what I'm doing wrong here, so I can hope to throw light on the myriad of similar problems I'm having? Thanks :-) Python 2.4.1 (#2, May 6 2005, 11:22:24) [GCC 3.3.6 (Debian 1:3.3.6-2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.getdefaultencoding() 'utf-8' >>> import htmlentitydefs >>> char = htmlentitydefs.entitydefs["copy"] # this is an HTML © - a copyright symbol >>> print char ? >>> str = u"Apple" >>> print str Apple >>> str + char Traceback (most recent call last): File "", line 1, in ? UnicodeDecodeError: 'utf8' codec can't decode byte 0xa9 in position 0: unexpected code byte >>> a = str+char Traceback (most recent call last): File "", line 1, in ? UnicodeDecodeError: 'utf8' codec can't decode byte 0xa9 in position 0: unexpected code byte >>> Basically my app is a search engine - I'm grabbing content from pages using HTMLParser and storing it in a database but I'm running in to these problems all over the shop (from decoding the entities to calling str.lower()) - I don't know what encoding my pages are coming in as, I'm just happy enough to accept that they're either UTF-8 or latin-1 with entities. Any help would be great, I just hope that I have a brainwave over the weekend because I've lost two days to Unicode errors now. It's even worse that I've written the same app in PHP before with none of these problems - and PHP4 doesn't even support Unicode. Cheers -Rob From nobody at 127.0.0.1 Wed Apr 19 14:07:28 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 19 Apr 2006 18:07:28 GMT Subject: multiline comments In-Reply-To: <26040951.rta0eh9q1Q@jupiter.g2ctech> References: <1145425311.771598.140970@i40g2000cwc.googlegroups.com> <26040951.rta0eh9q1Q@jupiter.g2ctech> Message-ID: Jorge Godoy wrote: > Edward Elliott wrote: > Try using Subversion. You can work and make diffs disconnected from the > network. rcs isn't the issue. I'm already assuming a local store, a networked one just makes my argument even easier. >>I'm not saying nested comments solve every problem, just that > > I don't miss them. :-) Fair enough. > Well, I believe they are since it looks like a habit of yours to use > multiline comments. It is common for people coming from other programming > languages that support them. Yes I cut my teeth on C, C++, and Java. That was a long time ago. I don't miss them because they're more C-like (the C-family actually has an awful implementation), I miss them because they're useful. Actually I never used multiline much until I did a project in ML and saw how they should work. However the last 4 years I've used Perl, Python, and PHP almost exclusively. I'm used to single-line comments, I just find their expressive power lacking. No shame in borrowing the best features of other languages. From grflanagan at yahoo.co.uk Sun Apr 30 17:44:54 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 30 Apr 2006 14:44:54 -0700 Subject: From the Tutorial Wiki: suggested restructure Message-ID: <1146433494.029518.316580@j33g2000cwa.googlegroups.com> For anyone interested, here's a blog entry I've added over at the Tutorial Wiki: ---------------------------------------- As mentioned by effbot in the previous post I've put together a suggested alternative factoring of the Tutorial here(http://pytut.infogami.com/gerard_refactor). At the minute it just amounts to a carving-up of the existing material into two sections: beginners and intermediate. It's a bit stilted in places, but not excessively. There's also a suggested advanced section - I'm not an advanced user myself so I don't really know what would be appropriate here. Each section in the beginners tutorial has links to relevant FAQS at pyfaq.infogami.com. I also thought the FAQS could be preceded by suitable examples, and maybe there could be a final chapter of exercises. I've been sitting for half an hour trying to articulate why I think this is a good idea, but the well has dried up...and I seem to have gone a bit snow-blind looking at the blank screen! I just remember that when I was learning Python, although the Tutorial was incredibly useful and a key source of info, it seemed that I always had to hunt excessively when I had questions like 'how does **kwargs work?', 'what does extend do again?' etc. - I always thought that things weren't ordered in the best way, and the chapter titles weren't that helpful. so this is how I think it should be done! I hope it's a positive contribution - maybe it will provoke discussion if nothing else. Unfortunately, I won't have easy access to a computer for the next few months, so I can't contribute any more at this point. ------------------------------------------------------------------ Comments welcome. Or contributions - particularly to the advanced section. All the best. Gerard From cgseymour at gmail.com Tue Apr 11 12:10:38 2006 From: cgseymour at gmail.com (Chris Seymour) Date: 11 Apr 2006 09:10:38 -0700 Subject: Application Generators In-Reply-To: <1144770265.241893.115810@j33g2000cwa.googlegroups.com> References: <1143917722.208117.223790@e56g2000cwe.googlegroups.com> <1144770265.241893.115810@j33g2000cwa.googlegroups.com> Message-ID: <1144771837.976918.177800@i39g2000cwa.googlegroups.com> Have you taken a look at CodeChargeStdio (http://www.yessoftware.com)? This will handle what you are looking to do and then some. Might be a bit pricey, but it is worth a look. Cheers. Chris From arkanes at gmail.com Wed Apr 26 12:38:39 2006 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 26 Apr 2006 11:38:39 -0500 Subject: wxpython warnings In-Reply-To: <1146054739.094951.278490@e56g2000cwe.googlegroups.com> References: <1146054739.094951.278490@e56g2000cwe.googlegroups.com> Message-ID: <4866bea60604260938w2f926964k15b086a6682ffa5a@mail.gmail.com> On 26 Apr 2006 05:32:19 -0700, Iain King wrote: > I have a wxpython program that displays TIF images. Sometimes it will > encounter a tag the tiff loader cant handle. Rather than silently > ignoring it, it pops up a window: > > Python Warning > unknown field with tag blah blah > > I don't want it to do this, but I can't work out how to turn it off. > Anyone know? > This is actually an error generated by libtiff, which wxWidgets traps & raises. It is shown via the wxLog mechanism so you can supress it by wrapping your call in calls to wx.Log.EnableLogging. Note that this will suppress *all* warning and error messages that libtiff (or wx) might raise. > Iain > > -- > http://mail.python.org/mailman/listinfo/python-list > From johnjsal at NOSPAMgmail.com Tue Apr 11 16:57:20 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 11 Apr 2006 20:57:20 GMT Subject: list.clear() missing?!? In-Reply-To: References: <1144767680.583085.310160@v46g2000cwv.googlegroups.com> Message-ID: Felipe Almeida Lessa wrote: > You see? lst[:] removes all elements from the list that lst refers to, > while lst = [] just creates a new list and discard the only one. The > difference is, for example: Thanks, your explanation was great! From ptmcg at austin.rr._bogus_.com Wed Apr 19 09:47:50 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 19 Apr 2006 13:47:50 GMT Subject: local greediness ??? References: <1145423359.206549.52510@v46g2000cwv.googlegroups.com> Message-ID: wrote in message news:1145423359.206549.52510 at v46g2000cwv.googlegroups.com... > hi, all. I need to process a file with the following format: > $ cat sample > [(some text)2.3(more text)4.5(more text here)] > [(aa bb ccc)-1.2(kdk)12.0(xxxyyy)] > [(xxx)11.0(bbb\))8.9(end here)] > ....... > > my goal here is for each line, extract every '(.*)' (including the > round > brackets, put them in a list, and extract every float on the same line > and put them in a list.. Are you wedded to re's? Here's a pyparsing approach for your perusal. It uses the new QuotedString class, treating your ()-enclosed elements as custom quoted strings (including backslash escape support). Some other things the parser does for you during parsing: - converts the numeric strings to floats - processes the \) escaped paren, returning just the ) Why not? While parsing, the parser "knows" it has just parsed a floating point number (or an escaped character), go ahead and do the conversion too. -- Paul (Download pyparsing at http://pyparsing.sourceforge.net.) -------------------- test = r""" [(some text)2.3(more text)4.5(more text here)] [(aa bb ccc)-1.2(kdk)12.0(xxxyyy)] [(xxx)11.0(bbb\))8.9(end here)] """ from pyparsing import oneOf,Combine,Optional,Word,nums,QuotedString,Suppress # define a floating point number sign = oneOf("+ -") floatNum = Combine( Optional(sign) + Word(nums) + "." + Word(nums) ) # have parser convert to actual floats while parsing floatNum.setParseAction(lambda s,l,t: float(t[0])) # define a "quoted string" where ()'s are the opening and closing quotes parenString = QuotedString("(",endQuoteChar=")",escChar="\\") # define the overall entry structure entry = Suppress("[") + parenString + floatNum + parenString + floatNum + parenString + Suppress("]") # scan for floats for toks,start,end in floatNum.scanString(test): print toks[0] print # scan for paren strings for toks,start,end in parenString.scanString(test): print toks[0] print # scan for entries for toks,start,end in entry.scanString(test): print toks print -------------------- Gives: 2.3 4.5 -1.2 12.0 11.0 8.9 some text more text more text here aa bb ccc kdk xxxyyy xxx bbb) end here ['some text', 2.2999999999999998, 'more text', 4.5, 'more text here'] ['aa bb ccc', -1.2, 'kdk', 12.0, 'xxxyyy'] ['xxx', 11.0, 'bbb)', 8.9000000000000004, 'end here'] From jantod at gmail.com Wed Apr 26 09:45:20 2006 From: jantod at gmail.com (jantod at gmail.com) Date: 26 Apr 2006 06:45:20 -0700 Subject: scipy and py2exe Message-ID: <1146059120.882012.268330@j33g2000cwa.googlegroups.com> I am trying to package my application with py2exe. Unfortunately it uses both scipy/numpy and numarray so I'm having to jump through a lot of hoops to get it going. I'm getting problems packaging an app that uses only scipy. See below. Thanks! Janto ===setup.py=== from distutils.core import setup import py2exe import sys sys.argv.append('py2exe') setup( windows = [{ "script": "test.py", }], options = dict( py2exe = dict( ascii=1, skip_archive = 1, packages = ["scipy"], excludes = [ '_gtkagg', '_tkagg', 'tcl', 'Tkconstants', 'Tkinter', 'tcl', ], ) ), ) ===test.py=== import time import scipy print scipy.array([1,2,3]) time.sleep(1) ===error file=== import core -> failed: No module named _internal import lib -> failed: 'module' object has no attribute '_ARRAY_API' import linalg -> failed: 'module' object has no attribute '_ARRAY_API' import dft -> failed: 'module' object has no attribute '_ARRAY_API' import random -> failed: 'module' object has no attribute 'dtype' Traceback (most recent call last): File "test.py", line 2, in ? File "scipy\__init__.pyc", line 25, in ? numpy name space File "numpy\__init__.pyc", line 49, in ?  File "numpy\add_newdocs.pyc", line 2, in ? `??Cc File "numpy\lib\__init__.pyc", line 5, in ? File "numpy\lib\type_check.pyc", line 8, in ? File "numpy\core\__init__.pyc", line 6, in ? File "numpy\core\umath.pyc", line 12, in ? File "numpy\core\umath.pyc", line 10, in __load AttributeError: 'module' object has no attribute '_ARRAY_API' From scott.daniels at acm.org Wed Apr 26 18:22:21 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Wed, 26 Apr 2006 15:22:21 -0700 Subject: print names of dictionaries In-Reply-To: <1146089119.905723.306200@v46g2000cwv.googlegroups.com> References: <1146085818.242086.206290@e56g2000cwe.googlegroups.com> <1146087140.319985.36690@u72g2000cwu.googlegroups.com> <1146089119.905723.306200@v46g2000cwv.googlegroups.com> Message-ID: <444fef3a$1@nntp0.pdx.net> BartlebyScrivener wrote: > This works for now. I just added their names as values: > > def printdict(dictionaries=[apps, dirs, sites]): > for dictionary in dictionaries: > print dictionary["name"] > keys = dictionary.keys() > keys.sort() > for key in keys: > if key != "name": > print key, ":",dictionary[key] > print '\n', > > Thank you both for your help. You might want to use a key of '_name', or '_name_', because 'name' is a fairly likely name to encounter. --Scott David Daniels scott.daniels at acm.org From fredrik at pythonware.com Mon Apr 10 15:32:36 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 10 Apr 2006 21:32:36 +0200 Subject: unboundlocalerror with cgi module References: <1282490.JcRWy2CgMu@teancum> Message-ID: "David Bear" wrote: > I'm attempting to use the cgi module with code like this: > > import cgi > fo = cgi.FieldStorage() > # form field names are in the form if 'name:part' > keys = fo.keys() > for i in keys: > try: > item,value=i.split(':') > except NameError, UnboundLocalError: > print "exception..." > item,value=(None,None) > return(item,value) > > However, the except block does not seem to catch the exception and an > unboundlocalerror is thrown anyway. What am I missing? why on earth do you expect a string split to result in either a NameError or an UnboundLocalError ? (both of which signify *programming* errors, most likely in *your* code, and should be fixed rather than ignored) From alainpoint at yahoo.fr Mon Apr 10 09:06:19 2006 From: alainpoint at yahoo.fr (alainpoint at yahoo.fr) Date: 10 Apr 2006 06:06:19 -0700 Subject: challenging (?) metaclass problem References: <1144656384.077748.229010@u72g2000cwu.googlegroups.com> Message-ID: <1144674379.740513.260070@u72g2000cwu.googlegroups.com> Now, a tab-free version of my previous post. (Sorry for the inconvenience) Hi, I have what in my eyes seems a challenging problem. Thanks to Peter Otten, i got the following code to work. It is a sort of named tuple. from operator import itemgetter def constgetter(value): def get(self): return value return get def createTuple(*names): class TupleType(type): pass class T(tuple): __metaclass__ = TupleType def __new__(cls, *args): if len(names) != len(args): raise TypeError return tuple.__new__(cls, args) for index, name in enumerate(names): setattr(T, name, property(itemgetter(index))) setattr(TupleType, name, property(constgetter(index))) return T if __name__ == '__main__': Point=makeTuple('x','y') p=Point(4,7) assert p.x==p[0] assert p.y==p[1] assert Point.x==0 assert Point.y==1 Now my problem is the following. I want to write a function called createDerivedTuple in order to create a class derived from the one created with the function createTuple, taking the parent class as first argument: def createDerivedTuple(parentclass,*names): ....... code yet to be figured out .... The usage should be as follows: DerivedPoint=makeDerivedTuple(Point,'z') p=DerivedPoint(4,7,9) assert p.x==p[0] assert p.y==p[1] assert p.z==p[2] assert DerivedPoint.x==0 assert DerivedPoint.y==1 assert DerivedPoint.z==2 I am still a newbie on metaclasses but i am convinced there are elegant solutions to this challenging problem. Best regards Alain From jjl at pobox.com Tue Apr 11 15:49:04 2006 From: jjl at pobox.com (John J. Lee) Date: 11 Apr 2006 19:49:04 +0000 Subject: XPath/Screen Scraping Gurus.. References: <237101c65d84$c0c54da0$0301a8c0@Mesa.com> Message-ID: <87lkub99lb.fsf@pobox.com> Peter Hansen writes: [...] > Screen-scraping refers, I believe, to the process of identifying what is > onscreen in GUI programs, possibly even at the pixel level, and trying > to translate that back into a higher level model (e.g. text in fields) > of what is going on. > > Web-scraping, on the other hand, generally doesn't need to involve the > graphic representation of anything, and can work at the level of HTML, > XML, and ... XPath. > > (Disclaimer: I know these terms are not really standardized, but I think > the defacto standard definitions match what I've described fairly closely.) Some people do seem to use "screen-scraping" to cover what you define above as "web-scraping". John From osv at javad.com Fri Apr 14 04:46:30 2006 From: osv at javad.com (Sergei Organov) Date: Fri, 14 Apr 2006 12:46:30 +0400 Subject: list.clear() missing?!? References: <1144767680.583085.310160@v46g2000cwv.googlegroups.com> <89iu32p2or66h7sqig37e8ur4c2rqd2s9h@4ax.com> Message-ID: Dennis Lee Bieber writes: > On Fri, 14 Apr 2006 09:17:05 +0400, Sergei Organov > declaimed the following in comp.lang.python: > >> >> I, as a newcomer, don't have much trouble understanding the binding vs >> the assignment by themselves. What does somewhat confuse is dual role of >> the "=" operator, -- sometimes it means "bind" and other times it means >> "assign", right? For me it seems that the language would be less > > It always means bind... But if the LHS is a mutable object, AND you > have specified a component of that object, it is the component that is > being rebound... > > lst[:] = [] > > is rebinding the elements inside the list "lst", and not rebinding the > name "lst". Essentially, once you add any "selector" to the name > (object[...]= or object.xxx=) you are going "inside" the object, and > manipulating (rebinding) what is inside. If the name is used "pure" > (object=), you are rebinding the /name/ to a different object. Me gets corrected, thanks. Now I need to unroll my mind somewhat back to figure out when and why I started to believe it sometimes assigns ;) -- Sergei. From williams.jasonscott at gmail.com Mon Apr 24 16:50:52 2006 From: williams.jasonscott at gmail.com (williams.jasonscott at gmail.com) Date: 24 Apr 2006 13:50:52 -0700 Subject: C API - tp_getattro and tp_methods In-Reply-To: <2341353.ZoQ3i2GqUK@news.perlig.de> References: <1145910179.468987.266850@u72g2000cwu.googlegroups.com> <2341353.ZoQ3i2GqUK@news.perlig.de> Message-ID: <1145911852.768851.36030@t31g2000cwb.googlegroups.com> Andr? Malo wrote: > tp_getattro is like defining __getattribute__, i.e. it gets called on every > attribute read access. You can use PyObject_GenericGetAttr inside the > function to find predefined attributes before applying your own rules. Thanks for the reply. I see and was afraid of that, I don't have a predefinded list of attributes. I want to get them from the C library as needed. Is there another way I should be accessing the data from my C lib since it isn't known at compile time? thanks again~ From sll_noSpamlicious_z_XXX_m at cc.usu.edu Sat Apr 1 00:06:52 2006 From: sll_noSpamlicious_z_XXX_m at cc.usu.edu (Luc The Perverse) Date: Fri, 31 Mar 2006 22:06:52 -0700 Subject: DO NOT USE JAVA BECAUSE IT IS NOT OPEN SOURCE References: <1143867556.814290.321740@i40g2000cwc.googlegroups.com> Message-ID: wrote in message news:1143867556.814290.321740 at i40g2000cwc.googlegroups.com... > Programing Languiges Are Ment to be free. That is why i am starting The > Coo De Tar thats french for Blow of state it is a flash/java > alternative and if you are going to use a server side languige use > Perl,Python or better yet Ruby. What is the point of a languige without > a standerd and without a open source distrabution. Coo De Tar will be > released as a api for perl,python and ruby. Java sucks because it IS > NOT FREE. I AM A GNU GUY I BELEVE THAT SOFTWARE MUST AND SHALL BE > FREE!!!!!!!!!!!!!! do not use java because it is an oxymoron > Dear Mr Troll, There are GNU implementations of JVM and compiler. And just because Sun's Java is not GNU does not mean it is not free. Now go get a life. -- LTP :) From john at castleamber.com Wed Apr 26 13:14:15 2006 From: john at castleamber.com (John Bokma) Date: 26 Apr 2006 17:14:15 GMT Subject: [Reported] (was Re: Xah's Edu Corner: Criticism vs Constructive Criticism) References: <1145992903.834316.198370@u72g2000cwu.googlegroups.com> <4GM3g.3084$TT.1768@twister.nyroc.rr.com> Message-ID: Eli Gottlieb wrote: > Oh, God, not another one. Instead of cross posting more garbage, do as follows: Email a complaint to the email addresses you can look up yourself and include the entire message of Xah: http://www.spamcop.net/sc?track=72.231.179.135 posting host http://www.spamcop.net/sc?track=xahlee.org spamvertized site If enough people complain with both, it might stop one day. -- John Bokma Freelance software developer & Experienced Perl programmer: http://castleamber.com/ From webraviteja at gmail.com Wed Apr 12 17:34:47 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 12 Apr 2006 14:34:47 -0700 Subject: New Karrigel page in Wikipedia In-Reply-To: References: <1144867025.095969.92870@e56g2000cwe.googlegroups.com> Message-ID: <1144877687.238186.66680@j33g2000cwa.googlegroups.com> > editor and even then it's still difficult. Stuffing it into Python > strings is a double pain because you have to figure out how may times > you have to quote your percent signs depending on how may times you > render a string. You don't need to do that. You can always use your favorite templating system. I am using Cheetah. > Akasha is not perfect, it's not full-featured, it doesn't have any > databases associated with it (thank god), but for me it's a dream to use > in contrast to the half a dozen web frameworks I tried. Karrigell's KirbyBase is strictly optional. I don't use it. And it is not bound to Karrigell either. You can use it stand alone in any other app by itself. It just happens to be bundled along and is meant solely for storage needs between a config file and a small database. So it is not intended for everything. > if you want to play with it, let me know and I will update CVS at > https://savannah.nongnu.org/projects/akasha with the current work in > progress Please do. I switched to Karrigell after problems with CherryPy in 'development mode'. I did find Karrigell amazingly simple and it just stepped out of the way but had all the things I thought were nice about CherryPy. Because of the simplicity, I did not have to deal with a single quirk so far. But maybe, I will like your framework better once I see it. > ps. If you check wikipedia it has some rather amusing uplifting > definitions for Akasha and Akasha records. Although on bad days I think > of Akasha as a code sucking vampire draining the life out of my hands. Akasha in many [Asian] Indian languages means 'Sky' :-). From jos at xos.nl Mon Apr 17 06:17:31 2006 From: jos at xos.nl (Jos Vos) Date: Mon, 17 Apr 2006 12:17:31 +0200 Subject: XML-RPC server via xinetd In-Reply-To: <44436987.4020407@sweetapp.com>; from brian@sweetapp.com on Mon, Apr 17, 2006 at 12:10:15PM +0200 References: <4442a56a$0$31651$e4fe514c@news.xs4all.nl> <4442dc54$0$31651$e4fe514c@news.xs4all.nl> <20060417115550.A22145@xos037.xos.nl> <44436987.4020407@sweetapp.com> Message-ID: <20060417121731.A22258@xos037.xos.nl> On Mon, Apr 17, 2006 at 12:10:15PM +0200, Brian Quinlan wrote: > If you take a look at CGIXMLRPCRequestHandler > (http://docs.python.org/lib/node564.html), you will see an example of > how to write an XMLRPCRequestHandler without HTTP. Thanks, this might work for me, will try it. -- -- Jos Vos -- X/OS Experts in Open Systems BV | Phone: +31 20 6938364 -- Amsterdam, The Netherlands | Fax: +31 20 6948204 From no-spam at no-spam-no-spam.com Wed Apr 26 08:01:28 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Wed, 26 Apr 2006 14:01:28 +0200 Subject: Passing Exceptions Across Threads In-Reply-To: References: Message-ID: Adam Mullins wrote: > Hello, I'm writing a physics simulator back-end with a built-in, > threaded server that for the moment is quite simple. I've faced a few > problems in writing this code, however, as it's the first time I've > played with threading. For the moment, everything works decently, but I > need (or rather, want) a method for passing caught exceptions in > sub-threads to the main thread to be raised there. Although this > solution isn't the only one, I feel it will be the most elegant (the > thread/class will be called inside the main module within a try/except > structure, which makes the program a bit more modular, in my opinion, > and cleaner). > > Here is my code so far: > http://rafb.net/paste/results/UESOWB24.html > > You can see near the top where I clumsily tried to a hack a function > into threading._MainThread, in the hopes that if it were called from a > sub-thread it would execute in the main thread. This is seemingly not > so. > > Many thanks for any help. > The CallQueue and BackgroundCall.get_return() do that exception transfer already by default: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/491281 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/491280 -robert From arobert at townisp.com Thu Apr 13 14:04:16 2006 From: arobert at townisp.com (News) Date: Thu, 13 Apr 2006 14:04:16 -0400 Subject: Can't see the forest for the trees - when reading file, only processing first line In-Reply-To: <1144949631.357927.190500@v46g2000cwv.googlegroups.com> References: <123t1kbige4ok93@corp.supernews.com> <1144949631.357927.190500@v46g2000cwv.googlegroups.com> Message-ID: <123t4l6fjbrvvf1@corp.supernews.com> matt at vazor.com wrote: > Suggest keeping it simple: > > def use_file(): > return open(options.filename).readlines() > > m > Very cool.. Didn't know you could do that. From bearophileHUGS at lycos.com Sat Apr 15 08:01:09 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 15 Apr 2006 05:01:09 -0700 Subject: The whitespaceless frontend References: Message-ID: <1145102469.595611.19950@u72g2000cwu.googlegroups.com> This seems nice: global.x = 1 is the same as global x x = 1 but maybe instead of the global.name something to refer to the upper namespace (that can be the global one or the namespace of the function that contains this one) can be more general: upper.x = 1 upper.upper.x = 1 I think that making self a reserved word that can be used only for its usual purpose can be positive. The $ and method statement seem interesting too, but the first is a little perlish (but Ruby has something similar, and people like it), and the method statement look a little redundant. I think the $ can be acceptable (Mostly to reduce typing), even if it doesn't look very nice. Bye, bearophile From steve at REMOVETHIScyber.com.au Tue Apr 11 21:46:25 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Wed, 12 Apr 2006 11:46:25 +1000 Subject: About classes and OOP in Python References: <1144678797.749000.155010@t31g2000cwb.googlegroups.com> <1144743716.408970.23840@z34g2000cwc.googlegroups.com> <00rn321nv3oqbjesmqpdl4p0s3tgdj7o2f@4ax.com> Message-ID: On Tue, 11 Apr 2006 18:20:13 +0000, Casey Hawthorne wrote: >>I think it's important not to wrongly confuse 'OOP' with ''data hiding' >>or any other aspect you may be familiar with from Java or C++. The >>primary concept behind OOP is not buzzwords such as abstraction, >>encapsulation, polymorphism, etc etc, but the fact that your program >>consists of objects maintaining their own state, working together to >>produce the required results, as opposed to the procedural method where >>the program consists of functions that operate on a separate data set. > > Isn't "inheritance" an important buzzword for OOP? Of course inheritance is an important and desirable feature of OOP, but it isn't a necessary feature. Python built-in objects like int, list etc. were still objects even before you could inherit from them. I don't know of many other OO languages that didn't/don't have inheritance, but there was at least one: Apple's Hypertalk, back in the late 80s early 90s. -- Steven. From sjmachin at lexicon.net Thu Apr 27 04:38:05 2006 From: sjmachin at lexicon.net (John Machin) Date: Thu, 27 Apr 2006 18:38:05 +1000 Subject: list of functions question In-Reply-To: <4bai48Fu890hU1@individual.net> References: <4bai48Fu890hU1@individual.net> Message-ID: <445082ED.4000600@lexicon.net> On 27/04/2006 10:38 AM, val bykoski wrote: > Hi The List: > I have a modeling app where i'm detecting events (in temporal > dynamics) applying a set of (boolean) functions - kind of: > > event_list = "f1 f2 etc".split() # each fi detects a specific event > i have defs for functions fi, or simple boolean expressions for each, so > that evList is a list of defs or boolean expressions > for ev in evList: > if ev: # this supposedly is a call ev(t) > # doing smth with the event > > I didn't succeed, though, (blindly) trying various options. > I thought/tried "apply()" but couldn't get it work. > I'd appreciate pointers to how to handle this kind of > functions or events lists (or objects?) and how to call those > functions in a loop. > thanks,val This may be something like what you are trying to achieve: # untested def fx(arg): pass def fy(arg): pass def fdefault(arg): pass funcmap = { 'x1': fx, 'x2': fx, 'y' : fy, } eventlist = "y x2 x2 x1 y".split() for ev in eventlist: efunc = funcmap.get(ev, fdefault) if efunc(t): # what is t???? # do something From podi.ex at gmail.com Mon Apr 10 13:22:01 2006 From: podi.ex at gmail.com (Podi) Date: 10 Apr 2006 10:22:01 -0700 Subject: How to create a single executable console application? Message-ID: <1144689721.446219.300610@i39g2000cwa.googlegroups.com> I followed the instructions from http://starship.python.net/crew/theller/moin.cgi/SingleFileExecutable Copied the second setup.nsi, setup.py, single.py and everything works like a champ. I then replaced "single.exe" by "hello.exe" in setup.nsi. Created hello.py as follows: #! python def main(): print 'Hello world' if __name__ == '__main__': main() #End of file And changed setup.py as follows: #! python from distutils.core import setup import py2exe sys.argv.append('py2exe') setup( console=["hello.py"] ) # End of file After running python setup.py, dist\hello.exe was created and it runs fine ("Hello world" printed on the console). Compiled setup.nsi, and hello.exe was created in current directory. However, when executed, nothing was printed. I might just missed something obvious. Can anyone help me? Has anyone built a single executable for console application? Please post your .nsi file. Thanks very much, P From martin at v.loewis.de Tue Apr 25 02:48:11 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 25 Apr 2006 08:48:11 +0200 Subject: MinGW and Python In-Reply-To: References: <1145861223.509630.247350@y43g2000cwc.googlegroups.com> <444C79D7.4060007@v.loewis.de> Message-ID: <444DC62B.7000702@v.loewis.de> Brian Elmegaard wrote: > What I don't understand is that it is not possible to distribute a > python compiled with gcc for windows. The main reason I saw in this > thread is that python uses mfc. So python requires api access, I > guess. You misunderstood. Python does not use MFC. PythonWin (for example) does. That has a lot of implications which are hard to understand if you are not familiar with Windows programming and the C library mess on Windows. It would certainly be possible to distribute a gcc-compiled python. However, what is the point in doing so? Cygwin already includes a gcc-compiled Python, for Windows: http://cygwin.com/packages/python/ > Once I asked about distutils here. The answer was that I had access to > the source so I could just extend it. After messing around I found I > couldn't because I don't have msvc. That is simply not true. You can build the entire Python interpreter with Cygwin (but you don't need to, because there is a precompiled version), and you can build extensions for the python.org binary using MingW. Regards, Martin From steve at REMOVETHIScyber.com.au Sat Apr 8 03:50:57 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 08 Apr 2006 17:50:57 +1000 Subject: calculating system clock resolution References: <1144434899.840346.220780@z34g2000cwc.googlegroups.com> <1144444527.376016.73100@i40g2000cwc.googlegroups.com> <1144453180.713760.12870@v46g2000cwv.googlegroups.com> Message-ID: Ah, drat -- hit the wrong key and sent the last post before I had finished writing it... the following is what I *intended* to send. On Fri, 07 Apr 2006 16:39:40 -0700, jUrner wrote: > Maybe it was not too clear what I was trying to point out. > > I have to calculate the time time.time() requires to return the next > tick of the clock. > Should be about 0.01ms but this may differ from os to os. I suspect that Python isn't quite fast enough to give an accurate measure for this, but I could be wrong. You can try this: def calc_time_res(): now = time.time start = now() x = start while start == x: x = now() print x - start Trying it, I get a fairly small number: >>> calc_time_res() 1.50203704834e-05 >>> calc_time_res() 1.50203704834e-05 >>> calc_time_res() 1.50203704834e-05 This is Python 2.3 running under Fedora Core 2 Linux. -- Steven. From felipe.lessa at gmail.com Mon Apr 3 21:05:22 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Mon, 03 Apr 2006 22:05:22 -0300 Subject: [ANN] markup.py - 1.2 - an HTML/XML generator In-Reply-To: References: <5f56302b0604031509r51af902dh2e908561bbf78d44@mail.gmail.com> <1144103244.20245.2.camel@kenshin.CASA> Message-ID: <1144112722.28978.11.camel@kenshin.CASA> Em Seg, 2006-04-03 ?s 17:20 -0700, Erik Max Francis escreveu: > Felipe Almeida Lessa wrote: > > > IMHO, it's strange and ugly. Besides, AFAIK everybody uses "cls" or > > "class_", this is the first place I see "klass", so this breaks > > consistency, too. But that's just my opinion... > > A quick Google Groups search indicates that `klass` is more commonly > mentioned than `class_`. Well... $ pwd /usr/lib/python2.4/site-packages $ grep -re klass . | wc -l 274 $ grep -re class_ . | wc -l 897 $ calc 897 / 274 ~3.27372262773722627737 $ cd /tmp $ svn co http://svn.python.org/projects/python/trunk/ A trunk/Python A trunk/Python/codecs.c A trunk/Python/thread_foobar.h ... [loads of files] ... A trunk/pyconfig.h.in A trunk/install-sh U trunk Gerado c?pia de trabalho para revis?o 43612. $ grep -re klass trunk/ | wc -l 534 $ grep -re class_ trunk/ | wc -l 1720 $ calc 1720 / 534 ~3.22097378277153558052 $ grep -re klass trunk/Lib/ | wc -l 340 $ grep -re class_ trunk/Lib/ | wc -l 1188 $ calc 1188 / 340 ~3.49411764705882352941 For me that's enough. "class_" is used at least three times more than "klass". Besides, as Scott pointed out, "class_" is prefered by the guidelines too. > `cls`, at least, is more commonly used within > Python itself (e.g., classmethods). Yes. cls wouldn't be a good choice. But class_ is. Or maybe even css_class. But klass isn't. -- Felipe. From grflanagan at yahoo.co.uk Fri Apr 21 13:22:01 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 21 Apr 2006 10:22:01 -0700 Subject: how to append to a list twice? References: <1145632430.282522.102090@v46g2000cwv.googlegroups.com> <1145636269.440949.197670@j33g2000cwa.googlegroups.com> Message-ID: <1145640121.294131.274260@i39g2000cwa.googlegroups.com> Gerard Flanagan wrote: > Gerard Flanagan wrote: > > John Salerno wrote: > > > If I want to create a list of the form [100, 99, 99, 98, 98, 97, 97...] > > > (where each item is repeated twice after the first one), how might I do > > > that most efficiently? > > > > series = [100] > > > > for i in range(1,10): > > series.extend([100-i]*2) > > > > print series > > > > [100, 99, 99, 98, 98, 97, 97, 96, 96, 95, 95, 94, 94, 93, 93, 92, 92, > > 91, 91] > > Alternative: > > --------------------------------------------------------- > series = [100] > > r = xrange(99,90,-1) > > for L in ( [a1,a2] for a1,a2 in zip( r, r ) ): > series.extend(L) > > print series > > out: [100, 99, 99, 98, 98, 97, 97, 96, 96, 95, 95, 94, 94, 93, 93, 92, > 92, 91, 91] > > --------------------------------------------------------- > series = ['a'] > > r = 'bcdefgh' > > for L in ( [a1,a2] for a1,a2 in zip( r, r ) ): > series.extend(L) > > print series > > out: ['a', 'b', 'b', 'c', 'c', 'd', 'd', 'e', 'e', 'f', 'f', 'g', 'g', > 'h', 'h'] > --------------------------------------------------------- > (Nothing better to do!) def multiplier( iterable, n ): for t in zip( *[iterable] * n): yield t series1 = [100] rng = xrange(99,90,-1) for L in multiplier( rng, 2 ): series1.extend(L) series2 = ['a'] rng = 'bcdefgh' for L in multiplier( rng, 2 ): series2.extend(L) print series1 print series2 Gerard From prouleau at impathnetworks.com Sat Apr 29 15:32:16 2006 From: prouleau at impathnetworks.com (Pierre Rouleau) Date: Sat, 29 Apr 2006 15:32:16 -0400 Subject: Can we create an_object = object() and add attribute like for a class? Message-ID: Hi all, Is there any reason that under Python you cannot instantiate the object class and create any attributes like you would be able for a normal class? Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> a = object() >>> a.data = 1 Traceback (most recent call last): File "", line 1, in ? AttributeError: 'object' object has no attribute 'data' >>> >>> class Object: ... pass ... >>> a = Object() >>> a.data = 1 >>> print "a.data = ", a.data a.data = 1 >>> >>> class Object2(object): ... pass ... >>> b = Object2() >>> b.data = 2 >>> b.data 2 I also tried with Python 2.4.3 with the same results. Being able to do it would seem a natural way of declaring namespaces. -- Pierre Rouleau From jacob.rael at gmail.com Fri Apr 14 23:27:48 2006 From: jacob.rael at gmail.com (Jacob Rael) Date: 14 Apr 2006 20:27:48 -0700 Subject: skip item in list "for loop" In-Reply-To: <4aagm1Fs467vU1@uni-berlin.de> References: <1145038171.945758.256600@j33g2000cwa.googlegroups.com> <4aa88dFs6u2cU1@uni-berlin.de> <4aagm1Fs467vU1@uni-berlin.de> Message-ID: <1145071668.899902.315810@v46g2000cwv.googlegroups.com> Thanks for the suggestions. The solution I liked most was to prevent the lines from appearing in the first place!! From kylotan at gmail.com Tue Apr 25 05:08:51 2006 From: kylotan at gmail.com (Ben Sizer) Date: 25 Apr 2006 02:08:51 -0700 Subject: need a thread to keep a socket connection alive? In-Reply-To: <1145934520.835771.123500@u72g2000cwu.googlegroups.com> References: <1145718638.526525.235090@i39g2000cwa.googlegroups.com> <1145885130.140370.166490@t31g2000cwb.googlegroups.com> <1145891966.658138.31310@i40g2000cwc.googlegroups.com> <1145900352.203424.105890@i40g2000cwc.googlegroups.com> <1145934520.835771.123500@u72g2000cwu.googlegroups.com> Message-ID: <1145956131.110122.104790@i40g2000cwc.googlegroups.com> nephish at xit.net wrote: > the data comming in is alway in 158 bytes though. And one day it may not. :) Consider yourself warned! (In a friendly manner.) -- Ben Sizer From bencvt at gmail.com Tue Apr 11 22:23:48 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 11 Apr 2006 19:23:48 -0700 Subject: How can I determine the property attributes on a class or instance? References: <1144807906.646773.279510@i40g2000cwc.googlegroups.com> Message-ID: <1144808628.215951.68910@u72g2000cwu.googlegroups.com> mrdylan wrote: > class TestMe(object): > def get(self): > pass > def set(self, v): > pass > > p = property( get, set ) > > t = TestMe() > type(t.p) #returns NoneType, what??? > t.p.__str__ #returns > ----------------------------------- > > What is the best way to determine that the attribute t.p is actually a > property object? Obviously I can test the __str__ or __repr__ > attributes using substring comparison but there must be a more elegant > idiom. Check the class instead of the instance: >>> type(TestMe.p) >>> type(t.__class__.p) >>> isinstance(t.__class__.p, property) True --Ben From greg at cosc.canterbury.ac.nz Sun Apr 16 03:13:33 2006 From: greg at cosc.canterbury.ac.nz (greg) Date: Sun, 16 Apr 2006 19:13:33 +1200 Subject: ANN: Pyrex 0.9.4 - LValue Casts are Dead! Message-ID: Pyrex 0.9.4 is now available: http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ Highlights of this version: No more lvalue casts I have redesigned the code generator to eliminate the need for lvalue casting. This means that Pyrex-generated code should now be gcc4-compatible, although I haven't tested this. Let me know if you find any remaining lvalue casts; they should be fairly easy to fix now. C++ compilable The generated code should now be compilable as either C or C++ without errors (although there may still be warnings). However, note that you can still only call C++ functions if they have been declared "extern C", even if you compile the Pyrex output as C++. I hope to introduce some C++ interface features soon. And more... A slew of other improvements and bug fixes have been made, see the CHANGES.txt file in the distribution or on the web page. What is Pyrex? -------------- Pyrex is a language for writing Python extension modules. It lets you freely mix operations on Python and C data, with all Python reference counting and error checking handled automatically. -- Greg Ewing, Computer Science Dept, +--------------------------------------+ University of Canterbury, | Carpe post meridiam! | Christchurch, New Zealand | (I'm not a morning person.) | greg.ewing at canterbury.ac.nz +--------------------------------------+ From alisonken1 at gmail.com Tue Apr 18 19:18:32 2006 From: alisonken1 at gmail.com (alisonken1) Date: 18 Apr 2006 16:18:32 -0700 Subject: indirect import of standard module In-Reply-To: <1145401271.166891.86660@t31g2000cwb.googlegroups.com> References: <1145386200.076643.253740@u72g2000cwu.googlegroups.com> <1145393476.931506.9650@e56g2000cwe.googlegroups.com> <1145401271.166891.86660@t31g2000cwb.googlegroups.com> Message-ID: <1145402312.069923.315960@g10g2000cwb.googlegroups.com> Although 'namespace' may be a misnomer, module interfaces are 'exposed' to the module that imports it - it's not imported a second time into the new 'namespace'. The confusion comes about thinking that modules and classes are related. When a module is first imported, an instance is created for the module and the public interfaces/variables are exposed to the module that did the import. When another call to import the same module from somewhere else, Python recognizes that the module has already been imported, so it only creates a reference link to the new module that called import. That is why you get the same ID number for the module function calls. It's similar to classes in that Python keeps track of 'instances' of classes as well as 'instances' of modules, the 'class' instance is based upon variables which can be either the same class (think of a call to a function with a class instance as the input) or a new instance (where the same class is reused, but with different values), whereas modules are based upon executable bytecode where there is only one instance at all times during the program execution. From ldo at geek-central.gen.new_zealand Sat Apr 22 04:55:59 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 22 Apr 2006 20:55:59 +1200 Subject: proposed Python logo References: <1145585399.871299.31900@t31g2000cwb.googlegroups.com> <1145628079.749480.191190@g10g2000cwb.googlegroups.com> <124hqel51rur33b@corp.supernews.com> <1145640106.269556.276060@u72g2000cwu.googlegroups.com> <124i8176of81331@corp.supernews.com> Message-ID: In article , Dennis Lee Bieber wrote: >On Fri, 21 Apr 2006 16:13:53 -0700, "Carl J. Van Arsdall" > declaimed the following in comp.lang.python: > >> Lawrence D'Oliveiro wrote: >> > >> > Six words: copyright violation ... trademark violation. >> > >> >> Six? >> >> Looks more like 4 to me. > > Ah, but maybe it is self-referential... At last, someone with the imagination I thought would be more common among Pythonistas. :) From antonyliu2002 at yahoo.com Sat Apr 22 16:10:46 2006 From: antonyliu2002 at yahoo.com (Anthony Liu) Date: Sat, 22 Apr 2006 13:10:46 -0700 (PDT) Subject: Generate a sequence of random numbers that sum up to 1? In-Reply-To: <1he66hz.1ip53lh1tibmr5N%aleaxit@yahoo.com> Message-ID: <20060422201046.80025.qmail@web35813.mail.mud.yahoo.com> Thanks a lot, Alex and Gerard. I am actually not very concerned about the inter-dependency of the floating numbers generated randomly. They are good enough if they are subject to the constraint of summing up to 1. It is simply not worth the time to get an HMM by training it on a large corpus. My sole purpose is to test the predicting power of an HMM, given a set of parameter values. I will definitely try out your snippet and see if it works. Thanks a lot! --- Alex Martelli wrote: > Anthony Liu wrote: > ... > > As a matter of fact, given that we have to specify > the > > number of states for an HMM, I would like to > create a > > specified number of random floating numbers whose > sum > > is 1.0. > > def forAL(N): > N_randoms = [random.random() for x in > xrange(N)] > total = sum(N_randoms) > return [x/total for x in N_randoms] > > > Does this do what you want? Of course, the > resulting numbers are not > independent, but then the constraints you pose would > contradict that. > > > Alex > -- > http://mail.python.org/mailman/listinfo/python-list > __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From panos.laganakos at gmail.com Sun Apr 23 19:59:24 2006 From: panos.laganakos at gmail.com (Panos Laganakos) Date: 23 Apr 2006 16:59:24 -0700 Subject: Passing data attributes as method parameters In-Reply-To: <1145835686.151946.324150@e56g2000cwe.googlegroups.com> References: <1145834871.667658.201550@u72g2000cwu.googlegroups.com> <1145835686.151946.324150@e56g2000cwe.googlegroups.com> Message-ID: <1145836764.003816.15720@t31g2000cwb.googlegroups.com> Thanks Ben. What does it mean that they're statically bound? It seems weird that I'm not able to access variables in the class namespace even though these attributes come into existance after class instantiation. From amy.berry at cox.net Mon Apr 10 23:32:24 2006 From: amy.berry at cox.net (ACB) Date: Mon, 10 Apr 2006 20:32:24 -0700 Subject: Saving files from post data via sys.stdin References: Message-ID: <7rF_f.206$Oe2.38@fed1read07> > form = cgi.FieldStorage() > > for k in form.keys(): > do_something_with(form, k) > >> Is there some class that can take this input and make it easier to deal >> with? > > A dictionary. > > I need to >> save each of the ulimage values as individual images and gain access to >> the values of sessionid and userid. >> James, Thanks for the reply, however... the problem I am having is that I need to use the data via sys.stdin and not the cgi.FormStorage object because cgi only takes the data after it has all been received. So, I need a good way to parse the data in sys.stdin unless their is some built-in way to do it. Thanks From nick at craig-wood.com Mon Apr 10 07:30:04 2006 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 10 Apr 2006 06:30:04 -0500 Subject: Difference in Python and Ruby interactive shells References: <1144159204.450444.297870@t31g2000cwb.googlegroups.com> <1144164876.820737.229810@i40g2000cwc.googlegroups.com> Message-ID: Lou Pecora wrote: > Impressive, but YIKES, there ought to be a simpler way to do this. I > think during the development phase editing and reloading would be very > common and you'd want everything updated. Sorry I missed this thread... This is what I use which is easy and works just fine. I only type it once and then press up arrow to get it back! import workinprogress; reload(workinprogress); del(workinprogress); from workinprogress import * That gives you the module and all its globals rebound. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From felipe.lessa at gmail.com Mon Apr 10 14:39:01 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Mon, 10 Apr 2006 15:39:01 -0300 Subject: unboundlocalerror with cgi module In-Reply-To: <1282490.JcRWy2CgMu@teancum> References: <1282490.JcRWy2CgMu@teancum> Message-ID: <1144694341.6280.31.camel@kenshin.CASA> Em Seg, 2006-04-10 ?s 11:29 -0700, David Bear escreveu: > However, the except block does not seem to catch the exception and an > unboundlocalerror is thrown anyway. What am I missing? See http://docs.python.org/tut/node10.html : """ A try statement may have more than one except clause, to specify handlers for different exceptions. At most one handler will be executed. Handlers only handle exceptions that occur in the corresponding try clause, not in other handlers of the same try statement. An except clause may name multiple exceptions as a parenthesized tuple, for example: ... except (RuntimeError, TypeError, NameError): ... pass """ -- Felipe. From grobinson at goombah.com Sat Apr 8 13:17:20 2006 From: grobinson at goombah.com (Gary Robinson) Date: Sat, 8 Apr 2006 13:17:20 -0400 Subject: Python-list Digest, Vol 31, Issue 94 In-Reply-To: References: Message-ID: <20060408131720.321298.01616968@goombah.com> > I can't see anything >> called a T2100. I have 3 X2100 servers which are opterons. Right I meant X2100's, sorry. > Python cannot use psyco on opterons at all - > 32 bit mode or otherwise. Are you sure? I'm not saying I have reason to believe differently, but I just want to be sure. The Psyco docs say it requires "A 32-bit Pentium or any other Intel 386 compatible processor. Sorry, no other processor is supported. Psyco does not support the 64-bit x86 architecture, unless you have a Python compiled in 32-bit compatibility mode". Sun's "The Solaris Operating System on x86 Platforms" guide says "The AMD64 (64bit x86) architecture was done in a way very similar to how Intel had done the i80386, and processors based on AMD64 (much unlike Itanium/IA64) are, in good old x86 tradition, fully binary backward compatible. Of course, actually using the new 64bit operating mode requires porting operating system and applications (like using 32bit on the i80386 did require at the time). But even when running a 64bit operating system does AMD64 provide a sandboxed 32bit environment to run existing applications in (again, like the i80386 which allowed the same for 16bit programs running on a 32bit OS). Therefore the AMD64 architecture offers much better investment protection than IA64 ? which will not run existing 32bit operating systems or applications. " As I read it, this says that when the Opteron is used in "the new 64bit operating mode," as it is on the X2100, it is no longer Intel 386 compatible except in a "sandboxed 32bit environment". Then the question would be whether 32-bit python can be run in the sandboxed 32bit environment. Since I don't have an X2100 yet and haven't played with it or studied the docs yet, I don't know what it entails. Have you explored that? > The T2000 has a new > cpu for which I have no data about python performance. The T2000 has up to 8 relatively slow cores. Python's GIL (and the way the app is designed) eliminate the possibility of making use of more than one core for now. In the future that may change, but I need an immediate solution and re-architecting is not possible right now. > If you can benchmark your own code on a target machine, on solaris, > linux or windows, you can quickly figure out if it's "fast enough". The more speed I have, the better output I'll be able to get. This application is a case where there is no "fast enough". The more speed, the better, within financial constraints. Gary -- Gary Robinson VP/Innovation Emergent Music, LLC grobinson at goombah.com 207-942-3463 Company: http://www.goombah.com Blog: http://www.garyrobinson.net O > Message: 2 > Date: Fri, 07 Apr 2006 02:34:02 GMT > From: ross lazarus > Subject: Re: 32-bit python on Opteron, Solaris 10? > To: python-list at python.org > Message-ID: > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > The answers depend entirely on the cpu in my experience. I'm staring > at http://www.sun.com/servers/index.jsp and I can't see anything > called a T2100. I have 3 X2100 servers which are opterons. Psyco only > runs on x86 cpu hardware. Python cannot use psyco on opterons at all - > 32 bit mode or otherwise. Pypy may fix this soon. The T2000 has a new > cpu for which I have no data about python performance. I am sure it > will run, but it may or may not be super fast if that's important to > you. On the ultrasparcs I have had an opportunity to fool with, python > runs "fast enough" for computationally intensive tasks (ie it's > useable) but relatively slowly compared to the x86 hardware I have > access to - particularly if psyco is available. I was once told that > python was more at home on CISC than on RISC CPU architecture and > being a trusting soul, accept this since it's consistent my own > limited experiments. > > If you can benchmark your own code on a target machine, on solaris, > linux or windows, you can quickly figure out if it's "fast enough". > Exactly what means depends on the throughput you require and a stopwatch. > > Your mileage may vary and there may be sun mavens on the list with > more reliable information than mine. > > Gary Robinson wrote: >> I'm in the market for a server to run some python code which is >> optimized via psyco. >> >> Sun T2100 servers come with Solaris 10, which comes with python >> pre-installed. >> >> Since those servers use the 64-bit Opteron box, I would assume that the >> Python is a 64-bit version. (Does anyone know whether this is >> true/false?) >> >> The Psyco documentation says that for psyco to work, Python needs to be >> compiled in "32-bit compatibility mode". I've never compiled Python, or >> tried having multiple versions running on Solaris. I looked at the >> README for the Python source and didn't see anything about "32-bit >> compatibility mode", though I may have missed it. Or is it a matter of >> choosing a 32 bit compiler to compile against? Any info would be >> appreciated. >> >> Finally, I'm wondering if anyone could give any feedback about >> problems/roadblocks in compiling Python in "32-bit compatibility mode" >> and running it alongside the pre-installed Python that comes with >> Solaris 10. >> >> Any input or tips would be greatly appreciated. >> >> Thanks >> Gary > From nobody at 127.0.0.1 Sun Apr 30 17:01:31 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Sun, 30 Apr 2006 21:01:31 GMT Subject: setting file permissions on a web server References: <445449f6$0$9437$c3e8da3@news.astraweb.com> <4454f1e1$0$1963$c3e8da3@news.astraweb.com> Message-ID: Daniel Nogradi wrote: > I have next to zero experience with windows but as far as I know > windows doesn't have file permissions at all (anyone, please correct > me if I'm wrong :)) so in windows land it doesn't make any sense to > "change file permissions". Actually Windows has a quite good permission scheme, with full owner/group ACLs and granular permissions for read, write, append, delete, and several others I can't recall. The problem is no one uses them much. The manipulation tools are a pain, and developers routinely ignore them (including Microsoft's own developers, although I hear they've gotten much better lately). > I guess so. But that's not a terribly big problem even if you can't > use ssh. What I would do is write a script (in python of course :)) > that does the file permission changing and run that script over the > web. Since this can have serious security implications my strategy > would be to place this script somewhere which is not reachable through > the web and only relocate it to a web accessible directory when you > want to run it over the web, and when you are done, you place it back > to its secure location so nobody can reach it. You're right about the security concerns, but your solution sounds like more trouble than it's worth. With a bit more effort, you could write a local python script that acts as an ftp client and applies permissions remotely. But why bother when a good ftp client already has that built-in (and is much less likely to contain destructive bugs). > You can find out how to > write this script from http://docs.python.org/lib/os-file-dir.html You're worried about security and you turn a novice with a scripting language loose in the briar patch of unix permissions, on a remote server no less? And I thought I was sadistic! :) From kent at kentsjohnson.com Fri Apr 7 05:57:44 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Fri, 07 Apr 2006 05:57:44 -0400 Subject: Unicode, command-line and idle In-Reply-To: <1144391227.670210.221930@e56g2000cwe.googlegroups.com> References: <1144321375.901932.161330@v46g2000cwv.googlegroups.com> <1144333536.440072.13830@i40g2000cwc.googlegroups.com> <44359427.6080805@v.loewis.de> <1144391227.670210.221930@e56g2000cwe.googlegroups.com> Message-ID: <44363234_2@newspeer2.tds.net> a.serrano at vielca.com wrote: > Martin v. L?wis wrote: >> a.serrano at vielca.com wrote: >>> This works if I use the console but gives the following error if I use >>> IDLE: >>> >>> Traceback (most recent call last): >>> File "C:\test.py", line 4, in ? >>> text2 = unicode(raw_input(), sys.stdin.encoding) >>> AttributeError: PyShell instance has no attribute 'encoding' >> What operating system and Python version are you using? This ought to >> work. >> >> Regards, >> Martin > > Python 2.4.3 > IDLE 1.1.3 > Windows XP SP2 ?? Works for me on Win2K Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. IDLE 1.1.3 >>> import sys >>> sys.stdin.encoding 'cp1252' Kent From apardon at forel.vub.ac.be Wed Apr 5 05:07:14 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 5 Apr 2006 09:07:14 GMT Subject: Dice probability problem References: Message-ID: Op 2006-04-04, Tomi Lindberg schreef : > First, thanks to Antoon and Alexander for replying. > > Antoon Pardon wrote: > >> It would be better to construct distributions for one >> die and make a function that can 'add' two distributions >> together. > > As both replies pointed to this direction, I tried to take > that route. Here's the unpolished code I came up with. Does > it look even remotely sane way to accomplish my goal? > -- code begins -- > > # A die with n faces > D = lambda n: [x+1 for x in range(n)] > > # A new die with 6 faces > d6 = D(6) > > # Adds another die to results. > def add_dice(sums, die): > # If first die, all values appear once > if not sums: > for face in die: > sums[face] = 1 > # Calculating the number of appearances for additional > # dice > else: > new_sums = {} > for k in sums.keys(): > for f in die: > if new_sums.has_key(k+f): > new_sums[k+f] += sums[k] > else: > new_sums[k+f] = sums[k] > sums = new_sums > return sums > > sums = add_dice({}, d6) > sums = add_dice(sums, d6) > sums = add_dice(sums, d6) > > -- code ends -- IMO you are making things too complicated and not general enough. Here is my proposal. ----- import operator class Distribution(dict): '''A distribution is a dictionary where the keys are dice totals and the values are the number of possible ways this total can come up ''' def __add__(self, term): '''Take two distributions and combine them into one.''' result = Distribution() for k1, v1 in self.iteritems(): for k2, v2 in term.iteritems(): k3 = k1 + k2 v3 = v1 * v2 try: result[k3] += v3 except KeyError: result[k3] = v3 return result def __rmul__(self, num): tp = num * [self] return reduce(operator.add, tp) def D(n): ''' One die has a distribution where each result has one possible way of coming up ''' return Distribution((i,1) for i in xrange(1,n+1)) sum3d6 = 3 * D(6) sum2d6p2d4 = 2 * D(6) + 2 * D(4) ----- -- Antoon Pardon From bdesth.quelquechose at free.quelquepart.fr Mon Apr 24 21:38:24 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 25 Apr 2006 03:38:24 +0200 Subject: check whether a value is scalar In-Reply-To: <1145760308.504929.71090@z34g2000cwc.googlegroups.com> References: <1145738972.246620.317070@i40g2000cwc.googlegroups.com> <1145740140.754279.152580@j33g2000cwa.googlegroups.com> <1145760308.504929.71090@z34g2000cwc.googlegroups.com> Message-ID: <444d4f1d$0$15517$626a54ce@news.free.fr> Eli a ?crit : > Python treats integers as objects, but as I mentioned that I do care > about the value only, and not its object methods. I mean that it's not > possible to share objects among application in different programming > languages, but it's possible to share the scalar values among them. Not so easily. Lower level languages have some strange rules about size of an integer, signed/unsigned stuff, precision issues for floats, etc... - and of course different representations for a 'string'. > Strings, booleans, integeres, floats, null are types that most > programming languages use. Arrays are also commonly used, but each > programming language defines and uses it differently, Same thing for strings. > so it's more > problematic to treat it as scalar (for example python uses dictionaries Python's dicts are hastables, not arrays. > while other langs uses regular arrays only). From julienfiore at gmail.com Fri Apr 28 02:37:38 2006 From: julienfiore at gmail.com (Julien Fiore) Date: 27 Apr 2006 23:37:38 -0700 Subject: Pyrex installation on windows XP: step-by-step guide References: <1145449777.731155.181600@i40g2000cwc.googlegroups.com> <1146076193.605314.70200@g10g2000cwb.googlegroups.com> <1146164100.552822.280630@j33g2000cwa.googlegroups.com> Message-ID: <1146206258.782000.295980@g10g2000cwb.googlegroups.com> sturlamolden wrote: > edit the text file "c:\mingw\lib\gcc\mingw32\3.2.4\specs" > and change "-lmsvcrt" to "-lmsvcr71". Thank you very much sturlamolden, This procedure should be added to the "step-by-step" guide (see 1st message of this thread) as "step A.5". For ignorant people like me, CRT = "C runtime library". From kent at kentsjohnson.com Mon Apr 10 14:41:51 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Mon, 10 Apr 2006 14:41:51 -0400 Subject: unboundlocalerror with cgi module In-Reply-To: <1282490.JcRWy2CgMu@teancum> References: <1282490.JcRWy2CgMu@teancum> Message-ID: <443aa178$1_1@newspeer2.tds.net> David Bear wrote: > I'm attempting to use the cgi module with code like this: > > import cgi > fo = cgi.FieldStorage() > # form field names are in the form if 'name:part' > keys = fo.keys() > for i in keys: > try: > item,value=i.split(':') > except NameError, UnboundLocalError: > print "exception..." > item,value=(None,None) > return(item,value) > > However, the except block does not seem to catch the exception and an > unboundlocalerror is thrown anyway. What am I missing? > I don't know why you would get an UnboundLocalError from the above code, but the correct syntax is except (NameError, UnboundLocalError): Your code is binding the actual exception to the name "UnboundLocalError" Kent From juncus at gmail.com Fri Apr 21 13:32:23 2006 From: juncus at gmail.com (juncus at gmail.com) Date: 21 Apr 2006 10:32:23 -0700 Subject: building pyParallel in Fedora Core 5 Linux Message-ID: <1145640743.115853.17790@t31g2000cwb.googlegroups.com> Hi, Perhaps this is not the right forum to post this, but I am having trouble installing pyParallel. When I try to do the usual "python setup.py build" or "python setup.py install", I get the following errors. My platform is a very nearly freshly install Fedora Core 5 Linux machine. Any input would be much appreciated. Thanks! $ python setup.py build running build running build_py Traceback (most recent call last): File "setup.py", line 19, in ? package_data = data_files File "/usr/lib/python2.4/distutils/core.py", line 149, in setup dist.run_commands() File "/usr/lib/python2.4/distutils/dist.py", line 946, in run_commands self.run_command(cmd) File "/usr/lib/python2.4/distutils/dist.py", line 966, in run_command cmd_obj.run() File "/usr/lib/python2.4/distutils/command/build.py", line 112, in run self.run_command(cmd_name) File "/usr/lib/python2.4/distutils/cmd.py", line 333, in run_command self.distribution.run_command(command) File "/usr/lib/python2.4/distutils/dist.py", line 965, in run_command cmd_obj.ensure_finalized() File "/usr/lib/python2.4/distutils/cmd.py", line 117, in ensure_finalized self.finalize_options() File "/usr/lib/python2.4/distutils/command/build_py.py", line 60, in finalize_options self.data_files = self.get_data_files() File "/usr/lib/python2.4/distutils/command/build_py.py", line 120, in get_data_files filenames = [ File "/usr/lib/python2.4/distutils/command/build_py.py", line 128, in find_data_files globs = (self.package_data.get('', []) AttributeError: 'NoneType' object has no attribute 'get' From ldo at geek-central.gen.new_zealand Sat Apr 22 05:48:57 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 22 Apr 2006 21:48:57 +1200 Subject: a flattening operator? References: <1145317740.898240.172830@i39g2000cwa.googlegroups.com> Message-ID: In article <1145317740.898240.172830 at i39g2000cwa.googlegroups.com>, "gangesmaster" wrote: >as we all know, * (asterisk) can be used to "inline" or "flatten" a >tuple into an argument list, i.e.: > >def f(a, b, c): > ... >x = (1,2,3) >f(*x) > >so... mainly for symmetry's sake, why not make a "flattening" operator >that also works outside the context of function calls? def flatten(*a) : return a From fredrik at pythonware.com Sun Apr 30 05:00:41 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 30 Apr 2006 11:00:41 +0200 Subject: Unpacking of query result References: <44547588@127.0.0.1> Message-ID: "DarkBlue" wrote: > Following part of an database query works fine : > > self.cur=con1.cursor > self.cur.execute('select a,b,c,d from t1') > for (a,b,c,d) in self.cur: > print a,b,c,d > > > but how to do this: > > self.cur.execute(sql_select_text_put_in_at_runtime) > for (whatever_was_in_the_select_text_part_of_the_query) in self.cur: > print 'returned result set' > > Will it be necessary to parse the sql string and find any possible > return columns or is there a better way so that the query can be used > generically , that is without knowing at coding time > what or how many columns will be returned ? reading the DB-API documentation might help: http://www.python.org/dev/peps/pep-0249/ /.../ Cursor Objects should respond to the following methods and attributes: .description This read-only attribute is a sequence of 7-item sequences. Each of these sequences contains information describing one result column: (name, type_code, display_size, internal_size, precision, scale, null_ok). The first two items (name and type_code) are mandatory, the other five are optional and must be set to None if meaningfull values are not provided. This attribute will be None for operations that do not return rows or if the cursor has not had an operation invoked via the executeXXX() method yet. The type_code can be interpreted by comparing it to the Type Objects specified in the section below. /.../ From weinhand at unileoben.ac.at Mon Apr 10 08:17:18 2006 From: weinhand at unileoben.ac.at (WEINHANDL Herbert) Date: Mon, 10 Apr 2006 14:17:18 +0200 Subject: Automated Graph Plotting in Python In-Reply-To: <1144552132.926125.222210@i39g2000cwa.googlegroups.com> References: <1144552132.926125.222210@i39g2000cwa.googlegroups.com> Message-ID: <443a4cce$0$11610$3b214f66@aconews.univie.ac.at> diffuser78 at gmail.com schrieb: > My python program spits lot of data. I take that data and plot graphs > using OfficeOrg spredsheet. I want to automate this task as this takes > so much of time. I have some questions. > > 1. Which is the best graph plotting utility in python or linux. Can I > write a code in such a way that my python code automatically gives me a > graph. I know little about gnuplot. If you know any better tool without > much learning curve please tell me in Linux. if you want to plot graphs : use pydot the wrapper for graphviz http://dkbza.org/pydot.html http://www.research.att.com/sw/tools/graphviz/ if you want to plot datas (2d) : matplotlib http://sourceforge.net/projects/matplotlib or (2d/3d) dislin (=a plotting library with a python-wrapper) http://www.dislin.de/ > 2. I want to write a script such that my python code writes to a file, > some graph utility like gnuplot takes that data from the file and I get > my graph ready made. Do you think its possible ? > > Any feedback regarding above is appreciated. > > Thanks > happy pythoning Herbert From http Thu Apr 13 11:44:36 2006 From: http (Paul Rubin) Date: 13 Apr 2006 08:44:36 -0700 Subject: New Karrigel page in Wikipedia References: <1144867025.095969.92870@e56g2000cwe.googlegroups.com> <1144915559.734587.131140@e56g2000cwe.googlegroups.com> <1144941258.864318.288600@z34g2000cwc.googlegroups.com> Message-ID: <7xlku9fpjv.fsf@ruckus.brouhaha.com> "Luis M. Gonz?lez" writes: > I appreciate all the observations regarding Wikipedia's nature, but I > confess that I'm surprised to see you, "python folks", so annoyed by > this article. I think it's more "wikipedia folks" (I'm one) who found the original version of the article annoying by Wikipedia standards. Wikipedia is besieged with hucksters trying to propagate marketing fluff through the encyclopedia and so they react unfavorably to anything that resembles that type of material. The current version is much more suitable as an encyclopedia article. It just needs a little bit of grammar and punctuation cleanup, no big deal. From nospam at nospam.com Sat Apr 22 11:06:55 2006 From: nospam at nospam.com (Solar^) Date: Sat, 22 Apr 2006 15:06:55 GMT Subject: Jython/Python Programmers Message-ID: Greetings Group! I'm trying to do a project for my CS class. I'm using this program from Mark Guzdial Jython text: def echoes(snd, delay, factor): sound1 = makeSound(snd) sndlen1 = getLength(sound1) sndlen2 = sndlen1 + (delay * factor) sound2 =decideLen(sound1, sndlen2) # this function return the length # new sound canvas echoamp = 1.0 for echocount in range(1, factor + 1): echoamp = echoamp * 0.6 for echoposition1 in range(1, sndlen1): echoposition2 = echoposition1 + (delay*echocount) value1 = getSampleValueAt(sound1, echoposition1) * echoamp #problem here# value2 = getSampleValueAt(sound2, echoposition2) setSampleValueAt(sound2, echoposition2, value1 + value2) play(sound2) return(sound2) def decideLen(snd1, len1): srate1 = getSamplingRate(snd1) time1 = len1/srate1 time1 =int( ceil(time1)) snd2 = makeEmptySound(time1) return snd2 The problem I'm having is that this program will work for a sampling rate of 22050, but not for the higher quality 44000 rate. I keep getting an array out of bounds message where I marked it on the program. Can't seem to find out why. Too much of a NewBe programmer I guess. Any one help? Regards, Solar^ From fredrik at pythonware.com Thu Apr 20 00:24:01 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 20 Apr 2006 06:24:01 +0200 Subject: Confused by Python and nested scoping (2.4.3) References: Message-ID: Sean Givan wrote: > Hi. I'm new to Python, and downloaded a Windows copy a little while > ago. I was doing some experiments with nested functions, and ran into > something strange. > > This code: > > def outer(): > val = 10 > def inner(): > print val > inner() > > outer() > > ..prints out the value '10', which is what I was expecting. > > But this code.. > > def outer(): > val = 10 > def inner(): > print val > val = 20 > inner() > print val > > outer() > > ..I expected to print '10', then '20', but instead got an error: > > print val > UnboundLocalError: local variable 'val' referenced before assignment. > > I'm thinking this is some bug where the interpreter is getting ahead of > itself, spotting the 'val = 20' line and warning me about something that > doesn't need warning. Or am I doing something wrong? reading the reference documentation may help: http://docs.python.org/ref/naming.html "If a name binding operation occurs anywhere within a code block, all uses of the name within the block are treated as references to the current block." From micklee74 at hotmail.com Mon Apr 17 01:35:24 2006 From: micklee74 at hotmail.com (micklee74 at hotmail.com) Date: 16 Apr 2006 22:35:24 -0700 Subject: any update to this? Message-ID: <1145252124.494322.149040@g10g2000cwb.googlegroups.com> hi i was looking at this : http://www.python.org/doc/essays/comparisons.html on comparisons of python and other languages? are there any updates to this doc? or is there other reliable source for such comparison elsewhere? thanks From piet at cs.uu.nl Fri Apr 21 08:13:57 2006 From: piet at cs.uu.nl (Piet van Oostrum) Date: Fri, 21 Apr 2006 14:13:57 +0200 Subject: Joining stdout & stderr of subprocess ? References: Message-ID: >>>>> robert (R) wrote: >R> when I run a command >R> myapp 2>&1 >R> yet: >R> #!python >R> print os.popen("myapp 2>&1").read() >R> the stderr stuff comes all after the stdout stuff. >R> How can I get ahold of all the out and err joined synchronously in the >R> order, it is created ? Make sure that myapp writes it synchronously. Probably myapp has it buffered, so it writes out at the end of the run. It is not caused by python. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From iainking at gmail.com Wed Apr 26 08:32:19 2006 From: iainking at gmail.com (Iain King) Date: 26 Apr 2006 05:32:19 -0700 Subject: wxpython warnings Message-ID: <1146054739.094951.278490@e56g2000cwe.googlegroups.com> I have a wxpython program that displays TIF images. Sometimes it will encounter a tag the tiff loader cant handle. Rather than silently ignoring it, it pops up a window: Python Warning unknown field with tag blah blah I don't want it to do this, but I can't work out how to turn it off. Anyone know? Iain From dhwild at talktalk.net Tue Apr 4 16:36:51 2006 From: dhwild at talktalk.net (David H Wild) Date: Tue, 04 Apr 2006 21:36:51 +0100 Subject: IDLE on Fedora Core 5 Message-ID: <4e127622d3dhwild@talktalk.net> I have just installed FC5 on a new computer. I can access Python by typing "Python" in a terminal window, but I can't find any way of getting to IDLE. Can anyone help? -- David Wild using RISC OS on broadband From peter at engcorp.com Mon Apr 10 10:37:07 2006 From: peter at engcorp.com (Peter Hansen) Date: Mon, 10 Apr 2006 10:37:07 -0400 Subject: can't pass command-line arguments In-Reply-To: <1144676885.317592.21780@e56g2000cwe.googlegroups.com> References: <1144676885.317592.21780@e56g2000cwe.googlegroups.com> Message-ID: BartlebyScrivener wrote: > No conflicting bat file. What about a conflicting non-BAT file? Anything in PATHEXT ahead of the .PY extension is a candidate... > if __name__ == "__main__": > print sys.argv > for path in all_files(sys.argv[1], sys.argv[2]): > print path > > If I run > > cbfindfiles.py d:/ *emacs* > > from the command prompt I get: > > ['d:\\python\\cbfindfiles.py', 'd:/', '*emacs*'] > followed by a list of matching files > > If I run > > cbfindfiles d:/ *emacs* > > If get an empty command prompt back. Then it's very likely not running this file... what if you put a print at the very top of that file, saying just this: print "running",__file__ If you don't see that, I think you have pretty good confirmation that it is *not* in fact running that file. > Oh, well. > > Not worth troubling over. But it is. To help others. Perhaps what you are encountering is a real bug, and solving it could avoid us having to deal with the same issue in the future (though it seems more likely it's something special to your case, but at least then we'll have a clear answer). Please reconsider and investigate further. If you run the following script and pass it the name "cbfindfiles", it will print out a list of all files in the PATH that might be executed when you type that name, in the order of the possible extensions in PATHEXT. While you may be sure there's no .BAT file with that name, maybe there is another with some other extension. import sys import os name = sys.argv[1] for dir in ['.'] + os.environ['PATH'].split(';'): path = os.path.join(dir, name) for ext in os.environ.get('PATHEXT', '').split(';'): fullpath = path + ext if os.path.isfile(fullpath): print fullpath -Peter From david.rasmussen at gmx.net Mon Apr 10 16:00:13 2006 From: david.rasmussen at gmx.net (David Rasmussen) Date: Mon, 10 Apr 2006 22:00:13 +0200 Subject: how relevant is C today? In-Reply-To: References: <44381ee4$0$4209$c3e8da3@news.astraweb.com> <871ww7elvu.fsf@ieee.org> <1144541959.611623.25540@i39g2000cwa.googlegroups.com> <44393167$1@nntp0.pdx.net> <443965f2$0$67257$157c6196@dreader2.cybercity.dk> Message-ID: <443ab93c$0$60783$157c6196@dreader1.cybercity.dk> Lawrence D'Oliveiro wrote: > In article <443965f2$0$67257$157c6196 at dreader2.cybercity.dk>, > David Rasmussen wrote: > >> In my everyday work, I am forced to use a C90 only compiler, and >> everyday I miss some C++ feature that wouldn't make my program any more >> complex, quite the opposite. These are features like "const", no default >> extern linkage, more typesafe enums etc. > > "const" is in C89/C90. Broken const is. C++ const is different from C90 const. > As for the others, how about hiding a copy of GCC > somewhere, just to use to preflight your code before actually building > it with your compulsory broken compiler? :) I can't do that. I compile for a special system with loads of special libraries. The code can never compiler on a stock gcc compiler. Besides, it doesn't help me to better and more precisely express notions in my code. /David From pratik.ganguly at gmail.com Thu Apr 20 00:06:25 2006 From: pratik.ganguly at gmail.com (prats) Date: 19 Apr 2006 21:06:25 -0700 Subject: help wanted regarding displaying Japanese characters in a GUI using QT and python In-Reply-To: <1145460813.222787.302360@z34g2000cwc.googlegroups.com> References: <1145454203.770652.79920@j33g2000cwa.googlegroups.com> <1145460813.222787.302360@z34g2000cwc.googlegroups.com> Message-ID: <1145505985.664590.39580@t31g2000cwb.googlegroups.com> No I need to replace the text given by the user in the GUI by a new text already in ISO-2022-JP encoding. Then I would have to redisplay this new text. I explain in detail. I have a text file(say) which has something written in it using base64 encoding and using charset ISO-2022-JP. I want to display this data in the GUI. What I did was first to read in the text and then decode it using 'decodestring' function of base64 module in python. " import base64 decoded_string = base64.decodestring(encoded_string) " here the encoded string is the text that was read from the file. How do I display this decoded_string to the GUI? ~pratik From vys at renet.ru Mon Apr 24 06:38:47 2006 From: vys at renet.ru (Vladimir 'Yu' Stepanov) Date: Mon, 24 Apr 2006 14:38:47 +0400 Subject: MySql -Python question In-Reply-To: <9doo42hquanqru36173frhmk1nj4kb8848@4ax.com> References: <1145852748.327176.69080@j33g2000cwa.googlegroups.com> <9doo42hquanqru36173frhmk1nj4kb8848@4ax.com> Message-ID: <444CAAB7.6030208@renet.ru> Dennis Lee Bieber wrote: > On 23 Apr 2006 21:25:48 -0700, ataanis at gmail.com declaimed the following > in comp.lang.python: > > >> Hey all, I'm running a query within some python code, and I'm having >> difficulties doing something that seems to be really simple . I'm >> running a query in the following form: >> query01 = 'select max(DirectorID) +1 from Director;' >> cursor.execute(query01) >> table = cursor.fetchall() >> the resulting table , is a 1 row , 1 column table,showing 1 number and >> I just need that number inside that table,and save it for a different >> query, but I can't get it , can anybody tell me the best way to do >> this? thanks >> > > What does > > table[0] #first element of list "table" > > return to you? Or, since fetchall() might be assuming multiple rows even > for a single row data set... > > table[0][0] #first element of first sublist of list "table" > There is no method for work with data who are presented only in one column. This method would raise speed of work with such data as it is not necessary to make allocation one-item tuple object. Therefore I have a some expanded the module py-sqlplug_mysql (http://sourceforge.net/projects/py-sqlplg-mysql) where such API it is delivered through methods of the cursor: fetchcol0, fetchallcol0, fetchmanycol0. Now on a site of the project the documentation is inaccessible. The basic methods correspond to the specification described in PEP-249. P.S. The project while was tested only on FreeBSD and Linux though can work and on other platforms. P.P.S. For drawing up of the documentation the translator from Russian is required. From fredrik at pythonware.com Thu Apr 6 17:40:39 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 6 Apr 2006 23:40:39 +0200 Subject: Partially unpacking a sequence References: <1144352710.190839.165580@z34g2000cwc.googlegroups.com> Message-ID: Paul McGuire wrote: > Forgot one: > > _,_,a,_,b,_,_,_ = y > > There actually is some merit to this form. If the structure of y changes > sometime in the future (specifically if a field is added or removed), this > statement will fail noisily, calling your attention to this change. But if > a new field is added, say at the front of the list, the previous methods > will all silently succeed, but now giving you the values formerly known as > y[1] and y[3]. if this is likely to happen, an straightforward assert is a lot easier to parse than a one-two-a-three-oops-one-two-a-four-five-etc number of underscores: assert len(y) == 8 a = y[2] b = y[4] From phpbird at gmail.com Sun Apr 9 10:37:43 2006 From: phpbird at gmail.com (Ju Hui) Date: 9 Apr 2006 07:37:43 -0700 Subject: how to print without blank? In-Reply-To: References: <1144562057.796460.277900@e56g2000cwe.googlegroups.com> Message-ID: <1144593463.700105.114460@g10g2000cwb.googlegroups.com> thank you all. IT's very helpful to me. >>> import sys >>> def no_space_before(x): ... sys.stdout.softspace = 0 ... return x ... >>> for x in range(3): ... print no_space_before(x), ... 012 From cretin at des.alpes.ch Wed Apr 5 10:13:14 2006 From: cretin at des.alpes.ch (Azolex) Date: Wed, 05 Apr 2006 16:13:14 +0200 Subject: small challenge : limit((x+1)**0.5 for x in itially(2)) In-Reply-To: <4433ccde$1_1@news.bluewin.ch> References: <4433ccde$1_1@news.bluewin.ch> Message-ID: <4433d085$1_2@news.bluewin.ch> Azolex wrote: > generators challenge > -------------------- > > define "limit" and "itially" > > so that > > limit(foo(x) for x in itially(bar)) > > works out the same as > > limit2(foo,bar) > > with > > def limit2(foo,bar) : > bar1 = foo(bar) > while bar != bar1 : > bar1,bar = foo(bar),bar1 oops, this should read bar1,bar = foo(bar1),bar1 sorry > return bar > > > Note : be careful with your choice of foo and bar, to prevent infinite > loops when the iterated value won't converge. > > To think of it, perhaps "abs(bar-bar1)>epsilon" would be more > appropriate than "bar != bar1" in the above loop - I can imagine > roundoff errors leading to tiny oscillations in the least significant > bits of an otherwise convergent computation. > > Best, az From bedouglas at earthlink.net Sat Apr 29 11:13:54 2006 From: bedouglas at earthlink.net (bruce) Date: Sat, 29 Apr 2006 08:13:54 -0700 Subject: (was Re: Xah's Edu Corner: Criticism vs Constructive Criticism) In-Reply-To: <1146285809.127897.24070@j33g2000cwa.googlegroups.com> Message-ID: <1d1001c66b9f$883bcb70$0301a8c0@Mesa.com> but you know... one could simply hit the delete/skip button when you see a msg you don't like!!! or email/spam filters... or you can spend more time complaining.. in life, you gotta' learn to pick your battles... peace.. -----Original Message----- From: python-list-bounces+bedouglas=earthlink.net at python.org [mailto:python-list-bounces+bedouglas=earthlink.net at python.org]On Behalf Of Tagore Smith Sent: Friday, April 28, 2006 9:43 PM To: python-list at python.org Subject: Re: (was Re: Xah's Edu Corner: Criticism vs Constructive Criticism) John Bokma wrote: > "Tagore Smith" wrote: > > > Your emails to his ISP > > are far more wasteful- you are using up very scarce resources > > dedicated to dealing with real abuse. > > According to his hosting provider dreamhost: > > I have warned this user that excessive offtopic cross-posting is not > allowed, and explained that if he doesn't quit he risks losing his > account. If you (or anyone else) notice this in the future, please do not > hesitate to submit another report. > Precisely: you have wasted the time of someone who might otherwise have spent that time dealing with real abuse. You got the standard email sent out to placate people like you. That was my point. Try sending mail to abuse at (any of my) desmesne(s). You won't get a response- in fact, no-one will read your mail. We just don't have the resources to deal with the easily offended. Too bad- we wouldn't mind handling real abuse, though it is unlikely given our selective set of users. I'm not sure that Xah's post was offtopic, and I am not sure how to determine that objectively. I am sure that it was excessively crossposted. I also know that Xah was posting to Usenet a long time before you, and that he will still be posting to Usenet long after you have given up in disgust, no matter who you complain to. > Reread it a few times, it might educate you (note the *cross-posting* and > the *submit another report*) I think I've mentioned the crossposting in every message I have posted on this thread, and that I don't approve of crossposting. I'm not sure that you are in a position to educate me, and that you suggest that you are is, frankly, obnoxious. I've been civil so far. > (Rest of your misinterpretation snipped). You can snip the important part, but that won't make the point go away. I happen to have been working in this industry for a long time. I have a lot of friends working at, and running, various enterprises. Some of those enterprises handle a lot of the internet's traffic, measured by packets at least. If I were really ethically impaired I could easily mess up internet access for a "list of people I don't like". A call from a backbone provider is not as ignorable as a random email to abuse at whateverlittleISP.com. But I am not ethically impaired (or at least not ethically impaired in that way). Every young sysadmin learns a simple thing: "you have disproportionate power, don't abuse it". Sometimes you have to read people's mail, to diagnose a problem. If they are into weird bondage stuff you avert your eyes, and you _never_ tell anyone (though I think you are allowed to look at them funny at the company picnic). If they are into child porn you call the cops, I think (the ethics are fuzzy here, but this is my conclusion). Crossposting is bad, unless it serves a specific purpose- Xah's post obviously doesn't. I dont like people reporting on Usenet posters to their ISPs, but... I can't really complain about that. Crossposting is not good, without a really good justification. But you are complaining about the content of his posts, and harassing his ISP based on that. That's not just bad, it is wicked. You can quote whatever you want from their emails, but I won't change my mind on this subject- Xah shouldn't crosspost, but otherwise he should be allowed to post. Would you like a Usenet campaign started to disrupt your internet access? You would be angry if that were done, and justifiably. -- http://mail.python.org/mailman/listinfo/python-list From siona at chiark.greenend.org.uk Thu Apr 20 09:18:08 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 20 Apr 2006 14:18:08 +0100 (BST) Subject: multiline comments References: Message-ID: Edward Elliott wrote: >Sion Arrowsmith wrote: >> Really? Under what circumstances is it easier to see what's going on >> with start/end comments than with comment-to-end-of-line? >Off the top of my head: > [ ... ] It appears to me that our fundamental difference is that you see value in long-term preservation of sections of commented-out code without any kind of real comment as to what's going on, whereas I consider this to be appallingly bad practice. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From johnjsal at NOSPAMgmail.com Wed Apr 12 17:20:36 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 12 Apr 2006 21:20:36 GMT Subject: Figure out month number from month abbrievation In-Reply-To: <443d6cf7$1@news.eftel.com> References: <1144873227.982973.18720@i40g2000cwc.googlegroups.com> <443d6cf7$1@news.eftel.com> Message-ID: John Machin wrote: > You can answer such questions yourself very easily, e.g. in this case: > > >>> import calendar > >>> calendar.month_abbr > > >>> list(calendar.month_abbr) > ['', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', > 'Oct', 'Nov', 'Dec'] Ah thanks. I did try it first, but I didn't know to cast it to a list, so I was just getting the object. From phpbird at gmail.com Sun Apr 9 01:54:17 2006 From: phpbird at gmail.com (Ju Hui) Date: 8 Apr 2006 22:54:17 -0700 Subject: how to print without blank? Message-ID: <1144562057.796460.277900@e56g2000cwe.googlegroups.com> I want to print 3 numbers without blank. >>> for x in range(3): ... print x ... 0 1 2 >>> for x in range(3): ... print x, ... 0 1 2 how to print 012 ? thanks. From shalabh.chaturvedi at gmail.com Sun Apr 9 22:25:32 2006 From: shalabh.chaturvedi at gmail.com (shalabh.chaturvedi at gmail.com) Date: 9 Apr 2006 19:25:32 -0700 Subject: "definitive" source on advanced python? In-Reply-To: <1144040231.239622.159630@j33g2000cwa.googlegroups.com> References: <1144040231.239622.159630@j33g2000cwa.googlegroups.com> Message-ID: <1144635932.032781.254250@z34g2000cwc.googlegroups.com> You might find http://www.cafepy.com/article/python_types_and_objects/ and http://www.cafepy.com/article/python_attributes_and_methods/ useful. These articles assume you know Python, and describe some of the mechanisms behind Python new-style objects - including descriptors (but not decorators). From onurb at xiludom.gro Fri Apr 14 13:17:18 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 14 Apr 2006 19:17:18 +0200 Subject: nested functions In-Reply-To: References: <1145014674.717433.75100@t31g2000cwb.googlegroups.com> Message-ID: <443fd96a$0$481$626a54ce@news.free.fr> Szabolcs Berecz wrote: > On 14 Apr 2006 04:37:54 -0700, micklee74 at hotmail.com > wrote: > >>def a(): >> def b(): >> print "b" >> def c(): >> print "c" >> >>how can i call c() ?? > > > Function c() is not meant to be called from outside function a(). > That's what a nested function is for: localizing it's usage and > prevent cluttering the global namespace There's actually more than this about Python's nested functions: they can be returned from the outer function and then carry the environnement in which they where created: def trace(func): fname = func.__name__ def traced(*args, **kw): print "calling func %s with *%s, **%s" % (fname, str(args), kw) try: result = func(*args, **kw) except Exception, e: print "%s raised %s" % (fname, e) raise else: print "%s returned %s" % (fname, str(result)) return result return traced def test(arg1, arg2='parrot'): print "in test, arg1 is %s" % arg1 return arg2 * 3 test = trace(test) test(42) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From onurb at xiludom.gro Thu Apr 27 05:07:43 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 27 Apr 2006 11:07:43 +0200 Subject: OOP / language design question In-Reply-To: References: <1145961248.794496.80220@j33g2000cwa.googlegroups.com> <444e0e97$0$2052$626a54ce@news.free.fr> <1145969107.837185.212970@e56g2000cwe.googlegroups.com> Message-ID: <44508a35$0$27867$626a54ce@news.free.fr> Lawrence D'Oliveiro wrote: > In article <1145969107.837185.212970 at e56g2000cwe.googlegroups.com>, > "Carl Banks" wrote: > > >>bruno at modulix wrote: >> >>>cctv.star at gmail.com wrote: >>> >>>>I was wondering, why you always have to remember to call bases' >>>>constructors >>> >>> >>>s/constructors/__init__/ >>> >>>the __init__() method is *not* the constructor. Object's instanciation >>>is a two-stage process: __new__() is called first, then __init__(). >>> >> >>You know, Python's __init__ has almost the same semantics as C++ >>constructors (they both initialize something that's already been >>allocated in memory, and neither can return a substitute object). I >>actually think constructors are misnamed in C++, they should be called >>initializers (and destructors finalizers). > > > "Constructor" is also the term used for the corresponding method in Java. > > Is there any OO language that does not use "constructor" in this sense? Smalltalk. Just like Python, it has constructor *and* initializer. > I don't think there is one. This is standard OO terminology. Being "standard" doesn't imply it's accurate. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From onurb at xiludom.gro Mon Apr 24 07:08:00 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Mon, 24 Apr 2006 13:08:00 +0200 Subject: Can you create an instance of a subclass with an existing instance of the base class? In-Reply-To: References: <1145650105.664762.321560@j33g2000cwa.googlegroups.com> Message-ID: <444cb1e3$0$28592$626a54ce@news.free.fr> Lawrence D'Oliveiro wrote: (snip) > I think you're taking Python's OO-ness too seriously. One of the > strengths of Python is that it can _look_ like an OO language without > actually being OO. According to which definition of OO ? -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From fredrik at pythonware.com Sat Apr 22 09:18:30 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 22 Apr 2006 15:18:30 +0200 Subject: String formatting using dictionaries References: <1145711112.738116.136780@j33g2000cwa.googlegroups.com> Message-ID: Clodoaldo Pinto wrote: > I know how to format strings using a dictionary: > > >>> d = {'list':[0, 1]} > >>> '%(list)s' % d > '[0, 1]' > > Is it possible to reference an item in the list d['list']?: > > >>> '%(list[0])s' % d > Traceback (most recent call last): > File "", line 1, in ? > KeyError: 'list[0]' not directly, but you can wrap the dictionary in a custom mapper class: class mapper(dict): def __getitem__(self, key): try: return dict.__getitem__(self, key) except KeyError: k, i = key.split("[") i = int(i[:-1]) return dict.__getitem__(self, k)[i] >>> d = {"list": [0, 1]} >>> d = mapper(d) >>> '%(list)s' % d [0, 1] >>> '%(list[0])s' % d 0 From cvanarsdall at mvista.com Mon Apr 10 13:51:40 2006 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Mon, 10 Apr 2006 10:51:40 -0700 Subject: [fcntl]how to lock a file In-Reply-To: References: Message-ID: <443A9B2C.20100@mvista.com> You know, I spent some time with this module and had some interesting results. I had to do file locking over nfs using lockd. This poised an interested problem as I couldn't get the python fcntl module to work correctly via nfs even with lockd setup. Anyhow, I ended up writing an extention in C and somehow this called fcntl differently and I had no issues. If you end up having problems working with the python fcntl module let me know your configuration I'd be interested to see if anyone else had similar problems to me. -c marcello wrote: > Hello > I need to do this: > 1 opening a file for writing/appending > 2 to lock the file as for writing (i mean: the program > that lock can keep writing, all others programs can't ) > 3 wtite and close/unlock > Even better would be changing the order of steps 1 and 2 (that > is,first locking than writing, but it seems to me that in order to block > i need the id of the file...) > > Untill now i have tried to do smthing like : > import fcntl > f=open("prova.txt", 'w') > fcntl.flock(f.fileno(),fcntl.LOCK_EX) > f.write("aaa") > > #meanwhile i open prova.txt with an editor in another window > #and write in "bbb" (without getting any error/warning)and then follow > #in the python shell with > > f.close() > > But then opening the file i can see "bbb" instead of "aaa" > I'm wandering, am i completely lost(misled?)Am i waiting for fcntl to do > what it doesn't? > > I have tried too with: > > f1=os.open('prova.txt',os.O_EXCL|os.O_APPEND) > os.write(f1,"qlcosa") > that should solve the problem of the order of the step, but i not even > can write from the python shell with that. > > python 2.2 > linux > kernel 2.4 > glibc-2.3.2-95.6 > > Thanks in advance for any help. > sorry for my bad english > Grazie > Marcello > -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From invalidemail at aerojockey.com Wed Apr 19 21:55:49 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 19 Apr 2006 18:55:49 -0700 Subject: Method Call in Exception References: <1145490879.789439.18030@t31g2000cwb.googlegroups.com> Message-ID: <1145498149.790387.289670@v46g2000cwv.googlegroups.com> mwt wrote: > In my latest attempt at some Python code, I've been tempted to write > something in the form of: > > try: > [...] #doing some internet stuff > except IOError: > alternate_method_that_doesnt_need_internet() > > This works when I try it, but I feel vaguely uneasy about putting > method calls in exception blocks. So tell me, Brave Pythoneers, is this > evil sorcery that I will end up regretting, or is it just plain good > ol' Python magic? It's ok. In fact a lot of Pythonistas recommend this way over the alternative, even when you don't have to. For example, a lot of people recommend this: try: name = record.name except AttributeError: name = "Freddy" instead of this: if hasattr(record,"name"): name = record.name else: name = "Freddy" I prefer the latter most of the time; however, sometimes (as it appears in your case) simply trying it and doing something else if it raises an exception is easier, more straightforward, and more robust than explicitly testing the condition. One thing to consider is whether something you don't expect could throw the same exception; might have to disambiguate them somehow in the except block. Language-wise, I doubt there are any serious gotchas whem running regular (as opposed to error handling) code in an except block. So go right ahead; no need to feel guilty about it. Carl Banks From kent at kentsjohnson.com Sat Apr 1 00:16:32 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Sat, 01 Apr 2006 00:16:32 -0500 Subject: logging producing redundant entries In-Reply-To: References: <442d74ca$1_3@newspeer2.tds.net> Message-ID: <442e0769$1_3@newspeer2.tds.net> Jed Parsons wrote: > > Thanks, Kent and Peter, > > Definitely making progress here. I've got propagate = 0, and am testing > for handlers before doing any addHandler business. (The handlers test > seems to make the most difference.) > > I'm down to two entries per time now! And prodding Zope to reload the > module doesn't cause the number to increase. Do you have a second module that is setting up the same logging? Kent From escalation746 at yahoo.com Sat Apr 1 12:00:48 2006 From: escalation746 at yahoo.com (robin) Date: Sat, 01 Apr 2006 18:00:48 +0100 Subject: New Python Logo Revealed Message-ID: <9bct22dngv6lncqfjju5oqi4772or4pdle@4ax.com> I have an entry on my blog discussing the new Python logo, which is apparently due to replace the current one within the month. I'd be interested in what people think of it. Surf: http://diagrammes-modernes.blogspot.com ----- robin noisetheatre.blogspot.com From python at rcn.com Thu Apr 13 14:06:28 2006 From: python at rcn.com (Raymond Hettinger) Date: 13 Apr 2006 11:06:28 -0700 Subject: list.clear() missing?!? References: <1144767680.583085.310160@v46g2000cwv.googlegroups.com> <1144774431.11151.5.camel@kenshin.CASA> <1144871740.682517.239660@i40g2000cwc.googlegroups.com> Message-ID: <1144951588.287887.19620@v46g2000cwv.googlegroups.com> [Dan Christensen] > It's true that this runs at the same speed as the del variants on my > machine. That's not too surprising to me, but I still don't > understand why the del variants are more than 5% faster than the first > version. Understanding it involves looking at implementation specific details such as the overallocation scheme for growing lists and the performance of your machine's underlying memory allocator. > Once this is understood, is it something that could be optimized? > It's pretty common to rebind a variable to a new value, and if > this could be improved 5%, that would be cool. Sorry, that's not how the language works. Something like "a=range(100000)" means: * build a NEW list for 100000 elements * THEN assign it to the variable "a" * which THEN reduces the ref count to the previous binding for "a" * and THEN IF the ref count is zero, free the list previously bound to "a" In other words, if "a" is already bound to a large list, then the above assignment necessarily creates a second, non-overlapping list in memory. However, if you write "a=None;a=range(100000)", then the original list gets freed BEFORE the new list is created and the system has a chance to re-use that large, contiguous block of memory. From alexci at web.de Thu Apr 13 17:16:14 2006 From: alexci at web.de (Aleksandar Cikota) Date: Thu, 13 Apr 2006 23:16:14 +0200 Subject: BSTR Message-ID: Hi all, I'm beginner in Python and need help. I'm writing software for a robotic telescope. For CCD camera control we use MaxIm DL (Diffraction Limited). I have a problem with CCDCamera.SaveImage. Error message: > File "S:MaxImmaxim.py", line 19, in ? > CCDCamera.SaveImage('C:/1.fit') > File "C:ProgrammePython24Libsite- > packageswin32comclientdynamic.py", line 491, in __getattr__ > raise pythoncom.com_error, details > com_error: (-2147352567, 'Ausnahmefehler aufgetreten.', > (65535, 'MaxIm DL 4', 'Invalid Input', None, 0, 0), None) Here is the answer that we recieved from Diffraction Limited: --------- For CCDCamera.SaveImage, 'Invalid Input' is reported only if the argument is not of an acceptable type. As you are probably aware from looking at the type library, the filename argument is declared as a variant. What the type library doesn't tell you is that the variant must be either a BSTR (unicode string with header) or a reference to a BSTR. Specifically, the 'vt' member of the VARIANT must be either VT_BSTR or VT_BSTR|VT_BYREF. Does python provide any way of influencing how arguments for COM methods are created? If so, you may be able to get this to work. It may be as simple as assigning the string to a variable name instead of passing it as a literal, or perhaps there's something equivalent to a C++ cast operator or a VB 'type' function (CInt, CStr, etc.). This problem is likely to affect any MaxIm DL automation method that takes a string as an argument. --------- Here is the code (Python): import win32com.client, time CCDCamera = win32com.client.Dispatch('MaxIm.CCDCamera') CCDCamera.LinkEnabled = True if CCDCamera.LinkEnabled == False: print 'Failed to start camera.' exp = int(raw_input('Exposition[sec]: ')) CCDCamera.Expose(exp, 1, 0) while CCDCamera.ImageReady == False: time.sleep print 'Done' time.sleep(3) CCDCamera.SaveImage('C:/1.fit') The question is, how to convert a String in a BSTR (unicodestring with header)? For your prompt reply, I say thank you in advance. Best regards, Aleksandar Cikota From aleaxit at yahoo.com Wed Apr 19 21:58:08 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 19 Apr 2006 18:58:08 -0700 Subject: Missing interfaces in Python... References: <1145306373.781129.305840@z34g2000cwc.googlegroups.com> <1145430546.625634.194710@g10g2000cwb.googlegroups.com> <7lrb429tg5c6dt1bt99d1131cafuulvqap@4ax.com> <4445f7f8$0$9451$626a54ce@news.free.fr> <1145438118.179643.140390@e56g2000cwe.googlegroups.com> <1he15id.pxmsobvfopabN%aleaxit@yahoo.com> <9qmc42hjms8h1olfa3ssk9r1nmm0g46jn7@4ax.com> Message-ID: <1he21mz.15568fs1by4yl3N%aleaxit@yahoo.com> Rene Pijlman wrote: > Alex Martelli: > >PEAK is an interesting counterexample, particularly since Philip Eby > >tends to be "ahead of the curve": > > I never noticed PEAK before. Is it well worth studying? Oh yes. Alex From steve at REMOVETHIScyber.com.au Tue Apr 11 21:36:36 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Wed, 12 Apr 2006 11:36:36 +1000 Subject: list.clear() missing?!? References: <1144767680.583085.310160@v46g2000cwv.googlegroups.com> <443BE426.20501@v.loewis.de> Message-ID: On Tue, 11 Apr 2006 19:15:18 +0200, Martin v. L?wis wrote: > Felipe Almeida Lessa wrote: >> I love benchmarks, so as I was testing the options, I saw something very >> strange: >> >> $ python2.4 -mtimeit 'x = range(100000); ' >> 100 loops, best of 3: 6.7 msec per loop >> $ python2.4 -mtimeit 'x = range(100000); del x[:]' >> 100 loops, best of 3: 6.35 msec per loop >> $ python2.4 -mtimeit 'x = range(100000); x[:] = []' >> 100 loops, best of 3: 6.36 msec per loop >> $ python2.4 -mtimeit 'x = range(100000); del x' >> 100 loops, best of 3: 6.46 msec per loop >> >> Why the first benchmark is the slowest? I don't get it... could someone >> test this, too? > > In the first benchmark, you need space for two lists: the old one and > the new one; Er, what new list? I see only one list, x = range(100000), which is merely created then nothing done to it. Have I missed something? I understood Felipe to be asking, why does it take longer to just create a list, than it takes to create a list AND then do something to it? -- Steven. From ryang at gol.com Tue Apr 4 04:02:27 2006 From: ryang at gol.com (Ryan Ginstrom) Date: Tue, 4 Apr 2006 17:02:27 +0900 Subject: Registration Code In-Reply-To: <1144096273.915268.90360@v46g2000cwv.googlegroups.com> Message-ID: <007201c657be$1da71610$030ba8c0@RYAN> > On Behalf Of Dave Mandelin: > Second, I hear that in general it is very difficult to make a > time-limited demo, because the code has to be all there, so all a > cracker has to do is bypass the "if". It seems that even this method > won't work for that. Do you know of any way to make time limiting > secure? If the application is to be Windows only (and I assume this from statement about using py2exe), one fairly secure and easy method is to put some critical functionality into a plain DLL or (compiled) COM module, and use a commercial software-protection program like Armadillo on that. Armadillo is much more secure than just about anybody could make on their own, and instead of wasting time (and probably introducing bugs) implementing it yourself, you can use that time improving your application. Armadillo handles all sorts of protection schemes, from time limitations to machine locking and "crippling," and combinations thereof. (I have no commercial or other interest in Armadillo.) Another tack to take is to maintain content updates on a Website for download. The Website would check the registration code. This foils most cracking methods, and even shared codes can be blacklisted when found. Of course, this only works for certain types of applications, but when it is possible it has the benefits of not requiring significant changes to your application, remaining transparent to the user, and most importantly, not antagonizing legitimate users. And of course, it would enable cross-platform (commercial) use of your application. A variation of this strategy is the subscription model. Regards, Ryan --- Ryan Ginstrom http://ginstrom.com From fredrik at pythonware.com Sun Apr 16 11:10:43 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 16 Apr 2006 17:10:43 +0200 Subject: Tkinter References: <1145198499.259375.90030@i39g2000cwa.googlegroups.com> Message-ID: "Jay" wrote: > I wold like to be able to generate buttons from a list in a file. > How would I go about making each button have a different command, > Lets say make the button print its label instead of print "." > > The problem I have is I don't know what the list is going to be until > it is opened or how big so I carnet make a def for each. def is an executable statement, and creates a new function object everytime it's executed. if you want a new function for each pass through a loop, just put the def inside the loop: > from Tkinter import * > > class App: > def __init__(self, root): > > self.DisplayAreaListsFrame = Frame(root) > self.DisplayAreaListsFrame.pack() > > Lists = ["A1","B2","C3","D4"] > > for i in Lists: def callback(text=i): print text > self.DisplayAreaListButton = Button( > self.DisplayAreaListsFrame, > text=i, > command=callback) > self.DisplayAreaListButton.pack(side=LEFT,padx=10) > > root = Tk() > app = App(root) > root.mainloop() the only think that's a little bit tricky is scoping: you can access all variables from the __init__ method's scope from inside the callbacks, but the callbacks will be called after the loop is finished, so the "i" variable will be set to the *last* list item for all callbacks. to work around this, you have to explicitly pass the *value* of "i" to to the callback; the "text=i" part in the above example uses Python's default argument handling to do exactly that. From onurb at xiludom.gro Thu Apr 20 10:14:48 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 20 Apr 2006 16:14:48 +0200 Subject: Python IDE for linux In-Reply-To: References: <20060419214307.2e63c5cd.neil.isaac@sympatico.ca> Message-ID: <444797a8$0$21107$626a54ce@news.free.fr> Fulvio wrote: > Alle 09:43, gioved? 20 aprile 2006, Neil Isaac ha scritto: > >>At this point I'm thinking that I would like to start using a real IDE. > > Idle, shipped with Python :-) The OP said "a *real* IDE" !-) > F -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From cncprgr at aim.com Mon Apr 10 11:31:01 2006 From: cncprgr at aim.com (dc) Date: 10 Apr 2006 08:31:01 -0700 Subject: newbie: Need Help Moving Data from Kirbybase to Gadfly Message-ID: <1144683061.069346.297680@v46g2000cwv.googlegroups.com> I am fairly new to python and SQL. I have been trying to move data from Kirbybase table to a Gadfly table and cannot get it to work. Win XP with python 2.4, Kirbase 1.9, Gadfly B5. Complete script shown here, with python traceback. # get global modules for python import os import sys #get database manager module from kirbybase import KirbyBase, KBError # open a database, embedded db = KirbyBase() result=db.select('test2.tbl', ['recno'],['*'], returnType='object') # open Gadfly database for storing data import gadfly connection = gadfly.gadfly() connection.startup("subscription", "pvfd_sql") cursor = connection.cursor() # Insert all records into SQL Database for record in result: sql="INSERT INTO addresslist (lastname, firstname, address, city, state, zip_code, phone) VALUES(?, ?, ?, ?, ?, ?, ?)" cursor.execute(sql,result) connection.commit() connection.close #------------------------------------------------------------------------------ # End of Script #------------------------------------------------------------------------------ Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. **************************************************************** Personal firewall software may warn about the connection IDLE makes to its subprocess using this computer's internal loopback interface. This connection is not visible on any external interface and no data is sent to or received from the Internet. **************************************************************** IDLE 1.1.2 ==== No Subprocess ==== >>> Traceback (most recent call last): File "C:\Documents and Settings\timothy volner\Desktop\puryear\move records to sql.py", line 30, in ? cursor.execute(sql,result) File "C:\Python24\lib\site-packages\gadfly\database.py", line 367, in execute cs[i] = cs[i].relbind(database) File "C:\Python24\lib\site-packages\gadfly\operations.py", line 601, in relbind target = self.target = db.get_for_update(name) File "C:\Python24\lib\site-packages\gadfly\store.py", line 201, in get_for_update test = rels[name] File "C:\Python24\lib\site-packages\gadfly\store.py", line 1043, in __getitem__ return self.shadow[key] KeyError: 'ADDRESSLIST' >>> No matter what I do to data, I always end up with this error. From fredrik at pythonware.com Tue Apr 18 03:43:15 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 18 Apr 2006 09:43:15 +0200 Subject: scanning through page and replacing all instances of 00:00:00.00 References: <17476.15332.903041.937401@montanaro.dyndns.org> Message-ID: skip at pobox.com wrote: > > Kun> assuming that my date column is 2, how would i parse out the date? > > No parsing required. Just get its date: > > d = record[2].date() > > The str() of a datetime.date object is a string in YYYY-MM-DD form. or, in other words, change: for col in range(0, numcols): print "", record[col], "" to # convert to list, so we can replace columns, if needed record = list(record) # fix the date column record[2] = record[2].date() # add other fixups here # print it out for col in range(0, numcols): print "", record[col], "" the last two lines are of course better written as for col in record: print "", col, "" From rcs at bgoark.no Sat Apr 8 19:26:46 2006 From: rcs at bgoark.no (baalbek) Date: Sun, 09 Apr 2006 01:26:46 +0200 Subject: Tkinter In-Reply-To: <1144538582.829134.82040@e56g2000cwe.googlegroups.com> References: <1144538582.829134.82040@e56g2000cwe.googlegroups.com> Message-ID: <44384715$0$22981$c83e3ef6@nn1-read.tele2.net> Excuse me for being slightly off-topic, but why not using wxPython (www.wxpython.org)? Baalbek From david at boddie.org.uk Wed Apr 5 09:55:11 2006 From: david at boddie.org.uk (David Boddie) Date: 5 Apr 2006 06:55:11 -0700 Subject: How to copy the content of a QPopupMenu ? In-Reply-To: <1144244508.239528.103020@z34g2000cwc.googlegroups.com> References: <1144237849.881072.220870@i40g2000cwc.googlegroups.com> <49hruqFoguidU1@uni-berlin.de> <1144241351.777589.161490@i40g2000cwc.googlegroups.com> <1144244508.239528.103020@z34g2000cwc.googlegroups.com> Message-ID: <1144245311.820807.251120@v46g2000cwv.googlegroups.com> Well, the Google web interface didn't quite work as expected there. Here's a version of the previous message containing just my advice. You might want to use QAction to define individual items that can be activated. That way you can just reuse the same actions in both menus or move them from one to another. Submenus will probably take more effort to move. In some ways, it might be useful to keep some sort of data structure around that you can use as a template for the menu, and regenerate the menu from that. Aside: The Qt 4 action system probably makes it a lot easier to do what you're trying to do, though that's not a lot of help if your project is based on Qt 3. :-/ From benchline at gmail.com Fri Apr 7 12:57:16 2006 From: benchline at gmail.com (benchline) Date: 7 Apr 2006 09:57:16 -0700 Subject: Jpype on RHEL v3 Message-ID: <1144429036.857542.290470@u72g2000cwu.googlegroups.com> I have been trying out jpype for python to java work and love it. It works great on my gentoo box with the java 1.4.2 blackdown sdk. I am now trying it on Red Hat Enterprise Linux 3 for access to business intelligence tools (JasperReports, Mondrian, Pentaho, etc) for which we don't have analogous tools in cpython yet. My idea it to use jpype in a cherrypy application server to tie these java BI tools into a website interface without having to delve into the more complex java J2EE application servers and lose all the python libraries that I know and love. Here is my problem. When trying to start the jvm with the sun jre I get this error. [root at servername root]# python2.4 Python 2.4.2 (#1, Dec 1 2005, 05:44:04) [GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-53)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import jpype >>> jpype.startJVM('/usr/lib/jvm/java-1.4.2-sun/jre/lib/i386/client/libjvm.so') Error occurred during initialization of VM Unable to load native library: libjvm.so: cannot open shared object file: No such file or directory and then python dies. When I try to start the jvm with the ibm jre I get this error. [root at servername root]# python2.4 Python 2.4.2 (#1, Dec 1 2005, 05:44:04) [GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-53)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import jpype >>> jpype.startJVM('/usr/lib/jvm/java-1.4.2-ibm-1.4.2.2/jre/bin/classic/libjvm.so') Unable to find UTE, path used libjava.so/libute.so JVMCI170: Please check the path to shared libraries Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.4/site-packages/jpype/_core.py", line 25, in startJVM _jpype.startup(jvm, tuple(args), True) RuntimeError: Unable to start JVM at src/native/common/jp_env.cpp:54 but the python interpreter is still running. Can anyone point me in the right direction so I can fix this? Thanks From onurb at xiludom.gro Wed Apr 12 07:10:55 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 12 Apr 2006 13:10:55 +0200 Subject: About classes and OOP in Python In-Reply-To: References: <1144678797.749000.155010@t31g2000cwb.googlegroups.com> <1144743716.408970.23840@z34g2000cwc.googlegroups.com> <00rn321nv3oqbjesmqpdl4p0s3tgdj7o2f@4ax.com> Message-ID: <443ce08a$0$13216$626a54ce@news.free.fr> Gregor Horvath wrote: > Steven D'Aprano schrieb: > > >>I don't know of many other OO languages that didn't/don't have >>inheritance, > > > VB4 - VB6 > VB6 has a kind of inheritance via interface/delegation. The interface part is for subtyping, the delegation part (which has to be done manually - yuck) is for implementation inheritance. Needless to say it's a king-size PITA... -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From grante at visi.com Fri Apr 21 19:06:05 2006 From: grante at visi.com (Grant Edwards) Date: Fri, 21 Apr 2006 23:06:05 -0000 Subject: proposed Python logo References: <1145585399.871299.31900@t31g2000cwb.googlegroups.com> <1145628079.749480.191190@g10g2000cwb.googlegroups.com> <124hqel51rur33b@corp.supernews.com> <1145640106.269556.276060@u72g2000cwu.googlegroups.com> <124i8176of81331@corp.supernews.com> <1145659600.115550.270520@e56g2000cwe.googlegroups.com> Message-ID: <124ipatre42p77a@corp.supernews.com> On 2006-04-21, Michael Tobis wrote: > This http://www.informatik.uni-trier.de/~roth/bilder/mpfc/GUMBY3.JPG > chap? > > I'm not sure that conveys the intended gravitas to the > corporate community, though. Monty Python never was very big on "corporate community gravitas", so that's probably going to be a persistent problem should one try to find a Monty Pythonesque logo. -- Grant Edwards grante Yow! Do I have a lifestyle at yet? visi.com From steve at REMOVETHIScyber.com.au Wed Apr 12 19:23:08 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Thu, 13 Apr 2006 09:23:08 +1000 Subject: list.clear() missing?!? References: <1144767680.583085.310160@v46g2000cwv.googlegroups.com> <1144870852.886477.238570@u72g2000cwu.googlegroups.com> Message-ID: On Wed, 12 Apr 2006 15:36:47 -0700, Alan Morgan wrote: > Serious question: Should it work more like "s=[]" or more like > "s[:]=[]". I'm assuming the latter, but the fact that there is > a difference is an argument for not hiding this operation behind > some syntactic sugar. Er, I don't see how it can possibly work like s = []. That merely reassigns a new empty list to the name s, it doesn't touch the existing list (which may or may not be garbage collected soon/immediately afterwards). As far as I know, it is impossible -- or at least very hard -- for an object to know which namesspaces it is in, so it can reassign one name but not the others. Even if such a thing was possible, I think it is an absolutely bad idea. -- Steven. From hnt20 at msn.com Sat Apr 15 15:25:30 2006 From: hnt20 at msn.com (HNT20) Date: Sat, 15 Apr 2006 19:25:30 GMT Subject: How to Convert a string into binary Message-ID: Hello All i am new to python language. i am working on a gnuradio project where it uses python as the primary programming language. i am trying to convert a message, text, or numbers into binary code so that i can process it. i googled many times and tried many of the answers out there, no luck so far. is there a way to convert a string into its binary representation of the ascii table.?? an example of what i want would be: hi --> 0110100001101001 Thanks -HNT From j.spies at hccnet.nl Mon Apr 17 14:38:18 2006 From: j.spies at hccnet.nl (Jaap Spies) Date: Mon, 17 Apr 2006 20:38:18 +0200 Subject: socket timeout error? Message-ID: Hi, Running Fedora Core 4: Python 2.4.3 and Python 2.4.1. I'm getting: IOError: [Errno socket error] (2, 'No such file or directory') all the time. Trying to track down this problem: Python 2.4.1 (#1, May 16 2005, 15:19:29) [GCC 4.0.0 20050512 (Red Hat 4.0.0-5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import socket >>> socket.getdefaulttimeout() >>> import urllib >>> urllib.urlopen('http://www.python.org') Traceback (most recent call last): File "", line 1, in ? File "urllib.py", line 77, in urlopen return opener.open(url) File "urllib.py", line 180, in open return getattr(self, name)(url) File "urllib.py", line 296, in open_http h.endheaders() File "/usr/lib/python2.4/httplib.py", line 794, in endheaders self._send_output() File "/usr/lib/python2.4/httplib.py", line 675, in _send_output self.send(msg) File "/usr/lib/python2.4/httplib.py", line 642, in send self.connect() File "/usr/lib/python2.4/httplib.py", line 610, in connect socket.SOCK_STREAM): IOError: [Errno socket error] (2, 'No such file or directory') >>> socket.setdefaulttimeout(0.1) >>> socket.getdefaulttimeout() 0.10000000000000001 >>> urllib.urlopen('http://www.python.org') >>>> socket.setdefaulttimeout(0.01) >>> urllib.urlopen('http://www.python.org') Traceback (most recent call last): File "", line 1, in ? File "urllib.py", line 77, in urlopen return opener.open(url) File "urllib.py", line 180, in open return getattr(self, name)(url) File "urllib.py", line 296, in open_http h.endheaders() File "/usr/lib/python2.4/httplib.py", line 794, in endheaders self._send_output() File "/usr/lib/python2.4/httplib.py", line 675, in _send_output self.send(msg) File "/usr/lib/python2.4/httplib.py", line 642, in send self.connect() File "/usr/lib/python2.4/httplib.py", line 626, in connect raise socket.error, msg IOError: [Errno socket error] timed out >>> socket.setdefaulttimeout(0.05) >>> urllib.urlopen('http://www.python.org') >>>> Seems a timeout of 0.01 is to small and a timeout >= 0.05 is working. What is the real problem here? Jaap From jbamsterdam at gmail.com Tue Apr 18 15:35:59 2006 From: jbamsterdam at gmail.com (Jonathan Amsterdam) Date: 18 Apr 2006 12:35:59 -0700 Subject: Queue can result in nested monitor deadlock In-Reply-To: <2ht842lakluo2gmorqncrtcd4shjngdvd8@4ax.com> References: <1145284326.177062.230120@v46g2000cwv.googlegroups.com> <1145292096.906390.254280@e56g2000cwe.googlegroups.com> <1145306244.336966.113470@e56g2000cwe.googlegroups.com> <2ht842lakluo2gmorqncrtcd4shjngdvd8@4ax.com> Message-ID: <1145388959.865294.183820@j33g2000cwa.googlegroups.com> No redesign necessary. I simply make M be the Queue's mutex, via the LQueue class I posted. I am making the modest suggestion that this feature be documented and exposed in the Queue class. From onurb at xiludom.gro Thu Apr 27 15:13:29 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 27 Apr 2006 21:13:29 +0200 Subject: OOP techniques in Python In-Reply-To: <1146158190.320947.108480@t31g2000cwb.googlegroups.com> References: <1146158190.320947.108480@t31g2000cwb.googlegroups.com> Message-ID: <44511831$0$18264$636a55ce@news.free.fr> Panos Laganakos wrote: > I've been thinking if there's a point in applying some specific OOP > techniques in Python as we do in other languages. Yes - but some of these techniques are somewhat python-specific. > i.e. we usually define private properties and provide public functions > to access them, in the form of: > get { ... } set { ... } > > Should we do the same in Python: No. > > Or there's no point in doing so? Absolutely. Python has descriptors and properties, which allow you to switch from a direct attribute access to a computed attributes without breaking the API. In fact, think of public attributes as automatic getter/setters pairs, that you can customize when needed !-) > Some other techniques come to mind, but I think that Python tends to > allow the programmer to access stuff he wants even though he shouldn't s/he shouldn't/he knows he's messing with implementation details and assume the consequences. FWIW, accessing 'private' attributes in Java or C++ is not a big deal. > or in the form of a dict or list, rather than a method to do so. Python is *object* oriented - not class-oriented - and doesn't force you to put everything into a class definition. Now everything in Python is an object (including functions and classes and modules...). This is a much less restricted (and IMHO much much more powerful) approach than what you may learn from Java, C++, C# etc. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From nashborges at gmail.com Sun Apr 16 10:37:26 2006 From: nashborges at gmail.com (AgenteSegreto) Date: 16 Apr 2006 07:37:26 -0700 Subject: Calling Python from Matlab In-Reply-To: <1145142008.801960.49110@t31g2000cwb.googlegroups.com> References: <1145142008.801960.49110@t31g2000cwb.googlegroups.com> Message-ID: <1145198246.653664.106540@e56g2000cwe.googlegroups.com> I've been a Matlab user for years and have recently started using Python with matplotlib and NumPy for most of my work. The only thing I found that is still lacking is a 3D capability in matplotlib. I was trying to visualize a hill climbing algorithm and I couldn't find anything comparable to Matlab's 'surface', 'mesh', or 'plot3'. I think VTK would have done the trick but there's only so much time in the day... From mwilson-to at sympatico.ca Fri Apr 21 22:52:20 2006 From: mwilson-to at sympatico.ca (Mel Wilson) Date: Fri, 21 Apr 2006 22:52:20 -0400 Subject: Generate a sequence of random numbers that sum up to 1? In-Reply-To: References: Message-ID: <5Wg2g.9024$wK1.505731@news20.bellglobal.com> Anthony Liu wrote: > I am at my wit's end. > > I want to generate a certain number of random numbers. > This is easy, I can repeatedly do uniform(0, 1) for > example. > > But, I want the random numbers just generated sum up > to 1 . > > I am not sure how to do this. Any idea? Thanks. numbers.append (random.uniform (0, 1.0-sum(numbers))) might help, perhaps. or scaled = [x/sum(numbers) for x in numbers] Mel. > From bogus at example.com Wed Apr 26 19:34:35 2006 From: bogus at example.com (Bo Gus) Date: Wed, 26 Apr 2006 16:34:35 -0700 Subject: Building a Dynamic Library (libpython.so) for Python 2.4.3 Final References: <6ABE4DBF-4B1F-4351-8B38-1EC3817C3913%notme@bogus.example.com> Message-ID: In article , Andrew MacIntyre wrote: > Dean wrote: > > I've been trying to make python a dynamic library. I downloaded Python > > 2.4.3 Final from the Python web site and I cannot get it to create the > > library. > > > > I've tried using the directive: > > > > --enable-shared > > > > and > > > > --enable-shared=yes > > > > and both of them had the same effect of creating a bunch of parts of > > the python interpreter in .so format but not in creating a single > > libpython2.4.so.X.Y file. I could probably hack something together > > using ar but I would prefer to do it "correctly" by setting some > > options. I'm compiling under OpenBSD 3.5. > > Well, I just confirmed that > > ./configure --enable-shared > > results in a libpython2.4.so.1 (and a libpython2.4.so) on FreeBSD 4.x. > The result runs the regression test suite without significant problems > (the test box didn't have a 2.4 installation). > > A quick look at the configure script suggests that --enable-shared should > work on OpenBSD. While I believe that there's actually an OpenBSD based > Python buildbot (though OpenBSD 3.[89] I think) running, I doubt that > this configuration is tested there. > > If you don't get any other responses, send me a copy of the full make log > (ie "make >make.log 2>&1") and I'll compare it to the log from my test > build. Thanks for the help. It didn't build the shared library on its own but I did manage to find where it is built and a simple make libpython2.4.so Got it built for me. Thanks for the idea! Dean From eligottlieb at gmail.com Wed Apr 26 11:51:28 2006 From: eligottlieb at gmail.com (Eli Gottlieb) Date: Wed, 26 Apr 2006 15:51:28 GMT Subject: Xah's Edu Corner: Criticism vs Constructive Criticism In-Reply-To: <1145992903.834316.198370@u72g2000cwu.googlegroups.com> References: <1145992903.834316.198370@u72g2000cwu.googlegroups.com> Message-ID: <4GM3g.3084$TT.1768@twister.nyroc.rr.com> Xah Lee wrote: > Criticism versus Constructive Criticism > > Xah Lee, 2003-01 > > A lot intelligent people are rather confused about criticism, > especially in our ?free-speech? free-for-all internet age. When > they say ?constructive criticisms are welcome? they mostly mean > ?bitching and complaints not welcome?. Rarely do people actually > mean that ?criticism without suggestion of possible solutions are not > welcome? or ?impolite criticism not welcome?. > > Such discernment is important. Wanton bitching as internet-using geeks > are used to is not criticism is any form. > > People can be respected and make a living out of criticisms, called > critics, but not bitching. And when one really value opinions, you > often want criticism without qualifications. Just be happy that > valuable criticisms may come to you free from the experts in the > public. The instant you qualify what kind of feedback are welcome, your > feedback is compromised. (this is particularly so for political or > controversial subjects) > > One easy way for many of the unix geeks to understand this is the > cryptology industry. > > If one really desires valuable criticisms that is polite or with > solutions or ?constructive? (whatever that means), one usually have > to pay. > ---- > This post is archived at: > http://xahlee.org/UnixResource_dir/writ/criticism.html > > Xah > xah at xahlee.org > ? http://xahlee.org/ > Oh, God, not another one. -- The science of economics is the cleverest proof of free will yet constructed. From Vijairaj.R at gmail.com Mon Apr 3 03:19:11 2006 From: Vijairaj.R at gmail.com (Vijairaj) Date: 3 Apr 2006 00:19:11 -0700 Subject: Getting a list of all classes derived from a base class In-Reply-To: <1hd6v7k.15gbqp4b4sh9iN%aleaxit@yahoo.com> References: <1144039905.692207.8790@g10g2000cwb.googlegroups.com> <1hd6v7k.15gbqp4b4sh9iN%aleaxit@yahoo.com> Message-ID: <1144048750.977970.221610@e56g2000cwe.googlegroups.com> Thanks Dylan and Alex, that was a new learning for me. but both the solutions don't work in jython 2.1 is there an alternative that will work with jython2.1 -- Thanks, Vijairaj From m.yanowitz at kearfott.com Thu Apr 6 08:54:16 2006 From: m.yanowitz at kearfott.com (Michael Yanowitz) Date: Thu, 6 Apr 2006 08:54:16 -0400 Subject: "The World's Most Maintainable Programming Language" In-Reply-To: Message-ID: -----Original Message----- From: python-list-bounces+m.yanowitz=kearfott.com at python.org [mailto:python-list-bounces+m.yanowitz=kearfott.com at python.org]On Behalf Of Peter Hansen Sent: Thursday, April 06, 2006 8:47 AM To: python-list at python.org Subject: Re: "The World's Most Maintainable Programming Language" Mirco Wahab wrote: > Hi Ralf >>So we should rename Python into Cottonmouth >>to get more attention. > > No, always take some word that relates to > something more or less 'feminine', its about > 96% of young males who sit hours on programming > over their beloved 'languages' ;-) > > Pythia? (http://en.wikipedia.org/wiki/Pythia) I guess that would make our motto "Pythia: now you're programming with ethylene." -Peter At-least Pythetic isn't a word (yet). From http Sat Apr 8 23:30:25 2006 From: http (Paul Rubin) Date: 08 Apr 2006 20:30:25 -0700 Subject: programming puzzles? References: <44381f2f$0$4209$c3e8da3@news.astraweb.com> <1144532090.213069.191600@i39g2000cwa.googlegroups.com> <4438428e$0$11362$c3e8da3@news.astraweb.com> <1144543413.421821.132730@e56g2000cwe.googlegroups.com> Message-ID: <7xpsjrwhm6.fsf@ruckus.brouhaha.com> "Michael Tobis" writes: > The first piece of code that I ever voluntarily wrote was intended to > solve this puzzle: > > Assign the number 2 to 'a', 3 to 'b' ... 27 to 'z'. To each word assign > the value of the product of its characters. Find the English (or > language of your choice) word whose product is closest to a million (or > number of your choice). Hey, that was a contest in Games Magazine in the 1980's. A co-worker and I used a PDP-10 BASIC program to search for numbers near 1 million with no prime factors higher than 27. The factorizations of those numbers told us which letters to try to use, and after a while of fooling around rearranging letters on a whiteboard, we came up with "curvy", a very recognizable word that multiplies out to 999,856. That's the closest number to 1 million (other than 1 million itself) which doesn't have any prime factors that are too large. We convinced ourselves that there was no word that multiplied to exactly 1 million, so we felt we were likely to win the contest. However, somebody apparently with a computerized word list won with "ixodid". It was fun to remember this. From jon+usenet at unequivocal.co.uk Tue Apr 18 14:51:24 2006 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: 18 Apr 2006 18:51:24 GMT Subject: 2.5 excitement (was Re: Java Developer Exploring Python) References: <1145290449.735642.120860@i40g2000cwc.googlegroups.com> <1204021.LzRF60KP7e@jupiter.g2ctech> Message-ID: In article , Aahz wrote: > On that front, I think that pysqlite is much more important because > it finally gets rid of the excuse for using Berkeley for simple > database purposes. Apologies if I'm being obtuse, but how does including the pysqlite wrapper module change anything? You still need to download and install SQLite, so what's the point of including a wrapper for something you may or may not have? Why is pysqlite included, for example, and not MySQL-Python or postgresql or whatever? From do_not_use_this_email at hotmail.com Wed Apr 19 12:37:31 2006 From: do_not_use_this_email at hotmail.com (rx) Date: Wed, 19 Apr 2006 18:37:31 +0200 Subject: extracting a substring References: <1145406353.280681.134630@t31g2000cwb.googlegroups.com> Message-ID: <4446676d$0$9303$ba624c82@nntp02.dk.telia.net> > and I want to extract the numbers 531, 2285, ...,359. > > One thing for sure is that these numbers are the ONLY part that is > changing; all the other characters are always fixed. > I'm not sure about what you mean by "always fixed" but I guess it means that you have n files with a fixed start and a changing ending, and m files with a fixed start and a changing ending, .... import re filenames=['ac99_124.txt', 'ac99_344.txt', 'ac99_445.txt'] numbers=[] for i in filenames: numbers.append(int(re.compile('[^_]*_(?P[^.]*).txt').match(i).group('number'))) this sets numbers to: [124, 344, 445] From fredrik at pythonware.com Fri Apr 7 02:34:38 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 7 Apr 2006 08:34:38 +0200 Subject: Simple string formatting question References: <4434DCEC.4080308@REMOVEMEcyber.com.au> Message-ID: Paul McGuire wrote: > Ooops, don't combine the two calls to rstrip(). > > def format(f, width=3): return ("%.*f" % (width, f)).rstrip(".0") > > print format(3.140) > print format(3.000) > print format(3.0000001) > print format(30.0000) > print format(300000.000) hey, I'm doing test-driven development. being able to handle 30 and 300000 wasn't part of the original spec ;-) > But this works fine: > def format(f, width=3): return ("%.*f" % (width, f)).rstrip("0").rstrip(".") indeed. From paul at boddie.org.uk Mon Apr 3 12:37:27 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 3 Apr 2006 09:37:27 -0700 Subject: Convertion of Unicode to ASCII NIGHTMARE References: <1144079830.734516.8390@z34g2000cwc.googlegroups.com> <1144081137.137744.253790@i39g2000cwa.googlegroups.com> Message-ID: <1144082247.387641.24360@i39g2000cwa.googlegroups.com> Oh, and it occurs to me, as I seem to have mentioned a document about PgSQL rather than pysqlite (although they both have the same principal developer), that you might need to investigate the client_encoding parameter when setting up your connection. The following message gives some information (but not much): http://groups.google.com/group/comp.lang.python/msg/f27fa9866c9b7b5f Sadly, I can't find the information about getting result values as Unicode objects, but I believe it involves some kind of SQL comment that you send to the database system which actually tells pysqlite to change its behaviour. Paul From http Sat Apr 1 22:09:24 2006 From: http (Paul Rubin) Date: 01 Apr 2006 19:09:24 -0800 Subject: Should any() and all() take a key= argument? References: Message-ID: <7x1wwgsmfv.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > >> any(map(lambda x: x==42, lst)) > ... > In any case, I question your assumption that the version using map must > automatically "waste memory". There's also always itertools.imap. > But then, unless these are big complex objects, why are we > micro-optimizing our code anyway? I'm running a Python process, and > it is consuming 6.7MB of memory at the moment. Do I really care about > saving 80 or 100 bytes?, or even 100 kilobytes? I don't think so. The idea is to write code to be assumption-free when possible. A general purpose library function should work efficiently on big complex objects even if some specific application might use it only for small objects. Similarly, application programs that will stay in use for a while should be written to be able to handle large workloads even if the initial requirements are small, unless significant extra development effort is needed. From reply.in.the.newsgroup at my.address.is.invalid Tue Apr 25 14:47:21 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Tue, 25 Apr 2006 20:47:21 +0200 Subject: Zope 3 References: <1145965796.432891.274310@i39g2000cwa.googlegroups.com> <444e3cf6$0$401$626a54ce@news.free.fr> Message-ID: Steve Juranich: >is there some big master diff, along the lines of "What's new >in Python X.X" that I could look at to get an idea of what z3 has that 2.9 >(which I'm currently still cutting my teeth on) doesn't? It's a redesign. Z2: mixin base classes Z3: component architecture with interfaces >Where are the Zope3 docs? Google! -- Ren? Pijlman From flamesrock at gmail.com Thu Apr 6 00:59:31 2006 From: flamesrock at gmail.com (flamesrock) Date: 5 Apr 2006 21:59:31 -0700 Subject: XMLRPCLIB appears to be broken? Message-ID: <1144299571.452329.310640@j33g2000cwa.googlegroups.com> Hi, I'm running xmlrpclib on python 2.4.2. The problem: When I pass arguments via xmlrpclib, it passes the args as a list to the first variable. Take this example (function should return second of two arguments, but always returns '') >>server = xmlrpclib.ServerProxy('http://simcitysphere.com/simnettest/simnet_XMLRPC.php') >>server.simnet.createDB('firstparam','secondparam') '' >> Here is the php server code: function createDB($firstparam,$secondparam) { return $secondparam; } If I change the function to return $firstparam, the first argument, it returns: ['firstparam', 'secondparam'] So.. why the heck is it doing this???? Clearly it's pythons fault, but 1)why? 2)how do I fix it? -Thanks in Advance. From fredrik at pythonware.com Wed Apr 26 09:58:13 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 26 Apr 2006 15:58:13 +0200 Subject: MinGW and Python References: <1145861223.509630.247350@y43g2000cwc.googlegroups.com><444C79D7.4060007@v.loewis.de><1145968496.649214.100040@i40g2000cwc.googlegroups.com><1hec9xh.m7rzefh64am3N%aleaxit@yahoo.com> Message-ID: Neal Becker wrote: >> What I did just post on another thread over the last couple of days is >> about MacOSX, which also uses gcc: 14% faster pybench using Python 2.4.3 >> under Win2000 under Parallels Workstation beta, compared to 2.4.3 >> Universal directly on MacOSX -- the standard build of 2.4.3 in either >> cause, i.e., the one built with MS compilers on Windows, vs the one >> built with Apple's gcc on MacOSX. > Please when quoting such benchmarks include gcc version. gcc >= 4.1 is > supposed to have a lot of performance improvements. This is the current > release. Since mingw is usually current, I haven't checked, but they may > be using 4.1 now. what part of "the standard build of 2.4.3 in either case" do you have trouble understanding ? (what makes you think that 2.4.3 for windows is compiled with the best possible compiler for the windows environment?) From brandon.mcginty at gmail.com Sat Apr 1 15:49:27 2006 From: brandon.mcginty at gmail.com (brandon.mcginty at gmail.com) Date: Sat, 1 Apr 2006 13:49:27 -0700 Subject: Python-implimenting-valueweb Message-ID: <008501c655cd$c540e920$6400a8c0@D1FWTS61> Hi All, I hope this post is acceptable on this list. I'm wondering if anyone here has experience using python on a web server? Specifically, has anyone used python on value web's servers? If anyone has any info, general or specific, please let me know. All help is appreciated. Sincerely, Brandon mcginty ---------- Feel free to contact me for technical support, or just to chat; I always have time to talk and help, and an open ear. Email:Brandon.mcginty at gmail.com Skype:brandon.mcginty Msn:brandon_mcginty at hotmail.com Aim:brandonmcginty (Not currently available.) Cell:4802025790 (Weekends and nights only, please.) "Kindness is a language that the deaf can hear and the blind can see." Mark Twain -- No virus found in this outgoing message. Checked by AVG Free Edition. Version: 7.1.385 / Virus Database: 268.3.4/299 - Release Date: 3/31/2006 From kinsman at nbnet.nb.ca Wed Apr 19 18:18:08 2006 From: kinsman at nbnet.nb.ca (Sean Givan) Date: Wed, 19 Apr 2006 22:18:08 GMT Subject: Confused by Python and nested scoping (2.4.3) Message-ID: Hi. I'm new to Python, and downloaded a Windows copy a little while ago. I was doing some experiments with nested functions, and ran into something strange. This code: def outer(): val = 10 def inner(): print val inner() outer() ..prints out the value '10', which is what I was expecting. But this code.. def outer(): val = 10 def inner(): print val val = 20 inner() print val outer() ..I expected to print '10', then '20', but instead got an error: print val UnboundLocalError: local variable 'val' referenced before assignment. I'm thinking this is some bug where the interpreter is getting ahead of itself, spotting the 'val = 20' line and warning me about something that doesn't need warning. Or am I doing something wrong? Thanks, -Sean Givan From durumdara at gmail.com Thu Apr 20 10:13:23 2006 From: durumdara at gmail.com (DurumDara) Date: Thu, 20 Apr 2006 16:13:23 +0200 Subject: DB Interface for SQLite Message-ID: <44479703.2090207@gmail.com> Hi ! I develop some tools for better/easier usage of SQLite wrapper(s). It have two parts: 1.) Custom interface with common methods. 2.) APSW oriented class. The codes are abs. free, no copyright, licence is freeware. Use them as you need. I publish them, because I does not found same thing in net, and I want to avoid to other programmers create them painfully... I hope this is "usable" for anothers. dd -------------- next part -------------- A non-text attachment was scrubbed... Name: dbif_apsw.py Type: application/x-python Size: 2831 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: dbiface.py Type: application/x-python Size: 6092 bytes Desc: not available URL: From bearophileHUGS at lycos.com Sat Apr 22 16:58:37 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 22 Apr 2006 13:58:37 -0700 Subject: list example References: <1145737240.221433.176160@i40g2000cwc.googlegroups.com> Message-ID: <1145739517.262424.40980@i39g2000cwa.googlegroups.com> PAolo>any comment, suggestion? Is there something not elegant?< Here you can see many little differences, some of them reflect just my style, but some other of them are Python standard style guidelines: even = [] odd = [] for i in xrange(1, 10): if i % 2: odd.append(i) else: even.append(i) print "Odd:", odd print "Even:", even numbers = even + odd print "Numbers:", numbers numbers.sort() print "Sorted numbers:", numbers There are surely more compact versions of that, but compactness is usually less important than clarity, expecially for someone that is learning Python. This is a more compact version (with the suggestion by Wojciech Mula, modified in two ways): even = range(1, 10)[1::2] odd = range(1, 10)[0::2] print "Odd:", odd print "Even:", even numbers = even + odd print "Numbers:", numbers print "Sorted numbers:", sorted(numbers) Bye, bearophile From rainbow.cougar at gmail.com Fri Apr 7 01:47:50 2006 From: rainbow.cougar at gmail.com (rainbow.cougar at gmail.com) Date: 6 Apr 2006 22:47:50 -0700 Subject: my vote for handy python system admin tool Message-ID: <1144388870.030271.13270@t31g2000cwb.googlegroups.com> denyhosts denyhosts.sourceforge.net I used it at a recent contract sys. admin job, and found it so handy I installed it on my home gateway FreeBSD box. It ROCKS!!! I watch the system logs just to snicker when it stops a sshd attack dead in its tracks ;-0 Curtis From fredrik at pythonware.com Wed Apr 19 13:24:08 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 19 Apr 2006 19:24:08 +0200 Subject: += append class operator References: <1145466931.858338.162110@z34g2000cwc.googlegroups.com> Message-ID: schwehr at gmail.com wrote: > This is probably a FAQ, but is there an operator mapping for += for > classes? obj.__iadd__(other) > Or does a += b get converted to a = a + b? only if __iadd__ is not defined. > I would like to make this operator faster for the BitVector class, but > I don't see += in http://docs.python.org/lib/operator-map.html that's documentation for the operator module. special method names are described in the language reference: http://docs.python.org/ref/specialnames.html http://docs.python.org/ref/numeric-types.html From steve at REMOVETHIScyber.com.au Wed Apr 12 01:19:17 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Wed, 12 Apr 2006 15:19:17 +1000 Subject: How can I determine the property attributes on a class or instance? References: <1144807906.646773.279510@i40g2000cwc.googlegroups.com> Message-ID: On Tue, 11 Apr 2006 19:11:46 -0700, mrdylan wrote: > Given a class like so: > > ------------------------------- > class TestMe(object): > def get(self): > pass > def set(self, v): > pass > > p = property( get, set ) > > t = TestMe() > type(t.p) #returns NoneType, what??? t.p calls t.get() which returns None. So t.p is None, and type(t.p) is NoneType. > t.p.__str__ #returns > ----------------------------------- > > What is the best way to determine that the attribute t.p is actually a > property object? Obviously I can test the __str__ or __repr__ > attributes using substring comparison but there must be a more elegant > idiom. If you want a general purpose solution for an object introspection tool, I must admit I'm as lost as you are. The only thing I have come up with is this nasty hack: >>> t.p is None True >>> dir(t.p) is dir(None) False >>> for attr in dir(None): ... print attr, getattr(None, attr) is getattr(t.p, attr) ... __class__ True __delattr__ False __doc__ True __getattribute__ False __hash__ False __init__ False __new__ True __reduce__ False __reduce_ex__ False __repr__ False __setattr__ False __str__ False I don't even know if this hack generalises to any values of p, and I suspect it isn't of practical use. Why do you want to know if p is a property? -- Steven. From skip at pobox.com Tue Apr 18 17:25:52 2006 From: skip at pobox.com (skip at pobox.com) Date: Tue, 18 Apr 2006 16:25:52 -0500 Subject: Better way to sift parts of URL . . . In-Reply-To: <1145392079.720766.122310@z34g2000cwc.googlegroups.com> References: <1145392079.720766.122310@z34g2000cwc.googlegroups.com> Message-ID: <17477.22880.625171.810170@montanaro.dyndns.org> Ben> I am working on a script that splits a URL into a page and a Ben> url. I couldn't tell quite what you mean to accomplish from your example. (In particular, I don't know what you mean by "default_group", as it's never defined, and I don't know why the desired output of examples 1 and 6 is the same, since the URLs are clearly different.) You don't mention having tried the urlparse module, so I thought I should ask: have you tried using urlparse? Skip From Kyler at news.Lairds.org Mon Apr 24 23:17:03 2006 From: Kyler at news.Lairds.org (Kyler Laird) Date: Tue, 25 Apr 2006 03:17:03 GMT Subject: Simple DAV server? References: Message-ID: <1fg0i3-7pc.ln1@snout.lairds.com> robert writes: >KL wrote, he added some more capabs. I'd need MOVE and saw PUT has bugs >to also not respect URL-quoted folders/elements (with spaces, utf-8 etc.) I've got MOVE working and I took care of the percent-escaped filenames but UTF-8 stuff is still giving me problems. (I've been testing with Litmus.) I don't recommend it but here's a preview of my simple additions. http://lairds.us/temp/Pandav.tar.bz2 Ivan's been working on a problem I've been experiencing with Windows XP ("failure to launch"). He sent a new version my way today. I'm going to test it tomorrow when I've got some XP users available. If it works I'm going to work on putting my changes into a subclass. I don't see this being a full-featured fully-compliant DAV server immediately but I'm betting that it will provide adequate service for my users soon. --kyler From john at castleamber.com Fri Apr 28 13:54:09 2006 From: john at castleamber.com (John Bokma) Date: 28 Apr 2006 17:54:09 GMT Subject: No subject References: <1145992903.834316.198370@u72g2000cwu.googlegroups.com> <4GM3g.3084$TT.1768@twister.nyroc.rr.com> <1146231280.733609.143230@e56g2000cwe.googlegroups.com> <4452258e$0$655$bed64819@news.gradwell.net> <1146235544.218219.71430@j73g2000cwa.googlegroups.com> <87psj1ionl.fsf@rpi.edu> Message-ID: Bill Atkins wrote: > John Bokma writes: >> >> Isn't it crazy that one person is allowed to create such a huge mess >> everytime he posts? > > Isn't it crazy that one person willfully creates such a mess every > time Xah posts? Shush! Since you're posting from an edu tld, why are you wasting time and money instead of getting educated? It might stop you from acting like an idiot like you did just now. -- John MexIT: http://johnbokma.com/mexit/ personal page: http://johnbokma.com/ Experienced programmer available: http://castleamber.com/ Happy Customers: http://castleamber.com/testimonials.html From jjl at pobox.com Thu Apr 20 15:13:27 2006 From: jjl at pobox.com (John J. Lee) Date: 20 Apr 2006 19:13:27 +0000 Subject: send cookie on request with urllib2 References: <1145539129.322307.77220@z34g2000cwc.googlegroups.com> Message-ID: <877j5kxdpk.fsf@pobox.com> "itay_k" writes: > Hi, > > I dont understand why this is so complicated, just to add one line of > cookie header on the GET request. You haven't said what you're really trying to do. http://www.catb.org/~esr/faqs/smart-questions.html#goal > This is my unworking code: > import time > import Cookie > import cookielib, urllib2 > > c= cookielib.Cookie(1,"Name","Tom", 80,False, "itay", False, False, > "d:\\asddd",False, False,time.time()+1000,False,None,None,None) Constructing your own Cookie instances is rarely necessary or sensible. If you do, I recommend getting the constructor arguments by inspecting the Cookie object the server actually returns, rather than using the values you *think* you know are correct. > cj = cookielib.CookieJar() > cj.set_cookie(c) > opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) > opener.open(r'http://itay/temp.html") > > why this isn't working? Please define "working". If you want to handle cookies when opening URLs, just do this: opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) opener.open("http://itay/temp.html") # more .open() calls go here... Of course, on the first HTTP request, cookie handling cannot have any effect at all unless you've somehow loaded some old cookies first. Your .open() may only involve a single HTTP request (though server-side software may detect the absence of a cookie on the first request, and do a page refresh or redirect so it can see its cookie returned to it again; vanilla urllib2 handles redirects but not refreshes; package ClientCookie handles the latter, amongst other things). Regardless, turning on cookielib and httplib debug output will likely be helpful if you're stuck (if only to post the output to this newsgroup): import logging, urllib2, sys hh = urllib2.HTTPHandler() hsh = urllib2.HTTPSHandler() hh.set_http_debuglevel(1) hsh.set_http_debuglevel(1) opener = urllib2.build_opener(hh, hsh, urllib2.HTTPCookieProcessor()) logger = logging.getLogger("cookielib") logger.addHandler(logging.StreamHandler(sys.stdout)) logger.setLevel(logging.DEBUG) response = opener.open("http://wwwsearch.sf.net/cgi-bin/cookietest.cgi") John From nyamatongwe+thunder at gmail.com Tue Apr 25 18:23:04 2006 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Tue, 25 Apr 2006 22:23:04 GMT Subject: MinGW and Python In-Reply-To: <1145996649.514911.99880@g10g2000cwb.googlegroups.com> References: <1145861223.509630.247350@y43g2000cwc.googlegroups.com> <444C79D7.4060007@v.loewis.de> <444DC62B.7000702@v.loewis.de> <1145985979.369429.114040@i39g2000cwa.googlegroups.com> <1145996649.514911.99880@g10g2000cwb.googlegroups.com> Message-ID: sturlamolden: > Uh .. I actually think it could be an EULA violation to publish mingw > vs. msvc benchmarks without permission from Microsoft. I don't want to > part of anything illegal or have M$ lawyers breathing down my back. If > we are going to do this, then we must do it properly and get the > permissions we need. The EULA attempted to stop disclosing benchmarks of .NET code, not C++ code. The most recent version of the EULA has replaced that with permission to disclose benchmarks of .NET code provided some conditions are met: full disclosure of benchmark code and environment; latest release of .NET; compliance with 'best practices'. Its still stupid as it would be in Microsoft's interest to encourage benchmarking .NET but not quite as stupid as before. Neil From aleaxit at yahoo.com Sun Apr 23 16:57:03 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 23 Apr 2006 13:57:03 -0700 Subject: Problem calling math.cos() References: <3ev2g.9680$%97.5795@newsfe15.lga> <1he74jb.126zvqm1jw41n5N%aleaxit@yahoo.com> Message-ID: <1he9221.77s2t01rmdpkfN%aleaxit@yahoo.com> Thomas Bellman wrote: > Alex Martelli wrote: > > > C has no stand on complex numbers. > > If by that you mean that C does not have complex numbers, then > you are wrong. C99 defines the three types float _Complex, > double _Complex, and long double _Complex, and also the header > . Yeah, I was thinking of the previous (C89) standard, the one which IS (still) required to build Python. Alex From reply.in.the.newsgroup at my.address.is.invalid Tue Apr 4 17:42:53 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Tue, 04 Apr 2006 23:42:53 +0200 Subject: socket connetion to url with port 80 References: <1144184532.778543.315410@e56g2000cwe.googlegroups.com> Message-ID: Sakcee: >how can i get page response from a site e.g. google.com port 80 [...] >can i do at socket level? Yes, but you'll need to implement HTTP: http://www.ietf.org/rfc/rfc2616.txt -- Ren? Pijlman From sijben at eemvalley.com Thu Apr 20 04:41:38 2006 From: sijben at eemvalley.com (Paul Sijben) Date: Thu, 20 Apr 2006 10:41:38 +0200 Subject: UDP performance In-Reply-To: <1145521664.857759.247400@i39g2000cwa.googlegroups.com> References: <44473787$0$31643$e4fe514c@news.xs4all.nl> <1145519675.476745.119480@g10g2000cwb.googlegroups.com> <444741dc$0$31652$e4fe514c@news.xs4all.nl> <1145521664.857759.247400@i39g2000cwa.googlegroups.com> Message-ID: <44474942.104@eemvalley.com> Serge Orlov wrote: > Paul Sijben wrote: >> Serge Orlov wrote: >>> Paul Sijben wrote: >>>> I am stumped by the following problem. I have a large multi-threaded >>>> server accepting communications on one UDP port (chosen for its supposed >>>> speed). >>>> >>>> I have been profiling the code and found that the UDP communication is >>>> my biggest drain on performance! Communication where the client and the >>>> server are on the same machine still takes 300ms or sometimes much more >>>> per packet on an Athlon64 3000+ running Linux (Fedora Core 5 x64). >>> [snip] >>> >>>> buf, address = socket.recvfrom(8192) >>> I'm not an expert here, but I AFAIK UDP packet size should be kept >>> below 512 bytes otherwise it can cause fragmentation and hence all the >>> slow stuff like acknoledgements, timeouts, etc... >>> >> good point in general but in practice they are in this case. but this is >> less of a problem on the loopback interface anyway. > > Isn't it still controlled by MTU even on the loopback? What is your MTU > on the loopback? > lo Link encap:Local Loopback inet addr:127.0.0.1 Mask:255.0.0.0 inet6 addr: ::1/128 Scope:Host UP LOOPBACK RUNNING MTU:16436 Metric:1 eth0 Link encap:Ethernet HWaddr 00:14:85:35:A4:5D inet addr:192.168.0.124 Bcast:192.168.0.255 Mask:255.255.255.0 inet6 addr: fe80::214:85ff:fe35:a45d/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 From chifran at acm.org Sat Apr 15 16:57:18 2006 From: chifran at acm.org (Chifran) Date: Sat, 15 Apr 2006 22:57:18 +0200 Subject: Best wx IDE Message-ID: <44415e50$0$18299$4fafbaef@reader1.news.tin.it> Hi, which is the best wx IDE for GUI development? Thanks. From python.list at tim.thechases.com Tue Apr 11 16:23:40 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 11 Apr 2006 15:23:40 -0500 Subject: RegExp question In-Reply-To: <1144783001.905105.305220@z34g2000cwc.googlegroups.com> References: <1144781090.622493.252460@t31g2000cwb.googlegroups.com> <1144783001.905105.305220@z34g2000cwc.googlegroups.com> Message-ID: <443C104C.8080408@tim.thechases.com> > I am testing it with grep. (i.e., grep -e '(and|or|xor)\s*#' myfile) Well, you asked for the python regexp...different environments use different regexp parsing engines. Your response is akin to saying "the example snippet of python code you gave me doesn't work in my Pascal program". For grep: grep '\(and\|or\|xor\)[[:space:]]*#' myfile For Vim: :g/\(and\|or\|xor\)\s*#/ The one I gave originally is a python regexp, and thus should be tested within python, not grep or vim or emacs or sed or whatever. It's always best to test in the real environment...otherwise, you'll get flakey results. -tkc From john at castleamber.com Thu Apr 27 18:50:37 2006 From: john at castleamber.com (John Bokma) Date: 27 Apr 2006 22:50:37 GMT Subject: Regular Expression help References: <1146162048.903980.281290@y43g2000cwc.googlegroups.com> <1146172456.106195.243160@j33g2000cwa.googlegroups.com> Message-ID: Edward Elliott wrote: > johnzenger at gmail.com wrote: >> If you are parsing HTML, it may make more sense to use a package >> designed especially for that purpose, like Beautiful Soup. > > I don't know Beautiful Soup, but one advantage regexes have over some > parsers is handling malformed html. Omitted closing tags can wreak > havoc. Regexes can also help if you only want elements > preceded/followed by a certain sibling or cousin in the parse tree. > It all depends on what you're trying to accomplish. In general > though, yes parsers are better suited to extracting from markup. A parser can be written in such a way that it doesn't give up on malformed HTML. Probably less hard then coming up with regexes that handle HTML that's well-formed. (and that coming from a Perl programmer ;-) ) -- John MexIT: http://johnbokma.com/mexit/ personal page: http://johnbokma.com/ Experienced programmer available: http://castleamber.com/ Happy Customers: http://castleamber.com/testimonials.html From betterp at gmail.com Wed Apr 19 14:08:42 2006 From: betterp at gmail.com (betterp at gmail.com) Date: 19 Apr 2006 11:08:42 -0700 Subject: Official Python logo Message-ID: <1145470122.145225.53110@z34g2000cwc.googlegroups.com> Where do I find one? Is it the banner by Just van Rossum or the Picasso snake on python.org? Thanks. From fredrik at pythonware.com Thu Apr 6 06:21:48 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 6 Apr 2006 12:21:48 +0200 Subject: how to convert string References: <1144261976.640631.9280@e56g2000cwe.googlegroups.com><1144284671.748880.187060@j33g2000cwa.googlegroups.com> <200604061813.58405.fulvio@pc.jaring.my> Message-ID: "Fulvio" wrote: > BTW, how to write a number repeatly in the same line and position, without let > the printout to scroll down. for i in range(100): print "\r", i, # do something print will work, as long as the message isn't too long, and you're printing to a console device that does "the usual thing" when it sees a carriage return. From egbert.bouwman at hccnet.nl Thu Apr 27 08:36:07 2006 From: egbert.bouwman at hccnet.nl (egbert) Date: Thu, 27 Apr 2006 14:36:07 +0200 Subject: can anyone advise me In-Reply-To: <1146131326.328919.285430@t31g2000cwb.googlegroups.com> References: <1146131326.328919.285430@t31g2000cwb.googlegroups.com> Message-ID: <20060427123607.GA8505@hccnet.nl> On Thu, Apr 27, 2006 at 02:48:46AM -0700, micklee74 at hotmail.com wrote: > why the output of this code : > x = 0 > while x < 10: > z = 0 > print x > x = x + 1 > while z < x: > print z, > z = z + 1 > > is > > 0 > 0 1 > 0 1 2 > 0 1 2 3 > 0 1 2 3 4 > 0 1 2 3 4 5 > 0 1 2 3 4 5 6 > 0 1 2 3 4 5 6 7 > 0 1 2 3 4 5 6 7 8 > 0 1 2 3 4 5 6 7 8 9 > 0 1 2 3 4 5 6 7 8 9 < ---extra > > > instead of : > 0 > 0 1 > 0 1 2 > 0 1 2 3 > 0 1 2 3 4 > 0 1 2 3 4 5 > 0 1 2 3 4 5 6 > 0 1 2 3 4 5 6 7 > 0 1 2 3 4 5 6 7 8 > 0 1 2 3 4 5 6 7 8 9 > In your nested loop you are printing an x followed by zero or more z's, but only after each x, including the first one, you switch to a new line. So the last digit on each line is an x, except for the last line, which are z's printed after the 9 (an x) ending the line above it. Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 ======================================================================== From rpdooling at gmail.com Thu Apr 13 16:48:09 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 13 Apr 2006 13:48:09 -0700 Subject: trying to grasp OO : newbie Q? References: <1144937168.508799.67410@i40g2000cwc.googlegroups.com> <1144941250.517385.144590@u72g2000cwu.googlegroups.com> Message-ID: <1144961289.959237.181580@z34g2000cwc.googlegroups.com> Pretty tough to beat Alan Gauld, but the more examples the merrier for me, and the infogami has plenty of those. Thanks. http://www.freenetpages.co.uk/hp/alan.gauld/tutclass.htm rpd From lycka at carmen.se Tue Apr 11 13:19:10 2006 From: lycka at carmen.se (Magnus Lycka) Date: Tue, 11 Apr 2006 19:19:10 +0200 Subject: Looking for a language/framework In-Reply-To: References: <1143559444.045808.38790@u72g2000cwu.googlegroups.com> <1hcwg6n.b3jwv5xq910tN%aleaxit@yahoo.com> <1143837635.846033.204910@u72g2000cwu.googlegroups.com> <442daf37$1@nntp0.pdx.net> <442ec2cc$1@nntp0.pdx.net> Message-ID: Gregor Horvath wrote: > Scott David Daniels schrieb: > >> Using a relational DBMS is most definitely _not_ premature optimization. >> A relational system provides a way to store data so that it is later > > I did not mean that using a relational DBMS is premature optimization > but not using a ORM because of performance considerations is one . Whether or not to use an ORM might be a fairly big design decision, and a part of the entire approach to your data handling. For some kinds of data and some kinds of applications, it will drastically reduce your flexibility in how you can conveniently deal with the data. Object oriented design and programming, is often very helpful, but it's not the only approach you can take to solving a problem in software, and I'm not sure it's always the best approach... Using an ORM means that you are making it much more difficult to use the full expressiveness of SQL. On the other hand, using the full expressiveness of SQL might make it much more difficult to use your data in an object oriented way... You have to weigh the pros and cons depending on the situation. I'm sure different ORMs might be more or less limiting on SQL. I suspect that this depends on how well the designer of the ORM knows SQL. I guess the problem is that those who are best at SQL and most capable of writing a non-limiting ORB are fairly good at working without an ORM, so it's the guys who don't really understand and appreciate the strengths of SQL that designs the ORMs... :) > If it turns out that the ORM is a performance problem you can always > tune it afterwards. (probably by the DBMS setup, indexes etc.) To a large extent, use of ORMs and a proper OO design, means that you move a lot of logic from the the DB and the SQL layer up to the Python (or whatever language you use) layer, and there are efficient SQL solutions you simply can't reach in that way. As a simple example, the natural way to calculate the averages of an attribute in a set of object in an OO system is to iterate over the objects, get the value, add up a sum, count the objects as you iterate and divide the sum with the count once you were done iterating. It's very simple and straight forward, and often magnitudes slower than the corresponding obvious SQL solution. > Its just a layer and therefore the endresult is SQL much the same as the > one you would hand code. (and you still can use direct SQL if you like > with most of them) That's a joke, right? It might be much the same as *you* would have hand coded, but perhaps very different from what *I* (and I suspect Scott) would have coded. With different approaches to your design, you solve problems in completely different ways. Different languages lend themselves to very different design approaches. The distinction between declarative and imperative languages is pretty big, as is the more concrete ways to actually work with data in Python and SQL. SQL is a really stupid language in many ways. It's pretty useless without a good partner, such as Python, and even considering its limited perspective as a language for querying and manipulating relational databases, I think it could have been designed so much better. I can't see any intelligent reason not to provide the kind of abstractions that function calls provide for instance. The amount of repetition in SQL code in large database applications is appalling. Still, there are applications where it's widely superior to any really existing alternatives, and it goes far beyond manipulating or fetching individual records in tables. > In any way you have to bridge the logical gap between the relational and > the object data model in your programm. Certainly. > So you will end up in building a layer between your persistence code and > your problem and domain specific application code, so what you are > actually doing is writing an ORM. Well, I wouldn't say it's an ORM unless it tries to be generic in some way. In many cases, this mapping is fairly trivial. I once used SQLObject for a whisky tasting database web app, and I think it made life easier for me than raw SQL would have been, but that was a small system where it was more important to make development fast than to make the end product fast and robust. > Not reinventing the wheel every time and using a existing one is IMHO a > better approach. Well, as usual... That depends... For each project you have to decide how well different available alternatives fit your actual requirements. If there's an ORM that fit yours, fine. No such external product would be able to handle the applications I work with right now. The kind of "conventional" use of SQL in ORMs simply won't work for our needs for several reasons. For us, and ORM simply can't solve the problem. For others, it's overkill. As I said, ORMs have their uses, but it seems to me that a reason for many people to use ORMs is to avoid having to properly understand the way relational databases work, and that means they will never use the database really well. I'm pretty certain there are cases where it's better with an ORM and a mediocre use of a database than no ORM and a complete mess, but that's not the kind of applications or developers I like to work with. From zannablu at libero.it Mon Apr 17 17:33:34 2006 From: zannablu at libero.it (Faber) Date: Mon, 17 Apr 2006 21:33:34 GMT Subject: Threading problem References: Message-ID: Aleksandar Cikota wrote: > How to integrate the Code-part in the main programm, so that the > mainprogramm works? > > Code: > > import win32com.client > import time > import os > import threading > > Document = win32com.client.Dispatch('MaxIm.Document') > Application = win32com.client.Dispatch('MaxIm.Application') > p = win32com.client.dynamic.Dispatch('PinPoint.Plate') > > class TestThread ( threading.Thread ): > path_to_watch = "F:/Images/VRT/" def run(self): # Put the following code in the run method > before = dict ([(f, None) for f in os.listdir (path_to_watch)]) > while 1: [cut] > TestThread().start() This should work -- Faber http://faberbox.com/ http://smarking.com/ The man who trades freedom for security does not deserve nor will he ever receive either. -- Benjamin Franklin From gregpinero at gmail.com Wed Apr 5 13:34:40 2006 From: gregpinero at gmail.com (=?ISO-8859-1?Q?Gregory_Pi=F1ero?=) Date: Wed, 5 Apr 2006 13:34:40 -0400 Subject: CD Burning In-Reply-To: <1144223176.314145.250790@u72g2000cwu.googlegroups.com> References: <1144223176.314145.250790@u72g2000cwu.googlegroups.com> Message-ID: <312cfe2b0604051034g1ce6ec63g6bcccc2a24e9b06a@mail.gmail.com> Nero has a commandline utility called NeroCMD.exe (not sure if you needed a free solution or not) Here's some sample code and write-up using NeroCMD.exe with Python: http://www.answermysearches.com/index.php/nerocmdexe-and-python-automating-the-burning-process/10/ -Greg On 5 Apr 2006 00:46:16 -0700, Tim Golden wrote: > Albert Leibbrandt wrote: > > Hi > > > > Can anybody tell me which windows API or python module they are using > > for writing cd's / dvd's with python? > > Other people have offered sound suggestions about using > cdrecord etc. under Cygwin. Just to make the point, though, > XP (and above, presumably) does have an inbuilt interface > for burning CDs. I've never used it, and I don't know how feasible > it would be to access it from Python. (Helpful, eh?) > > The interface is ICDBurn and it should be possible to wrap > it with ctypes / ctypes.com but I haven't the time at the > moment to try it out. (And I haven't a CD writer in this machine > either!) > > Ultimately, it might still be easier to install Cygwin and use > the cdrecord approach. I just wanted to make the point that > there *was* an in-built mechanism. > > ICDBurn: > http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc/platform/shell/reference/ifaces/icdburn/icdburn.asp > ctypes.com: http://starship.python.net/crew/theller/ctypes/com.html > > TJG > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Gregory Pi?ero Chief Innovation Officer Blended Technologies (www.blendedtechnologies.com) From mensanator at aol.com Wed Apr 5 17:37:32 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 5 Apr 2006 14:37:32 -0700 Subject: Counting all permutations of a substring References: <1144271242.858677.124490@t31g2000cwb.googlegroups.com> Message-ID: <1144273052.349507.41220@j33g2000cwa.googlegroups.com> Chris Lasher wrote: > Hi all, > How can one count all the permutations of a substring in a string? For > a more concrete example, let's say > targetstr = 'AAA' > and > probestr = 'AA' > > I want to consider how many times one can count probestr ('AA') in > targetstr ('AAA'). The value in this example is, obviously, 2: you can > match the first and second A's as 'AA' and also the second and third > A's as 'AA'. Compiling a regular expression of the probestr and doing a > findall(targetstr) will not work because the RE stops on the first > combination of 'AA' that it finds (the first and second A's of the > targetstr). The regular expression re.compile(r'A{2,}'} will not work, > either; it simply consumes all three A's as one match. The string > method count('AA') acts similarly to the findall of the 'AA' RE, > returning 1, as it only matches the first and second A's. > > Any suggestions on how to get at that 2nd pair of A's and count it? > Humbly, I'm a bit stumped. Any help would be appreciated. >>> def ss(a,b): matches = 0 lc = len(a)-len(b)+1 for i in xrange(lc): if a[i:i+lb]==b: print a print ' '*i+b print matches += 1 return matches >>> ss('AAABCDEAAAAABSAABAWA','AA') AAABCDEAAAAABSAABAWA AA AAABCDEAAAAABSAABAWA AA AAABCDEAAAAABSAABAWA AA AAABCDEAAAAABSAABAWA AA AAABCDEAAAAABSAABAWA AA AAABCDEAAAAABSAABAWA AA AAABCDEAAAAABSAABAWA AA 7 > > Many thanks in advance, > Chris From fabiofz at gmail.com Wed Apr 5 14:30:51 2006 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Wed, 5 Apr 2006 15:30:51 -0300 Subject: Pydev and Pydev Extensions 1.0.5 release Message-ID: Hi All, Pydev and Pydev Extensions 1.0.5 have been released Check http://www.fabioz.com/pydev for details on Pydev Extensions and http://pydev.sf.net for details on Pydev Release Highlights in Pydev Extensions: ----------------------------------------------------------------- - The pop-up does not pop as much for unlicensed versions Release Highlights in Pydev: ---------------------------------------------- - Another batch of things to improve indentation: * Indent does not try to make auto-indentation when pasting * When smart-indent is not selected, it will still add an indentation level after ':' * It will keep the indent of the previous line on new-lines if the current line is empty * Other little things - Added a place to specify vm arguments (for jython or python) -- thanks to Rudi de Andrade for this patch - Added a way to kill the underlying python/jython shells (Ctrl+2+kill) What is PyDev? --------------------------- PyDev is a plugin that enables users to use Eclipse for Python and Jython development -- making Eclipse a first class Python IDE -- It comes with many goodies such as code completion, syntax highlighting, syntax analysis, refactor, debug and many others. Cheers, -- Fabio Zadrozny ------------------------------------------------------ Software Developer ESSS - Engineering Simulation and Scientific Software http://www.esss.com.br Pydev Extensions http://www.fabioz.com/pydev Pydev - Python Development Enviroment for Eclipse http://pydev.sf.net http://pydev.blogspot.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From siona at chiark.greenend.org.uk Mon Apr 3 10:58:03 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 03 Apr 2006 15:58:03 +0100 (BST) Subject: string building References: Message-ID: John Salerno wrote: >Out of curiosity, is there any kind of equivalent in Python to the >StringBuilder class in C#? Here's a quick description from the .NET >documentation: > >"This class represents a string-like object whose value is a mutable >sequence of characters. The value is said to be mutable because it can >be modified once it has been created by appending, removing, replacing, >or inserting characters." You can get a long way with list of characters wrapped in list() and "".join(). Seems to me like the main gotcha is to be careful with things like: >>> mutable_string = list("initial\nvalue") >>> mutable_string[7] = "\r\n" and make sure you do: >>> mutable_string[7:8] = "\r\n" (Although note that you have to spell find() and other string methods "".join(mutable_string).find("value").) -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From n.estner at gmx.de Wed Apr 26 13:07:12 2006 From: n.estner at gmx.de (nikie) Date: 26 Apr 2006 10:07:12 -0700 Subject: Events in Python? References: <1146065995.016939.187440@i40g2000cwc.googlegroups.com> Message-ID: <1146071232.275024.5310@e56g2000cwe.googlegroups.com> redefined.horizons at gmail.com wrote: > Here is another non-pythonic question from the Java Developer. (I beg > for forgiveness...) > > Does Python have a mechanism for events/event-driven programming? > > I'm not necessarily talking about just GUIs either, I'm interested in > using events for other parts of an application as well. > > If there isn't some sort of event mechanism built into Python, where > might I find some information about implementing one? Maybe I got your question wrong, but why not simply use something like: class Sender: def __init__(self, event): self.event = event def raiseEvent(self): self.event("Event") class Receiver: def receiveEvent(self, msg): print "Received %r" % msg r = Receiver() s = Sender(r.receiveEvent) s.raiseEvent() You can pass around functions and bound methods, I always found that's often a really good substitute for full-blown event mechanisms. From michele.simionato at gmail.com Thu Apr 20 10:46:47 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 20 Apr 2006 07:46:47 -0700 Subject: Missing interfaces in Python... In-Reply-To: <1145500996.149358.23470@g10g2000cwb.googlegroups.com> References: <1145306373.781129.305840@z34g2000cwc.googlegroups.com> <1145430546.625634.194710@g10g2000cwb.googlegroups.com> <7lrb429tg5c6dt1bt99d1131cafuulvqap@4ax.com> <4445f7f8$0$9451$626a54ce@news.free.fr> <1145438118.179643.140390@e56g2000cwe.googlegroups.com> <1145500996.149358.23470@g10g2000cwb.googlegroups.com> Message-ID: <1145544407.308977.183230@z34g2000cwc.googlegroups.com> Carl Banks wrote: > Only after a lot of effort, a lot > of refactoring, and a large part of the problem space explored, will > the interfaces be mature enough that writing interface definitions > would be useful and not a burden. (And let's face it: there aren't > many projects that get that far. :) +1 QOTW Michele Simionato From broek at cc.umanitoba.ca Mon Apr 24 18:51:19 2006 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Mon, 24 Apr 2006 17:51:19 -0500 Subject: RESOLVED Re: PYTHONPATH In-Reply-To: References: <1145535721.138411.145790@z34g2000cwc.googlegroups.com> <44478f30$0$12862$626a54ce@news.free.fr> Message-ID: <444D5667.9000908@cc.umanitoba.ca> Hi all, As a fairly new linux user running ubuntu 5.10 I'd had problems persistently setting my PYTHONPATH environment variable. bruno and Edward got me most of the way (thanks!); I'm posting what worked for future googling. bruno at modulix said unto the world upon 20/04/06 08:38 AM: >>Can anyone help me to make my path persistant? > > > Just like any other environnement variable on your system. With most > distros, it will be something like adding the line: > > export PYTHONPATH="/a/possible/path;/another/one;/and/a/third" > > either in /etc/profile (will be system-wide default) or ~/.bash_profile > (will be user-specific). and Edward Elliott said unto the world upon 23/04/06 07:56 PM: > Brian van den Broek wrote: >>So, it seems that I currently have to invoke '. .bash_profile' >>manually with each new shell opened for this to have effect. > > > Your shell must not be opening as a login shell. From the bash man page: > "When an interactive shell that is not a login shell is started, bash > reads and executes commands from /etc/bash.bashrc and ~/.bashrc, if > these files exist." > So, to get the terminal ubuntu launches when you click on the panel's terminal icon to have a customized PYTHONPATH, one must, as Edward said, modify ~/.bashrc or link it with ~/.bash_profile. The syntax that worked for me was *almost* what bruno suggested. It didn't work here until I used ':' rather than bruno's ';' as the path element separator. So, the lines PYTHONPATH="/home/brian/FirstDir:/home/brian/SecondDir" export PYTHONPATH added to ~.bashrc make the terminal launched from the panel icon include /home/brian/FirstDir and /home/brian/SecondDir right after pwd in sys.path as desired. Thanks Edward and bruno! Best, Brian vdB From brochu121 at gmail.com Fri Apr 14 20:04:27 2006 From: brochu121 at gmail.com (david brochu jr) Date: Fri, 14 Apr 2006 20:04:27 -0400 Subject: ping Message-ID: <9583ed900604141704x39542865ie71665c071aaf571@mail.gmail.com> Thanks, Unfortunately substituting os.system with os.popen results in the output being: instead of giving me the ping stats "pinging etc etc, packets sent 4 recienved 4 etc) Any idea around this? -------------- next part -------------- An HTML attachment was scrubbed... URL: From cctv.star at gmail.com Tue Apr 25 07:08:31 2006 From: cctv.star at gmail.com (cctv.star at gmail.com) Date: 25 Apr 2006 04:08:31 -0700 Subject: OOP / language design question In-Reply-To: References: <1145961248.794496.80220@j33g2000cwa.googlegroups.com> Message-ID: <1145963311.348482.15080@i40g2000cwc.googlegroups.com> Heiko Wundram wrote: > Because sometimes you don't want to call the base classes constructors? Sounds strange to me at the moment, but I'll try to adjust to this thought. > Python zen says: "Better explicit than implicit," and in this case it hits > the nail on the head. Better to see right away what your code does (the > explicit call to the base class), than to have to work around calling a bases > constructor if you don't want to call it. Thanks, that explains it somehow - at least, it's consistent with explicit "self". I think I'll need some shift in thinking after C++. From jjl at pobox.com Fri Apr 21 15:21:55 2006 From: jjl at pobox.com (John J. Lee) Date: 21 Apr 2006 19:21:55 +0000 Subject: send cookie on request with urllib2 References: <1145539129.322307.77220@z34g2000cwc.googlegroups.com> <4447ffcb$1_2@newspeer2.tds.net> <1145617290.301990.65870@u72g2000cwu.googlegroups.com> Message-ID: <87irp2ag4s.fsf@pobox.com> "itay_k" writes: > ok. > i will explain what exactly i wanna do. > > i want to simulate the following client-side script with python: > > > > Ah! In which case what you're trying to do is a reasonable hack, but better (UNTESTED): import urllib2, cookielib cj = cookielib.CookieJar opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) request = urllib2.Request(url) response = opener.open(request) response["Set-Cookie"] = "name=tom" cj.extract_cookies(response, request) If you have HTML-parsing code to extract these JS cookies that you want to run on every request (e.g. so even cookies set by JS during redirections get handled), you can make all this transparent very easily by using a handler similar to HTTPCookieProcessor itself (using a recent version of package ClientCookie here for (a recent version of) the response_seek_wrapper class) UNTESTED: import urllib2, cookielib class JSHTTPCookieProcessor(urllib2.BaseHandler): handler_order = 400 # before HTTPCookieProcessor def process_response(self, request, response): from ClientCookie import response_seek_wrapper if not hasattr(response, "seek"): response = response_seek_wrapper(response) try: name, value = get_js_cookie(response) # your ugly HTML parsing code here ;-) finally: response.seek(0) response["Set-Cookie"] = "%s=%s" % (name, value) return response opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(), JSHTTPCookieProcessor()) response = opener.open(url) # now we're handling JS cookies transparently! John From ndbecker2 at gmail.com Sat Apr 8 10:50:16 2006 From: ndbecker2 at gmail.com (Neal Becker) Date: Sat, 08 Apr 2006 10:50:16 -0400 Subject: Compleated Begginers Guide. Now What? References: <1144497870.999295.162450@i39g2000cwa.googlegroups.com> Message-ID: Maybe find a spell checker? From siona at chiark.greenend.org.uk Thu Apr 13 13:21:55 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 13 Apr 2006 18:21:55 +0100 (BST) Subject: list.clear() missing?!? References: <1144767680.583085.310160@v46g2000cwv.googlegroups.com> <1144946086.185381.274320@e56g2000cwe.googlegroups.com> Message-ID: Fredrik Lundh wrote: >except that arguments along the line of "if the syntax is not obj.method(), >it's not OO enough" are likely to be mostly ignored. > >(nobody's going to be impressed by yet another "len(obj) isn't OO" variant) Does that suggest that what's needed is clear(obj) and __clear__ methods? 8-) -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From tim.peters at gmail.com Sat Apr 8 08:45:38 2006 From: tim.peters at gmail.com (Tim Peters) Date: Sat, 8 Apr 2006 08:45:38 -0400 Subject: calculating system clock resolution In-Reply-To: References: <1144434899.840346.220780@z34g2000cwc.googlegroups.com> <1144452910.634097.117310@e56g2000cwe.googlegroups.com> <1144494980.132199.237290@i39g2000cwa.googlegroups.com> Message-ID: <1f7befae0604080545h183ea521k9efd4befbefe13d3@mail.gmail.com> [jUrner] >> def calc_time_res(): >> now = time.time >> start = now() >> x = start >> while start == x: >> x = now() >> print x, start # <-- >> print x - start >> >> print calc_time_res() >> 1.50203704834e-05 >> >> Something is going wrong here. >> If you look at the function ,time.time() returns time in microseconds >> (most oses and so does mine). Don't confuse resolution with precision (or make up other words you like better ;-)): just because some quantity is given with N bits doesn't mean it's _accurate_ to N bits. See below for a more extreme example. [Steven D'Aprano] > ... > This brings me to an even simpler method of getting the resolution of > time.time(), without the overhead of a while loop: > > >>> abs(time.time() - time.time()) > 1.0013580322265625e-05 > > which is approximately 0.01ms, just as you expected. Caution: the most likely outcome on Windows for that line is 0.0. That's because the clock mechanism underlying time.time() on Windows only updates at a frequency of 18.2 Hz (older systems) or 64 Hz (newer systems). IOW, time.time() only "changes" 18.2 to 64 times per second on Windows, and two consecutive calls are consequently likely to return exactly the same result. In contrast, time.clock() on Windows typically updates more than a million times per second. From lorinh at gmail.com Mon Apr 3 21:36:40 2006 From: lorinh at gmail.com (lorinh at gmail.com) Date: 3 Apr 2006 18:36:40 -0700 Subject: Sending C-c to Emacs Message-ID: <1144114600.323981.180970@e56g2000cwe.googlegroups.com> Hi all, I've written a Python script with functionality similar to the Unix "script" program, which keeps a record of shell commands issued (I capture some additional stuff like timestamps). The code is borrowed largely from http://groups.google.com/group/comp.lang.python/msg/de40b36c6f0c53cc Anyways, one problem is that it doesn't handle Control-C correctly. This is a particular problem when invoking Emacs since C-x C-c is the sequence to exit Emacs. Catching the KeyboardInterrupt and doing os.kill(pid,signal.SIGINT) doesn't seem to do the trick. A simplified version of the program looks something like this (I've eliminated the parts where I log the data to a file and some tty-related cleanup stuff, this is just shuffling data between user and shell) import select,os,pty shell = '/bin/bash' pid, fd = pty.fork() if pid == 0: os.execvp(shell,(shell,)) # various tty magic goes here exit = 0 while True: r, w, e = select.select([0, fd], [], [], 1) for File in r: if File == 0: from_user = os.read(0, bufsize) os.write(fd, from_user) elif File==fd: try: from_shell = os.read(fd, bufsize) os.write(1, from_shell) if from_shell=='': exit=1 except OSError: exit=1 if exit==1: break The problem is that this doesn't work when the user hits Control-C. I thought the solution would be to send the child process a SIGINT, and I tried to do that as follows: try: r, w, e = select.select([0, fd], [], [], 1) ... except KeyboardInterrupt: os.kill(pid,signal.SIGINT) But that doesn't have the desired effect. When I have this code here, it's as if I never hit Control-C at all. What's the proper way to pass the Control-C to the child process? Thanks, Lorin Hochstein From jjl at pobox.com Wed Apr 26 16:58:07 2006 From: jjl at pobox.com (John J. Lee) Date: 26 Apr 2006 20:58:07 +0000 Subject: how to browse using urllib2 and cookeilib the correct way References: <1146024468.154244.162510@t31g2000cwb.googlegroups.com> Message-ID: <87wtdcm4v4.fsf@pobox.com> Edward Elliott writes: > jnair at ensim.com wrote: > > can anybody explain, in the first case why i need to do two attempts. > > I would guess it's because redhat requires your browser to submit a session > cookie with the login form. In the urllib2 example, the first request you > make tries to submit login form data directly. Since it's your first hit > on their site, you don't have a cookie yet. People browsing interactively > would at least load the login page first before submitting it. > > Your twill example takes care of this by requesting a page before trying to > login. > > That would be my guess. Uh, yeah you're right actually. Forget what I said about Refresh... John From trentm at ActiveState.com Mon Apr 10 20:40:07 2006 From: trentm at ActiveState.com (Trent Mick) Date: Mon, 10 Apr 2006 17:40:07 -0700 Subject: How to write a python program to export the help document to a file? In-Reply-To: References: Message-ID: <20060411004007.GA25196@activestate.com> [boyeestudio wrote] > How to write a python program to export the help document to a file? > for example: > I need the os document,I use: > >>>import os > >>>help(os) > then it will show me all about os.But I need it redirect to a file. > How to do that? $ pydoc os > os.txt Trent -- Trent Mick TrentM at ActiveState.com From bignose+hates-spam at benfinney.id.au Wed Apr 19 18:38:04 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 20 Apr 2006 08:38:04 +1000 Subject: mini component distribution question References: Message-ID: <87slo9fayb.fsf@benfinney.id.au> "Eric S. Johansson" writes: > as one would expect when creating a body of software, eventually you > create a series of relatively generic components you find yourself using > over and over again. As a result, I'm finding myself slightly bit by > the same problem I have faced multiple times of the past. Namely, how > do you distribute "small" components that are used in a series of larger > applications. The developing wisdom is to: - bundle up reusable discrete functional components as Python eggs - publish them on the Cheeseshop - use easy_install to automatically download and install them when the main package is installed -- \ "Pity the meek, for they shall inherit the earth." -- Donald | `\ Robert Perry Marquis | _o__) | Ben Finney From antroy at gmail.com Mon Apr 17 03:01:40 2006 From: antroy at gmail.com (Ant) Date: 17 Apr 2006 00:01:40 -0700 Subject: passing string from one file to another In-Reply-To: References: <1145250925.878549.53870@i39g2000cwa.googlegroups.com> <1145252087.514616.237880@u72g2000cwu.googlegroups.com> Message-ID: <1145257300.011726.166540@g10g2000cwb.googlegroups.com> I assume that you are trying to pass data from one 'standalone' cgi script to another cgi script (mail.py). Depending on what exactly you are trying to do, you could either set the information in a cookie, or simply have a hidden input () element in the HTML which gets populated by the initial cgi script and is then read by mail.py. From wrongbad at gmail.com Mon Apr 17 17:48:33 2006 From: wrongbad at gmail.com (I V) Date: 17 Apr 2006 14:48:33 -0700 Subject: Missing interfaces in Python... In-Reply-To: References: <1145306373.781129.305840@z34g2000cwc.googlegroups.com> Message-ID: <1145310512.955078.201370@j33g2000cwa.googlegroups.com> Jonathan Daugherty wrote: > Except when you need to handle exceptions when those methods don't > exist. I think interfaces can definitely be useful. I think I see what you mean, but that's an odd way to put it. Typically, you aren't going to handle the exceptions produced by type errors. Of course, you want some way to test that your code doesn't have type errors. Static type checking is one way of doing the requisite testing, unit tests are another, but it's the tests that are useful, not the interfaces per se. Adding interfaces to python, which doesn't support static type checking, would be useless IMO. From adam.deprince at gmail.com Wed Apr 5 10:32:01 2006 From: adam.deprince at gmail.com (Adam DePrince) Date: Wed, 05 Apr 2006 10:32:01 -0400 Subject: using range() in for loops In-Reply-To: <443324dc$0$11257$c3e8da3@news.astraweb.com> References: <443324dc$0$11257$c3e8da3@news.astraweb.com> Message-ID: <1144247522.3195.33.camel@localhost.localdomain> On Tue, 2006-04-04 at 21:54 -0400, John Salerno wrote: > I'm reading Text Processing in Python right now and I came across a > comment that is helping me to see for loops in a new light. I think > because I'm used to the C-style for loop where you create a counter > within the loop declaration, for loops have always seemed to me to be > about doing something a certain number of times, and not about iterating > over an object. This is a normal reaction. Try to keep in mind that when you use any "higher level" language your code will closer reflect what you want rather than how to accomplish what you want. When you are creating a loop over numbers, is your goal really to count, or to use the integer that you are counting to do something else, like perhaps dereference elements of a string. Also, part of the problem is a preconceived restriction that you hold on the use of forloops. They arn't just for counting, there are all sorts of interesting things that can go in there. Remember, a for loop is basically a while loop with a little bit of syntactic sugar. Look at this: for( a, b, c ) { d; e; } is the same as a; while (b) { d; e; c; } C for and while are the same creature. Python's while loop is Python's version of for/while. If you wanted to mimick C you could write i = 0 while( i<10 ): print i i+=1 but this is clumbsy and slower. for(i=0;i<10;i++) is a common enough programing pattern, you arn't really interested in setting i, incrementing, doing all of that housekeeping. You really want to repeat 10 times with with i set to 0, 1 ... for ... xrange does this well and is somewhat the motivation for the creation of xrange. > The reason for this distinction comes from the fact that I read a lot > how using range and for is somewhat discouraged, because it doesn't > really use a for loop for it's true purpose. So my question is, is this Nothing in a well defined language has a true purpose. The true purpose of an int in C isn't to be for loop fodder. One of the hallmarks of a well designed language is orthogonality; most anything works with anything else. A feature that has one specific use doesn't provide much utility to justify the effort used to create it. > just a Python-oriented opinion about for loops, or is it a general idea? Programming languages borrow from heavily from natural languages; yes, for is a loaned word from English that exists in C, python ... lots of languages. But just as when one human language borrows from another, the resulting semantics are not always the same. Each as a formal semantic. C and Python are somewhat different, and yes, you could describe the philosophical difference as a matter of opinions. > > Also, what if you *do* need to just do something a set number of times. > Is this okay, or does it mean you are approaching the problem > incorrectly? Using for and range together seems to be a common idiom, > yet at the same time discouraged, so I'm wondering what is a good balance. The correct idiom is for( xrange( foo )). This is preferred over range for efficiency. Historically there were no iters. If you wanted to do loop you would say for x in range( 10 ): foo bar range created a list of 10 items and x marched over them. Creating this list in advance doesn't need to take any more time; you have to create the number objects anyway to assign to x at some point, so you might as well get that done with upfront. The problem was memory consumption. The memory requirements of the list put a bound on large your iteration could be. xrange was created, and soon followed general iters. Now, the range object generates the numbers on the fly as the loop runs .. the loop says "hey, whats next" and the next item is returned. When people say "don't say for x in range" they are really saying "use xrange instead of range." From andre.roberge at gmail.com Fri Apr 28 19:45:24 2006 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 28 Apr 2006 16:45:24 -0700 Subject: Using a browser as a GUI: which Python package Message-ID: <1146267924.602318.238640@j73g2000cwa.googlegroups.com> First, an apology: I realise that I don't know enough about what I am asking to make sure to use the proper language to phrase my question. I would like to use a browser (e.g. Firefox) as a simple GUI "framework". Note that this is to be done on a single user machine, so the question of sandboxing is not really relevant here. The simplest application I would like to start with would be one with two "windows" (within a browser window) and a single button. One window would be used as a Python code editor; the other as an output window. On clicking on the button, the code in the editor window would be run by Python with the result appearing in the output window. [A more advanced, future version, would be to have Python create some graphical code (e.g. SVG) that could be passed to the browser to be displayed within the output window.] Ideally, I would prefer a Python-based solution only. My ultimate goal would be to port the main features of two wxPython-based apps I wrote (rur-ple and Lightning Compiler, both found at https://sourceforge.net/project/showfiles.php?group_id=125834) within a standard browser. Any help/pointers would be appreciated. Andr? From reply.in.the.newsgroup at my.address.is.invalid Fri Apr 21 08:50:32 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Fri, 21 Apr 2006 14:50:32 +0200 Subject: Read and extract text from pdf References: Message-ID: Julien ARNOUX: >I have a problem :), I just want to extract text from pdf file with >python. There is differents libraries for that but it doesn't work... > >pyPdf and pdfTools, I don't know why but it doesn't works with some >pdf... Text can be represented in different ways in PDF: as tagged text, bitmap and vector images, and even algorithms (IIRC). Most tools will only be able to retrieve text represented as tagged text. So some tools may work on some texts in some files and fail on others. -- Ren? Pijlman Wat wil jij leren? http://www.leren.nl From aleaxit at yahoo.com Wed Apr 19 00:06:16 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 18 Apr 2006 21:06:16 -0700 Subject: 2.5 excitement References: <1145290449.735642.120860@i40g2000cwc.googlegroups.com> <1145292795.565277.288760@v46g2000cwv.googlegroups.com> <1hdyb46.1yllkst1o2asjlN%aleaxit@yahoo.com> <1204021.LzRF60KP7e@jupiter.g2ctech> Message-ID: <1he09pm.1txy84o1mprpfjN%aleaxit@yahoo.com> Aahz wrote: ... > Heh. Since we're just finally turning in our 100% first draft of Python > for Dummies, I tend to think more in terms of what a Python newbie will Funny timing coincidence: your 1st draft of Python for Dummies going in now, my 2nd edition of Python in a Nutshell just went to production, AND Wesley Chun's 2nd ed is also being finished this week. Three Baypiggies (or whatever we'll have to call ourselves) all finishing Python books (be they new, or 2nd eds) all within one week of Easter -- what's the chances of THAT?-) Alex From pwatson at redlinepy.com Sun Apr 2 07:40:16 2006 From: pwatson at redlinepy.com (Paul Watson) Date: Sun, 02 Apr 2006 06:40:16 -0500 Subject: Is pwm Python MegaWidgets viable? Message-ID: <499rh1Fnh7voU1@individual.net> Does pwm run well on Python 2.4? The last release appears to be in 2003. The Manning discussion forum is dead. Is there a better path to learning and producing tkInter apps? Has there been any discussion of wxPython becoming part of the base Python distro? A requirement here is to not require download/install of anything other than the Python release. From pmartin at snakecard.com Mon Apr 10 14:14:03 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Mon, 10 Apr 2006 13:14:03 -0500 Subject: python + access + odbc + linux References: Message-ID: Thanks TIM. Philippe Tim Golden wrote: > [Philippe Martin] > > | I understand that access can be accessed through an ODBC driver under > | windows (instead of Jet). > | > | I am wondering if the same can be done under Linux. > > You need to look at the mdbtools packages > > http://mdbtools.sourceforge.net/ > > which includes a Jet-ODBC driver which can be used under > Linux via iODBC or UnixODBC and mxODBC on the Python side. > At least in theory: I had only qualified success, and > eventually gave up. But it was clear from the mailing > lists that other people had succeeded. > > TJG > > ________________________________________________________________________ > This e-mail has been scanned for all viruses by Star. The > service is powered by MessageLabs. For more information on a proactive > anti-virus service working around the clock, around the globe, visit: > http://www.star.net.uk > ________________________________________________________________________ From fredrik at pythonware.com Tue Apr 11 03:39:35 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 11 Apr 2006 09:39:35 +0200 Subject: writing captcha image file References: <1144723853.566700.151680@z34g2000cwc.googlegroups.com> <1144725003.989669.273190@t31g2000cwb.googlegroups.com> Message-ID: amaltasb at gmail.com wrote: > I get this msg: > Traceback (most recent call last): > File "/usr/local/apache/cgi-bin/newuser.cgi", line 61, in ? > cstatus = im.save(file_name,'JPEG') > File "/usr/local/lib/python2.4/PIL/Image.py", line 1299, in save > fp = __builtin__.open(fp, "wb") > IOError: [Errno 13] Permission denied: > '/usr/local/apache/htdocs/captcha/t13uum15a2jgfj2sqg.jpg' that means exactly what it says: the user account that your CGI script is running under is not allowed to write to that directory. this is a Unix/Apache configuration issue, not really a Python issue. see this apache FAQ entry for some additional info: http://httpd.apache.org/docs/2.2/faq/error.html#error.permissiondenied From devdoer at gmail.com Sat Apr 22 08:47:39 2006 From: devdoer at gmail.com (devdoer at gmail.com) Date: 22 Apr 2006 05:47:39 -0700 Subject: python's thread problem on Linux platform Message-ID: <1145710059.777339.73230@u72g2000cwu.googlegroups.com> I found that multi-threaded program(io-centralize ) runs very slowly on linux while the same program runs very quickly on windows.If I change the thread number to one ,the program runs quickly on linux, in fact the speed is quicker than the multi-threaded version . It turns out that python's multi-thread support on linux has some problems.Any comments? From aahz at pythoncraft.com Tue Apr 25 23:05:01 2006 From: aahz at pythoncraft.com (Aahz) Date: Tue, 25 Apr 2006 20:05:01 -0700 Subject: REMINDER: BayPIGgies: April 26, 7:30pm (Google) Message-ID: <20060426030501.GA6421@panix.com> NOTE: Special date of WEDNESDAY April 26 at Google, usual time of 7:30pm Please show up by 7:15 so we can start the meeting on time! This does not change the usual May meeting on May 11 at Google; stay tuned for an announcement of that. Special meeting! One of the lead developers of Django is in town! Jacob Kaplan-Moss will be talking about Django at Google. He says he'll be fine-tuning the talk until the last minute but plans to cover: * How Django came into being -- a bit about the Journal-World, the problems that Django was designed to solve, some bits about its evolution, and a glance at how *we* use Django today. * What writing Django apps look -- I'll show off some real code and talk about each of the bits of Django's stack. This'll be the bulk of the talk. * What's in store for the future of Django -- there's some awesome community work going on, as well as some under-the-radar stuff we're working on that I'll try to preview or at least talk about. BayPIGgies meetings alternate between IronPort (San Bruno, California) and Google (Mountain View, California). For more information and directions, see http://baypiggies.net/ Before the meeting, we sometimes meet at 6pm for dinner. Discussion of dinner plans is handled on the BayPIGgies mailing list. Advance notice: We have speakers for May. We are currently setting up the schedule for the rest of the year. Please e-mail baypiggies at python.org if you want to suggest an agenda (or volunteer to give a presentation). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Argue for your limitations, and sure enough they're yours." --Richard Bach From esj at harvee.org Wed Apr 12 13:18:42 2006 From: esj at harvee.org (Eric S. Johansson) Date: Wed, 12 Apr 2006 13:18:42 -0400 Subject: drag and drop to icon In-Reply-To: <4a4plvFreg7fU1@uni-berlin.de> References: <4a4plvFreg7fU1@uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > Eric S. Johansson wrote: > Drag'n'Drop is highly OS-dependand and clearly out of scope for > standard-out-of-the-box python. If you are on macintosh, pyobjc and > > http://www.cocoadev.com/index.pl?DragAndDrop > > will certainly help. it does, thank you. as for drag and drop being highly GUI dependent, I was under the impression that the standard toolkits like tkinter had some form of abstraction for drag-and-drop built-in. I wasn't sure if it was possible to leverage some small portion of that for my application. ---eric From redefined.horizons at gmail.com Wed Apr 26 15:22:24 2006 From: redefined.horizons at gmail.com (redefined.horizons at gmail.com) Date: 26 Apr 2006 12:22:24 -0700 Subject: Events in Python? In-Reply-To: <1146071232.275024.5310@e56g2000cwe.googlegroups.com> References: <1146065995.016939.187440@i40g2000cwc.googlegroups.com> <1146071232.275024.5310@e56g2000cwe.googlegroups.com> Message-ID: <1146079344.627176.27280@e56g2000cwe.googlegroups.com> Thank you for all of the responses. I will check out the Traits link. It looked very interesting. It seems like Python doesn't have a "standard" implementation of an event or messaging system. That is really what I was curious about. I wanted to check before I implemented something of my own. Thanks again for the help. Scott Huey From tim.peters at gmail.com Tue Apr 25 14:15:36 2006 From: tim.peters at gmail.com (Tim Peters) Date: Tue, 25 Apr 2006 14:15:36 -0400 Subject: Probability Problem In-Reply-To: <699E9A7E-7773-4EC9-974B-1DE3E4127957@curi.us> References: <1hebf8p.1sb844li5y2g3N%aleaxit@yahoo.com> <1hebh2i.v0yximmkmwktN%aleaxit@yahoo.com> <699E9A7E-7773-4EC9-974B-1DE3E4127957@curi.us> Message-ID: <1f7befae0604251115k173930b4j56478c16d0ce1e92@mail.gmail.com> [Elliot Temple] > I think I got it. I noticed my code is essentially the same as Tim > Peter's (plus the part of the problem he skipped). I read his code 20 > minutes before recreating mine from Alex's hints. Thanks! > > def main(): > ways = ways_to_roll() > total_ways = float(101**10) > running_total = 0 > for i in range(1000-390+1): > j = i + 390 > running_total += ways[i] * ways[j] > print running_total / total_ways**2 > print ways[:10] > > def ways_to_roll(): > result = [1] > for i in xrange(10): > result = combine([1] * 101, result) > return result > > def combine(a, b): > results = [0] * (len(a) + len(b) - 1) > for i, ele in enumerate(a): > for j, ele2 in enumerate(b): > results[i+j] += ele * ele2 > return results > > main() > # output: 3.21962542309e-05 and > # [1, 10, 55, 220, 715, 2002, 5005, 11440, 24310, 48620] > # 3.21962542309e-05 is 32 out of a million You should sanity-check the computation by generalizing it, then applying it to a case so small you can easily work out the result via exhaustive enumeration by hand. For example, suppose you took integers from the much smaller set {0, 1}, and did that only twice. Then the possible sums and their probabilities are clearly: 0 1/4 1 1/2 2 1/4 If you did this twice, what's the probability that the sums differ by 1? Suitably generalized, your program above would compute 1/4. Is that actually right? It depends on what exactly "the sums differ by 1" means. If it means the second sum is one larger than the first sum, 1/4 is correct. Ditto if it means the second sum is one smaller than the first sum. But if it means 1 is the absolute value of the difference of the sums, the right answer is 1/2. I'm not sure which meaning you have in mind, but the last one was my guess. From bokr at oz.net Tue Apr 25 03:21:22 2006 From: bokr at oz.net (Bengt Richter) Date: Tue, 25 Apr 2006 07:21:22 GMT Subject: Why new Python 2.5 feature "class C()" return old-style class ? References: <1144752553.305591.88050@j33g2000cwa.googlegroups.com> <1144756774.177225.311120@z34g2000cwc.googlegroups.com> <443ba5a9$0$14281$626a54ce@news.free.fr> <1144763398.243329.231380@g10g2000cwb.googlegroups.com> <443bbdbe$0$15517$626a54ce@news.free.fr> <444befc6.251077400@news.oz.net> Message-ID: <444dcc07.43231884@news.oz.net> On Sun, 23 Apr 2006 22:12:01 GMT, bokr at oz.net (Bengt Richter) wrote: [...] >(IMO the proper way to indicate the you don't have a tuple is to use None or some other sentinel, >not abuse a perfectly legal tuple value). > > >>> dis.dis(compile('class X:pass','','exec')) > 1 0 LOAD_CONST 0 ('X') <<--+-- ought to be LOAD_CONST 0 (None) Oops, leave the 'X' of course, just replace the next line > 3 BUILD_TUPLE 0 <<--' > 6 LOAD_CONST 1 () > 9 MAKE_FUNCTION 0 > 12 CALL_FUNCTION 0 > 15 BUILD_CLASS > 16 STORE_NAME 0 (X) > 19 LOAD_CONST 2 (None) > 22 RETURN_VALUE > >vs code for class x(something):pass > > >>> dis.dis(compile('class X(object):pass','','exec')) > 1 0 LOAD_CONST 0 ('X') > 3 LOAD_NAME 0 (object) > 6 BUILD_TUPLE 1 > 9 LOAD_CONST 1 () > 12 MAKE_FUNCTION 0 > 15 CALL_FUNCTION 0 > 18 BUILD_CLASS > 19 STORE_NAME 1 (X) > 22 LOAD_CONST 2 (None) > 25 RETURN_VALUE > Regards, Bengt Richter From onurb at xiludom.gro Thu Apr 13 14:11:32 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 13 Apr 2006 20:11:32 +0200 Subject: Can't see the forest for the trees - when reading file, only processing first line In-Reply-To: <123t1kbige4ok93@corp.supernews.com> References: <123t1kbige4ok93@corp.supernews.com> Message-ID: <443e94a0$0$994$626a54ce@news.free.fr> News wrote: > Hi Everyone, > > > The attached code creates client connections to websphere queue managers > and then processes an inquiry against them. > > The program functions when it gets options from the command line. > > It also works when pulling the options from a file. > > My issue is that it only processes the first line of the file. > > Does anyone know why this might be the case? > > The use_file() function should be returning each file line. > > Any help you can provide on this would be greatly appreciated. > > Thanks > > (snip) > > # > # Read a file into a list Hint : use docstrings for this kind of comments. > def use_file(): > myfile = open(options.filename) 1/ options.filename should be passed as an argument. Globals are definitively evil and should be avoided by all means. 2/ open() may raise an error. You may (or not) want to handle this error here. > while True: > line=myfile.readline() > print line Why this print statement ? debug ? > if len(line) == 0: > myfile.close() > break > else: > return line This of course will read only the first line. The return statements terminates execution of the function. And BTW: > myfile.close() ... This will never execute. (snip) > if options.filename is not None: > line = use_file() > (options,args) = parser.parse_args(line.split()) Using it that way wouldn't work anyway... and may have unexpected results, since you're overwriting the existing options object. > check_params() > else: > check_params() Since you call check_params() anyway, it would simpler to write it: if options.filename is not None: do_someting_with_options_here() check_params() Now for your question: if options.filename is not None: try: f = open(options.filename) except IOError, e: # stdout is for normal program outputs only, # error messages should go to stderr print >> sys.stderr, \ "failed to open options file %s : %s" \ % (options.filename, e) sys.exit(1) for line in f: # pass the existing options object in, # so it's updated with the new args instead of # being overwritten options, args = parser.parse_args(line.split(), options=options) f.close() del f check_params() BTW, check_params() should also takes the options object as argument. Globals are evil. Definitively. Also, and if I may suggest, check_options() would be a better name IMVHO. And while we're at it, you're once again in a bad case of reinventing the SquareWheel(tm) with the usage() function - optparse takes care of this: http://docs.python.org/lib/optparse-generating-help.html (snip) if options.quiet is False: You'd better not identity test against True or False. There are lot of expressions that evaluate to True or False in a boolen context, without actually *being* neither the True object nor the False object. -> if not options.quiet: (snip) HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From sjuranic at gmail.com Tue Apr 25 12:24:51 2006 From: sjuranic at gmail.com (Steve Juranich) Date: Tue, 25 Apr 2006 09:24:51 -0700 Subject: Zope 3 References: <1145965796.432891.274310@i39g2000cwa.googlegroups.com> <444e3cf6$0$401$626a54ce@news.free.fr> Message-ID: bruno at modulix wrote: > Actually, the OP was asking about Zope3, which is a *very* different > beast. Okay, so my ignorance is showing (/me pauses to stuff it back where it belongs). So is there some big master diff, along the lines of "What's new in Python X.X" that I could look at to get an idea of what z3 has that 2.9 (which I'm currently still cutting my teeth on) doesn't? I've looked at the documentation on the main Zope page (zope.org) and all of the documents I've seen are apparently geared towards Zope 2.X. Where are the Zope3 docs? Thanks. -- Steve Juranich Tucson, AZ USA From ldo at geek-central.gen.new_zealand Tue Apr 11 03:12:54 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 11 Apr 2006 19:12:54 +1200 Subject: How can I reduce the number of queries to my PostgreSQL database? References: <1144489087.794505.277930@v46g2000cwv.googlegroups.com> Message-ID: In article <1144489087.794505.277930 at v46g2000cwv.googlegroups.com>, "SR" wrote: >The script works fine, if a little slow. I think that's because if I >have 50 books in my database, my script performs 51 database queries (1 >for all book names; then 1 for each book) If your database is that small, why bother with sophisticated relational-database queries at all? Why not just load everything into memory, and use sets and dicts and things to put it all together? This is feasible for databases with up to thousands or even tens of thousands of records in them, on today's machines. From steve at rueb.com Mon Apr 17 17:17:08 2006 From: steve at rueb.com (Steve Bergman) Date: 17 Apr 2006 14:17:08 -0700 Subject: piping question References: Message-ID: <1145308628.097556.280510@g10g2000cwb.googlegroups.com> Have you tried running python with '-u'? That turns off most buffering within python at least. I'm not familiar with newspost, so I've no idea what to do about any output buffering it might be doing. From alainpoint at yahoo.fr Tue Apr 11 05:48:23 2006 From: alainpoint at yahoo.fr (alainpoint at yahoo.fr) Date: 11 Apr 2006 02:48:23 -0700 Subject: challenging (?) metaclass problem In-Reply-To: References: <1144656384.077748.229010@u72g2000cwu.googlegroups.com> Message-ID: <1144742158.290991.6460@i40g2000cwc.googlegroups.com> Hi Peter, I don't know if you noticed but i changed my mind and removed the post as i realised that people seemed to have much more interest in how relevant c code still is than in solving an interesting problem. I only speak French and Dutch and my knowledge of Belgium's third official language (German) is only passive. Otherwise i would have posted on the german newsgroup (the French newsgroup does not seem to be so interesting and there are no belgian or dutch newsgroups either). Anyway, thank you for accepting the challenge. I'll try out your code and get back if i have any problem. Viele dank. Alain From rschroev_nospam_ml at fastmail.fm Fri Apr 14 06:16:46 2006 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri, 14 Apr 2006 10:16:46 GMT Subject: Remove Whitespace In-Reply-To: References: <9583ed900604131200n5c43829ckeb01ba4503763954@mail.gmail.com> <443f4257$1@news.eftel.com> Message-ID: Fredrik Lundh schreef: > John Machin wrote: > >>> $ python2.4 -mtimeit -s "str = 'D c a V e r \" = d w o r d : 0 0 0 0 0 6 >>> 4 0'" 'str.replace(" ", "")' >> Oi! The OP mentioned "whitespace" ... > > yeah. but as is obvious from his examples, he really means "UTF-16", not > whitespace. Yes, that's what I was thinking. His data looks like a part of a Windows registry export, which at least on my system is in what Windows calls Unicode. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From lard at tardis.ed.ac.molar.uk Sun Apr 2 06:11:59 2006 From: lard at tardis.ed.ac.molar.uk (Alex Hunsley) Date: Sun, 02 Apr 2006 10:11:59 GMT Subject: DO NOT USE JAVA BECAUSE IT IS NOT OPEN SOURCE In-Reply-To: <1143867556.814290.321740@i40g2000cwc.googlegroups.com> References: <1143867556.814290.321740@i40g2000cwc.googlegroups.com> Message-ID: atbusbook at aol.com wrote: > Programing Languiges Are Ment to be free. That is why i am starting The > Coo De Tar > thats french for Blow of state No, "Coup d'?tat" is French. http://en.wikipedia.org/wiki/Coup > it is a flash/java > alternative and if you are going to use a server side languige use > Perl,Python or better yet Ruby. What is the point of a languige without > a standerd and without a open source distrabution. Coo De Tar will be > released as a api for perl,python and ruby. Java sucks because it IS > NOT FREE. I AM A GNU GUY I BELEVE THAT SOFTWARE MUST AND SHALL BE > FREE!!!!!!!!!!!!!! do not use java because it is an oxymoron Your AOL is showing. Badly. From piet at cs.uu.nl Sat Apr 1 04:13:20 2006 From: piet at cs.uu.nl (Piet van Oostrum) Date: Sat, 01 Apr 2006 11:13:20 +0200 Subject: Python 2.5 licensing: stop this change References: <1143880645.973457.105300@t31g2000cwb.googlegroups.com> Message-ID: >>>>> "Fuzzyman" (F) wrote: >F> Can I ask for clarification. The charge applies to any commercial use >F> of a derivative work based on the Python source code ? >F> Normal applications that use Python, including bunding the standard >F> CPython as an executable, using tools like py2exe, won't be covered. >F> Right ? As I understand it, distributing Python is also covered. For a commercial vendor $1.25 is peanuts, but for the PSA it is a significant amount (think about all the Mac OSX copies if Apple decides to switch to 2.5). -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From adaviscg1 at hotmail.com Sat Apr 8 07:03:55 2006 From: adaviscg1 at hotmail.com (geletine) Date: 8 Apr 2006 04:03:55 -0700 Subject: DO NOT USE JAVA BECAUSE IT IS NOT OPEN SOURCE References: <1143867556.814290.321740@i40g2000cwc.googlegroups.com> <1144335907.627872.55590@i39g2000cwa.googlegroups.com> Message-ID: <1144494235.399140.233970@j33g2000cwa.googlegroups.com> Nobody has mentioned that c was proprietary until richard stallman wrote gcc in 1987, c is a great for system programming. Just because something is originally proprietary does not mean its technically rubbish, there are plenty of merits in java escially for new programmers or anyone who wants to get a program going very quickly. Gcj at the moment can do most tasks apart from swing gui, i believe Awt is well supported. To further my position, without the proprietary(it was licenced on a liberal account at the time) UNIX created in bell labs, they would possibly not be linux. Miguel de Icaza started implemening mono as he too saw technical advantages in .net, he is freeing the language in my opinion. Technology is just as important as polictics, hopefully i am well understood From pmartin at snakecard.com Thu Apr 27 08:58:49 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Thu, 27 Apr 2006 07:58:49 -0500 Subject: print names of dictionaries References: <1146085818.242086.206290@e56g2000cwe.googlegroups.com> <1146086980.998908.281140@g10g2000cwb.googlegroups.com> <1c34g.4097$B42.528@dukeread05> Message-ID: OK, totally dumb ! g_dict[s] = p Philippe Martin wrote: > Hi, > > I do not know if there is a way to overload the instantiation of all > objects in Python but I thought of something like this to fetch any object > with its name: > > g_dict = {} > > > def create_object (v,s): > p = v > g_dict[s] = id(p) > return p > > #ex > object = create_object ([1,2,3,4], 'A LIST') > > Philippe > > > > > > Thomas Nelson wrote: > >> Here's an OO way that may do what you want: >>>>> class MyD(dict): >> ... def __init__(self,dic,rep): >> ... dict.__init__(self,dic) >> ... self.rep = rep >> ... def __repr__(self): >> ... return self.rep >> ... >>>>> apps = MyD({'alpha':1,'beta':2},'apps') >>>>> apps >> apps >>>>> apps.keys() >> ['alpha', 'beta'] >> >> Of course, the easiest way is just to use a tuple (dict,string). >> >> THN From sambo at void.com Mon Apr 17 13:31:55 2006 From: sambo at void.com (Sambo) Date: Mon, 17 Apr 2006 13:31:55 -0400 Subject: Fixing Python instalation in win2000 by hand In-Reply-To: References: <7YP%f.393$nK2.12@newsfe22.lga> <1145035088.113942.264660@e56g2000cwe.googlegroups.com> <1145053798.560072.305950@i40g2000cwc.googlegroups.com> Message-ID: > > c:\temp1>msiexec /I c:\temp1\python-2.4c1.msi /L*v install.log > /L*v ???? ok here it is... before downloading and installin the VB > scripting crap.( in case it starts closing apps > trying to reboot and clear all this typing I've done hehe. > install.log > === Verbose logging started: 17/04/2006 12:28:52 Build type: SHIP > UNICODE 3.01.4000.2435 Calling process: C:\WINNT\system32\msiexec.exe === > MSI (c) (84:10) [12:28:52:609]: Resetting cached policy values > MSI (c) (84:10) [12:28:52:609]: Machine policy value 'Debug' is 0 > MSI (c) (84:10) [12:28:52:609]: ******* RunEngine: > ******* Product: c:\temp1\python-2.4c1.msi > ******* Action: ******* CommandLine: ********** > MSI (c) (84:10) [12:28:52:609]: Machine policy value > 'DisableUserInstalls' is 0 > MSI (c) (84:10) [12:29:23:156]: Failed to connect to server. Error: > 0x80080005 > > MSI (c) (84:10) [12:29:23:156]: MainEngineThread is returning 1601 > === Verbose logging stopped: 17/04/2006 12:29:23 === Well, I installed the scripten.exe but to no avail. same log , same behavior. install1.log === Verbose logging started: 17/04/2006 13:20:01 Build type: SHIP UNICODE 3.01.4000.2435 Calling process: C:\WINNT\system32\msiexec.exe === MSI (c) (4C:10) [13:20:01:781]: Resetting cached policy values MSI (c) (4C:10) [13:20:01:781]: Machine policy value 'Debug' is 0 MSI (c) (4C:10) [13:20:01:781]: ******* RunEngine: ******* Product: python-2.4c1.msi ******* Action: ******* CommandLine: ********** MSI (c) (4C:10) [13:20:01:890]: Machine policy value 'DisableUserInstalls' is 0 MSI (c) (4C:10) [13:20:33:296]: Failed to connect to server. Error: 0x80080005 MSI (c) (4C:10) [13:20:33:312]: MainEngineThread is returning 1601 === Verbose logging stopped: 17/04/2006 13:20:33 === Windows Installer (box) The windows Installer Service could not be accessed. this can occur.... in safe mode, or if Installer is not correctly installed. Contact.... for assistance. So I guess no way to retrieve the contents/instructions of python.msi SCRYPT to find out what should go where? Cheers. From fulvio at pc.jaring.my Sat Apr 29 06:10:32 2006 From: fulvio at pc.jaring.my (Fulvio) Date: Sat, 29 Apr 2006 18:10:32 +0800 Subject: ANN: Leo 4.4 rc1 released In-Reply-To: <04q4g.28$9R.27@fe04.lga> References: <04q4g.28$9R.27@fe04.lga> Message-ID: <200604291810.32249.fulvio@pc.jaring.my> Alle 22:58, venerd? 28 aprile 2006, Edward K. Ream ha scritto: > Many new commands, including Small question..... Has it way of using macro or programmable input? I mean this because for linux there arent many text editors with macro (recording/playing back) nor any with script commands. Thank you. If Leo lack of this, would be appreciated to give some idea to get involved on making it running python code. F From siona at chiark.greenend.org.uk Thu Apr 6 11:33:23 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 06 Apr 2006 16:33:23 +0100 (BST) Subject: pre-PEP: The create statement References: <59Wdnbd8EazRCqnZnZ2dnUVZ_vudnZ2d@comcast.com> <1144328362.729594.173160@z34g2000cwc.googlegroups.com> <13B*uLudr@news.chiark.greenend.org.uk> <1144335440.387962.250960@u72g2000cwu.googlegroups.com> Message-ID: <3wF*W0udr@news.chiark.greenend.org.uk> Michele Simionato wrote: >Sion Arrowsmith wrote: >> A quick scan of the standard library suggests that it will have >> a grand total of 3 modules requiring a fix (it's a method name >> in imaplib and a named argument in a couple of places in bsddb >> and distutils). Your own code my fare worse (mine does, but not >> by much). >This agrees with my scan (except I also found an occurrence of 'create' >in Tkinter). >BTW, I would be curious to see the script you are using for the >scanning. Old-fashioned egrep '\Wcreate\W' and eyeball out the false positives 8-) . I missed the Tkinter one because I don't appear to have it installed. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From nobody at 127.0.0.1 Thu Apr 27 20:45:50 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Fri, 28 Apr 2006 00:45:50 GMT Subject: stdin: processing characters References: Message-ID: <2Bd4g.21380$tN3.16246@newssvr27.news.prodigy.net> Kevin Simmons wrote: > I have a python script that prompts the user for input from stdin via a > menu. I want to process that input when the user types in two characters > and not have to have the user press . As a comparison, in the bash > shell one can use (read -n 2 -p "-->" CHOICE; case $CHOICE in...). Works > great and is very I did something like this a couple years ago, curses was the easiest way I found to do it. It's pretty painless with the wrapper function, which restores your terminal on error/exit. From timrueAT at mindspringDOT.com Mon Apr 24 00:32:42 2006 From: timrueAT at mindspringDOT.com (threeseas) Date: Mon, 24 Apr 2006 04:32:42 GMT Subject: Remember me... The Virtual Interaction configuration? Message-ID: for those who don't like me, here's your last chance to shoot me down See wikipedia entries for Timothy Rue and Abstraction Physics. From kruhftREMOVE at gmail.com Wed Apr 12 13:13:35 2006 From: kruhftREMOVE at gmail.com (Burton Samograd) Date: 12 Apr 2006 11:13:35 -0600 Subject: Initializing defaults to module variables Message-ID: <87psjm3ef4.fsf@gmail.com> Hi, I'm writing an app that stores some user configuration variables in a file ~/.program/config, which it then imports like so: import sys from posix import environ sys.path.append(environ["HOME"]+"/.program") import config I can then access the configuration through code like: login(config.username) My question is, how can I setup my program defaults so that they can be overwritten by the configuration variables in the user file (and so I don't have to scatter default values all over my code in try/catch blocks)? Basically, I would like to be able to do something like this: config.login = "noone" config.password = "secret" . . . import sys from posix import environ sys.path.append(environ["HOME"]+"/.program") import config So I guess the real question is: Is there a way to create a module namespace and populate it before sourcing the file? -- burton samograd kruhft .at. gmail kruhft.blogspot.com www.myspace.com/kruhft metashell.blogspot.com From jg.lists at sympatico.ca Fri Apr 7 18:07:58 2006 From: jg.lists at sympatico.ca (Jim Gallacher) Date: Fri, 07 Apr 2006 18:07:58 -0400 Subject: mod_python + apache + winxp => nogo In-Reply-To: <1144445910.877992.80210@v46g2000cwv.googlegroups.com> References: <1144445910.877992.80210@v46g2000cwv.googlegroups.com> Message-ID: <4436E2BE.8060802@sympatico.ca> cyberco wrote: > And I thought this would be trivial...getting mod_python to run within > apache on windows XP. > > ============= > mod_python 3.2.8 > apache 2.0.55 > python2.4 > winxp > ============= > > After adding: > "LoadModule python_module modules/mod_python.so" > > to apache's httpd.conf, apache refuses to start, saying: > "cannot load c://mod_python.so into server: the specified module > could not be found" > > 'mod_python.so' is in the modules folder under apache, though. > > I've searched everywhere, but could not find a solution. Anybody here > that has been successful in getting this combo to work? > Surely not *everywhere*, since a similar question was posed on the mod_python mailing list just 3 days ago. ;) For possible solutions see: http://modpython.org/pipermail/mod_python/2006-April/020770.html Jim From jjl at pobox.com Tue Apr 4 19:18:16 2006 From: jjl at pobox.com (John J. Lee) Date: 04 Apr 2006 23:18:16 +0000 Subject: socket connetion to url with port 80 References: <1144184532.778543.315410@e56g2000cwe.googlegroups.com> <1144187795.017072.230120@i40g2000cwc.googlegroups.com> Message-ID: <871wwdc4lj.fsf@pobox.com> "Sakcee" writes: > I got the response using s.send("GET / HTTP/1.0\r\n\r\n"), > > but this socket is being blocked by squid server that we have installed > in our socket. You don't have squid installed "in your socket". You have it installed on a computer. Going through squid may indeed be the only way of getting to the outside world, depending on how squid and your network are configured. > do you know how can i configure the squid to stop > blocking the socket If you don't already know the answer to that (or even if you did), I wonder if you might live to regret delving into all this nonsense, but, for example: http://www.ietf.org/rfc/rfc2617.txt Or look at httplib.py and urllib.py from the standard library. John From ryang at gol.com Tue Apr 25 09:44:47 2006 From: ryang at gol.com (Ryan Ginstrom) Date: Tue, 25 Apr 2006 22:44:47 +0900 Subject: Hooking things up in GUI application In-Reply-To: <1145965957.073830.320580@y43g2000cwc.googlegroups.com> Message-ID: <001201c6686e$6afdb160$030ba8c0@RYAN> > Behalf Of sturlamolden > If you use PyGTK (it also runs on Windows), you can design > the GUI with > GLADE and then use libglade to import the gui as an xml-resource. Yes, I've tried something similar with wxGlade. Nice, but it doesn't seem to remove the most tedious work -- hooking up handlers (although it does help here, at the cost of some behind-the-scenes magic), and getting data into and out of GUI widgets. That's the kind of boilerplate code that makes GUI development a pain in my opinion -- the actual GUI design/layout isn't so bad, especially with the spacer layout concept. -- Regards, Ryan Ginstrom From rpdooling at gmail.com Fri Apr 21 09:59:34 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 21 Apr 2006 06:59:34 -0700 Subject: what has python added to programming languages? (lets be esoteric, shall we ; ) In-Reply-To: <1145626586.497042.72080@i39g2000cwa.googlegroups.com> References: <1145626586.497042.72080@i39g2000cwa.googlegroups.com> Message-ID: <1145627974.914804.14540@z34g2000cwc.googlegroups.com> In the Tutorial, the BFDL says: Strings can be subscripted (indexed); like in C, the first character of a string has subscript (index) 0. There is no separate character type; a character is simply a string of size one. Like in Icon, substrings can be specified with the slice notation: two indices separated by a colon. http://www.python.org/doc/current/tut/node5.html#SECTION005120000000000000000 From xah at xahlee.org Thu Apr 27 17:22:03 2006 From: xah at xahlee.org (Xah Lee) Date: 27 Apr 2006 14:22:03 -0700 Subject: Xah's Edu Corner: What Languages to Hate In-Reply-To: <1145992903.834316.198370@u72g2000cwu.googlegroups.com> References: <1145992903.834316.198370@u72g2000cwu.googlegroups.com> Message-ID: <1146172923.830732.187130@i40g2000cwc.googlegroups.com> What Languages to Hate Xah Lee, 20020718 Dear lisp comrades and other concerned parties, First, all languages have equal rights. Do not belittle other languages just because YOUR favorite language is a bit better in this aspect or that. Different people have different ideas and manners of perception. Ideas compete and thrive in all unexpected fashions. Societies improve, inventions progress. Lisp may be a first in this or that, or faster or flexibler, or higher level than other languages old and new, but then there are other languages the like of Mathematica & Haskell & Dylan et al which ridicule lisps in the same way lisp ridicule other languages. Just because YOU are used to more functional programing or love lots of parenthesis doesn't mean they are the only and best concepts. The so-called Object Oriented programing of Java fame, or the visual programing of Visual Basic fame, or the logic programing of Prolog fame, or the format-stable syntax of Python fame, or the ?one line of Mathematica equals ten to one thousand lines of lisp? of _A New Kind Of Science_ fame... all are parts of healthy competing concepts, paradigms, or directions of growth. The way some of you deride other languages is like sneering heterogeneousness. If unchecked, soon you'll only have your sister to marry to. Cute, but you do not want incest to become the only sex. Next time your superiority complex makes you sneer at non-lisp or other non-popular languages, remember this. It is diversity of ideas, that drives the welfare of progress. Now, there is one judgmental criterion, that if a language or computer technology fits it, then we not only should castigate at their missionaries, but persecute and harass the language to the harshest death. That is: utter sloppiness, irresponsibility, and lies. These things are often borne out of some student's homework or moron's dirty-work, harbored by ?free? and wanton lies and personal fame, amassed thru ignorance. Of my short but diligent industrial unix computing experience since 1998, i have identified the following targets: * C (and consequences like csh, C++) * vi * Perl * MySQL * unix, unixism, and things grown out of unix. (languages, protocols, philosophies, expectations, movements) In our software industry, i like to define criminals as those who cause inordinate harm to society, not necessarily directly. Of the above things, some of their authors are not such criminals or are forgivable. While others, are hypocritical fantastic liers selfish to the core. When dealing with these self-promoting jolly lying humble humorous priests and their insidious superficially-harmless speeches, there should be no benefit of doubt. Tell them directly to stop their vicious lies. Do a face-off. As to their brain-washed followers for example the not-yet-hard-core unix, C, or Perl coders rampant in industry, try to snap them out of it. This you do by loudly snapping fingers in front of their face, making it sound like a ear piercing bang. Explain to them the utter stupidity of the things they are using, and the harm to their brain. IMPORTANT: _teach_, not _debate_ or _discuss_ or falling back into your philosophical deliberating indecisiveness. I've seen enough criticisms among learned programers or academics on these, so i know you know what i'm talking about. When you see a unixer brainwashed beyond saving, kick him out of the door. He has became a zombie who cannot be helped. There are other languages or technology, by itself technically are perhaps mediocre but at least is not a egregious irresponsible hack, therefore does not deserve scorn, but sometimes it comes with overwhelming popular outrageous lies (euphemized as hype). Java is a example. For this reason, it is equally deserving the harshest treatment. Any loud proponents of such should be immediately slapped in the mouth and kicked in the ass in no ambiguous ways. Summary: all languages have equal rights. However, those utterly SLOPPY and IRRESPONSIBLE HACKS with promoter's LIES should be severely punished. It is these, that cause computing industry inordinate harm. Meanwhile, it is wrong to haughtily criticize other languages just because they are not your cup of tea. Now, please remember this and go do society good. ---- This post is archived at: http://xahlee.org/UnixResource_dir/writ/language_to_hate.html Xah xah at xahlee.org ? http://xahlee.org/ From bj_666 at gmx.net Wed Apr 5 17:40:04 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 05 Apr 2006 23:40:04 +0200 Subject: how to comment lot of lines in python References: <1143760897.940841.285300@i39g2000cwa.googlegroups.com> <1144194320.725889.228140@u72g2000cwu.googlegroups.com> <00A7FOGZ38812.3771990741@reece.net.au> Message-ID: In <00A7FOGZ38812.3771990741 at reece.net.au>, Michael Sperlle wrote: > What's wrong with using three sets of double-quotes? One can't comment out code that contains multiline strings. Especially nested comment out does not work. > I do it with kwrite and it works like a charm. Why not Ctrl+D (comment) and Ctrl+Shift+D (uncomment)? Ciao, Marc 'BlackJack' Rintsch From aleaxit at yahoo.com Tue Apr 25 10:32:41 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 25 Apr 2006 07:32:41 -0700 Subject: MinGW and Python References: <1145861223.509630.247350@y43g2000cwc.googlegroups.com> <444C79D7.4060007@v.loewis.de> <1145968496.649214.100040@i40g2000cwc.googlegroups.com> Message-ID: <1hec9xh.m7rzefh64am3N%aleaxit@yahoo.com> sturlamolden wrote: > Robert Kern wrote: > > > Dunno. Depends on the machine. Depends on the program. Depends on how > > the interpreter and any extension modules and underlying libraries were > > built. Depends on which Linux and which Windows. > > > > I'm sorry, but your question is a non sequitur. I don't understand its > > relevance to this thread. > > The relevance: Python is built with GCC on Linux. Do you or do you not > see a performance hit on Linux? > > MinGW is GCC. Will you get a performance hit when building Python with > MinGW? I cannot predict this, though it would be great if somebody who does have both VS2003 and mingw could give it a try. What I did just post on another thread over the last couple of days is about MacOSX, which also uses gcc: 14% faster pybench using Python 2.4.3 under Win2000 under Parallels Workstation beta, compared to 2.4.3 Universal directly on MacOSX -- the standard build of 2.4.3 in either cause, i.e., the one built with MS compilers on Windows, vs the one built with Apple's gcc on MacOSX. Alex From ToddLMorgan at gmail.com Sat Apr 22 03:40:51 2006 From: ToddLMorgan at gmail.com (ToddLMorgan) Date: 22 Apr 2006 00:40:51 -0700 Subject: Looking for resources for making the jump from Java to Python easier and more productive Message-ID: <1145691651.385835.298600@u72g2000cwu.googlegroups.com> I'm just starting out with python, after having a long history with Java. I was wondering if there were any resources or tips from anyone out there in Python-land that can help me make the transition as successfully as possible? Perhaps you've made the transition yourself or just have experience with folks who have made the transition. I'm looking for the common types of mistakes that say a Java/C# or even C++ developer may commonly make. More examples like those highlighted here http://dirtsimple.org/2004/12/python-is-not-java.html would be particularly useful. I've already made the static class method mistake, and been thoroughly confused by packages and imports/froms and extremely frustrated with attempting to call super constructors etc. I'm getting the hang of passing around functions (ala the command pattern), customising the operators and extending inbuilt classes. All of these concepts I've done before so there nothing really great and wonderful about using them in another language. Some of the really powerful ideas of python (eg as suggested in the link) about creating one function containing a template function that can cater to all possible implementations sounds really cool and alien to me at the same time. That's the sort of stuff I'm interested in. At this point in time I'd say my python code is more coding Java in python than doing it in a pythonic way. Perhaps there some good/great examples of Python scripts or projects that I could look at to get inspired or learn pythonic implementation ideas? I just don't know of any. Are there python specific equivalents to the common Patterns, Anti-Patterns and Refactoring books that are so prevalent as reccomended reading in C++ and Java? If so what? Given the rising popularity of Python these days there has got to be a few of you out there who've made the transition successfully and have some pearls-of-wisdom to share that you'd wished you'd known about earlier. Thanks Todd From bob at coolgroups.com Fri Apr 28 19:00:22 2006 From: bob at coolgroups.com (bob at coolgroups.com) Date: 28 Apr 2006 16:00:22 -0700 Subject: iputils module Message-ID: <1146265222.593028.203080@u72g2000cwu.googlegroups.com> Anyone know where to get the iputils module for python? From remi at cherrypy.org Tue Apr 4 11:04:21 2006 From: remi at cherrypy.org (remi at cherrypy.org) Date: 4 Apr 2006 08:04:21 -0700 Subject: ANN: CherryPy-2.2.0 released Message-ID: <1144163061.525564.95820@i40g2000cwc.googlegroups.com> (sorry for the double-post, the title of the previous one was wrong) Hello everyone, After six months of hard work and 300 changesets since the last stable release I'm happy to announce that CherryPy-2.2.0-final is out. The biggest changes are: - switch to a lowercase api (although the old camelCase API is still supported for backward compatibility) - support for multiple applications (new "cherrypy.tree" object) - better error handling - lots of bug fixes (especially in file-based sessions) - better test suite. Check out http://www.cherrypy.org/wiki/UpgradeTo2.2 for more details. *************** About CherryPy: CherryPy is a simple (no dependencies), pythonic (doesn't get in your way) web development framework. Here is a sample Hello, World in CherryPy: # import cherrypy # class HelloWorld: # @cherrypy.expose # def index(self): # yield "" # yield "Hello world!" # yield "" # cherrypy.root = HelloWorld() # cherrypy.server.start() The project has been growing strongly lately: cherrypy.org averaged 3000 visitors/day in March, up from 2000 visitors/day in January and February; and the cherrypy-users list just passed 700 users. Details and downloads are available from: http://www.cherrypy.org Remi. From jzgoda at o2.usun.pl Tue Apr 4 14:17:19 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Tue, 04 Apr 2006 20:17:19 +0200 Subject: kinterbas and Python In-Reply-To: <1144169752.389326@anc-srv.fastnet.it> References: <1144169752.389326@anc-srv.fastnet.it> Message-ID: Balin napisa?(a): > con = kinterbasdb.connect(host='192.168.1.20', > database='/home/db/TEST.FDB', user='SYSDBA', password='masterkey) <--- E I don't think it's valid. If you connect to remote host, don't give a path to database, just its name. Specifying full path long time ago was supported only using "local" connection. -- Jarek Zgoda http://jpa.berlios.de/ From jnair at ensim.com Mon Apr 17 08:41:13 2006 From: jnair at ensim.com (jnair at ensim.com) Date: 17 Apr 2006 05:41:13 -0700 Subject: something similar to LWP::Simple mirror function Message-ID: <1145277673.562151.101750@t31g2000cwb.googlegroups.com> from the perl man pages of LWP::Simple mirror($url, $file) Get and store a document identified by a URL, using If-modified- since, and checking the Content-Length. Returns the HTTP response code. is there something similar in python regards jitya From paddy3118 at netscape.net Thu Apr 20 17:33:36 2006 From: paddy3118 at netscape.net (Paddy) Date: 20 Apr 2006 14:33:36 -0700 Subject: How should multiple (related) projects be arranged (structured) and configured so that they can share code, have a related package structure and enable proper unittesting, and ensuring no namespace collisions References: <1145546785.268550.154240@e56g2000cwe.googlegroups.com> <1145563823.160038.257950@j33g2000cwa.googlegroups.com> <4447ee60$0$5199$626a54ce@news.free.fr> <1145565632.131816.146560@i40g2000cwc.googlegroups.com> Message-ID: <1145568816.554279.323420@e56g2000cwe.googlegroups.com> Thanks alisonken1, I did indeed mean that when you have production code and test code then its time to bring in the version control systems. But having said that ;-) i have been naughty in the past and used the -s or --symbolic-link option of the gnu cp (sometimes available as gcp), command which copies a whole directory tree of the production release to a test area, copying directories but putting links in to the original files. I make sure that the production code is all read-only thenwork in the test area. If I need to modify a file I: * list the link * remove the link, replacing it with a copy of the file linked to * get write priviliges to the new copy * edit the copy. But we should all be using a version control system right :-) - paddy. From sandravandale at yahoo.com Sat Apr 8 20:19:19 2006 From: sandravandale at yahoo.com (Sandra-24) Date: 8 Apr 2006 17:19:19 -0700 Subject: how relevant is C today? References: <44381ee4$0$4209$c3e8da3@news.astraweb.com> <871ww7elvu.fsf@ieee.org> Message-ID: <1144541959.611623.25540@i39g2000cwa.googlegroups.com> C/C++ is used for a lot of things and not going anywhere. I recommend you learn it not because you should create applications in C or C++, but because it will increase your skills and value as a programmer. I recommend you even spend a few weeks with an assembly language, for the same reason. However, when it comes to beginning new things with an eye for getting the job done, C/C++ (or Java for that matter...) is usually a bad idea. That having been said, there are always exceptions to the rule and you'll learn better how to call things as you advance your skills as a programmer. There are also sometimes parts of your application that just cannot be optimized any more in a high level language, and might benefit from being converted to C or C++. But do yourself a favor and only do such things after taking careful measurements and exhausting other options. Many time consuming algorithms don't gain a noticable speed improvement in lower level languages. -Sandra From grflanagan at yahoo.co.uk Sun Apr 23 10:29:36 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 23 Apr 2006 07:29:36 -0700 Subject: Generate a sequence of random numbers that sum up to 1? References: <1145693855.407215.102720@j33g2000cwa.googlegroups.com> <1145695700.800395.219050@i40g2000cwc.googlegroups.com> <1145714242.942988.315490@g10g2000cwb.googlegroups.com> Message-ID: <1145802576.356726.135180@i40g2000cwc.googlegroups.com> Nick Craig-Wood wrote: > Gerard Flanagan wrote: > > def distribution(N=2): > > p = [0] + sorted( random.random() for _ in range(N-1) ) + [1] > > for j in range(N): > > yield p[j+1] - p[j] > > > > spread = list(distribution(10)) > > > > print spread > > print sum(spread) > > This is simpler, easier to prove correct and most likely quicker. > > def distribution(N=2): > L = [ random.uniform(0,1) for _ in xrange(N) ] > sumL = sum(L) > return [ l/sumL for l in L ] > simpler:- ok easier to prove correct:- in what sense? quicker:- slightly slower in fact (using xrange in both functions). This must be due to 'uniform' - using random() rather than uniform(0,1) then yes, it's quicker. Roughly tested, I get yours (and Alex Martelli's) to be about twice as fast. (2<=N<1000, probably greater difference as N increases). All the best. Gerard From bencvt at gmail.com Tue Apr 11 21:13:02 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 11 Apr 2006 18:13:02 -0700 Subject: finish_endtag in sgmllib.py [Python 2.4] References: <1144802230.446613.297980@i39g2000cwa.googlegroups.com> Message-ID: <1144804382.736878.309380@g10g2000cwb.googlegroups.com> Richard Hsu wrote: > code:- > > # Internal -- finish processing of end tag > def finish_endtag(self, tag): > if not tag: # <---- i am confused about this > found = len(self.stack) - 1 > if found < 0: > self.unknown_endtag(tag) # <---- and this > return > > I am a little confused as to what is intended by " if not tag: " > does it mean > if tag == None or tag == "": # ? Technically, not quite. See http://docs.python.org/lib/truth.html In practice, tag will indeed be a string type (shouldn't ever be None), so 'tag == ""' would work just as well* as 'not tag'. However, it's cleaner and clearer to use the latter. * = barring some contrived custom string type > tag here is suppose to be a string. > > so the only way it will be True is when its either None or its "", then > we are essentially passing None or "" to self.unknown_endtag(tag) ?? Yes, a string of length zero will always be passed to unknown_endtag here. Answering your implicit question, there's no good reason to write it as "self.unknown_endtag(None)" instead. --Ben From ginstrom at tree.odn.ne.jp Thu Apr 20 21:24:06 2006 From: ginstrom at tree.odn.ne.jp (Ryan Ginstrom) Date: Fri, 21 Apr 2006 10:24:06 +0900 Subject: tail a file (win) In-Reply-To: <9583ed900604200933s4439022cw845b5a24f371d7d6@mail.gmail.com> Message-ID: <006c01c664e2$4874f9d0$030ba8c0@RYAN> > Behalf Of david brochu jr > I wrote a script to monitor ping activity and output it to a > log file. I am using windows and want to have another script > constantly check the latest entry to see if Request timed out > is seen. Is there a way to "tail" a file much like I would in > Unix so I can just see the latest entry and move from there? The method I would use that is not RAM/CPU intensive would be to create a memory-mapped file, take the size of the file, and increment your pointer to file_length - tail_size. The Windows API functions to look at are: CreateFile CreateFileMapping MapViewOfFile I'm sorry, but I'm not a ctypes guru so can't tell you how you would accomplish this in python. (The C(++) code is fairly straightforward, however). --- Regards, Ryan Ginstrom From wahab at chemie.uni-halle.de Sat Apr 8 16:44:18 2006 From: wahab at chemie.uni-halle.de (Mirco Wahab) Date: Sat, 08 Apr 2006 22:44:18 +0200 Subject: Compleated Begginers Guide. Now What? In-Reply-To: <1144497870.999295.162450@i39g2000cwa.googlegroups.com> References: <1144497870.999295.162450@i39g2000cwa.googlegroups.com> Message-ID: Jay wrote: > I have compleated the beginers guide to python > http://www.freenetpages.co.uk/hp/alan.gauld/. > then i found the Toolkit Tkinter and started on that. its graight and > av made lots of apps to help me with litle things but i have a big > problem. the CLASS method. Ledds viddy, my droog - you tried to rabbit hard but diddnt get your horrorshow? So you start platching here? > when i seperate things up into classes i carnt get one class to tell > the other class somthing. it just opens another coppy of the class. i > am confused. Malchick, you cracked your veshchs to classes, which is not that gloopy. So rabbit on them and add class methods that sloosh on beeing called and do the proper veshchs to the gulliwuts of their classes. > oh and i carnt fathem out how to run to loops at the same time. EG . > Ball Blaster i wanted to permenetly run the ball with a loop well my > main loop ran the bat. > can sumone point me to the right studeing material. All TK-lewdies here will creech 'callback' at you sth. So prod your working TK app by rabbit out a 'callback domy', just filly around with this http://effbot.org/zone/wck-2.htm#handling-user-events or that http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/464635 Tolchock it, M. From panos.laganakos at gmail.com Mon Apr 24 12:22:13 2006 From: panos.laganakos at gmail.com (Panos Laganakos) Date: 24 Apr 2006 09:22:13 -0700 Subject: Packing a list of lists with struct.pack() Message-ID: <1145895732.963584.231100@j33g2000cwa.googlegroups.com> Hello, I have a list that includes lists of integers, in the form of: li = [[0, 1, 2], [3, 4, 5], ...] packed = struct.pack(str(len(li)*3)+'i', li) The frmt part is right, as I'm multiplying by 3, 'cause each inner list has 3 elements. What can I do to get li as a single list of integers? I tried list comprehension in the form of: [([j for j in i]) for i in li] But that doesn't seem to work, any ideas? From kent at kentsjohnson.com Wed Apr 5 08:21:13 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Wed, 05 Apr 2006 08:21:13 -0400 Subject: String pattern matching In-Reply-To: <1144234164.742160.173640@e56g2000cwe.googlegroups.com> References: <1143888648.234963.326000@j33g2000cwa.googlegroups.com> <443159e6$1_1@newspeer2.tds.net> <1144234164.742160.173640@e56g2000cwe.googlegroups.com> Message-ID: <4433b0dc$1_2@newspeer2.tds.net> jimlewis at emachineshop.com wrote: > Thanks to all for the various good approaches. Kent's plain RE approach > seems the most straightforward - did not know that RE can handle this > situation - good to know! Thanks to Eddie Corns also who showed how to express the problem as a parsing problem. I am also trying a pyparsing solution but I don't see a way to repeat a previous element in pyparsing. Paul McGuire, are you listening? Kent From bignose+hates-spam at benfinney.id.au Tue Apr 18 18:45:59 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 19 Apr 2006 08:45:59 +1000 Subject: semi-[OT]: adding a reply-to line to these mails? References: <4444CD12.7080807@freakmail.de> Message-ID: <87r73uh594.fsf@benfinney.id.au> Wildemar Wildenburger writes: > I've noticed that I replied to individual posters' private addresses > several times now ... That's a much preferable, and much more easily corrected, error than the alternative: replying to the entire group what was intended only for the individual in private. > So a quick note to the admin(s): see topic ;) The Reply-To header field is to be set by an individual on their own messages, to indicate where a *private* reply should go. -- \ "I'd like to see a nude opera, because when they hit those high | `\ notes, I bet you can really see it in those genitals." -- Jack | _o__) Handey | Ben Finney From rrrn at yahoo.com Mon Apr 3 19:50:49 2006 From: rrrn at yahoo.com (Butternut squash) Date: Mon, 03 Apr 2006 23:50:49 GMT Subject: wxpython in action book References: Message-ID: Tim Roberts wrote: > Dabo Thanks for the info. I'll check out dabo. I understand that web is easier to distribute and more likely easier to program. I loath CSS and HTML though and that's why I want a fat client program. We'll see From onurb at xiludom.gro Tue Apr 25 05:41:18 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 25 Apr 2006 11:41:18 +0200 Subject: Looking for resources for making the jump from Java to Python easier and more productive In-Reply-To: References: <1145691651.385835.298600@u72g2000cwu.googlegroups.com> <444cb3e1$0$21091$626a54ce@news.free.fr> Message-ID: <444def12$0$14288$626a54ce@news.free.fr> Lawrence D'Oliveiro wrote: > In article <444cb3e1$0$21091$626a54ce at news.free.fr>, > bruno at modulix wrote: > > >>Lawrence D'Oliveiro wrote: >> (snip) >>>I suppose this is an instance of the more general rule: "using OO when >>>you don't have to". >> >>Lawrence, I'm afraid you're confusing OO with "statically-typed >>class-based". FWIW, dynamic typing is part of OO since Smalltalk. > > > I wasn't talking about dynamic typing, I was talking about subclassing, > which is very much a part of OO. What you wrote implies (well, at least I understand it that way) that polymorphic dispatch *not* based on subclassing is not OO. Hence my reaction : the need to use subclassing (inheritance) for subtyping (polymorphic dispatch) is not a requirement of object orientation and has never been - it's only a limitation of languages with declarative static typing (C++, Java, C# etc). > Unless you subscribe to the "OO is whatever looks like a good > programming idea" definition . Not really !-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From grante at visi.com Tue Apr 25 21:06:17 2006 From: grante at visi.com (Grant Edwards) Date: Wed, 26 Apr 2006 01:06:17 -0000 Subject: can someone explain why .. References: Message-ID: <124ths9lu6c1723@corp.supernews.com> On 2006-04-25, Farshid Lashkari wrote: > Sch?le Daniel wrote: >> I don't understand what is the difference between commented lines >> 1 and 2 >> >> with 1 uncommented and 2 commented it works as expected >> with 1 commented and 2 uncommented the picture doesn't appear > > > I'm not familiar with Tkinter, but it seems as thought with 2, the > "image" variable is garbage collected after the constructor of Main is > called. With 1, you save a reference to the image, so it does not get > garbage collected. Yes. That's exactly correct. It's sort of a FAQ. See the highlighted note at the bottom of http://effbot.org/tkinterbook/bitmapimage.htm -- Grant Edwards grante Yow! LOU GRANT froze at my ASSETS!! visi.com From fulvio at pc.jaring.my Sun Apr 16 07:05:50 2006 From: fulvio at pc.jaring.my (Fulvio) Date: Sun, 16 Apr 2006 19:05:50 +0800 Subject: List operation: Removing an item In-Reply-To: References: <1243ikb79qbujfc@corp.supernews.com> Message-ID: <200604161905.51051.fulvio@pc.jaring.my> On Sunday 16 April 2006 13:37, Terry Reedy wrote: >Do you really need the items sorted? Do you really think he isn't a troll? See the latest thread on lists end related PEP..... However there's always some good info on your reply (all of those had reply to OP). F From jelleferinga at gmail.com Tue Apr 18 08:00:55 2006 From: jelleferinga at gmail.com (jelle) Date: 18 Apr 2006 05:00:55 -0700 Subject: Shell like syntax for subprocess.Popen # overloading >, <, | In-Reply-To: References: <1145349423.908658.53180@g10g2000cwb.googlegroups.com> Message-ID: <1145361655.910837.300770@g10g2000cwb.googlegroups.com> Hi Christos, Thanks for your pointers there, impressive to see -that a 12 year old thread still can make an interesting read -you being able to remember & trace it... impressive... Thanks for your pointers. I think the input > process > output Syntax is more powerful , since it would let you build chaining commmands in a more readable fashion. The goal of this class would be to construct command chains such as: input > processA | processB > ouput Something which wouldn't be possible if only one operator is overloaded. I'm curious to see if its doable via overloading, since no __rgt__ methods exists... From martin at v.loewis.de Wed Apr 26 13:05:31 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 26 Apr 2006 19:05:31 +0200 Subject: MinGW and Python In-Reply-To: <1145995815.818582.166230@y43g2000cwc.googlegroups.com> References: <1145861223.509630.247350@y43g2000cwc.googlegroups.com> <444C79D7.4060007@v.loewis.de> <444DC62B.7000702@v.loewis.de> <1145985979.369429.114040@i39g2000cwa.googlegroups.com> <1145995815.818582.166230@y43g2000cwc.googlegroups.com> Message-ID: <444FA85B.7010104@v.loewis.de> Ross Ridge wrote: > Not exactly. They're both GCC, but the MinGW compiler that you can > download from MinGW WWW site is a native Win32 appliction, while the > "MinGW" compiler included with Cygwin and invoked by "-mno-cygwin" is a > Cygwin application. Any Cygwin application is a native Win32 application, which just happens to link with cygwin1.dll (which also is a native Win32 DLL). Just to make that clear: Everything that cygwin does is done solely with the Win32 API. The C library differs in semantics from the MS C library, but the system API is just the same. Regards, Martin From locoyfeo at gmail.com Mon Apr 3 13:43:06 2006 From: locoyfeo at gmail.com (El Loco) Date: 3 Apr 2006 10:43:06 -0700 Subject: New Python Logo Revealed In-Reply-To: References: <9bct22dngv6lncqfjju5oqi4772or4pdle@4ax.com> Message-ID: <1144086186.670816.14150@i39g2000cwa.googlegroups.com> Alec Jang wrote: > I guess it is absolutely a joke. If not, there will be a disaster, and > that means ruby will rule the world. Yes, we'll become slaves, our leaders crucified, and our culture will vanish forever... From python.list at tim.thechases.com Tue Apr 11 14:51:24 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 11 Apr 2006 13:51:24 -0500 Subject: RegExp question In-Reply-To: <1144781090.622493.252460@t31g2000cwb.googlegroups.com> References: <1144781090.622493.252460@t31g2000cwb.googlegroups.com> Message-ID: <443BFAAC.5050009@tim.thechases.com> > I would like to form a regular expression to find a few > different tokens (and, or, xor) followed by some variable > number of whitespace (i.e., tabs and spaces) followed by > a hash mark (i.e., #). What would be the regular > expression for this? (and|or|xor)\s*# Unless "varible number of whitespace" means "at least *some* whitespace", in which case you'd want to use (and|or|xor)\s+# Both are beautiful and precise. -tim From sushant.sirsikar at gmail.com Wed Apr 5 00:50:00 2006 From: sushant.sirsikar at gmail.com (sushant.sirsikar at gmail.com) Date: 4 Apr 2006 21:50:00 -0700 Subject: using range() in for loops In-Reply-To: <443324dc$0$11257$c3e8da3@news.astraweb.com> References: <443324dc$0$11257$c3e8da3@news.astraweb.com> Message-ID: <1144212600.591743.293570@j33g2000cwa.googlegroups.com> hi John, Python doesn't provide for loop like C / C++ but using Range() or Xrange() you can achive all the functionalities of the C for loop.If you wants distributed for loop You can use Xrange. John Salerno wrote: > I'm reading Text Processing in Python right now and I came across a > comment that is helping me to see for loops in a new light. I think > because I'm used to the C-style for loop where you create a counter > within the loop declaration, for loops have always seemed to me to be > about doing something a certain number of times, and not about iterating > over an object. > > The reason for this distinction comes from the fact that I read a lot > how using range and for is somewhat discouraged, because it doesn't > really use a for loop for it's true purpose. So my question is, is this > just a Python-oriented opinion about for loops, or is it a general idea? > > Also, what if you *do* need to just do something a set number of times. > Is this okay, or does it mean you are approaching the problem > incorrectly? Using for and range together seems to be a common idiom, > yet at the same time discouraged, so I'm wondering what is a good balance. > > Thanks. From nobody at 127.0.0.1 Tue Apr 25 13:12:21 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Tue, 25 Apr 2006 17:12:21 GMT Subject: Counting elements in a list wildcard References: <1145921582.526072.120480@u72g2000cwu.googlegroups.com> <444d90a1$0$2568$ed2619ec@ptn-nntp-reader02.plus.net> <444ddf2f$1@news.eftel.com> Message-ID: John Machin wrote: > On 25/04/2006 3:15 PM, Edward Elliott wrote: >> Phoneme matching seems overly complex and might >> grab things like Tsu-zi. > > It might *only* if somebody had a rush of blood to the head and devised > yet another phonetic key "algorithm". Tsuzi does *not* give the same > result as any of Suzi, Suzie, Susi, and Susie when pushed through any of > the following; Soundex, NYSIIS, Metaphone, Dolby, and Caverphone. None > of them throw away the 'T' sound. Spelling isn't phonetic. The 't' character doesn't necessarily affect pronounciation. Or it may affect pronounciation in a way the soundex doesn't understand (think tonal languages). Latinizing foreign languages raises all sorts of problems. A soundex is only as good as its pronounciation database. It may work well in many situations, but it isn't fool-proof. From http Mon Apr 3 19:15:22 2006 From: http (Paul Rubin) Date: 03 Apr 2006 16:15:22 -0700 Subject: question about nasty regex References: <4N2dnea4rqrZ26zZnZ2dnUVZ_tKdnZ2d@speakeasy.net> Message-ID: <7xacb2fdyt.fsf@ruckus.brouhaha.com> Peter writes: > >> What I mean is, I want to change, e.g.: > [snip regular expressions lesson] > > > > Whoa. That is super-duper extra cool. Thank you *very* much. "Some people, when confronted with a problem, think ``I know, I'll use regular expressions.'' Now they have two problems." --JWZ From newsgroup_mail... at ...binarystar.org Fri Apr 28 01:54:20 2006 From: newsgroup_mail... at ...binarystar.org (*binarystar*) Date: Fri, 28 Apr 2006 15:54:20 +1000 Subject: can i set up a mysql db connection as a class ? In-Reply-To: <1146199764.328276.241320@j33g2000cwa.googlegroups.com> References: <1146183359.932904.298760@g10g2000cwb.googlegroups.com> <1146199764.328276.241320@j33g2000cwa.googlegroups.com> Message-ID: your on the right track ... create something like this ( hope the formatting doesn't go to hay wire ) class DB_Connector(object): """ Humble Database Connection Class """ def __init__(self, host="localhost", user="MyUser",passwd="MyPassword", **other_db_arguments): self.host = host self.user = user self.passwd = passwd # Unpack Other Database Arguments Here self.CreateConnection() def CreateConnection( self ): self.cursor = MySQLdb.connect(self.host, self.user, self.passwd) def DestroyConnection( self ): self.cursor.close() def Execute( self, sql_statement ): self.cursor.Execute( sql_statement ) return self.cursor.FetchAll() Then when you run your program create an instance of the object db_connection = DB_Connector( 'localhost', 'administrator', 'betelgeuse99', auto_commit=1, other_keyword_arg="yes" ) now when you pass the db_connection instance to other classes, a copy will be made automagically thread_1_instance = ThreadingClass( db_connection ) thread_2_instance = ThreadingClass( db_connection ) thread_3_instance = ThreadingClass( db_connection ) should work .. I hope this is useful nephish at xit.net wrote: > This is great ! > > ok, i dont really have a lot of time to get into the ORMS (before your > post, this is the first i have heard of it) and my stuff is due on > Monday. he he. > > but, if i am able to make a global db connection, and multiple cursors > pointing to the same connection object, how do i pull that off without > making new db connections? > > something like > class db(self): > def __init__(self): > db = MySQLdb.connect(host="localhost", user="MyUser", > passwd="MyPassword", > db="Stuff") > def cursor(self): > cursor = db.cursor() > return cursor > > > then have in my threads that need to connect > > cursor = db.cursor() > cursor2 = db.cursor() > > and so on ? i may be way outta whack here. i am still new at classes, > methods, and modules. > i do have Essential Reference on the way from Amazon though ! :) > > thanks again > From fredrik at pythonware.com Mon Apr 17 17:37:12 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 17 Apr 2006 23:37:12 +0200 Subject: scanning through page and replacing all instances of 00:00:00.00 References: Message-ID: "Kun" wrote: > I have a python-cgi file that pulls data from an sql database, i am > wondering what is the easiest way to remove all instances of > '00:00:00.00' in my date column. > > how would i write a python script to scan the entire page and delete all > instances of '00:00:00.00', would i use regular expressions? umm. if you're using a database, why not filter out uninteresting dates either in the SQL statement, or when you're building the page ? From felipe.lessa at gmail.com Wed Apr 5 22:09:53 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Wed, 05 Apr 2006 23:09:53 -0300 Subject: efficiency of range() and xrange() in for loops In-Reply-To: References: Message-ID: <1144289394.4166.15.camel@kenshin.CASA> Em Qua, 2006-04-05 ?s 22:24 +0200, Fredrik Lundh escreveu: > the difference isn't very > large, xrange is actually slower in some python versions, and you'll > need the integer objects sooner or later anyway... Some code is worth a thousand words: $ python2.3 Python 2.3.5 (#2, Mar 6 2006, 10:12:24) [GCC 4.0.3 20060304 (prerelease) (Debian 4.0.2-10)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from timeit import Timer >>> min(Timer('for i in range(1): pass').repeat(3, 100000))/100 0.00099303960800170891 >>> min(Timer('for i in xrange(1): pass').repeat(3, 100000))/100 0.00077417135238647464 >>> min(Timer('for i in range(10): pass').repeat(3, 1000)) 0.0016450881958007812 >>> min(Timer('for i in xrange(10): pass').repeat(3, 1000)) 0.0013418197631835938 >>> min(Timer('for i in range(100): pass').repeat(3, 1000)) 0.010170936584472656 >>> min(Timer('for i in xrange(100): pass').repeat(3, 1000)) 0.0073339939117431641 >>> min(Timer('for i in range(1000): pass').repeat(3, 1000)) 0.083337783813476562 >>> min(Timer('for i in xrange(1000): pass').repeat(3, 1000)) 0.070460796356201172 >>> min(Timer('for i in range(10000): pass').repeat(3, 1000)) 0.88027620315551758 >>> min(Timer('for i in xrange(10000): pass').repeat(3, 1000)) 0.71050214767456055 >>> min(Timer('for i in range(100000): pass').repeat(3, 1000)) 13.938336849212646 >>> min(Timer('for i in xrange(100000): pass').repeat(3, 1000)) 7.0900959968566895 >>> min(Timer('for i in range(1000000): pass').repeat(3, 100))*10 141.37096881866455 >>> min(Timer('for i in xrange(1000000): pass').repeat(3, 100))*10 70.822579860687256 $ python2.4 Python 2.4.3 (#2, Mar 30 2006, 21:52:26) [GCC 4.0.3 (Debian 4.0.3-1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from timeit import Timer >>> min(Timer('for i in range(1): pass').repeat(3, 100000))/100 0.00084012031555175776 >>> min(Timer('for i in xrange(1): pass').repeat(3, 100000))/100 0.00069013833999633791 >>> min(Timer('for i in range(10): pass').repeat(3, 1000)) 0.0014748573303222656 >>> min(Timer('for i in range(10): pass').repeat(3, 1000)) 0.0014920234680175781 >>> min(Timer('for i in xrange(10): pass').repeat(3, 1000)) 0.0012860298156738281 >>> min(Timer('for i in range(100): pass').repeat(3, 1000)) 0.0079219341278076172 >>> min(Timer('for i in xrange(100): pass').repeat(3, 1000)) 0.0069670677185058594 >>> min(Timer('for i in range(1000): pass').repeat(3, 1000)) 0.079225063323974609 >>> min(Timer('for i in xrange(1000): pass').repeat(3, 1000)) 0.067707061767578125 >>> min(Timer('for i in range(10000): pass').repeat(3, 1000)) 0.84912896156311035 >>> min(Timer('for i in xrange(10000): pass').repeat(3, 1000)) 0.6791541576385498 >>> min(Timer('for i in range(100000): pass').repeat(3, 1000)) 13.973598003387451 >>> min(Timer('for i in xrange(100000): pass').repeat(3, 1000)) 6.8047640323638916 >>> min(Timer('for i in range(1000000): pass').repeat(3, 100))*10 138.38916063308716 >>> min(Timer('for i in xrange(1000000): pass').repeat(3, 100))*10 68.15216064453125 In sum, difference is as big as the function argument, but xrange was *never* slower on Python 2.3 or Python 2.4 on x86 with Linux. I'd say three things: 1) Probably xrange is faster than range on other architectures and operational systems as well. 2) I can't say anything for Python < 2.3. 3) Run your own tests. If you see the same I saw, use xrange everywhere you can. The 3rd point is specially true if your code can be break in the middle, for example (a really dumb example, I know): for i in xrange(0, 10000000, 42): if i**2 >= x: break This way you won't create all numbers, in this case just those less than sqrt(x) plus one. Cheers, -- Felipe. From mtobis at gmail.com Sat Apr 15 19:00:08 2006 From: mtobis at gmail.com (Michael Tobis) Date: 15 Apr 2006 16:00:08 -0700 Subject: Calling Python from Matlab In-Reply-To: References: Message-ID: <1145142008.801960.49110@t31g2000cwb.googlegroups.com> I'm afraid I can't be very helpful to you, but you could be most helpful to some of us. Can you elaborate on what specifically you found difficult? In some circles Python is regarded as a direct competitor to Matlab. Your preference for Python for "other things than standard mathematical work" in a scientific or engineering context could be most useful if you have some real-world examples. Also, can you elaborate on what (if anything) it is about Matlab that you feel you can't replicate in Python? Are you aware of matplotlib and numpy? thanks mt From roman.yakovenko at gmail.com Mon Apr 17 03:53:44 2006 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Mon, 17 Apr 2006 10:53:44 +0300 Subject: ANN: pygccxml - 0.7.2 In-Reply-To: <7465b6170604170050q59c77b21v8d0c9e0dfc2987cd@mail.gmail.com> References: <7465b6170604170050q59c77b21v8d0c9e0dfc2987cd@mail.gmail.com> Message-ID: <7465b6170604170053u74b276c7o95befe4414560e5@mail.gmail.com> Hi. The next version of pygccxml is available. Download page: http://www.language-binding.net/pygccxml/download.html What is it? "...The purpose of the GCC-XML extension is to generate an XML description of a C++ program from GCC's internal representation. Since XML is easy to parse, other development tools will be able to work with C++ programs without the burden of a complicated C++ parser..." The purpose of pygccxml is to read GCC-XML generated file and provide a simple framework to navigate C++ declarations using Python classes. Project home page: http://www.language-binding.net/pygccxml/pygccxml.html What is new? A lot of new functionality have been added: it is possible now to print declarations tree to find declaration by some criteria few new type_traits has been added Logging functionality has been added to almost all operations Documentation has been improved a lot. Bug fixes This version should work fine with GCC-XML CVS version Full list of changes you can find here: http://www.language-binding.net/pygccxml/history/history.html Many thanks to Matthias Baas, John Pallister and Allen Bierbaum. They fixed bugs and wrote documentation. Enjoy -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ From __peter__ at web.de Thu Apr 13 15:13:56 2006 From: __peter__ at web.de (Peter Otten) Date: Thu, 13 Apr 2006 21:13:56 +0200 Subject: function prototyping? References: <87hd4x1hx4.fsf@gmail.com> <87bqv51h7i.fsf@gmail.com> Message-ID: Burton Samograd wrote: > Duncan Booth writes: > >> Burton Samograd wrote: >> > Is there any way to 'prototype' functions in python, as you would in >> > C? Would that be what the 'global' keyword is for, or is there a more >> > elegant or 'pythonic' way of doing forward references? >> > >> There isn't really such a thing as a forward reference in Python. Always >> remember that 'def' and 'class' are executable statements: > > Ok, we'll here's what I'm trying to do. I have a dictionary that I > would like to initialize in a module file config.py: > > -- config.py ------------------------- > global a_fun, b_fun > dict = { > 'a': a_fun, > 'b': b_fun > } > -------------------------------------- > > where a_fun and b_fun are in fun.py: > > -- fun.py ---------------------------- > def a_fun(): pass > def b_fun(): pass > > import config > def main(): > config.dict['a']() > config.dict['b']() > main() > -------------------------------------- > > I like having the module/namespace seperation with the configuration > variables but I would like to make them easily (re)defined in the > configuration file by the user. Does python have the idea of a 'weak' > reference or lazy style evaluation for the definition of the dict in > the config file above so I can achive what i'm tryin to do? I'd say Python has *only* that idea, but as a practical approach the following might be easiest: -- config.py -- a = a_fun # As a_fun is nowhere defined, config.py cannot be # used stand-alone and may be hard to test. b = b_fun def c(): print "c-fun" -- fun.py -- def a_fun(): print "a-fun" def b_fun(): print "b-fun" execfile("config.py") # Think #include def main(): a() b() c() if __name__ == "__main__": main() A slightly stricter variant avoids cycles by using three modules: -- fun.py -- def a_fun(): print "a-fun" def b_fun(): print "b-fun" -- config.py -- import fun a = fun.a_fun b = fun.b_fun -- main.py -- import config def main(): config.a() config.b() if __name__ == "__main__": main() Thanks to the if... guard you could put the main.py code into fun.py, too, but I suppose it's easier to understand with three files. Peter From mike.klaas at gmail.com Sat Apr 1 22:15:09 2006 From: mike.klaas at gmail.com (Klaas) Date: 1 Apr 2006 19:15:09 -0800 Subject: Pickle or Mysql In-Reply-To: <1143864315.283697.20970@v46g2000cwv.googlegroups.com> References: <1143864315.283697.20970@v46g2000cwv.googlegroups.com> Message-ID: <1143947709.346007.109140@i39g2000cwa.googlegroups.com> > Can I use Pickle to store about 500,000 key value pairs.. or should I > use mySql. Which one is best for performance, as the key value pair > increases. Pickle: absolutely out of the question. Mysql: might work, albeit slowly. Use berkeley DB (bsddb3), or zodb. I have no experience with the latter, but bdb's scale far beyond that magnitude if necessary. -Mike From rpdooling at gmail.com Thu Apr 20 09:24:35 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 20 Apr 2006 06:24:35 -0700 Subject: Help! Identical code doesn't work in Wing IDE but does in Komodo. In-Reply-To: <1145519650.863418.274800@v46g2000cwv.googlegroups.com> References: <1145519650.863418.274800@v46g2000cwv.googlegroups.com> Message-ID: <1145539475.550439.251430@g10g2000cwb.googlegroups.com> Not sure if this would cause it, but I also have both Wing and Komodo, and when I search for files named FeedParser, I get this: c:/Documents and Settings\Richard Dooling\Local Settings\Application Data\Wing IDE 2\cache\analysis\C\Python24\lib\email\FeedParser.py.ether c:/Program Files\ActiveState Komodo 3.5\lib\python\Lib\email\FeedParser.py c:/Python24\Lib\email\FeedParser.py Maybe you need to investigate and see if those versions are all the same? Then check and see which one is running at any given time? rick "My mother buried three husbands, and two of them were just napping." --Rita Rudner From sakcee at gmail.com Fri Apr 21 19:36:43 2006 From: sakcee at gmail.com (Sakcee) Date: 21 Apr 2006 16:36:43 -0700 Subject: converting xmllib to xml.sax Message-ID: <1145662603.483538.106270@z34g2000cwc.googlegroups.com> Hi I am trying to convert an override of xmllib.XMLparser , in the handle_doctype method we are catching the entities using load_dtd(sysid).gen_ents how can I do the same with xml.sax, does xml.sax has anything to catch the entties thanks From sandravandale at yahoo.com Fri Apr 21 16:08:25 2006 From: sandravandale at yahoo.com (Sandra-24) Date: 21 Apr 2006 13:08:25 -0700 Subject: Can you create an instance of a subclass with an existing instance of the base class? Message-ID: <1145650105.664762.321560@j33g2000cwa.googlegroups.com> Can you create an instance of a subclass using an existing instance of the base class? Such things would be impossible in some languages or very difficult in others. I wonder if this can be done in python, without copying the base class instance, which in my case is a very expensive object. Any ideas? Thanks, -Sandra From piet at cs.uu.nl Mon Apr 10 09:17:29 2006 From: piet at cs.uu.nl (Piet van Oostrum) Date: Mon, 10 Apr 2006 15:17:29 +0200 Subject: any() and all() on empty list? References: <7x3bh1x0ym.fsf@ruckus.brouhaha.com> <42qWf.18211$uX5.7574@tornado.texas.rr.com> <7xzmj9u1di.fsf@ruckus.brouhaha.com> <85tWf.2748$Aa1.1605@dukeread05> <7xy7ytmtk2.fsf@ruckus.brouhaha.com> <7xpsk2f8ab.fsf@ruckus.brouhaha.com> Message-ID: >>>>> "Steve R. Hastings" (SRH) wrote: [snip] >SRH> vowels = frozenset("aeiouAEIOU") >SRH> f = open("a_file.txt") # note that f is an iterator >SRH> counts = tally(line[0] in vowels for line in f) tally([line[0] in vowels for line in f]) >SRH> # counts is a dict; counts.keys() == [False, True] No guarantee about the order. It could be [True, False]. >SRH> count_nonvowels, count_vowels = counts.values() So you must use counts[False] and counts[True]. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From bj_666 at gmx.net Wed Apr 5 02:14:18 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 05 Apr 2006 08:14:18 +0200 Subject: Standalone Python functions in UML? References: Message-ID: In , Roman Susi wrote: > Out of curiosity, how do I draw functions outside classes with UML? How > module could be drawn in this case? I just create a (UML) class for modules. After all a Python module can be seen as a class definition for a singleton which is instantiated at import time. Ciao, Marc 'BlackJack' Rintsch From phil at riverbankcomputing.co.uk Sat Apr 29 08:36:00 2006 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Sat, 29 Apr 2006 13:36:00 +0100 Subject: PyQt 4.0beta1 Released In-Reply-To: References: Message-ID: <200604291336.00268.phil@riverbankcomputing.co.uk> On Saturday 29 April 2006 1:27 pm, Skink wrote: > Phil Thompson wrote: > > Riverbank Computing is pleased to announce the release of PyQt v4.0beta1 > > available from http://www.riverbankcomputing.co.uk/pyqt/. > > > > PyQt is a comprehensive set of Qt bindings for the Python programming > > language and supports the same platforms as Qt (Windows, Linux and > > MacOS/X). Like Qt, PyQt is available under the GPL and a commercial > > license. > > > > PyQt v4 supports Qt v4 (http://www.trolltech.com/products/qt/index.html). > > PyQt v3 is still available to support earlier versions of Qt. > > Phil, great news! > However I have one question: my qt4 is built with QT_NO_ACCESSIBILITY > and when I try to build pyqt I got errors no such method > QWidget.setAccessibleName > > What should I do? Rebuild qt4 without QT_NO_ACCESSIBILITY #define? > > My qt is 4.1.2 Yes - the current code assumes a fully configured Qt. Phil From fulvio at pc.jaring.my Thu Apr 20 06:07:41 2006 From: fulvio at pc.jaring.my (Fulvio) Date: Thu, 20 Apr 2006 18:07:41 +0800 Subject: Python IDE for linux In-Reply-To: <20060419214307.2e63c5cd.neil.isaac@sympatico.ca> References: <20060419214307.2e63c5cd.neil.isaac@sympatico.ca> Message-ID: <200604201807.41755.fulvio@pc.jaring.my> Alle 09:43, gioved? 20 aprile 2006, Neil Isaac ha scritto: > At this point I'm thinking that I would like to start using a real IDE. Idle, shipped with Python :-) F From deets at nospam.web.de Fri Apr 21 09:35:45 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 21 Apr 2006 15:35:45 +0200 Subject: are docstrings for variables a bad idea? References: <1145615763.943050.170950@j33g2000cwa.googlegroups.com> <4ars48Fucf8sU1@uni-berlin.de> <1145622021.708392.5490@g10g2000cwb.googlegroups.com> <4as2n8FpmaqcU1@uni-berlin.de> <1145625383.881200.307110@j33g2000cwa.googlegroups.com> Message-ID: <4as5djFuqdciU1@uni-berlin.de> jelle wrote: > > why is this ambigious at all? > am i seriously overlooking something? Yes. A full example is this: import random class A: """I'm A """ pass class B: """ I'm B """ pass def factory(): if random.random() >= .5: return A() return B() o = factory() Now what is the IDE to show at o for the docstring? The point is: pythons dynamic nature allows for _runtime_ checks of this only. Now the special-case of classes can be worked around with a static analyzer to some extent - because ususally, import statements are easy enough to spot and resolve statically. But using __import__ even that can be obfuscated. Now I'm not saying that this should suppress all efforts to have IDEs more supportive. Yet a class is a declaration, as is a method - can be parsed easily. But e.g. setting an instance variable by means of setattr(self, name, value) instead of self. = value is perfectly legal, often wanted and totally opaque to any IDE trying to give support. Diez From arv.nntp at gmail.com Fri Apr 21 15:02:48 2006 From: arv.nntp at gmail.com (Alexis Roda) Date: Fri, 21 Apr 2006 21:02:48 +0200 Subject: PyLint results? In-Reply-To: References: Message-ID: Michael Yanowitz escribi?: > Hello: > > I ran the new pylint and my code and I had a few questions on why those > are warnings or what I can do to fix them: > > 2) C: 0: Missing required attribute "__revision__" > What is this? Is that for CVS? I don't use CVS (we use SVN). I have not > seen any sample code which includes this tag yet. But if I include > __revision 1.0 somewhere in the code it will remove that warning? try it and see what happens > 3) W:230:readDiscreteData: Using the global statement > What is wrong with using the global statement? I know the use of Globals > should be discouraged, but often they can't be avoided. > Suppose I have a constant. In C or C++, I could just use a #define and > it would be known throughout the whole file. In Python, there isn't a > similar construct, so rather than creating a large parameter list, of > constants, I like to use globals. * define all your constants in a separate module constants.py, then: from constants import * * add the constants to __builtins__ __builtins__.constant_name = value this approach is a bit tricky > 4) W:261:getDiscreteData: Catch "Exception" > What is wrong with that? cause you're masquerading *all* exceptions, this could be potentially dangerous > 6) R:722:waitDiscretes: Too many local variables (38/15) > That's new to me. What is wrong with too many local variables? > Can anything be done to improve that besides having too many globals? too many local variables probably means "too complex function, split it in smaller functions" From johnjsal at NOSPAMgmail.com Tue Apr 11 11:04:53 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 11 Apr 2006 15:04:53 GMT Subject: setting up mod_python handlers on a server? In-Reply-To: <1144766317.290453.65920@i39g2000cwa.googlegroups.com> References: <1144766317.290453.65920@i39g2000cwa.googlegroups.com> Message-ID: Gerard Flanagan wrote: > and I think what you want is: > > AddHandler mod_python .psp > PythonHandler mod_python.psp This is what I have in my htaccess file (along with debugging). But there is also an option in the control panel to set new handlers and extensions on the server, but I'm not sure what to call them, so I've been trying several combinations, like: mod_python .psp #this wasn't there yesterday, but is now PythonHandler .psp mod_python.psp .psp You get the idea. I'm not sure if I'm even on the right track by trying to add new handlers though. From python-url at phaseit.net Mon Apr 17 15:08:02 2006 From: python-url at phaseit.net (Peter Otten) Date: Mon, 17 Apr 2006 19:08:02 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Apr 17) Message-ID: QOTW: "Discussion about Python 3000 is heating up. What I haven't seen so far is a list of things that will be dropped from the language to make room for new ideas." - Greg Wilson "The longer I work at writing software, the more I come to appreciate that people are the hardest thing to figure out." - Ned Batchelder An extra generator makes skipping items in a sequence painless, as Diez B. Roggisch shows: http://groups.google.com/group/comp.lang.python/browse_thread/thread/39e384173b6bdb97?tvc=1 Paul Moore has set up a wiki page to help you build Python from source on Windows with tools available free of charge. http://wiki.python.org/moin/Building_Python_with_the_free_MS_C_Toolkit Steven Bethard proposes a new 'make' statement as a generalization of the class-declaration syntax. http://groups.google.com/group/comp.lang.python/browse_frm/thread/cdacc75d99f56612/7237a512fecd741b?tvc=1 Are you abusing them, too? Tuples are not just constant lists. http://jtauber.com/blog/2006/04/15/python_tuples_are_not_just_constant_lists Python's random integers are not limited by the underlying hardware's long. Expect your web browser to explode when Google discovers this capability for generating their usenet group URLs. http://groups.google.com/group/comp.lang.python/browse_frm/thread/2e10b56da6ae823a/ Michele Simionato's little script lets you search for a name in Python scripts, avoiding false positives that a standard tool like grep would yield. http://groups.google.com/group/comp.lang.python/msg/e84e36ad10d78303 Brian Hayes brings Python to the classroom of an eighteenth century school in the german province, and finds that the resident math genius may lose his competitive advantage. http://bit-player.org/2006/summing-up ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. For far, FAR more Python reading than any one mind should absorb, much of it quite interesting, several pages index much of the universe of Pybloggers. http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog http://www.planetpython.org/ http://mechanicalcat.net/pyblagg.html comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html Steve Bethard, Tim Lesher, and Tony Meyer continue the marvelous tradition early borne by Andrew Kuchling, Michael Hudson and Brett Cannon of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topic/python/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From rob at digital-crocus.com Thu Apr 6 13:30:04 2006 From: rob at digital-crocus.com (Robin Haswell) Date: Thu, 06 Apr 2006 18:30:04 +0100 Subject: Quickie: converting r"\x2019" to int Message-ID: Hey guys. This should just be a quickie: I can't figure out how to convert r"\x2019" to an int - could someone give me a hand please? Cheers -Rob From neurogasm at gmail.com Mon Apr 17 17:15:19 2006 From: neurogasm at gmail.com (Kun) Date: Mon, 17 Apr 2006 17:15:19 -0400 Subject: scanning through page and replacing all instances of 00:00:00.00 Message-ID: I have a python-cgi file that pulls data from an sql database, i am wondering what is the easiest way to remove all instances of '00:00:00.00' in my date column. how would i write a python script to scan the entire page and delete all instances of '00:00:00.00', would i use regular expressions? From duncan.booth at invalid.invalid Mon Apr 17 13:48:29 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 Apr 2006 17:48:29 GMT Subject: Queue can result in nested monitor deadlock References: <1145284326.177062.230120@v46g2000cwv.googlegroups.com> <1145292096.906390.254280@e56g2000cwe.googlegroups.com> Message-ID: Jonathan Amsterdam wrote: > If you don't want to call it deadlock, fine, but the program execution > I describe will make no progress to the end of time. Thread 2 can never > put anything in the queue, because Thread 1 holds M, and Thread 1 will > never release M because that can only happen if someone puts something > on the queue. > If your class is using a queue to handle the inter-thread communication why is it also using a semaphore? If your methods are already locked so only one thread runs at a time why are you then using a queue to provide another layer of locking: a simple list should suffice? From aahz at pythoncraft.com Wed Apr 19 11:24:02 2006 From: aahz at pythoncraft.com (Aahz) Date: 19 Apr 2006 08:24:02 -0700 Subject: 2.5 excitement (was Re: Java Developer Exploring Python) References: <1145290449.735642.120860@i40g2000cwc.googlegroups.com> Message-ID: In article , Jon Ribbens wrote: > >I guess I just don't get why the inclusion of the pysqlite wrapper >is so exciting if all it's doing is changing the situation from >"Python does not come with a DB, but you can install extra software >to provide one" to "Python does not come with a DB, but you can >install extra software to provide one". There's a difference between "needing to install extra software" and "compiling Python allows you to use your installed software". -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "LL YR VWL R BLNG T S" From amorgan at xenon.Stanford.EDU Mon Apr 17 14:30:24 2006 From: amorgan at xenon.Stanford.EDU (Alan Morgan) Date: Mon, 17 Apr 2006 11:30:24 -0700 (PDT) Subject: Queue can result in nested monitor deadlock References: <1145284326.177062.230120@v46g2000cwv.googlegroups.com> <1145292096.906390.254280@e56g2000cwe.googlegroups.com> Message-ID: In article <1145292096.906390.254280 at e56g2000cwe.googlegroups.com>, Jonathan Amsterdam wrote: >If you don't want to call it deadlock, fine, but the program execution >I describe will make no progress to the end of time. Thread 2 can never >put anything in the queue, because Thread 1 holds M, and Thread 1 will >never release M because that can only happen if someone puts something >on the queue. That's not a problem in the design of the queue class, it is a problem in how you are using it. Two possible solutions are: 1. Don't have the global lock on the object (or, at the very least, don't have that global lock taken when you read from the queue). 2. Don't use a syncronized queue. If the only access to the queue is through the object and the object is protected then you don't need a synchronized queue. Alan -- Defendit numerus From bignose+hates-spam at benfinney.id.au Wed Apr 19 02:02:18 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 19 Apr 2006 16:02:18 +1000 Subject: multiline comments References: <1145425311.771598.140970@i40g2000cwc.googlegroups.com> Message-ID: <87wtdmf6hh.fsf@benfinney.id.au> "Atanas Banov" writes: > Edward Elliott wrote: > > Saying coders shouldn't use multiline comments to disable code > > misses the point. Coders will comment out code regardless of the > > existence of multiline comemnts. There has to be a better > > argument for leaving them out. > > i beg to differ: you'd be surprised how much effect can little > inconveniences have. > > want to comment block of code? use tripple-quotes. does not nest? > ahhh, maybe it's time to get rid of that block you commented out a > month ago "just in case the new code doesnt work". Indeed. Using revision control means never needing to comment out blocks of code. If your revision control system is so inconvenient to use that you'd rather have large blocks of commented-out code, it's time to start using a better RCS -- perhaps a distributed one, so you can commit to your own local repository with abandon while trying out changes. -- \ "I saw a sign: 'Rest Area 25 Miles'. That's pretty big. Some | `\ people must be really tired." -- Steven Wright | _o__) | Ben Finney From finite.automaton at gmail.com Fri Apr 7 18:20:49 2006 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 7 Apr 2006 15:20:49 -0700 Subject: minidom + wxPython woes Message-ID: <1144448449.586601.293480@v46g2000cwv.googlegroups.com> Hi all, I'm getting a seg fault when I try to use minidom to parse some XML inside a wxPython app. I was wondering if someone else could run the simple code below on Linux and, if it doesn't crash horribly, post which versions of (Python, wxPython) they are using? I can't find other messages related to this, so I suspect it is something broken with my installation. I'm using Python 2.4.2 and wx 2.6.1.0. Incidentally, writing XML with minidom works fine, and this is all happening in wxPython's main thread. import wx from xml.dom import minidom app = wx.PySimpleApp() frame = wx.Frame(None, -1, "Hello World") frame.Show(True) button = wx.Button(frame, -1, "Click me") testxml = 'xml version="1.0" ?>' def click(event): doc = minidom.parseString(testxml) # seg fault?! print "Success!" frame.Bind(wx.EVT_BUTTON, click, button) app.MainLoop() From lucaberto at libero.it Mon Apr 3 08:04:38 2006 From: lucaberto at libero.it (luca72) Date: 3 Apr 2006 05:04:38 -0700 Subject: wx.checklistbox In-Reply-To: <1144053250.212944.76140@i40g2000cwc.googlegroups.com> References: <1143815725.730867.324970@j33g2000cwa.googlegroups.com> <1143900250.243912.309390@v46g2000cwv.googlegroups.com> <1143922446.596030.299380@i40g2000cwc.googlegroups.com> <1144053250.212944.76140@i40g2000cwc.googlegroups.com> Message-ID: <1144065878.439987.248850@z34g2000cwc.googlegroups.com> I have solve in this way i'm sure it's not the best, but it works: lista1leggi = open('/lista1.txt', 'r') mt = lista1leggi.readlines() lunghezzamt = len(mt) lucianino = 0 while lucianino < (lunghezzamt - 1): if mt[lucianino] == '\n': del mt[lucianino] lucianino = lucianino - 1 lunghezzamt = lunghezzamt - 1 else: lucianino = lucianino + 1 pippo = self.checkListBox1.AppendItems(mt) Ragards Luca From aldonnelley at gmail.com Thu Apr 27 02:41:58 2006 From: aldonnelley at gmail.com (aldonnelley at gmail.com) Date: 26 Apr 2006 23:41:58 -0700 Subject: blob problems in pysqlite References: Message-ID: <1146120118.189170.275060@y43g2000cwc.googlegroups.com> Excellent. Got that working. Now, how to get the pickled data out of the database? I'm trying to use cPickle.loads(data) (code attached), and I get a: "TypeError: loads() argument 1 must be string, not list" Is there a workaround for this? I've tried converting the List of files to a String before cPickling it, but the same result (expected). I've read, in a post of Gerhard's somewhere, about marshal, but I don't see how this would work for the HTML. (where I have the same problem.) Cheers, Al. ps. Tim: Your clean take on my code made me realise that I had stupidly included quotes in the URL argument passed to sqlite, ie I'd ended up with, effectively, DBURL= '"http://www.myhomepage.com"', rather than = 'http://www.myhomepage.com'. It's the little things that matter... Thanks for your help. Oh, and your 'representative samples' are spot on! #code starts URL = "http://www.myhomepage.com" db = sqlite.connect("ImageInfoDatabase.db") c = db.cursor() DBURL = str(URL) print DBURL c.execute("select Images from FileURLInfo where URL= ?;", (DBURL,)) KnownFilesResult = c.fetchall() print KnownFilesResult #where I get a r/w buffer, as expected cPickle.loads(KnownFilesResult) #where I get the error described above. #code ends. From duncan.booth at invalid.invalid Wed Apr 26 03:44:00 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 26 Apr 2006 07:44:00 GMT Subject: OOP / language design question References: <1145961248.794496.80220@j33g2000cwa.googlegroups.com> <1145963311.348482.15080@i40g2000cwc.googlegroups.com> <444e0dec$0$27071$626a54ce@news.free.fr> <444e38e9$0$29686$636a55ce@news.free.fr> <1hedc5l.toeunc1twg6bsN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: >> What I think I'm trying to get at is that I believe that most >> situations where someone actually tries to do something in the base >> initialiser which requires calling a virtual method are probably also >> cases where the initialiser is doing too much: i.e. separating the >> construction/initialisation from actually doing something is usually >> a good idea. > > But why should that be? Template Method is perhaps the MOST generally > useful design pattern -- why would it be any less useful in > initialization than elsewhere?! > Because it is error prone? Any method which is called from the constructor/initialiser has to operate correctly on an object which at that point is not fully constructed/initialised. So instead of having to write a method on a Foo object, your template method has to operate on a partial Foo. The danger is that you haven't clearly defined the partial Foo interface sufficiently and the method tries to use other parts of the object which haven't yet been set up. That situation gets worse when you have a class hierarchy as the subclass needs to know that it has to do complete its own initialisation before constructing the base class instead of afterwards, and if you are going to document that requirement, why not do it properly and split the construction in two? That's why I would go for the 2-phase construction: after the first phase you have an object which is fully initialised, just not yet used/connected/running. For example httplib.HTTPConnection does this: you construct the object with a host and port, but the actual connection is triggered by a separate object. I would suggest your example of a database connection belongs in that category: it should have an initial unconnected idle state and a separate connection. I think your example of a composite window building subwindows is the sort of use case I was asking for: it does sound tempting to construct the window and all its subwindows together. I'm happy to concede on that one. From ToddLMorgan at gmail.com Fri Apr 21 10:35:28 2006 From: ToddLMorgan at gmail.com (ToddLMorgan) Date: 21 Apr 2006 07:35:28 -0700 Subject: How should multiple (related) projects be arranged (structured) and configured so that they can share code, have a related package structure and enable proper unittesting, and ensuring no namespace collisions In-Reply-To: References: <1145546785.268550.154240@e56g2000cwe.googlegroups.com> <1145563823.160038.257950@j33g2000cwa.googlegroups.com> <4447ee60$0$5199$626a54ce@news.free.fr> <1145565632.131816.146560@i40g2000cwc.googlegroups.com> <1145568816.554279.323420@e56g2000cwe.googlegroups.com> <444801d0$0$20922$636a55ce@news.free.fr> <1145581506.477674.54130@t31g2000cwb.googlegroups.com> <1145587344.845567.181960@j33g2000cwa.googlegroups.com> Message-ID: <1145630128.782825.35220@j33g2000cwa.googlegroups.com> Thanks everyone for their assistance. I have managed to achieve all that I set out to do: - separation between src and test folders - now successfully sharing code between projects - running unittest s and suites - avoiding namespace collisions The solution involved the following (if anyone else is interested) - ammending all my __init__.py packages so that they included the following: from pkgutil import extend_path __path__ = extend_path(__path__, __name__) as per Peter Otten's suggestion - refactoring all the code so that the imports and froms conformed to the new package structure (a.b.c.common, a.b.c.app1 etc) and physically moving all the required files - ammending the PYTHONPATH so that the src and test directories for each project is included at the time of running ie PYTHONPATH=COMMON/src;COMMON/test;APP1/src;APP1/test;APP2/src;APP2/test Of course the /test entries are only required for testing and not runtime but you get the idea. I understand that flatter package structures are apparently the python way (http://dirtsimple.org/2004/12/python-is-not-java.html) but I like a nice little small little related package of functionality when I am l carving up a complex problem so I'm happy to incur any extra performance penalty in dict lookups. thanks again Todd From paul at boddie.org.uk Thu Apr 20 13:49:03 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 20 Apr 2006 10:49:03 -0700 Subject: SQLite (with APSW) and transaction separate References: Message-ID: <1145555342.958725.123420@i39g2000cwa.googlegroups.com> Dennis Lee Bieber wrote: > > Isolation levels I've seen, but not in the RDBMs I tend to have most experience > with (and for those I have documentation of, "The Firebird Book" is the > only one that seems to be explicit about multiple generations of updates > based on transactions; others seem to imply that updates block all other > transactions until committed -- at which point other transactions would > see them). Take a look here for some PostgreSQL documentation on transaction isolation levels: http://www.postgresql.org/docs/7.4/static/transaction-iso.html Paul From Andre_Mikulec at Hotmail.com Sun Apr 23 23:31:31 2006 From: Andre_Mikulec at Hotmail.com (AIM) Date: 23 Apr 2006 20:31:31 -0700 Subject: MS VC++ Toolkit 2003, where? In-Reply-To: <1he8sbx.dqqp3q10n5thaN%aleaxit@yahoo.com> References: <1he8pss.1yk7ug81rv7pw2N%aleaxit@yahoo.com> <1145811839.042394.73260@t31g2000cwb.googlegroups.com> <1he8sbx.dqqp3q10n5thaN%aleaxit@yahoo.com> Message-ID: <1145849491.347970.112150@e56g2000cwe.googlegroups.com> The site comes back with a message saying ... "The download you requested is unavailable. If you continue to see this message when trying to access this download, go to the "Search for a Download" area on the Download Center home page." Does anyone have any other ideas of where to look? From arobert at townisp.com Thu Apr 13 05:18:09 2006 From: arobert at townisp.com (News) Date: Thu, 13 Apr 2006 05:18:09 -0400 Subject: Iterating command switches from a data file - have a working solution but it seems inefficient In-Reply-To: <443e0edc$0$20655$636a55ce@news.free.fr> References: <123r6925duev9b2@corp.supernews.com> <443e0edc$0$20655$636a55ce@news.free.fr> Message-ID: <123s5qm84atdf5d@corp.supernews.com> bruno at modulix wrote: > News wrote: >> Hi everyone, >> >> My goal is to pull command switches/options from a file and then assign >> the values to select variables which would eventually be included in a >> class object. >> >> The data file looks something like this but the switches could be in any >> order and not all may be used. >> >> -m quemanager -s server -p port -k key -o object -c 20 -t test at email.com > > Have you looked at optparse ? > I have. In the interactive version of the code, I use: # # Parse command line options and automatically build help/usage # parser = OptionParser() parser.add_option("-q", "--quiet", action="store_false", dest="verbose", default=1, help="don't print status messages to stdout") parser.add_option("-m", dest="qmanager", help="Queue Manager to inquire against") parser.add_option("-s", dest="host", help="Host the que manager resides on") parser.add_option("-p", dest="port", help="Port queue manager listens on"), parser.add_option("-o", dest="object", help="Queue object being inquired on"), parser.add_option("-k", dest="key", help="object attribute to be inquired about"), parser.add_option("-t", type="string",dest="mto", help="e-mail address the report will go to"), parser.add_option("-d", action="store_false",dest="report", help="optional switch - enabling this sends output to e-mail") (options, args) = parser.parse_args() The module optparse seemed to be aimed at reading from commandline versus pulling attributes from a read line. From grflanagan at yahoo.co.uk Tue Apr 11 10:38:37 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 11 Apr 2006 07:38:37 -0700 Subject: setting up mod_python handlers on a server? In-Reply-To: References: Message-ID: <1144766317.290453.65920@i39g2000cwa.googlegroups.com> John Salerno wrote: > I get this internal error message when I try to access a PSP page: > > "Invalid command 'PythonHandler', perhaps mis-spelled or defined by a > module not included in the server configuration" > > So it seems that mod_python is not fully configured yet to handled PSP > pages. When I check the installed Apache handlers, there is an entry > called "mod_python .psp" where the first term is the handler and the > second is the extension. I also tried adding "PythonHandler" as it > appears in the htaccess file, but nothing is working. Sometimes the HTML > is displayed, and other times I get a 500 Internal Server Error page. > > I had assumed when a server has mod_python installed, you can start > using PSP functionality automatically, but I guess there's more work to > do to set it up. Can anyone tell me what else I might need to do? Add > another handler, perhaps? > > Thanks. I'm just learning apache and mod_python myself so no expertise, but do you have an 'AddHandler' or a 'SetHandler' before 'PythonHandler'? I have this: SetHandler mod_python PythonPath "sys.path" PythonHandler mod_python.publisher PythonDebug On and I think what you want is: AddHandler mod_python .psp PythonHandler mod_python.psp Gerard From kent at kentsjohnson.com Fri Apr 14 11:48:48 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Fri, 14 Apr 2006 11:48:48 -0400 Subject: requestion regarding regular expression In-Reply-To: <1145026037.790344.205630@e56g2000cwe.googlegroups.com> References: <1145006270.632156.144790@j33g2000cwa.googlegroups.com> <443f91d7$1_2@newspeer2.tds.net> <1145026037.790344.205630@e56g2000cwe.googlegroups.com> Message-ID: <443fc460$1_2@newspeer2.tds.net> BartlebyScrivener wrote: > Kent, > > Running > > path = "d:/emacs files/emacsinit.txt" > lines = open(path).readlines() > # my defun lines are lowercase, > # next two lines are all on one > starts = [i for i, line in enumerate(lines) if > line.startswith('(defun')] > for i, start in starts: > while start > 0 and lines[start-1].startswith(';'): > starts[i] = start = start-1 > print starts > > I get > > File "D:\Python\findlines.py", line 7, in __main__ > for i, start in starts: > TypeError: unpack non-sequence Sorry, should be for i, start in enumerate(starts): start is a specific start line, i is the index of that start line in the starts array (so the array can be modified in place). Kent From peter at engcorp.com Tue Apr 11 21:03:28 2006 From: peter at engcorp.com (Peter Hansen) Date: Tue, 11 Apr 2006 21:03:28 -0400 Subject: Help...TT Python 2.4 decompiler In-Reply-To: References: <003501c65c49$7f16da90$8edbd5a5@LocalHost> Message-ID: Robert Boyd wrote: > Can anyone on the list shed light on this? I'm accustomed to having > readable .py files with my .pyc files and I am unfamiliar with any > scenario where one would need to turn the byte-compiled version back > to the text version. One scenario is that you've lost your source code through carelessness or something (most likely not using a revision control system like any decent programmer does these days). My team did that once, and I've seen two or three other such instances in the newsgroup over the years. Another scenario is that you are trying to reverse engineer some code, perhaps like that used within the QuickTax package by Intuit. The answer for the OP is either "search for decompyle" or "there's nothing available for Python 2.4 but decompyle is the closest you'll get". (Obviously I don't know enough about decompyle to know if it supports 2.4. The last time I saw anything about it it was only up to 2.2 or 2.3.) -Peter From robert.kern at gmail.com Wed Apr 5 23:35:32 2006 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 05 Apr 2006 22:35:32 -0500 Subject: python on Mac In-Reply-To: References: <1144284073.446005.53950@t31g2000cwb.googlegroups.com> Message-ID: Robert Kern wrote: > James Stroud wrote: >>The python in /usr/bin is a link (to a link). You can do this: >> >>sudo rm /usr/bin/python >>sudo ln -s \ >> /System/Library/Frameworks/Python.framework/Versions/2.4/bin/python \ >> /usr/bin/python > > No, for the love of all that is holy, don't do that! OS X depends on stuff in > /usr/bin/. Don't pull the carpet out from under your OS! C.f.: "FAQ 5.7 Describe Apple's Framework implementation of Python and how that affects me adding new Python implementations" http://pythonmac.org/wiki/FAQ#head-392d16c2e6e49d6de6555634fc94759989464b5a -- Robert Kern robert.kern at gmail.com "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From fredrik at pythonware.com Tue Apr 18 10:50:13 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 18 Apr 2006 16:50:13 +0200 Subject: Any Python lullabies? References: <1145364607.000467.204880@g10g2000cwb.googlegroups.com> Message-ID: "Dustan" wrote: > Howsabout this? > > >>> import this > The Zen of Python, by Tim Peters > > Beautiful is better than ugly. > Explicit is better than implicit. > Simple is better than complex. > Complex is better than complicated. > Flat is better than nested. > Sparse is better than dense. > Readability counts. > Special cases aren't special enough to break the rules. > Although practicality beats purity. > Errors should never pass silently. > Unless explicitly silenced. > In the face of ambiguity, refuse the temptation to guess. > There should be one-- and preferably only one --obvious way to do it. > Although that way may not be obvious at first unless you're Dutch. > Now is better than never. > Although never is often better than *right* now. > If the implementation is hard to explain, it's a bad idea. > If the implementation is easy to explain, it may be a good idea. > Namespaces are one honking great idea -- let's do more of those! sung to what tune? (lite ipren-mannen-varning h?r, liksom) From rpdooling at gmail.com Fri Apr 28 11:06:02 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 28 Apr 2006 08:06:02 -0700 Subject: os.startfile() - one or two arguments? Message-ID: <1146236762.657595.23240@u72g2000cwu.googlegroups.com> Can any Windows user give a working example of adding a "command verb" to os.startfile()? When I try it, it squawks that it takes only one argument. >>> os.startfile('d:/','explore') Traceback (most recent call last): File "", line 1, in ? TypeError: startfile() takes exactly 1 argument (2 given) from os module startfile( path[, operation]) Start a file with its associated application. When operation is not specified or 'open', this acts like double-clicking the file in Windows Explorer, or giving the file name as an argument to the start command from the interactive command shell: the file is opened with whatever application (if any) its extension is associated. When another operation is given, it must be a ``command verb'' that specifies what should be done with the file. Common verbs documented by Microsoft are 'print' and 'edit' (to be used on files) as well as 'explore' and 'find' (to be used on directories). Thanks, rpd "Give a man a fire and keep him warm for a day. Light a man on fire and he will be warm for rest of his life." --Terry Pratchett From steven.bethard at gmail.com Fri Apr 14 16:44:54 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 14 Apr 2006 14:44:54 -0600 Subject: PEP 359: The "make" Statement In-Reply-To: References: Message-ID: <1qmdnTLsqL5ZlN3ZnZ2dnUVZ_vidnZ2d@comcast.com> Rob Williscroft wrote: > Steven Bethard wrote in news:Pfydnbapx4Bi7qPZnZ2dnUVZ_t-dnZ2d at comcast.com > in comp.lang.python: > >> Open Issues >> =========== >> >> Does the ``make`` keyword break too much code? Originally, the make >> statement used the keyword ``create`` (a suggestion due to Nick >> Coghlan). However, investigations into the standard library [4]_ and >> Zope+Plone code [5]_ revealed that ``create`` would break a lot more >> code, so ``make`` was adopted as the keyword instead. However, there >> are still a few instances where ``make`` would break code. Is there a >> better keyword for the statement? >> > > I don't know wether this has been suggested or not, but > what about def: > > def namespace ns: > x = 1 > > def type blah(object): > pass > > def property x: > def get(): > return ns.x I think that's probably a bad idea because it would make people think that the statement acts like a function definition, when it actually acts like a class definition. STeVe From cvanarsdall at mvista.com Fri Apr 21 12:58:23 2006 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Fri, 21 Apr 2006 09:58:23 -0700 Subject: threading, how to? In-Reply-To: <1145612262.485501.262300@i40g2000cwc.googlegroups.com> References: <1145612262.485501.262300@i40g2000cwc.googlegroups.com> Message-ID: <44490F2F.4090405@mvista.com> akrapus wrote: > Hi, > > I am trying to understand how to use threading in Python. I get > threading as a concept, but not the implementation. > > In order to start threading, do you call it as a separate function, > which will then be applied to the rest of the code (functions) or do > you open threading in each function. This all can probably be answered > by 'How python threads different functions'? > > Hope if somebody can drop me a few lines. I've been trying with > different tutorials, but still do not understand. > > Cheers, > > Stevan > So, I've played with python threading a fair bit, but if you don't need to delve too far into anything special you can get away with doing things fairly simply using the threading module Basically (and this may be over simplifiied for this example), but you can create a thread() object and basically pass it a function pointer. Then you can control the thread object fairly easily with methods such as start() and join(). So, here's an example of how I might thread a function: #BEGIN Code def funcToThread(): print "I'm a function" myThread = threading.Thread(target=functToThread) #a function name without parens basically yields a function pointer myThread.start() #Performs necessary tasks in order to run this thread #Here might be other stuff in your main thread of execution myThread.join() #say you want to force synchronization at some point #END Code Anyhow, there are more ways to do it and it really depends on your needs as to how far you need to take this. Hope that helps. -carl -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From martin at v.loewis.de Fri Apr 28 23:39:57 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 29 Apr 2006 05:39:57 +0200 Subject: not quite 1252 In-Reply-To: <44526dac$1@usenet.zapto.org> References: <444f5e6b$1@usenet.zapto.org> <444FAA49.1000909@v.loewis.de> <444fe3e2$1@usenet.zapto.org> <4450587D.6060103@v.loewis.de> <44526dac$1@usenet.zapto.org> Message-ID: <4452E00D.4040403@v.loewis.de> Anton Vredegoor wrote: >> So if that is the case: What is the problem then? If you interpret >> the document as cp1252, and it contains \x93 and \x94, what is >> it that you don't like about that? In yet other words: what actions >> are you performing, what are the results you expect to get, and >> what are the results that you actually get? > > Well, where do these cp1252 codes come from? The xml-file claims it's > utf-8. Ah. Then the document is most likely right: \x94 can very well occur in an UTF-8 file. > I just tried out some random decodings and cp1252 seemed to work. I > don't like to have to guess this way. I think John wouldn't even allow > it :-) Well, if the document is UTF-8, you should decode it as UTF-8, of course. Regards, Martin From kwangjin45.lee at samsung.com Sun Apr 9 22:50:16 2006 From: kwangjin45.lee at samsung.com (=?ks_c_5601-1987?B?wMyxpMH4?=) Date: Mon, 10 Apr 2006 11:50:16 +0900 Subject: Help...TT Python 2.4 decompiler Message-ID: <003501c65c49$7f16da90$8edbd5a5@LocalHost> Hello, I am a sofware engineer in Korea. Would you kindly give me the way to receive(take) python deccomplier as an urgent business? Thanks for help..^^ -------------- next part -------------- An HTML attachment was scrubbed... URL: From wrongbad at gmail.com Mon Apr 17 01:15:25 2006 From: wrongbad at gmail.com (I V) Date: 16 Apr 2006 22:15:25 -0700 Subject: passing string from one file to another In-Reply-To: References: Message-ID: <1145250925.878549.53870@i39g2000cwa.googlegroups.com> Kun wrote: > This works fine but instead of typing in a 'body', i would like the > initial python program to just send a string as the body of the email. > now normally i'd just set the msg in the mail.py file equal to the > string, however, i do not know how to link a string from another python > file to the mail.py file. Where does mail.py get the body from at the moment? And how are you invoking mail.py? The obvious would be to import mail.py and call a function in it; then, you would just need to change the string you pass to the function. But presumably that's not how you've got it set up or you wouldn't be asking the question. If you can explain a bit more how your program works that would be helpful, maybe post an exerpt of the code that shows where mail.py gets invoked from the main program, and the bit of mail.py that accesses the body that gets sent. From rpdooling at gmail.com Mon Apr 17 13:59:20 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 17 Apr 2006 10:59:20 -0700 Subject: Fixing Python instalation in win2000 by hand In-Reply-To: References: <7YP%f.393$nK2.12@newsfe22.lga> <1145035088.113942.264660@e56g2000cwe.googlegroups.com> <1145053798.560072.305950@i40g2000cwc.googlegroups.com> Message-ID: <1145296760.773058.318870@e56g2000cwe.googlegroups.com> >> the reason I can't move to brand new installation is because I am missing sound drivers. If I were you, I'd download the latest ActiveState version of Python from: http://www.activestate.com/Products/ActivePython/ I would install it from c:\ Who cares about sound drivers if all you want to do is get Python up and running? rd From rpdooling at gmail.com Tue Apr 18 17:14:29 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 18 Apr 2006 14:14:29 -0700 Subject: indirect import of standard module In-Reply-To: <1145393476.931506.9650@e56g2000cwe.googlegroups.com> References: <1145386200.076643.253740@u72g2000cwu.googlegroups.com> <1145393476.931506.9650@e56g2000cwe.googlegroups.com> Message-ID: <1145394869.577973.165070@v46g2000cwv.googlegroups.com> You're right! When running bar.py, id(os) and id(foo.os) give the same number! Cool. I'll go read about INSTANCES and pointers. Thank you very much, rick From qlng2000 at gmail.com Thu Apr 6 19:39:24 2006 From: qlng2000 at gmail.com (beta) Date: 6 Apr 2006 16:39:24 -0700 Subject: binding - python References: <1144284193.604084.141910@i40g2000cwc.googlegroups.com> Message-ID: <1144366764.240620.46310@i39g2000cwa.googlegroups.com> Hi John, It works! thank you vey much. I have another question. I would very appreciated if you have any clue. I want the ball STOP whenever mouse is clicked anywhere, then ball KEEP MOVING when next mouse click is applied. Thanks. Regards, Quoc From steven.bethard at gmail.com Thu Apr 6 12:18:00 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 06 Apr 2006 10:18:00 -0600 Subject: pre-PEP: The create statement In-Reply-To: <1144339912.936273.208170@j33g2000cwa.googlegroups.com> References: <59Wdnbd8EazRCqnZnZ2dnUVZ_vudnZ2d@comcast.com> <1144302248.639529.161700@j33g2000cwa.googlegroups.com> <1144339912.936273.208170@j33g2000cwa.googlegroups.com> Message-ID: Michele Simionato wrote: > Carl Banks wrote: >>> create module mod: >>> "This creates a sub-module named mod with an f1 function" >>> >>> def f1(): >>> ... >> Let's not do this, really. A module should be one-to-one with a file, >> and you should be able to import any module. Having in-line modules >> complicates everything. And it becomes a misnomer. So, please, let's >> get a better example. If you must, call it a scope or namespace. > > You are right, I think I am responsible for the wrong choice of the > name. > What I had in mind was a namespace or, if you wish, a named dictionary. > An simple-minded implementation could be > > class Namespace(object): > def __init__(self, name, args, dic): > self.__name__ = name > self.__dict__.update(dic) > > create Namespace keymap: > A = 1 > B = 2 I changed the PEP to use "namespace" instead of "module": http://ucsu.colorado.edu/~bethard/py/pep_create_statement.txt http://ucsu.colorado.edu/~bethard/py/pep_create_statement.html STeVe From sybrenUSE at YOURthirdtower.com.imagination Sat Apr 22 09:46:41 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Sat, 22 Apr 2006 15:46:41 +0200 Subject: =?big5?B?prPD9qnzIE1pbmluZyBnb29nbGUgd2ViIHNlcnZpY2VzIDogQnVpbGRpbmcgYXBwbGljYXRpb25zIHdpdGggdGhlIEdvb2dsZSBBUEmzb6W7rtGqur1kqNI=?= References: <1145712061.078703.8120@i39g2000cwa.googlegroups.com> Message-ID: pou629 at hotmail.com enlightened us with: > ?z?n?A > ?O?o?????A?????e???b???s "Mining Google Web Services >: Building Applications with > the Google API"?o?@?????A????chapter 6??"Using SQL Server as a > Database"?????????? > ?M?????B?A???q???w?g?w??SQL Server 2000 > sp4?A?????b?????????d???{?????A.net?X?{?F > ?u?L?k?B?z?????~???p: System.Data.SqlClient.SqlException: SQL > Server > ???s?b???????s???C?v?o?@?q???r?A?????M???L???N???A?Q???U???????????@?U?C?P???U??. > Thank you. It helps if you post in ASCII and English. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From rpdooling at gmail.com Fri Apr 14 10:07:36 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 14 Apr 2006 07:07:36 -0700 Subject: Upgrading and modules References: Message-ID: <1145023656.353186.114000@z34g2000cwc.googlegroups.com> Are you saying you're on Windows? If so, try: http://www.activestate.com/Products/ActivePython/ It's a one-click, msi install with everything you need for win32, including IDE etc. Only thing to watch for is that sometimes the msi file won't install from a logical drive other than c:\. So if you get a file access error or something, copy the install file to the root of your c:\ drive and double-click on it. I'm sure someone else will come along with advice for the Python.org installation. rick From nobody at 127.0.0.1 Thu Apr 20 17:35:08 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Thu, 20 Apr 2006 21:35:08 GMT Subject: perspective on ruby In-Reply-To: References: <1145555339.316764.123210@i39g2000cwa.googlegroups.com> Message-ID: Peter Otten wrote: > Edward Elliott wrote: >>The fact that even numeric literals are objects make me suspicious of Ruby >>as a general-purpose language though. > >>>>add_one = 1 .__add__ > > Just in case you didn't know... True enough, but I don't often see Python code treating numbers as objects. In Ruby it's right in the tutorials. Which may be fine; I'm not discounting Ruby, I'm just cautious. From edreamleo at charter.net Fri Apr 21 08:56:50 2006 From: edreamleo at charter.net (Edward K. Ream) Date: Fri, 21 Apr 2006 07:56:50 -0500 Subject: ANN: Leo 4.4 b4 released Message-ID: Leo 4.4 beta 4 is now available at: http://sourceforge.net/project/showfiles.php?group_id=3458&package_id=29106 This version fixes a long-standing MacOS bug. It is likely to be the last beta release before 4.4 rc1. This release also adds several new commands and contains a script for updating leoSettings.leo. Warning: The previous beta was not widely distributed. Please do some testing in your environment before recommending this version of Leo to others, (such as your students). Leo is a text editor, data organizer, project manager and much more. See: http://webpages.charter.net/edreamleo/intro.html The highlights of Leo 4.4: -------------------------- - An Emacs-like mini-buffer: you can now execute any command by typing its long name, with tab completion. - Many new commands, including cursor and screen movement, basic character, word and paragraph manipulation, and commands to manipulate buffers, the kill ring, regions and rectangles. You can use Leo without using a mouse. - Flexible key bindings and input modes. You can emulate the operation of Emacs, Vim, or any other editor. - A tabbed log pane. The Find and Spell Check commands now use tabs instead of dialogs, making those commands much easier to use. Plugins or scripts can easily create new tabs. The Completion tab shows possible typing completions. - Autocompletion and calltips. - Dozens of other new features and bug fixes since Leo 4.3.3. Links: ------ Leo: http://webpages.charter.net/edreamleo/front.html Home: http://sourceforge.net/projects/leo/ Download: http://sourceforge.net/project/showfiles.php?group_id=3458 CVS: http://sourceforge.net/cvs/?group_id=3458 Quotes: http://webpages.charter.net/edreamleo/testimonials.html Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From steve at hastings.org Wed Apr 5 19:42:28 2006 From: steve at hastings.org (Steve R. Hastings) Date: Wed, 05 Apr 2006 16:42:28 -0700 Subject: efficiency of range() and xrange() in for loops References: Message-ID: On Thu, 06 Apr 2006 09:08:45 +1000, Steven D'Aprano wrote: > Yes, the above example is a good use case for xrange. Did you think that > anyone denied that there were good cases for it? I am now officially sorry for starting this thread. Please let me just summarize what I wanted to say: * Question: Does Python do anything special with "for i in range"? (And I got an answer: the answer is "no".) * If Python does not do anything special with "for i in range", then you are building a list and tearing it down again without using the list, and for memory efficiency you might want to use xrange. (I used a more pithy phrase, which I now regret.) * It would be nice if the Python compiler checked for the special case of "for i in range" and compiled it to "for i in itr" where itr is a lightweight iterator that generates the same values as the range statement. Potentially, I speculated, this special iterator might be more lightweight than an xrange() object. That is all. I did not mean to tell anyone how to write a for loop. I did not mean to suggest that range() should be changed to always return an iterator. I did not mean to insult anyone. I don't even know what I ever wrote that sounded like "range should never be used". And I hope everyone recognized that the bit about "those responsible... have been sacked" was a reference to the opening credits of the movie _Monty Python and the Holy Grail_. I was trying to be funny, not sarcastic, bitter, etc. Thank you for your patience and I am done with this thread, unless I have written something unclear in *this* post and I have to post another post to clarify it as well. :-( -- Steve R. Hastings "Vita est" steve at hastings.org http://www.blarg.net/~steveha From tim.golden at viacom-outdoor.co.uk Fri Apr 28 06:45:00 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Fri, 28 Apr 2006 11:45:00 +0100 Subject: Get all attributes of a com object Message-ID: [bruno at modulix] | Duncan Booth wrote: | > That will show him the attributes of the Python wrapper | around the COM | > object, it won't show him the attributes of the underlying | COM object | > itself. | | I stand corrected - and shouldn't answer questions about MS technos :( In fact, if a static wrapper has been built for the object in question, the usual help (), inspect () stuff will work, eg: import win32com.client # # Make sure a proxy module is built behind-the-scenes # word = win32com.client.gencache.EnsureDispatch ("Word.Application") help (word.__class__) class _Application(win32com.client.DispatchBaseClass) | Methods defined here: | | Activate(self) | | AddAddress(self, TagID=, Value=) | | AutomaticChange(self) | | BuildKeyCode(self, Arg1=, Arg2=, Arg3=, Arg4=) | | CentimetersToPoints(self, Centimeters=) | | ChangeFileOpenDirectory(self, Path=) | | CheckGrammar(self, String=) [snip] The only thing is that you can't always build a proxy module. I'm never quite sure why or why not. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From ygao2004 at gmail.com Fri Apr 7 09:45:34 2006 From: ygao2004 at gmail.com (ygao) Date: 7 Apr 2006 06:45:34 -0700 Subject: how convert "\\xd6\\xd0\\xb9\\xfa" into "\xd6\xd0\xb9\xfa" Message-ID: <1144417534.363639.90270@u72g2000cwu.googlegroups.com> in python dd = "\\xd6\\xd0\\xb9\\xfa" d = "\xd6\xd0\xb9\xfa" but how to convert one to other ? thanks. From jzgoda at o2.usun.pl Thu Apr 27 17:16:15 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Thu, 27 Apr 2006 23:16:15 +0200 Subject: How to align the text of a Listbox to the right In-Reply-To: References: Message-ID: Sori Schwimmer napisa?(a): > For a listbox, I would give a width and go with string > formatting. In your case, I guess that what I'll do is > to limit the width to something acceptable, and show > only the tail of the line. > > Say, your width is w, then I'll show only the last w-4 > chars, preceded by '... ' (ellipsis+space). It might > be nice to put a label on top of your listbox and > dynamically change it's text attribute to the complete > version of your selection in the listbox, broken in > lines of appropriate length. Yeah, but what is the question? -- Jarek Zgoda http://jpa.berlios.de/ From thulben at no-spam.com Mon Apr 3 09:21:05 2006 From: thulben at no-spam.com (Ben Thul) Date: Mon, 03 Apr 2006 08:21:05 -0500 Subject: Oserror: [Errno 20] In-Reply-To: References: Message-ID: <12328a1o4lp3i64@corp.supernews.com> I think that if you go back and look at the original reply, he spelled it "isdir"...;) --Ben k r fry wrote: > Again, I apologise. Not knowing much about Python means that I don't > know what needs to be provided. I meant it doesn't work in the same way > that "istdir" didn't work. > > Here is what I have coded: > > for subdir in os.path.istdir(DATADIR): #loop through list > of strings > > file=FITS.Read(DATADIR+'/'+subdir+'/flux.fits') #opens flux.fits > file and reads > > summation=open(DATADIR+'/'+subdir+'/flux.dat','w') #opens the > summation results file for writing to > > spotbyspot=open(DATADIR+'/'+subdir+'/spotflux.dat','w') #opens the > spot-by-spot file for writing to > > output='' > print'\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n'+sys.argv[1]+' > '+subdir+'\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n' > > And here is what I get when I try to run it: > > Traceback (most recent call last): > File "katiescint.py", line 153, in ? > for subdir in os.path.istdir(DATADIR): #loop through > list of strings > AttributeError: 'module' object has no attribute 'istdir' > > Here is trying with listdir: > > for subdir in os.path.listdir(DATADIR): #loop through list > of strings > > and here is what I get: > > Traceback (most recent call last): > File "katiescint.py", line 153, in ? > for subdir in os.path.listdir(DATADIR): #loop through > list of strings > AttributeError: 'module' object has no attribute 'listdir' > > > > > Sybren Stuvel wrote: > >> k r fry enlightened us with: >> >>> I did think maybe it was meant to be "listdir" instead of "istdir", >>> but that doesn't work either. >> >> >> >> And again you don't tell us in what way it doesn't work. >> >> Think about what you post from our point of view. Then re-read it, and >> think about it again. Only if you're sure that we'll be able to fully >> understand it, hit the 'send' button. That will save us a lot of >> guessting and asking, and will also get you your answer a lot faster. >> >> Sybren From bencvt at gmail.com Thu Apr 6 22:17:14 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 6 Apr 2006 19:17:14 -0700 Subject: pre-PEP: The create statement In-Reply-To: References: <59Wdnbd8EazRCqnZnZ2dnUVZ_vudnZ2d@comcast.com> Message-ID: <1144376234.518595.122140@e56g2000cwe.googlegroups.com> Michael Ekstrand wrote: > Is there a natural way > to extend this to other things, so that function creation can be > modified? For example: > > create tracer fib(x): > # Return appropriate data here > pass > > tracer could create a function that logs its entry and exit; behavior > could be modifiable at run time so that tracer can go away into oblivion. > > Given the current semantics of create, this wouldn't work. What would be > reasonable syntax and semantics to make something like this possible? The standard idiom is to use a function wrapper, e.g. def tracer(f): def wrapper(*args): print 'call', f, args result = f(*args) print f, args, '=', result return result return wrapper def fact(x): if not x: return 1 return x * fact(x-1) fact = tracer(fact) # wrap it The decorator syntax was added in Python 2.4 to make the wrapper application clearer: @tracer def fact(x): if not x: return 1 return x * fact(x-1) http://www.python.org/dev/peps/pep-0318 --Ben From me+python at modelnine.org Sun Apr 30 13:49:59 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Sun, 30 Apr 2006 19:49:59 +0200 Subject: Hierarchy - how? In-Reply-To: <1146417996.915773.304250@j73g2000cwa.googlegroups.com> References: <1146417996.915773.304250@j73g2000cwa.googlegroups.com> Message-ID: <200604301949.59350.me+python@modelnine.org> Am Sonntag 30 April 2006 19:26 schrieb veracon: > -- Keep in mind that I don't want a string, I want a dictionary (but I > can't figure out how to do it). The following code does what you want: >>> # -*- coding: iso-8859-15 -*- data = """food fruit red cherry yellow banana meat pork foo bar baz qux""" top = {} stack = [-1] items = {-1:top} for l in data.split("\n"): lindent, ldata = len(l[:-len(l.lstrip())].expandtabs()), l.lstrip() while stack[-1] >= lindent: del items[stack[-1]] stack.pop() items[lindent] = {} items[stack[-1]][ldata] = items[lindent] stack.append(lindent) print top >>> Making a function out of it is up to you. ;-) --- Heiko. From enleverlesX.XmcX at XmclaveauX.com Thu Apr 6 08:22:41 2006 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI) Date: Thu, 6 Apr 2006 14:22:41 +0200 Subject: Unicode, command-line and idle References: <1144321375.901932.161330@v46g2000cwv.googlegroups.com> Message-ID: <443509c2$0$21265$8fcfb975@news.wanadoo.fr> (just for confirm) Hi! if the console is in cp1252, raw_input work OK with "?" This (your) script : # -*- coding: cp1252 -*- import sys text1 = u'espa?a' text2 = unicode(raw_input(), sys.stdin.encoding) if text1 == text2: print 'same' else: print 'not same' work OK with "chcp 850" AND "chcp 1252" @-salutations Michel Claveau From arobert at townisp.com Thu Apr 13 07:44:16 2006 From: arobert at townisp.com (News) Date: Thu, 13 Apr 2006 07:44:16 -0400 Subject: Iterating command switches from a data file - have a working solution but it seems inefficient In-Reply-To: <443e2c0f$0$11337$636a55ce@news.free.fr> References: <123r6925duev9b2@corp.supernews.com> <443e0edc$0$20655$636a55ce@news.free.fr> <123s5qm84atdf5d@corp.supernews.com> <443e2c0f$0$11337$636a55ce@news.free.fr> Message-ID: <123seclltcb1tab@corp.supernews.com> bruno at modulix wrote: > News wrote: >> bruno at modulix wrote: >> >>> News wrote: >>> >>>> Hi everyone, >>>> >>>> My goal is to pull command switches/options from a file and then assign >>>> the values to select variables which would eventually be included in a >>>> class object. >>>> >>>> The data file looks something like this but the switches could be in any >>>> order and not all may be used. >>>> >>>> -m quemanager -s server -p port -k key -o object -c 20 -t test at email.com >>> Have you looked at optparse ? >>> >> I have. >> >> In the interactive version of the code, I use: >> >> # >> # Parse command line options and automatically build help/usage >> # >> parser = OptionParser() >> >> parser.add_option("-q", "--quiet", >> action="store_false", dest="verbose", default=1, >> help="don't print status messages to stdout") >> parser.add_option("-m", dest="qmanager", >> help="Queue Manager to inquire against") >> parser.add_option("-s", dest="host", >> help="Host the que manager resides on") >> parser.add_option("-p", dest="port", >> help="Port queue manager listens on"), >> parser.add_option("-o", dest="object", >> help="Queue object being inquired on"), >> parser.add_option("-k", dest="key", >> help="object attribute to be inquired about"), >> parser.add_option("-t", type="string",dest="mto", >> help="e-mail address the report will go to"), >> parser.add_option("-d", action="store_false",dest="report", >> help="optional switch - enabling this sends output >> to e-mail") >> (options, args) = parser.parse_args() >> > > So why do you inflict yourself the pain of rewriting all the parsing etc??? > >> The module optparse seemed to be aimed at reading from commandline >> versus pulling attributes from a read line. > > http://www.python.org/doc/2.4.2/lib/optparse-parsing-arguments.html: > """ > The whole point of creating and populating an OptionParser is to call > its parse_args() method: > > (options, args) = parser.parse_args(args=None, options=None) > > where the input parameters are > > args > the list of arguments to process (sys.argv[1:] by default) > """ > > what about something like : > > line = myfile.readline() > options = parser.parse_args(line.split()) > > But what, if you prefer to rewrite (and maintain) a custom parser doing > exactly the same thing, please do !-) > sometimes you can't see the forest .. trees and all that :) I really appreciate everyones insight on this. It was very helpful. OT: I saw several references to "OP". What does this mean? From fredrik at pythonware.com Thu Apr 20 17:37:18 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 20 Apr 2006 23:37:18 +0200 Subject: Confused about properties, descriptors, and attributes... References: <1145562065.423388.9410@v46g2000cwv.googlegroups.com> Message-ID: redefined.horizons at gmail.com wrote: > But what is the difference between an Attribute of a Class, a > Descriptor in a Class, and a Property in a Class? A class has a class dictionary, which contains methods and other class-level members for this class. Each instance of a class has its own instance dictionary, which holds the attributes for that instance. An attribute is an instance variable that lives in the instance dictionary. if you ask for the attribute value, you get the value from the instance dictionary. If the attribute is not found in the instance, Python looks in the class dictionary. If you assign to an attribute, Python adds it to the instance dictionary. A descriptor is a special kind of class attribute that implements a descriptor protocol. if you ask for the attribute value for a descriptor attribute, or assign to it, Python will ask the descriptor object what to do. A property is simply a ready-made descriptor type that maps attribute access to getter and setter methods. Still with me? > If I had a Monster Class, and I wanted to give each Monster a member > variable called ScaryFactor, how would I define it? Assign to it in the initialization method: class Monster(object): def __init__(self): self.ScaryFactor = 100 This gives all monsters their own ScaryFactor value. Since Python will look in the class dictionary if an attribute is not found in the instance dictionary, you can also do: class AltMonster(object): ScaryFactor = 100 If you do this, all monsters will share the same factor value. However, if you set the factor on the instance (either by assigning to self inside a method, or by assigning to it from the outside), that object will get its own copy. m1 = AltMonster() m2 = AltMonster() m3 = AltMonster() print m1.ScaryFactor, m2.ScaryFactor, m3.ScaryFactor # prints 100, 100, 100 (all three refers to the same object) m1.ScaryFactor = 200 print m1.ScaryFactor, m2.ScaryFactor, m3.ScaryFactor # prints 200, 100, 100 (m1 has its own attribute value) Monster.ScaryFactor = 300 # update the class attribute print m1.ScaryFactor, m2.ScaryFactor, m3.ScaryFactor # prints 200, 300, 300 (!) > Does a Property simply provide methods that access an Attribute? It maps attribute accesses to method calls, yes. You can use it instead of a plain attribute when you need to add getter or setter logic; there's usually no reason to use properties instead of attributes for plain data members. To learn more about descriptors (which are really simple, and rather mind- boggling), see http://users.rcn.com/python/download/Descriptor.htm Hope this helps! From sjmachin at lexicon.net Wed Apr 12 16:58:31 2006 From: sjmachin at lexicon.net (John Machin) Date: Thu, 13 Apr 2006 06:58:31 +1000 Subject: base64 In-Reply-To: <1144865224.094993.149200@u72g2000cwu.googlegroups.com> References: <1144865224.094993.149200@u72g2000cwu.googlegroups.com> Message-ID: <443d6a0d@news.eftel.com> On 13/04/2006 4:07 AM, Jay wrote: > I have bean trying to get my head around reading .GIF files from base64 > strings, FROM base64? Sounds a tad implausible. > Basically I need to specify a filename and convert it to base64 then I > can copy/past the string to wear I want it. TO base64? That's better, provided the referent of the first "it" is the file contents, not the filename. > Cold somebody check this for me to see what I have done wrong: > The bit I can not understand: > > It will generate the base64 string No it doesn't and no it can't; it's reading the *FILE* one "line" at a time. This is in fact the root cause of your problem; a GIF file is a binary file; there are no "lines"; any '\n' or '\r' characters are binary data. Why is it stopping early? Possibly there is a ctrl-Z character in the file and you are running on Windows. You need to open the file with "rb" as the second arg, and read the whole file in as one string. *After* encoding it, you can break up the base64 string into bite-size chunks, append a newline (that's "\n", NOT "/n") to each chunk, and send it over a 7-bit-wide channel. You may wish to try a small console script that might help you understand what's going on: # Input: name of file as 1st arg # Output: base64 encoding written to stdout in 64-byte chunks import sys, base64 CHUNKSIZE = 64 fname = sys.argv[1] fhandle = open(fname, "rb") fcontents = fhandle.read() b64 = base64.b64encode(fcontents) for pos in xrange(0, len(b64), CHUNKSIZE): print b64[pos:pos+CHUNKSIZE] [snip] > > def Encode(self,event): > ''' > Take's the string from (self.FileInputLine), > converts it to base64 then desplays it in (self.DisplayText) > ''' The above documentation reflects neither what the method is doing now nor what it should be doing. The latter is something like: Takes (LTFA!) a filename from self.FileInputLine Opens the file in binary mode Encodes the file's contents as base64 Displays the encoded string in self.DisplayText > self.DisplayText.insert(END, "...No Sutch File...") Is the GIF file meant to be a photo of the late Screaming Lord? HTH, John From nobody at 127.0.0.1 Thu Apr 27 15:09:16 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Thu, 27 Apr 2006 19:09:16 GMT Subject: Regular Expression help References: <1146162048.903980.281290@y43g2000cwc.googlegroups.com> Message-ID: RunLevelZero wrote: > 10:00am - 11:00am: > Here is the re. > > findshows = > re.compile(r'(\d\d:\d\d\D\D\s-\s\d\d:\d\d\D\D:*.*)') 1. A regex remembers everything it matches -- no need to wrap the entire thing in parens. Just call group() on the returned MatchObject. 2. If all you want is the link text, you don't need to do so much matching. If you don't need the time, don't match it in the first place. If you're using it as a marker, try matching each time with r'[\d:]{4,5}[ap]m'. Not as exact but a bit simpler. Or just r'[\d:apm]{6,7}' 3. To grab what's inside the link: r']*>(.*?)' 4. If the link text itself contains html tags, you'll have to strip those off separately. Extracting the text from arbitrarily nested html tags in one shot requires a parser, not a regex. 5. If you're just going to run this regex repeatedly on an html doc and make a list of the results, it's easier to read the whole doc into a string and then use re.findall. > I have used a for loop to remove the extra data but then it ruins the > list that I am building. Basically I want the list to be something > like this. > > [[Government Access], [Price Is Right, Guiding Light, Another show]] > > the for loop just comma deliminates all of them so I lose the list in a > list that I need. I hope I have explained this well enough. Any help > or ideas would be appreciated. No one can help with that unless you show us how you're building your list. From onurb at xiludom.gro Mon Apr 10 08:23:29 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Mon, 10 Apr 2006 14:23:29 +0200 Subject: how relevant is C today? In-Reply-To: <1144632983.039143.203330@u72g2000cwu.googlegroups.com> References: <44381ee4$0$4209$c3e8da3@news.astraweb.com> <44382711.10403@v.loewis.de> <44393fbe$0$19226$c3e8da3@news.astraweb.com> <44398651$0$4206$c3e8da3@news.astraweb.com> <1144632983.039143.203330@u72g2000cwu.googlegroups.com> Message-ID: <443a4e8a$0$21013$626a54ce@news.free.fr> gregarican wrote: > Here are a few languages I recommend most programmers should at least > have a peek at: > (snip) > 2) Lisp - Along with FORTRAN, one of the oldest programming languages > still in use. Pure functional programming model Err... Even if Lisp is the father of functional programming, it is definitively not a 'pure' FPL. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From pyguy at speakeasy.net Tue Apr 4 16:30:35 2006 From: pyguy at speakeasy.net (pyguy at speakeasy.net) Date: Tue, 04 Apr 2006 20:30:35 +0000 Subject: Binary tree problem (searching) Message-ID: Hi all, I am running into a conceptual glitch in implementing a simple binary tree class. My insertion and printing (sorting) seems to be ok, but when I search the tree, my find method isn't doing what I thought it should. Here is the output of running my tests: >python -i trees.py ********************************************************************** File "trees.py", line 70, in __main__.BinaryTree.find Failed example: t.find('Leo') Expected: -1 Got nothing ********************************************************************** File "trees.py", line 72, in __main__.BinaryTree.find Failed example: t.find('Cancer') Expected: 1 Got nothing ********************************************************************** 1 items had failures: 2 of 7 in __main__.BinaryTree.find ***Test Failed*** 2 failures. >>> So it appears my find method is failing to return -1 for a missing key and 1 for any key below the root. If anyone could clue me in on why this is so, I'd appreciate it. Here is the code (trees.py): class BinaryTree: """Binary Tree""" def __init__(self, key, left=None, right=None): self.key = key self.left = left self.right = right def __str__(self): return str(self.key) def addNode(self,key): if key < self.key: if self.left: self.left.addNode(key) else: self.left = BinaryTree(key) elif key > self.key: if self.right: self.right.addNode(key) else: self.right = BinaryTree(key) def printTree(self): """ >>> t=BinaryTree('Capricorn') >>> t.addNode('Aquarius') >>> t.addNode('Pices') >>> t.addNode('Cancer') >>> t.printTree() Capricorn Aquarius Cancer Pices """ print self.key if self.left: self.left.printTree() if self.right: self.right.printTree() def printSortedTree(self): """ >>> t=BinaryTree('Capricorn') >>> t.addNode('Aquarius') >>> t.addNode('Pices') >>> t.addNode('Cancer') >>> t.printSortedTree() Aquarius Cancer Capricorn Pices """ if self.left: self.left.printSortedTree() print self.key if self.right: self.right.printSortedTree() def find(self, key, child=None): """ >>> t=BinaryTree('Capricorn') >>> t.addNode('Aquarius') >>> t.addNode('Pices') >>> t.addNode('Cancer') >>> t.find('Capricorn') 1 >>> t.find('Leo') -1 >>> t.find('Cancer') 1 """ if self.key == key: return 1 elif key < self.key: if self.left: self.left.find(key) else: return -1 elif key > self.key: if self.right: self.right.find(key) else: return -1 def _test(): import doctest doctest.testmod() if __name__ == '__main__': _test() From newsgroup_mail... at ...binarystar.org Fri Apr 28 02:35:36 2006 From: newsgroup_mail... at ...binarystar.org (*binarystar*) Date: Fri, 28 Apr 2006 16:35:36 +1000 Subject: can i set up a mysql db connection as a class ? In-Reply-To: <4451b394$0$31649$e4fe514c@news.xs4all.nl> References: <1146183359.932904.298760@g10g2000cwb.googlegroups.com> <1146199764.328276.241320@j33g2000cwa.googlegroups.com> <4451b394$0$31649$e4fe514c@news.xs4all.nl> Message-ID: I suppose that is possible because you are calling the one instance of a cursor object ... maybe you have to create a copy of the cursor object, rather than passing a reference to the one object? or set up the db_connection objects inside each of the threads? .. Winfried Tilanus wrote: > On 04/28/2006 07:54 AM, *binarystar* wrote: > > Just wondering: is there any risk of two threads accessing the Execute > function at the same time and getting something like this on the same > cursor object: > > thread_1: self.cursor.Execute( sql_statement ) > thread_2: self.cursor.Execute( sql_statement ) > thread_1: return self.cursor.FetchAll() > thread_2: return self.cursor.FetchAll() > > In that case the queries would seriously be messed up. My intuition says > this would need some locking or a 'cursor-pool'. > > best wishes, > > Winfried > > >> your on the right track ... create something like this ( hope the >> formatting doesn't go to hay wire ) >> >> class DB_Connector(object): >> >> """ Humble Database Connection Class """ >> def __init__(self, host="localhost", >> user="MyUser",passwd="MyPassword", **other_db_arguments): >> self.host = host >> self.user = user >> self.passwd = passwd >> # Unpack Other Database Arguments Here >> self.CreateConnection() >> def CreateConnection( self ): >> self.cursor = MySQLdb.connect(self.host, self.user, >> self.passwd) >> def DestroyConnection( self ): >> self.cursor.close() >> def Execute( self, sql_statement ): >> self.cursor.Execute( sql_statement ) >> return self.cursor.FetchAll() >> Then when you run your program create an instance of the object >> >> db_connection = DB_Connector( 'localhost', 'administrator', >> 'betelgeuse99', auto_commit=1, other_keyword_arg="yes" ) >> >> now when you pass the db_connection instance to other classes, a copy >> will be made automagically >> >> thread_1_instance = ThreadingClass( db_connection ) >> thread_2_instance = ThreadingClass( db_connection ) >> thread_3_instance = ThreadingClass( db_connection ) >> >> should work .. >> I hope this is useful From harveysthomas at yahoo.com Thu Apr 27 11:38:45 2006 From: harveysthomas at yahoo.com (harveysthomas at yahoo.com) Date: 27 Apr 2006 08:38:45 -0700 Subject: =?utf-8?q?Re:_writing_some_lines_after_reading_goes_wrong_on_windows=EF=BC=9F?= References: <1146150173.947811.269820@y43g2000cwc.googlegroups.com> Message-ID: <1146152324.617203.205040@e56g2000cwe.googlegroups.com> If you are opening a file for read and write access use "rb+" or "wb+". Seeking and subsequent read/write will then work fine. Without the "b", Windows opens the file in its "text" mode. Don't seek on files opened in "text" mode. From larry.bates at websafe.com Fri Apr 14 11:28:16 2006 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 14 Apr 2006 10:28:16 -0500 Subject: Iterating command switches from a data file - have a working solution but it seems inefficient In-Reply-To: <123r6925duev9b2@corp.supernews.com> References: <123r6925duev9b2@corp.supernews.com> Message-ID: News wrote: > Hi everyone, > > My goal is to pull command switches/options from a file and then assign > the values to select variables which would eventually be included in a > class object. > > The data file looks something like this but the switches could be in any > order and not all may be used. > > -m quemanager -s server -p port -k key -o object -c 20 -t test at email.com > > Also, please keep in mind that the source code will have more than one > line in it and each has to be treaded separately. > > > In a first pass, I wrote the following code which works but there is > probably a better way of doing it. > > Any ideas to make it more efficient/stream-lined would be greatly > appreciated. > > #!/usr/bin/python > > import string > inp = open("const.txt","r") > # > # Read File > # > > while True: > > # > # Get line from file > # > line=inp.readline() > > # > # Check for EOF or break line up to extract relevant pieces > # > if len(line) == 0: > break > else: > split_line=line.split() > length=len(split_line) > count=0 > > # > # Evaluate list item and assign variable based on its contents > # Print statements are for debugging purposes only > # > for i in range(length): > if split_line[count] == "-m": > qmgr=split_line[count+1] > print "Queue Manager",qmgr; > elif split_line[count] == "-s": > server=split_line[count+1] > print "Server",server; > elif split_line[count] == "-p": > port=split_line[count+1] > print "Port",port; > elif split_line[count] == "-o": > object=split_line[count+1] > print "Object",object; > elif split_line[count] == "-k": > key=split_line[count+1] > print "Key",key; > elif split_line[count] == "-t": > mto=split_line[count+1] > print "To",mto; > elif split_line[count] == "-c": > check=split_line[count+1] > print "Check",check; > elif split_line[count] == "-d": > report="" > print "Report",report; > elif split_line[count] == "-q": > display=False > print "Display",display; > else: > continue > > count=count+1 > > # Close input file > # > inp.close() > Others have addressed your specific question. I'm going to make a different suggestion. Change your thinking so that you can use ConfigParser to get your values from a .INI/.CONF file instead. The file would look something like: [section001] m=queuemanager server=myserver port=1080 key=somekey object=someobject c=20 emailtolist=test at email.com [section002] . . If you have many of these just put things in a loop . and process each section . You can then read with (not tested): import ConfigParser inifilename='program.ini' INI=ConfigParser.ConfigParser() INI.read(inifilename) section='section001' option='m' try: m=INI.get(section, option) except: m=None option='server' try: server=INI.get(section, option) except: server=None option='port' try: port=INI.getint(section, option) except: port=None # Or set to default port option='key' try: key=INI.get(section, option) except: key=None option='object' try: object=INI.get(section, option) except: object=None option='c' try: c=INI.getint(section, option) except: c=None option='emailtolist' try: emailtolist=INI.get(section, option).split(';') except: emailtolist=None Just a suggestion. -Larry Bates From ldo at geek-central.gen.new_zealand Thu Apr 27 03:46:35 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 27 Apr 2006 19:46:35 +1200 Subject: Can you create an instance of a subclass with an existing instance of the base class? References: <1145650105.664762.321560@j33g2000cwa.googlegroups.com> <444cb1e3$0$28592$626a54ce@news.free.fr> <444e0fff$0$7724$636a55ce@news.free.fr> Message-ID: In article <444e0fff$0$7724$636a55ce at news.free.fr>, bruno at modulix wrote: >Lawrence D'Oliveiro wrote: >> In article <444cb1e3$0$28592$626a54ce at news.free.fr>, >> bruno at modulix wrote: >> >> >>>Lawrence D'Oliveiro wrote: >>>(snip) >>> >>>>I think you're taking Python's OO-ness too seriously. One of the >>>>strengths of Python is that it can _look_ like an OO language without >>>>actually being OO. >>> >>>According to which definition of OO ? >> >> Isn't there one? > >Your claim that Python "_look_ like an OO language without actually >being OO" implicitely relies on a definition of OO - or is just >meaningless. Which nicely evades answering the question. From greg.kujawa at gmail.com Mon Apr 10 13:22:18 2006 From: greg.kujawa at gmail.com (gregarican) Date: 10 Apr 2006 10:22:18 -0700 Subject: how relevant is C today? References: <44381ee4$0$4209$c3e8da3@news.astraweb.com> <44382711.10403@v.loewis.de> <44393fbe$0$19226$c3e8da3@news.astraweb.com> <44398651$0$4206$c3e8da3@news.astraweb.com> <1144632983.039143.203330@u72g2000cwu.googlegroups.com> <1144675918.682524.227240@t31g2000cwb.googlegroups.com> Message-ID: <1144689738.097396.177900@g10g2000cwb.googlegroups.com> Rune wrote: > No. Simula is the "original object oriented programming language". Thanks for pointing this out. I had read about references to Simula but never looked beyond the term itself. Interesting stuff. Especially since it was developed so long ago. Very interesting... From sybrenUSE at YOURthirdtower.com.imagination Fri Apr 21 12:18:15 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Fri, 21 Apr 2006 18:18:15 +0200 Subject: how to append to a list twice? References: <1B62g.16669$0Z4.581@tornado.texas.rr.com> <3772g.1992$No6.43411@news.tufts.edu> Message-ID: John Salerno enlightened us with: > Interesting. I tried the *2 method twice, but I kept getting weird > results, I guess because I was using append and not extend. I > thought extend added lists to lists, but obviously that's not the > case here. [100].extend([90]) -> [100, 90] [100].append([90]) -> [100, [90]] [100].append(90) -> [100, 90] Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From ldo at geek-central.gen.new_zealand Fri Apr 21 19:08:13 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 22 Apr 2006 11:08:13 +1200 Subject: proposed Python logo References: <1145585399.871299.31900@t31g2000cwb.googlegroups.com> <1145628079.749480.191190@g10g2000cwb.googlegroups.com> <124hqel51rur33b@corp.supernews.com> <1145640106.269556.276060@u72g2000cwu.googlegroups.com> <124i8176of81331@corp.supernews.com> Message-ID: In article <124i8176of81331 at corp.supernews.com>, Grant Edwards wrote: >Sincy Python wasn't named after the snake, why the insistence >on using a snake in the logo? ... >I think something Monty Python related would be better. How >about a nice can of spam? Six words: copyright violation ... trademark violation. From loguser at almad.net Mon Apr 10 03:25:03 2006 From: loguser at almad.net (loguser at almad.net) Date: Mon, 10 Apr 2006 09:25:03 +0200 (CEST) Subject: wiki engine (just engine) available? Message-ID: <45063.217.169.177.54.1144653903.squirrel@mail.include.cz> Hello, I'm thinking about embedding a wiki into one of my project. However, I'm looking just for a wiki-text-processing library, not a complete out-of-box solution. Ideal feature set is ReStructureText, some easy way to add custom commands (to keep my pages integrated in way Trac is doing) and (ideally) docbook export (althrough I'm ready to write one). Suggestions, or do this has to be just-another-wiki-project? Thank You, Almad From rogerb at rogerbinns.com Sat Apr 8 18:44:24 2006 From: rogerb at rogerbinns.com (Roger Binns) Date: Sat, 8 Apr 2006 15:44:24 -0700 Subject: Insertion (sql) bug in Py2.4 pySQLite 2.2 References: Message-ID: "DurumDara" wrote in message news:mailman.4267.1144523723.27775.python-list at python.org... > I have this code in my program. Before this I use APSW, but that project's connection object doesn't have close method... The connection object is released when there are no more references to it, and there are no outstanding cursors. The existence of the connection object does not hold a database open. In fact the only thing that holds a database open is cursors inside a transaction. And if those exist, calling an explicit close on the connection object would merely generate an error message that cursors etc exist. I recommend reading this document: http://www.catb.org/~esr/faqs/smart-questions.html Roger From timr at probo.com Fri Apr 7 02:43:53 2006 From: timr at probo.com (Tim Roberts) Date: Fri, 07 Apr 2006 06:43:53 GMT Subject: Python CGI problem: correct result, but incorrect browser response. References: <1144308015.256501.80980@e56g2000cwe.googlegroups.com> Message-ID: <0e2c32pbhqi7m565ft1o75aci6o5j7c388@4ax.com> "Sullivan WxPyQtKinter" wrote: > >title:Python CGI problem: correct result, but incorrect browser >response. > >In one of my CGI program,named 'login.py', the script return a HEADER >to web browser: > >Set-Cookie: sessionID=LAABUQLUCZIQJTZDWTFE; >Set-Cookie: username=testuser; >Status:302 >Location:edit.py >(blank line) > >but the IE prompted to let me choose to save the 'login.py'. When I >save it, the file is just the header. That means the IE failed to parse >the header. My IE has already enabled cookie read and write. I also >tried Firefox, but the result is the same. How does this happen? Perhaps you should show us the script. Is it possible that you have already printed a "Content-Type" header and blank line before these headers, or perhaps just a blank line? Remember that this will fail: print """ Set-Cookie: sessionID=LAABUQLUCZIQJTZDWTFE; Set-Cookie: username=testuser; Status:302 Location:edit.py """ because you get a blank line first, which terminates the headers. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From girodt at gmail.com Thu Apr 13 11:51:58 2006 From: girodt at gmail.com (Thomas Girod) Date: 13 Apr 2006 08:51:58 -0700 Subject: new-style classes and len method In-Reply-To: References: <1144936961.203493.169840@v46g2000cwv.googlegroups.com> Message-ID: <1144943518.552961.80840@e56g2000cwe.googlegroups.com> It's alright I found where my mistake came from. I was misunderstanding the meaning of "classmethod", thinking of it as an instance method. From jjl at pobox.com Wed Apr 12 18:42:41 2006 From: jjl at pobox.com (John J. Lee) Date: 12 Apr 2006 22:42:41 +0000 Subject: Python editing with emacs/wordstar key bindings. References: Message-ID: <877j5uquu6.fsf@pobox.com> "Thomas Bartkus" writes: [...] > > 1) When I load a .py file, emacs automatically overrides my wordstar-mode > with python-mode, forcing all the keybindings back to emacs native keys. > Why? > > Why should a python-mode care what key bindings are in use? > > 2) We get for block indentation instead of the spaces I prefer. [...] Have you tried an emacs mailing list / newsgroup re these points? You might get more help there... John From rjh at cyberscience.com Wed Apr 5 07:30:58 2006 From: rjh at cyberscience.com (Richie Hindle) Date: Wed, 05 Apr 2006 12:30:58 +0100 Subject: HTMLParser fragility In-Reply-To: References: Message-ID: [Daniel] > You could try HTMLTidy (http://www.egenix.com/files/python/mxTidy.html) > as a first step to get well formed HTML. But Tidy fails on huge numbers of real-world HTML pages. Simple things like misspelled tags make it fail: >>> from mx.Tidy import tidy >>> results = tidy("Hello world!") >>> print results[3] line 1 column 7 - Warning: inserting missing 'title' element line 1 column 13 - Error: is not recognized! line 1 column 13 - Warning: discarding unexpected line 1 column 31 - Warning: discarding unexpected This document has errors that must be fixed before using HTML Tidy to generate a tidied up version. Is there a Python HTML tidier which will do as good a job as a browser? -- Richie From martin at v.loewis.de Thu Apr 27 02:00:35 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 27 Apr 2006 08:00:35 +0200 Subject: MinGW and Python In-Reply-To: <1146088651.980286.97220@j33g2000cwa.googlegroups.com> References: <1145861223.509630.247350@y43g2000cwc.googlegroups.com> <444C79D7.4060007@v.loewis.de> <444DC62B.7000702@v.loewis.de> <1145985979.369429.114040@i39g2000cwa.googlegroups.com> <1145995815.818582.166230@y43g2000cwc.googlegroups.com> <444FA85B.7010104@v.loewis.de> <1146088651.980286.97220@j33g2000cwa.googlegroups.com> Message-ID: <44505e03$0$13138$9b622d9e@news.freenet.de> Ross Ridge wrote: > Nonetheless, Cygwin applications are not generally considered native > Win32 applications because of the dependency on CYGWIN1.DLL and the > related environment. While what you're saying a strictly true, the > term "native Win32" is used to make a distinction between a port of a > program that doesn't use or require the Cygwin environment from one > that does. I know it is common to take that view, but I believe it is wrong, no matter how you look at it: - Is winword.exe not a native Win32 library because it uses "MSO.DLL"? - A cygwin application does *not* require the Cygwin environment. You don't need to invoke it from bash.exe, you don't need to install Cygwin to run it, and you don't need a directory structure including /usr or /etc to make it work. > For example, the official version of Python for Windows is > considered a native Win32 application because it's implemented using > the Windows APIs directly That isn't (entirely) true. Python largely doesn't use the Win32 API directly, but instead, it uses the C library of the C compiler it was built with. It also uses the Win32 API directly, and more so in Python 2.5 than in earlier versions, but reliance on the C library still hasn't been dropped. For Py3k, perhaps the C library can be dropped entirely: Guido wants to drop usage of stdio as an implementation of the file object; if then malloc/free is dropped in favour of a "direct" implementation (e.g. based on HeapAlloc), then Python could become a "native Win32 application" in the sense you defined above. Regards, Martin From arne.meissner at gmx.de Sat Apr 8 06:39:57 2006 From: arne.meissner at gmx.de (Arne) Date: Sat, 8 Apr 2006 12:39:57 +0200 Subject: Documentation for Tkinter/Tix Message-ID: Hello! Where can I find a documentation for Tkinter/Tix. I already have the standard documentation ditributed with Python. Especially I am looking for documentation about the options for some tix widgets like Dirlist (How can I link it to a certain directory, etc.) Thanks! Arne From scott.daniels at acm.org Fri Apr 14 16:57:09 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Fri, 14 Apr 2006 13:57:09 -0700 Subject: requestion regarding regular expression In-Reply-To: <1145031538.601388.71130@j33g2000cwa.googlegroups.com> References: <1145006270.632156.144790@j33g2000cwa.googlegroups.com> <443f91d7$1_2@newspeer2.tds.net> <1145026037.790344.205630@e56g2000cwe.googlegroups.com> <443fc460$1_2@newspeer2.tds.net> <1145031538.601388.71130@j33g2000cwa.googlegroups.com> Message-ID: <444009a0$1@nntp0.pdx.net> BartlebyScrivener wrote: > That's it. Thank you! Very instructive. > > Final: > > path = "d:/emacs files/emacsinit.txt" > lines = open(path).readlines() > # next two lines all on one > starts = [i for i, line in enumerate(lines) if > line.startswith('(defun')] > for i, start in enumerate(starts): > while start > 0 and lines[start-1].startswith(';'): > starts[i] = start = start-1 > print starts > If you don't want to hold the whole file in memory, this gets the starts a result at a time: def starts(source): prelude = None for number, line in enumerate(source): # read and number a line if line[0] == ';': if prelude is None: prelude = number # Start of commented region # else: this line just extends previous prelude else: if line.startswith('(defun'): # You could append to a result here, but yield lets # the first found one get out straightaway. if prelude is None: yield number else: yield prelude prelude = None path = "d:/emacs files/emacsinit.txt" source = open(path) try: for line in starts(source): print line, # could just do: print list(starts(source)) finally: source.close() print -- -Scott David Daniels scott.daniels at acm.org From prouleau at impathnetworks.com Sat Apr 29 18:54:32 2006 From: prouleau at impathnetworks.com (Pierre Rouleau) Date: Sat, 29 Apr 2006 18:54:32 -0400 Subject: Can we create an_object = object() and add attribute like for a class? In-Reply-To: <1hek76f.48x7rvw33771N%aleaxit@yahoo.com> References: <1hek76f.48x7rvw33771N%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Pierre Rouleau wrote: > > >>Hi all, >> >>Is there any reason that under Python you cannot instantiate the object >>class and create any attributes like you would be able for a normal class? > > > Yep: instances of type object do not have a __dict__ and therefore there > is no place to put any attributes. This is necessary to allow ANY > subclass of object, and thus any type whatsoever, to lack a per-instance > __dict__ (and thus to save its per-instance memory costs), Makes sense. I was under the impresssion that instances of type object did have a __dict__ but was hidden for some reason. I should have known ... explicit is better than implicit... > > >>Being able to do it would seem a natural way of declaring namespaces. > > > I find that ns = type('somename', (), dict(anattribute=23)) isn't too > bad to make a namespace ns, though it has some undesirable issues (e.g., > ns is implicitly callable, which may make little sense for a namespace). > > At any rate, any natural way of declaring a namespace SHOULD allow > arbitrary named arguments in the instantiation call -- bending > principles to give each instance of object a __dict__ would still not > fix that, so that wouldn't do much. I think it's worth the minor bother > to write out something like > > class Namespace(object): > def __init__(self, **kwds): self.__dict__ = kwds > > and I generally go further anyway, by defining at least a repr that > shows the attributes' names and values (very useful for debugging...). > > That's what I do too, but sometimes i just want to have a quick holder attribute in a class and am lazy to do it. I could declare one such class inside a module and import it but again, that means importing, name space of the module, etc... I can understand the design decision not to give object a __dict__, but I wonder if i'd be a good idea to have a class that derives from object and has a __dict__ to be in the standard library. I posted the original question because I run into this quite often and I just saw a post a little before mine ("self modifying code") where the idiom was used. -- Pierre Rouleau From mtallen at gmail.com Sat Apr 8 11:30:50 2006 From: mtallen at gmail.com (mtallen at gmail.com) Date: 8 Apr 2006 08:30:50 -0700 Subject: Working with decimal points In-Reply-To: <1144509666.471858.55160@v46g2000cwv.googlegroups.com> References: <1144509666.471858.55160@v46g2000cwv.googlegroups.com> Message-ID: <1144510250.788190.317860@i39g2000cwa.googlegroups.com> Byte wrote: > How come: > > sum = 1/4 > print sum > > returns 0? 1/4=0.25, not 0. How do I fix this? Make sure there is at least one float in your equation. In your example Python is doing interger math for you and returing the floor. You need to give it a hint that you would like to do floating point math. >>> sum = 1.0/4 >>> print sum 0.25 >>> sum = 1/4.0 >>> print sum 0.25 >>> From sjmachin at lexicon.net Wed Apr 19 20:29:23 2006 From: sjmachin at lexicon.net (John Machin) Date: Thu, 20 Apr 2006 10:29:23 +1000 Subject: Image open problem In-Reply-To: References: Message-ID: <4446D5E3.1030600@lexicon.net> On 20/04/2006 6:55 AM, Aleksandar Cikota wrote: > Hi all, > > I have a problem with openning of an image. > > Here is the Code: > > from Tkinter import * > from PIL import Image, ImageTk Insert here: print type(Image), type(Image.open), Image.version Here are my results: Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from PIL import Image, ImageTk >>> Image.VERSION '1.1.5' >>> type(Image) >>> type(Image.open) ... which is what I expected [snip] If the print statement gives incorrect results, I'd advise re-installing PIL. If it gives correct results, add a copy of the print further towards where the error occurs. Binary search until you have found the culprit that is mangling Image. > image = Image.open('G:/Robot teleskop/VRT/'+ > str(name[0:-4])+'.jpg') I thought I'd already seen somebody point out to you that all those str() calls are rather redundant ... [snip]> > > The error message: > Exception in thread TestThread: > Traceback (most recent call last): > File "C:\Program Files\Python\lib\threading.py", line 442, in __bootstrap > self.run() > File "G:\Robot teleskop\VRT\soft\GUI.py", line 60, in run > image = Image.open('G:/Robot teleskop/VRT/'+ str(name[0:-4])+'.jpg') > AttributeError: 'function' object has no attribute 'open' The implication is that Image is a function, which is weird. > > > I think the modul is not imported how it should be. I hope for help. From randomtalk at gmail.com Sat Apr 29 14:08:35 2006 From: randomtalk at gmail.com (randomtalk at gmail.com) Date: 29 Apr 2006 11:08:35 -0700 Subject: opposite function to split? Message-ID: <1146334115.556040.54550@i40g2000cwc.googlegroups.com> hello everyone! I can't seem to find a function that combines a list of items into a string with a seperator between the individual elements.. Is there such a method that does the opposite of sting.split? thanks alot! From kpdere at derenet.us Mon Apr 24 10:38:30 2006 From: kpdere at derenet.us (Ken Dere) Date: Mon, 24 Apr 2006 10:38:30 -0400 Subject: How I learned Tkinter References: <1145810017.100862.215950@j33g2000cwa.googlegroups.com> Message-ID: <10eb9$444ce2ec$477ea626$1815@news.flashnewsgroups.com> peter wrote: > I've been trying to teach myself Tkinter programming over the last few > months > (in a strictly amateur way), and have made a number of requests for > help in this > newsgroup and elsewhere. > > I've now (sort of) got there - in that I have used Tkinter for some > programs for > personal use - and I've written up my experiences at > > http://www.aqzj33.dsl.pipex.com/how_i_learned_tkinter/contents.htm > > > In general I found that while Frederik Lundh's tutorial is > comprehensive and > well written, there is little else around to help the newcomer working > without > the benefit of more experienced colleagues, and that in places the > documentation > is too sparse to be of much help. > > Any thoughts? Is my experience typical? > > Peter "Programming Python" by Mark Lutz has several chapters on Tkinter (O'Reilly). Thanks for your notes as I am still behind you. Ken D. From could.net at gmail.com Wed Apr 5 22:36:40 2006 From: could.net at gmail.com (Frank Potter) Date: Thu, 6 Apr 2006 10:36:40 +0800 Subject: how to login a newsgroup programmely and fetch its emails to read? Message-ID: <311b5ce10604051936j27e7cce3scd3482c768208a02@mail.gmail.com> how to login a newsgroup and get its informations by an account and a password? From xah at xahlee.org Wed Apr 19 18:36:19 2006 From: xah at xahlee.org (Xah Lee) Date: 19 Apr 2006 15:36:19 -0700 Subject: Generating Thumbnail Images of a Photo Gallery Message-ID: <1145486179.679980.172310@i39g2000cwa.googlegroups.com> The following is a program to generate thumbnail images for a website. Useful, if you want to do that. It is used to generate the thumbnails for my ?Banners, Damsels, and Mores? project gallery. ( http://xahlee.org/Periodic_dosage_dir/lanci/lanci.html ) Comments and versions in other lang welcome. Xah xah at xahlee.org ? http://xahlee.org/ # -*- coding: utf-8 -*- # Python # ? 2006-04 by Xah Lee, ? http://xahlee.org/, 2006-04 # Given a webite gallery of photos with hundreds of photos, i want to generate a thumbnail page so that viewers can get a bird's eye's view images. # Technically: # Given a dir: e.g. /Users/xah/web/Periodic_dosage_dir/lanci/ # This dir has many html files inside it, maybe in sub dir. # Any html file is a photo gallery, with inline images of photos. # all the image files are in under the given dir, or in subdir. # ? The goal is to create thumbnail images of all the inline images in all html files under that dir. # ? These thumbnail images destination can be specified, unrelated to the given dir. # ? Thumbnail images must preserve the dir structure they are in. For example, if a inline image's full path is /a/b/c/d/1.img, and the a root is given as /a/b, then the thumbnail image's path must retain the c/d, as sud bir under the specified thumbnail destination. # ? if the inline image's size is smaller than a certain given size (specified as area), then skip it. # Note: online inline images in a html file will be considered for thumbnail. Any other images in the given dir or as linked images should be ignored. ############################################### import re, subprocess, os.path # path where html files and images are at. e.g. /a/b/c/d inPath= '/Users/xah/3D-XplorMath/Curves' # no trailing slash # a substring of inPath. The thumbnails will preserve dir structures. If a image is at /a/b/c/d/e/f/1.png, and rootDir is /a/b/c, then the thumbnail will be at /x/y/d/e/f/1.png rootDir= '/Users/xah/3D-XplorMath/Curves' # no trailing slash # the destination path of thumbanil images. It will be created. Existing things will be over-written. e.g. /x/y thumbnailDir= '/Users/xah/3D-XplorMath/Curves/tn' # no trailing slash # thumbnail size thumbnailSizeArea = 150 * 150 # if a image is smaller than this area, don't gen thumbnail for it. minArea = 200*200 # imageMagic 'identify' program path identify = r'/sw/bin/identify' convert = r'/sw/bin/convert' # depth of nested dir to dive into. minLevel=1; # files and dirs of mydir are level 1. maxLevel=9; # inclusive ############################### ## functions def scaleFactor(A,(w,h)): '''getInlineImg(A,(w,h)) returns a number s such that w*s*h*s==A. This is used for generating the scaling factor of a image with a given desired thumbnail area A. The w and h are width and height of rectangle (image). The A is given size of thumbnail of the photo (as area). When the image is scaled by s in both dimensions, it will have desired size specified by area A as thumbnail.''' return (float(A)/float(w*h))**0.5 def getInlineImg(file_full_path): '''getInlineImg(html_file_full_path) returns a array that is a list of inline images. For example, it may return ['xx.jpg','../image.png']''' FF = open(file_full_path,'rb') txt_segs = re.split( r'src', unicode(FF.read(),'utf-8')) txt_segs.pop(0) FF.close() linx=[] for linkBlock in txt_segs: matchResult = re.search(ur'\s*=\s*\"([^\"]+)\"', linkBlock,re.U) if matchResult: linx.append( matchResult.group(1).encode('utf-8') ) return linx def linkFullPath(dir,locallink): '''linkFullPath(dir, locallink) returns a string that is the full path to the local link. For example, linkFullPath('/Users/t/public_html/a/b', '../image/t.png') returns 'Users/t/public_html/a/image/t.png'. The returned result will not contain double slash or '../' string.''' result = dir + '/' + locallink result = re.sub(r'//+', r'/', result) while re.search(r'/[^\/]+\/\.\.', result): result = re.sub(r'/[^\/]+\/\.\.', '', result) return result def buildThumbnails(dPath, fName, tbPath, rPath, areaA): u'''Generate thumbnail images. dPath is directory full path, and fName is a html file name that exists under it. The tbPath is the thumbnail images destination dir. The areaA is the thumbnail image size in terms of its area. This function will create thumbnail images in the tbPath. rPath is a root dir subset of dPath, used to build the dir structure for tbPath for each thumbnail. For Example, if dPath = '/Users/mary/Public/pictures' fName = 'trip.html' (this exits under dPath) tbPath = '/Users/mary/Public/thumbs' rPath = '/Users/mary/Public' (must be a substring of dPath or equal to it.) and trip.html contains then a thumbnail will be generated at '/Users/mary/Public/thumbs/pictures/Beijin/day1/img1.jpg' This func uses the imagemagick's shell command ?convert? and ?identify?, and assumes that both's path on the disk are set in the global vars ?convert? and ?identify?.''' # outline: # ? Read in the file. # ? Get the img paths from inline images tags, accumulate them into a list. # ? For each image, find its dimension w and h. # ? Generate the thumbnail image on disk. # Generate a list of image paths. imgPaths=[] for im in filter(lambda x : (not x.startswith('http')) and (not x.endswith('icon_sum.gif')), getInlineImg(dPath + '/' + fName)): imgPaths.append (linkFullPath(dPath, im)) # Change the image path to the full sized image, if it exists. # That is, if image ends in -s.jpg, find one without the '-s'. imgPaths2=[] for myPath in imgPaths: p=myPath (dirName, fileName) = os.path.split(myPath) (fileBaseName, fileExtension)=os.path.splitext(fileName) if(re.search(r'-s$',fileBaseName,re.U)): p2=os.path.join(dirName,fileBaseName[0:-2]) + fileExtension if os.path.exists(p2): p=p2 imgPaths2.append(p) # find out each images's width & height # Each element in imgData has the form [image full path, [width, height]] imgData=[] for imp in imgPaths2: # DSCN2699m-s.JPG JPEG 307x230+0+0 DirectClass 8-bit 51.7k 0.0u 0:01 print "Identifying:", imp imgInfo=subprocess.Popen([identify, imp], stdout=subprocess.PIPE).communicate()[0] (width,height)=(imgInfo.split()[2]).split('x') height=height.split('+')[0] if int(width)*int(height) > minArea: imgData.append( [imp, [int(width), int(height)]]) ##print '' # create the scaled image files in thumbnail dir. The dir structure is replicated. for imp in imgData: print "Thumbnailing:", imp oriImgFullPath=imp[0] thumbnailRelativePath = oriImgFullPath[ len(rPath) + 1:] thumbnailFullPath = tbPath + '/' + thumbnailRelativePath print 'r',thumbnailRelativePath print 'f',thumbnailFullPath sf=scaleFactor(areaA,(imp[1][0],imp[1][1])) #print '' # make dirs to the thumbnail dir (dirName, fileName) = os.path.split(thumbnailFullPath) (fileBaseName, fileExtension)=os.path.splitext(fileName) print "Creating thumbnail:", thumbnailFullPath try: os.makedirs(dirName,0775) except(OSError): pass # create thumbnail subprocess.Popen([convert, '-scale', str(round(sf*100,2)) + '%', oriImgFullPath, thumbnailFullPath] ) #print '' ################# # main def dirHandler(dummy, curdir, filess): curdirLevel=len(re.split('/',curdir))-len(re.split('/',inPath)) filessLevel=curdirLevel+1 if minLevel <= filessLevel <= maxLevel: for child in filess: # if 'act1.html' == child and os.path.isfile(curdir+'/'+child): if '.html' == os.path.splitext(child)[1] and os.path.isfile(curdir+'/'+child): print "processing:", curdir+'/'+child buildThumbnails(curdir,child,thumbnailDir,rootDir,thumbnailSizeArea) while inPath[-1] == '/': inPath = inPath[0:-1] # get rid of trailing slash os.path.walk(inPath, dirHandler, 'dummy') From k.r.fry at durham.ac.uk Mon Apr 3 08:54:21 2006 From: k.r.fry at durham.ac.uk (k r fry) Date: Mon, 03 Apr 2006 13:54:21 +0100 Subject: Oserror: [Errno 20] In-Reply-To: References: Message-ID: Again, I apologise. Not knowing much about Python means that I don't know what needs to be provided. I meant it doesn't work in the same way that "istdir" didn't work. Here is what I have coded: for subdir in os.path.istdir(DATADIR): #loop through list of strings file=FITS.Read(DATADIR+'/'+subdir+'/flux.fits') #opens flux.fits file and reads summation=open(DATADIR+'/'+subdir+'/flux.dat','w') #opens the summation results file for writing to spotbyspot=open(DATADIR+'/'+subdir+'/spotflux.dat','w') #opens the spot-by-spot file for writing to output='' print'\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n'+sys.argv[1]+' '+subdir+'\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n' And here is what I get when I try to run it: Traceback (most recent call last): File "katiescint.py", line 153, in ? for subdir in os.path.istdir(DATADIR): #loop through list of strings AttributeError: 'module' object has no attribute 'istdir' Here is trying with listdir: for subdir in os.path.listdir(DATADIR): #loop through list of strings and here is what I get: Traceback (most recent call last): File "katiescint.py", line 153, in ? for subdir in os.path.listdir(DATADIR): #loop through list of strings AttributeError: 'module' object has no attribute 'listdir' Sybren Stuvel wrote: > k r fry enlightened us with: > >>I did think maybe it was meant to be "listdir" instead of "istdir", >>but that doesn't work either. > > > And again you don't tell us in what way it doesn't work. > > Think about what you post from our point of view. Then re-read it, and > think about it again. Only if you're sure that we'll be able to fully > understand it, hit the 'send' button. That will save us a lot of > guessting and asking, and will also get you your answer a lot faster. > > Sybren From matthew.garrish at sympatico.ca Sat Apr 29 08:48:44 2006 From: matthew.garrish at sympatico.ca (Matt Garrish) Date: Sat, 29 Apr 2006 08:48:44 -0400 Subject: No subject References: <1145992903.834316.198370@u72g2000cwu.googlegroups.com> <4GM3g.3084$TT.1768@twister.nyroc.rr.com> <1146231280.733609.143230@e56g2000cwe.googlegroups.com> <4452258e$0$655$bed64819@news.gradwell.net> <1146235544.218219.71430@j73g2000cwa.googlegroups.com> <87psj1ionl.fsf@rpi.edu> Message-ID: "Bill Atkins" wrote in message news:87psj1ionl.fsf at rpi.edu... > John Bokma writes: >> >> Isn't it crazy that one person is allowed to create such a huge mess >> everytime he posts? > > Isn't it crazy that one person willfully creates such a mess every > time Xah posts? Shush! > Don't waste your time with the Bokma. He wants everyone to follow the posting rules that annoy Bokma the least, but he never follows them himself. Matt From no-spam at no-spam-no-spam.com Sat Apr 22 06:40:15 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Sat, 22 Apr 2006 12:40:15 +0200 Subject: perspective on ruby In-Reply-To: References: <1145555339.316764.123210@i39g2000cwa.googlegroups.com> <1he41sz.r7aasv1oo5lfN%aleaxit@yahoo.com> Message-ID: Edward Elliott wrote: > Alex Martelli wrote: > >> While Mozart appears cool, I really think that a wider variety of >> languages would help -- some machine code (possibly abstract a la >> Mixal), C (a must, *SO* much is written in it!), at least one of C++, D, >> or ObjectiveC, either Scheme or Lisp, either *ML or Haskell, either >> Python or Ruby, and at least one "OOP-only" language such as Java, C#, >> Eiffel, or Smalltalk. > > > Yeah I agree that more is better. The problem is using a new language > every couple courses without bogging down in implementation details. > Personally I'd just say "Here's a book, learn it yourself". It's what > they gotta do on the job anyway. Yes - start them explore. I'd not want to be "teached" a specific _language_ in a course longer that one day. A language cannot be teached. Who of the posters in this thread want themselves to be _teached_ more than one day on a language? I've seen many graduates who "know" Java, C, this and that words and patterns, but hardly can write a loop and evolve things. Those, who can write loops are mostly self-educated and can do all things quickly in any language. Isn't the fun, finding the right tools for certain purposes one-self? The job of (CS) courses more to provide a map ( "what fun to explore yourself" ) and display extremes (ASM and Lisp) to prevent from identification ? -robert From claird at lairds.us Sun Apr 30 09:07:42 2006 From: claird at lairds.us (Cameron Laird) Date: Sun, 30 Apr 2006 13:07:42 GMT Subject: stdin: processing characters References: <2Bd4g.21380$tN3.16246@newssvr27.news.prodigy.net> Message-ID: In article <2Bd4g.21380$tN3.16246 at newssvr27.news.prodigy.net>, Edward Elliott wrote: >Kevin Simmons wrote: >> I have a python script that prompts the user for input from stdin via a >> menu. I want to process that input when the user types in two characters >> and not have to have the user press . As a comparison, in the bash >> shell one can use (read -n 2 -p "-->" CHOICE; case $CHOICE in...). Works >> great and is very > >I did something like this a couple years ago, curses was the easiest way I >found to do it. It's pretty painless with the wrapper function, which >restores your terminal on error/exit. > Kevin, the bad news is that curses() is as good as Python gets in this regard. For better or worse, to the best of my knowledge, unextended Python caNOT implement bash's read. Here's the closest small approximation I know: import curses import os msvcrt = curses.initscr() msvcrt.addstr("-->") first = msvcrt.getch() second = msvcrt.getch() os.system("stty echo -nl") print "\nThe two characters are '%s' and '%s'." % (first, second) I hope someone proves me wrong. From scott.daniels at acm.org Mon Apr 3 12:42:51 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 03 Apr 2006 09:42:51 -0700 Subject: Oserror: [Errno 20] In-Reply-To: References: Message-ID: <44314dd8$1@nntp0.pdx.net> Peter Hansen wrote: > k r fry wrote: >> Hi, I am new to this list and also programming with python. >> I have an error: oserror [errno 20] not a directory "katiescint.py" >> The piece of code causing the problem is: >> [code] >> >> for subdir in os.listdir(DATADIR): #loop through list of >> strings >> >> file=FITS.Read(DATADIR+'/'+subdir+'/flux.fits') #opens >> flux.fits file and reads > > os.listdir() returns a list of all files and directories inside the > directory specified (DATADIR), so you can't assume that "subdir" is > always going to be a directory. Use os.path.isdir() to confirm that it > is and ignore those items for which that function returns False. I'd guess you might want to go with something like: for root, dirs, files in os.walk(DATADIR): if 'flux.fits' in files: file = FITS.Read(os.path.join(root, 'flux.fits')) read up on: os.path.join and os.walk The previous code will do lots of recursive walking in a deeply nested directory structure. If you only want to look at single-level subdirs, you could either do: root, dirs, files = iter(os.walk(DATADIR)).next() for subdir in dirs: file = FITS.Read(os.path.join(root, subdir, 'flux.fits')) or: for root, dirs, files in os.walk(DATADIR): if 'flux.fits' in files: file = FITS.Read(os.path.join(root, 'flux.fits')) if root != DATADIR: del dirs[:] # Stop recursing after the first descent) depending on whether you know 'flux.fits' should be there or you only want to work on subdirs where it is in the directory. -Scott David Daniels scott.daniels at acm.org From martin at v.loewis.de Mon Apr 3 01:39:57 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 03 Apr 2006 07:39:57 +0200 Subject: print() in Python 3000 return value? In-Reply-To: <1144014336.593470.27870@j33g2000cwa.googlegroups.com> References: <1143997643.857261.186430@i40g2000cwc.googlegroups.com> <44300797$0$28451$9b622d9e@news.freenet.de> <1143999680.091690.253340@g10g2000cwb.googlegroups.com> <1144004749.150519.284270@i39g2000cwa.googlegroups.com> <1144014336.593470.27870@j33g2000cwa.googlegroups.com> Message-ID: <4430B52D.1090803@v.loewis.de> bayerj wrote: >> Sorry? 2+2 here returns 4, and certainly should with your Python. > > Err. Never mind. I was thinking about assignments, like > >>>> x += 2 > > which returns None. Actually, assignment, in Python, is a statement, not an expression. Statements don't return anything, not even None (they don't have a value). If print becomes a function, the question about its return value becomes meaningful. Regards, Martin From rrr at ronadam.com Thu Apr 6 11:27:50 2006 From: rrr at ronadam.com (Ron Adam) Date: Thu, 06 Apr 2006 10:27:50 -0500 Subject: pre-PEP: The create statement In-Reply-To: <59Wdnbd8EazRCqnZnZ2dnUVZ_vudnZ2d@comcast.com> References: <59Wdnbd8EazRCqnZnZ2dnUVZ_vudnZ2d@comcast.com> Message-ID: > Abstract > ======== > > This PEP proposes a generalization of the class-declaration syntax, > the ``create`` statement. The proposed syntax and semantics parallel > the syntax for class definition, and so:: > > create : > > > is translated into the assignment:: > > = ("", , ) > > where ```` is the dict created by executing ````. > The PEP is based on a suggestion [1]_ from Michele Simionato on the > python-dev list. I'll have to think on this one a bit. So I'm undecided for now. Could it possibly use the 'as' keyword? create as : It has also been suggested that a pattern where functions and classes are assigned be used. Possibly something like... name = class(): name = def(): name = create(): Or it could be... name = object(): This is a bigger change than adding the create keyword, (definitely not a pre-P3k item), and I'm not sure if it fits your use case, but it does allow for a larger variety of types without adding additional keywords. Cheers, Ron From cretin at des.alpes.ch Thu Apr 13 10:30:23 2006 From: cretin at des.alpes.ch (Azolex) Date: Thu, 13 Apr 2006 16:30:23 +0200 Subject: trying to grasp OO : newbie Q? In-Reply-To: <1144937168.508799.67410@i40g2000cwc.googlegroups.com> References: <1144937168.508799.67410@i40g2000cwc.googlegroups.com> Message-ID: <443e6085$1_2@news.bluewin.ch> mitsura at skynet.be wrote: > Hi, > > I just started with Python and I am new to OO programming. > Here is a simple code: > " > class Obj: > myVar = 1 > > def __init__(self): > myVar = 2 > > # > > > myObj = Obj() > > print myObj.myVar > " > > The output is of this script is '1'. I would except it to be '2'. > I not understanding something fundamentally here. You want to replace "myVar = 2" by "self.myVar = 2" to get the result you expect. > > Can anybody explain? > Your "myVar = 1" sets a variable in the namespace of the class Your "myVar = 2" sets a variable in the local frame of execution of the __init__ method, that is invisible outside that frame Putting "self.myVar = 2" will set a variable in the instance dict that will shadow the class variable of the same name when you access myObj.myVar hth From gene.tani at gmail.com Mon Apr 17 10:51:41 2006 From: gene.tani at gmail.com (gene tani) Date: 17 Apr 2006 07:51:41 -0700 Subject: Python certification/training In-Reply-To: References: <1145193231.657614.275950@v46g2000cwv.googlegroups.com> Message-ID: <1145285501.007723.42730@e56g2000cwe.googlegroups.com> aum wrote: > > Makes me wonder, just out of curiosity - are there any universities > actually teaching python (in anything bigger than a small elective > module), or are they all still owned by Java, C++, C# and Visual Basic? > like NLTK, maybe? http://www.ldc.upenn.edu/sb/home/papers/nltk.pdf From felipe.lessa at gmail.com Mon Apr 10 13:17:24 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Mon, 10 Apr 2006 14:17:24 -0300 Subject: how to make a generator use the last yielded value when it regains control In-Reply-To: <1144688740.056988.183640@u72g2000cwu.googlegroups.com> References: <4435cde3$0$11677$c3e8da3@news.astraweb.com> <1144390994.551650.31490@v46g2000cwv.googlegroups.com> <443a40e0$1_1@news.bluewin.ch> <1144688740.056988.183640@u72g2000cwu.googlegroups.com> Message-ID: <1144689444.6280.26.camel@kenshin.CASA> Em Seg, 2006-04-10 ?s 10:05 -0700, Lonnie Princehouse escreveu: > I happen to think the recursive version is more elegant, but that's > just me ;-) It may be elegant, but it's not efficient when you talk about Python. Method calls are expensive: $ python2.4 -mtimeit 'pass' 10000000 loops, best of 3: 0.0585 usec per loop $ python2.4 -mtimeit -s 'def x(): pass' 'x()' 1000000 loops, best of 3: 0.291 usec per loop $ calc 0.291/0.0585 ~4.97435897435897435897 $ calc 0.291-0.0585 0.2325 This happens because of the dynamic nature of Python and its lack of tail call optimization. IOW, avoid recursive methods when possible (I usually write those for the first version of a method then rethink it using a non-recursive approach), specially if they are part of a hot spot. -- Felipe. From shay at shay-riggs.fsnet.co.uk Tue Apr 11 18:06:31 2006 From: shay at shay-riggs.fsnet.co.uk (SR) Date: 11 Apr 2006 15:06:31 -0700 Subject: How can I reduce the number of queries to my PostgreSQL database? References: <1144489087.794505.277930@v46g2000cwv.googlegroups.com> <87fykonmiy.fsf@fangorn.rev.stofanet.dk> Message-ID: <1144793191.489173.164550@i40g2000cwc.googlegroups.com> Martin Christensen said: >SR> Scenario: I have a python script which creates web page listing >SR> all books in the database, and all authors for each book. My >SR> python script does essentially three things: > >SR> 1. retrieve a list of all book_ids and book_titles. > >SR> 2. for each book_id, query the bookauthors table and retrieve all >SR> author names for that book_id. > >SR> 3. display it all out as an html table on a web page. > >That's one query, if you're willing to make it advanced enough, >although you need to make an aggregate to enable PostgreSQL to >concatenate and comma separate author names. However, this aggregate >will typically need more than one database function. Such an aggregate >could be as follows: >This is the solution that I would use after working nearly a decade >with databases. It is neither simple nor obvious to the novice, but >it's the Right Way To Do It. For a learning exercise, this is way over >the top, but I thought you might benefit from seeing that - so long as >you only need information that would reasonably fit in one table on a >web page or the equivalent - one query is always enough. Or perhaps >that should be One Query Is Always Enough. :-) Learn at your own pace, >though, but you might want to keep this in mind for future reference. Thanks for that... I'm not going to argue with a decade's experience! I'd never heard of aggregates before, but I'll look into them. Perhaps I'll be able to impress my friends with them one day. The reason for keeping the authors separate was to wrap them with an appropriate HTML href, but presumably your solution could be adapted for this purpose? Cheers, Shay From sybrenUSE at YOURthirdtower.com.imagination Thu Apr 6 17:43:12 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Thu, 6 Apr 2006 23:43:12 +0200 Subject: Partially unpacking a sequence References: <1144352710.190839.165580@z34g2000cwc.googlegroups.com> <1144357119.010550.284510@j33g2000cwa.googlegroups.com> Message-ID: tkpmep at hotmail.com enlightened us with: >>>> y[1,3] > Traceback (most recent call last): > File "", line 1, in ? > TypeError: list indices must be integers > > The error message gave me no clue as to what I was doing wrong (in > my mind, I was just writing out the elements of a range), and I > thought perhaps that my inclusion of a comma was the problem. You thought correct. List indices must be integers, not tuples. > Perhaps a more explicit error message would have helped. Why? You thought the right thing. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From Serge.Orlov at gmail.com Sun Apr 16 00:14:48 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 15 Apr 2006 21:14:48 -0700 Subject: My python can not get addr info In-Reply-To: <1145159807.133572.103950@t31g2000cwb.googlegroups.com> References: <1145159807.133572.103950@t31g2000cwb.googlegroups.com> Message-ID: <1145160888.038802.291340@e56g2000cwe.googlegroups.com> ??? wrote: > socket.gaierror: (10104, 'getaddrinfo failed') You're using a buggy firewall, write to your firewall vendor about this bug. IDLE shell is making a connection over loopback network interface in other words making a connection from your computer to your computer, this type of connection should not be blocked by a firewall. From rvernica at gmail.com Mon Apr 3 16:58:31 2006 From: rvernica at gmail.com (Rares Vernica) Date: Mon, 03 Apr 2006 13:58:31 -0700 Subject: readline support Message-ID: Hi, I am trying to get readline support in python. I am working on Linux and I have the latest version from svn. After I ./configure and make I can run python, but the readline support is not there. If I do: %./configure >& out.txt %grep readline out.txt checking for readline in -lreadline... yes checking for rl_callback_handler_install in -lreadline... yes checking for rl_pre_input_hook in -lreadline... yes checking for rl_completion_matches in -lreadline... yes it seems that readline library is there and is found by python. How can I further track down this issue? Thanks, Ray From steven.bethard at gmail.com Wed Apr 12 11:35:27 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 12 Apr 2006 09:35:27 -0600 Subject: list.clear() missing?!? In-Reply-To: References: <1144767680.583085.310160@v46g2000cwv.googlegroups.com> <1144792144.168802.146310@i39g2000cwa.googlegroups.com> Message-ID: Steven D'Aprano wrote: > On Tue, 11 Apr 2006 14:49:04 -0700, Ville Vainio wrote: > >> John Salerno wrote: >> >>> Thanks guys, your explanations are really helpful. I think what had me >>> confused at first was my understanding of what L[:] does on either side >>> of the assignment operator. On the left, it just chooses those elements >>> and edits them in place; on the right, it makes a copy of that list, >>> right? (Which I guess is still more or less *doing* the same thing, just >>> for different purposes) >> Interestingly, if it was just a "clear" method nobody would be confused. > > Even more importantly, you could say help(list.clear) and learn something > useful, instead of trying help(del) and getting a syntax error. [snip more reasons to add list.clear()] I think these are all good reasons for adding a clear method, but being that it has been so hotly contended in the past, I don't think it will get added without a PEP. Anyone out there willing to take out the best examples from this thread and turn it into a PEP? STeVe From tim.golden at viacom-outdoor.co.uk Thu Apr 27 03:41:34 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 27 Apr 2006 08:41:34 +0100 Subject: Speed of shutil.copy vs os.system("copy src dest") in win32 Message-ID: [Russell Warren] | I just did a comparison of the copying speed of shutil.copy | against the | speed of a direct windows copy using os.system. I copied a file that | was 1083 KB. | | I'm very interested to see that the shutil.copy copyfileobj | implementation of hacking through the file and writing a new one is | significantly faster... any clue as to why this is? I figure I'm | missing something here. There are a couple of other options as well which may or may not be faster. I'd meant to time things before putting this page up but never got round to it; maybe I'll give it another go: http://tgolden.sc.sabren.com/python/win32_how_do_i/copy-a-file.html TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From http Sat Apr 1 17:55:09 2006 From: http (Paul Rubin) Date: 01 Apr 2006 14:55:09 -0800 Subject: Scatter/gather on sockets? References: Message-ID: <7x64lsvrci.fsf@ruckus.brouhaha.com> Roy Smith writes: > This is true, but I'm generating the message being sent in very small > chunks (often as small as 4 bytes at a time), and typically need to flush a > packet out onto the network after a few dozen bytes. Maybe at most a few > hundred. I don't know of any networks with MTU's smaller than that. > Measurements show a 10-fold improvement in protocol throughput with large > packets vs. small ones. The only question is what's the most efficient way > in Python to generate the large packets. Probably: build up the packet with cStringIO or with the array module instead of as a list of small strings. But if you time both versions I don't think it'll matter much. Python (at least CPython) simply will not be very fast no matter what you do. The overhead of building a large string (with ''.join, say) from a bunch of small ones isn't that big a deal compared with what you already lose in interpreter overhead running the application. From heidiweber at freenet.de Sun Apr 9 07:43:55 2006 From: heidiweber at freenet.de (HeidiWeber) Date: 9 Apr 2006 04:43:55 -0700 Subject: Round Message-ID: <1144583035.135712.307920@i40g2000cwc.googlegroups.com> Hello i?m a beginner in python. With version 14 in SPSS (statistic software) there are the posibility to use python. i want do the following: double NCases NCases=10/6 is this correct in python? Because in SPSS there are an error message. Thank you very much cu Heidi From conor.robinson at gmail.com Mon Apr 10 14:42:11 2006 From: conor.robinson at gmail.com (conor.robinson at gmail.com) Date: 10 Apr 2006 11:42:11 -0700 Subject: very strange problem in 2.4 In-Reply-To: <4437cac3$0$15517$626a54ce@news.free.fr> References: <1144454473.488240.271200@t31g2000cwb.googlegroups.com> <4437cac3$0$15517$626a54ce@news.free.fr> Message-ID: <1144694531.703144.199770@j33g2000cwa.googlegroups.com> Ok, so I found out that even though mylist[] and all objects in it were fine ie id(mylist[i]) != id(mylist[all others]) what was happening is that during a reproduction function a shallow copies were being made making all offspring (genetic algorithm) have different id(mylist[0..n]), however the actual attributes were referenced for offspring on the same parent(s). Fixed it with a deepcopy and used properties insead of java like get sets. thanks for all the help, Conor From alec.jang at gmail.com Mon Apr 3 10:20:51 2006 From: alec.jang at gmail.com (Alec Jang) Date: Mon, 03 Apr 2006 22:20:51 +0800 Subject: New Python Logo Revealed In-Reply-To: References: <9bct22dngv6lncqfjju5oqi4772or4pdle@4ax.com> Message-ID: robin ??: > "Giovanni Bajo" wrote: > >> robin wrote: >> >>> I have an entry on my blog discussing the new Python logo, which is >>> apparently due to replace the current one within the month. I'd be >>> interested in what people think of it. >>> >>> Surf: >>> http://diagrammes-modernes.blogspot.com >> Tell me tell me it's an april's joke, please? :) > > yes :-) > ----- > robin > noisetheatre.blogspot.com I guess it is absolutely a joke. If not, there will be a disaster, and that means ruby will rule the world. -- Best regards, Alec Jang From niceyama at googlemail.com Thu Apr 13 20:01:55 2006 From: niceyama at googlemail.com (niceyama at googlemail.com) Date: 13 Apr 2006 17:01:55 -0700 Subject: Socket Error: Connection Refused Message-ID: <1144972915.659416.326230@t31g2000cwb.googlegroups.com> Dear c.l.p, I have recently been doing the tutorial of Python and everything is well, i'm upto the pass section. Anyway, when I try to launch idle now I get the error message: Socket Error: Connection Refused. I do not have a firewall, so I don't know what is going on. Also, this comes up after it: IDLE's subprocess didn't make the connection. Either IDLE can't start a subprocess or personal firewall software is blocking the connection. [OK] Any help would be appreciate. Yamas From scott.daniels at acm.org Mon Apr 3 12:50:17 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 03 Apr 2006 09:50:17 -0700 Subject: can I get the index number in for x in y loop? In-Reply-To: <1144079271.758144.92070@v46g2000cwv.googlegroups.com> References: <1144078372.411795.21570@i39g2000cwa.googlegroups.com> <1144078792.350510.57870@i39g2000cwa.googlegroups.com> <1144079271.758144.92070@v46g2000cwv.googlegroups.com> Message-ID: <44314f92$1@nntp0.pdx.net> JuHui wrote: > which one has best performance? > > a:for i in range(0,len(a)) > b:for x in a > c:for x,y in enumerate(a) Read up on the timeit module and figure it out for yourself. The answer will depend on the distribution of your data. > but, it seems I can't get index number with b format..:( Well, that's true, but it is a bit like saying: I cannot find the distance in meters between Paris and London with: for i in range(10): print i --Scott David Daniels scott.daniels at acm.org From cretin at des.alpes.ch Fri Apr 7 04:52:42 2006 From: cretin at des.alpes.ch (Azolex) Date: Fri, 07 Apr 2006 10:52:42 +0200 Subject: how to make a generator use the last yielded value when it regains control In-Reply-To: <4435cde3$0$11677$c3e8da3@news.astraweb.com> References: <4435cde3$0$11677$c3e8da3@news.astraweb.com> Message-ID: <44362866_2@news.bluewin.ch> just couldn't help taking the bait... def morris(seed) : """ >>> m = morris('3447221') >>> m.next() '1324172211' >>> m.next() '1113121411172221' >>> m.next() '31131112111431173211' """ assert isinstance(seed,basestring) and seed.isdigit(),"bad seed" def itially(z) : feedback.z = z while True : yield feedback.z def feedback(gen) : while True : feedback.z = gen.next() yield feedback.z def morrisify(number) : from itertools import groupby for digit,sequence in groupby(number) : yield str(len(tuple(sequence))) yield digit return feedback(''.join(morrisify(number)) for number in itially(seed)) From sijben at eemvalley.com Thu Apr 20 06:08:21 2006 From: sijben at eemvalley.com (Paul Sijben) Date: Thu, 20 Apr 2006 12:08:21 +0200 Subject: UDP performance In-Reply-To: <4447523e$0$31655$e4fe514c@news.xs4all.nl> References: <44473787$0$31643$e4fe514c@news.xs4all.nl> <4447523e$0$31655$e4fe514c@news.xs4all.nl> Message-ID: <44475d93$0$31649$e4fe514c@news.xs4all.nl> Martin P. Hellwig wrote: [snip] > Is the connection 1:1 i.e. the receiving end receives data only from one > sender at the time? And how do you handle lost packages in your > application? > no the server is receiving from multiple clients. and at the moment I do not handle lost packets. From jparlar at cogeco.ca Fri Apr 7 00:28:43 2006 From: jparlar at cogeco.ca (Jay Parlar) Date: Thu, 6 Apr 2006 21:28:43 -0700 Subject: Missing C modules in 2.5 on OS X? In-Reply-To: <88edbc6803fde62c9f3b1517d0714f14@cogeco.ca> References: <88edbc6803fde62c9f3b1517d0714f14@cogeco.ca> Message-ID: <55b55363bef69f7a6c8e941a258ea655@cogeco.ca> On Apr 6, 2006, at 3:25 PM, Jay Parlar wrote: > I just downloaded, built, and installed the new 2.5 alpha on OS X > 10.3, and it seems that the new 'functional' didn't get installed. > > I know that it got built (done from the 2.5 source directory): > > Jay-Computer:~/Desktop/Python-2.5a1 jayparlar$ find . -iname > functional* > ./build/lib.darwin-7.9.0-Power_Macintosh-2.5/functional.so > ./build/temp.darwin-7.9.0-Power_Macintosh-2.5/functionalmodule.o > ./Modules/functionalmodule.c > > > But it doesn't seem to have been installed, as the same 'find' from > /usr/local/lib/python2.5 produces nothing at all. > > I used the 'make altinstall' option when installing. > > Now that I'm looking closer at it, it seems that *no* modules > implemented in C have been installed... > > Jay P. > > Never mind, I just forgot to reset my PYTHONPATH variable to point to the new site-packages. It all works when I set it to /Users/jayparlar/Library/Python2.5/site-packages. Kind of weird though that only the C modules went to ~/Library/Python2.5/site-packages, but all the .py modules went to /usr/local/lib/python2.5/. Could that be because of my ~/.pydistutils.cfg having the following: [install] install_lib = ~/Library/Python$py_version_short/site-packages install_scripts = ~/bin Jay P. From richie at entrian.com Thu Apr 13 10:34:22 2006 From: richie at entrian.com (Richie Hindle) Date: Thu, 13 Apr 2006 15:34:22 +0100 Subject: list.clear() missing?!? In-Reply-To: <1144937913.006463.241520@j33g2000cwa.googlegroups.com> References: <1144767680.583085.310160@v46g2000cwv.googlegroups.com> <1144937913.006463.241520@j33g2000cwa.googlegroups.com> Message-ID: [Mystilleef] > Lists should have a clear method. But what's shocking is that > it doesn't seem obvious to others. list.clear() is a whole lot more > readable, intuitive, "flowable" and desirable than [the alternatives] +1 to all of that. -- Richie Hindle richie at entrian.com From jhefferon at smcvt.edu Sun Apr 16 19:43:33 2006 From: jhefferon at smcvt.edu (Jim) Date: 16 Apr 2006 16:43:33 -0700 Subject: Validate XML against DTD and/or XML Schema? In-Reply-To: References: Message-ID: <1145231013.408790.322820@t31g2000cwb.googlegroups.com> For DTD's: have you stumbled across: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/220472 ? Jim From roy at panix.com Mon Apr 3 10:37:11 2006 From: roy at panix.com (Roy Smith) Date: 3 Apr 2006 10:37:11 -0400 Subject: Difference between 'is' and '==' References: <1143459098.385264.139560@g10g2000cwb.googlegroups.com> Message-ID: Adam DePrince wrote: > It just happens that the >logical operation > > (a is b ) -> (a == b ) > >is always True. Only for small values of "always". You can always do pathological things with operators: class Foo: def __eq__ (self, other): return False f = Foo() print f is f print f == f frame:play$ ./is.py True False This may even be useful. What if you were trying to emulate SQL's NULL? NULL compares false to anything, even itself. To test for NULLness, you have to use the special "is NULL" operator. From steve at REMOVETHIScyber.com.au Wed Apr 12 10:28:36 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Thu, 13 Apr 2006 00:28:36 +1000 Subject: converting lists to strings to lists References: <1144850003.574939.261390@v46g2000cwv.googlegroups.com> Message-ID: On Wed, 12 Apr 2006 06:53:23 -0700, robin wrote: > hi, > > i'm doing some udp stuff and receive strings of the form '0.870000 > 0.250000 0.790000;\n' > what i'd need though is a list of the form [0.870000 0.250000 0.790000] > i got to the [0:-3] part to obtain a string '0.870000 0.250000 > 0.790000' but i can't find a way to convert this into a list. i tried > eval() but this gives me the following error: > > Traceback (most recent call last): > File "", line 1, in ? > File "", line 1 > .870000 0.250000 0.79000 # untested! def str2list(s): """Expects a string of the form '0.87 0.25 0.79;\n' and returns a list like [0.87, 0.25, 0.79] WARNING: this function has only limited error checking. """ s = s.strip() # ignore leading and trailing whitespace if s.endswith(';'): s = s[:-1] L = s.split() assert len(L) == 3, "too many or too few items in list." return [float(f) for f in L] > and i have the same problem the other way round. e.g. i have a list > which i need to convert to a string in order to send it via udp. That's even easier. def list2str(L): """Expects a list like [0.87, 0.25, 0.79] and returns a string of the form '0.870000 0.250000 0.790000;\n'. """ return "%.6f %.6f %.6f;\n" % tuple(L) -- Steven. From erchamion.beren at gmail.com Wed Apr 5 11:15:51 2006 From: erchamion.beren at gmail.com (erchamion.beren at gmail.com) Date: Wed, 5 Apr 2006 11:15:51 -0400 Subject: save file as utf-8 format In-Reply-To: <200604051053.35591.orome.the.valar@gmail.com> References: <200604051053.35591.orome.the.valar@gmail.com> Message-ID: <200604051115.51837.orome.the.valar@gmail.com> On Wednesday 05 April 2006 10:53, erchamion.beren at gmail.com wrote: > hi, what should i do to save file as utf-8 encoding. thanks. from http://evanjones.ca/python-utf8.html The Byte-Order Marker (BOM) section did the trick. From trepca at gmail.com Wed Apr 5 07:05:54 2006 From: trepca at gmail.com (Sebastjan Trepca) Date: Wed, 5 Apr 2006 13:05:54 +0200 Subject: Distribution of Python apps Message-ID: Hi, I was wondering if there is anything similar to py2exe for OS X and Linux distributions so that I wouldn't have to pre-install Python and required modules for my application. Thanks. -- Sebastjan http://www.trepca.si/blog -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Mon Apr 10 08:22:36 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 10 Apr 2006 14:22:36 +0200 Subject: Is this object counter code pythonic References: <1144666496.940311.148120@j33g2000cwa.googlegroups.com> <1144668918.777564.310590@t31g2000cwb.googlegroups.com> <1144670451.089729.205450@v46g2000cwv.googlegroups.com> Message-ID: <49v11oFqlo6oU1@uni-berlin.de> jnair at ensim.com wrote: > Fredrik is then this a valid "property" use case and pythonic to > get/set a common varibale across objects No. you do that only if you have some kind of behavior attached - e.g. if there are database queries to be made for returning a property or something like that. Diez From johnjsal at NOSPAMgmail.com Wed Apr 12 13:50:44 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 12 Apr 2006 17:50:44 GMT Subject: just one more question about the python challenge In-Reply-To: References: <%2a%f.1965$No6.42797@news.tufts.edu> Message-ID: Georg Brandl wrote: > At the second, don't rename the file, rename the URL. Do you mean rename the URL *aside from* the file name? Here's the path I've taken so far, with a little spoiler space just in case: SPOILER SPACE * * * * * * * * * * * * * * * * * * * * * * evil.html (starting page) evil2.jpg [evil2.gfx] evil3.jpg evil4.jpg (no image) From conor.robinson at gmail.com Fri Apr 7 20:01:13 2006 From: conor.robinson at gmail.com (conor.robinson at gmail.com) Date: 7 Apr 2006 17:01:13 -0700 Subject: very strange problem in 2.4 Message-ID: <1144454473.488240.271200@t31g2000cwb.googlegroups.com> The Problem (very basic, but strange): I have a list holding a population of objects, each object has 5 vars and appropriate funtions to get or modify the vars. When objects in the list have identical vars (like all = 5 for var "a" and all = 10 for var "b" across all vars and objects) and i change self.mylist[i].change_var_a(5) to a new value, in this case var "a" in object i to 5, now all vars of type "a" in all objects in my list are changed to 5 instead of just var "a" in object mylist[i], which is my goal. if i print self.mylist[i].return_var_a() right after I change var "a" in object i, I get the correct change, however when i print out the whole list, the last change to var "a" in the last object modified takes over for all objects in the list. note: all the vars not being modified must be the same across all objects in the list, the var being modified need not be the same as the one before it in the list (but will be once just one of the identical object are changed). The value changed in the last object var modified takes over for all object vars making them exactly identical. ****If, for example, half the list has objects with random vars init. and the other half is identical, as above, and I perform the same operation, as above, to one of the identical var objects self.mylist[i].change_var_a(5) (to an object that has identicals in the list) all the identicals are changed in the same way as above, however the objects that have different var values are unchanged. What is python doing? Am I missing something? Any ideas at all would be wonderful? From orsenthil at gmail.com Mon Apr 17 09:00:18 2006 From: orsenthil at gmail.com (Phoe6) Date: 17 Apr 2006 06:00:18 -0700 Subject: How do I use Code Context under Options in IDLE? Message-ID: <1145278818.250198.145660@i40g2000cwc.googlegroups.com> Hi all, I have this Code Context feature under Options in the IDLE. How should I use it? Are there folks here who use it regularly and find it useful. Please guide me. Thanks! Senthil From jordan.taylor2 at gmail.com Thu Apr 27 10:06:31 2006 From: jordan.taylor2 at gmail.com (jordan.taylor2 at gmail.com) Date: 27 Apr 2006 07:06:31 -0700 Subject: Twisted and Tkinter In-Reply-To: <1146104350.843046.186230@v46g2000cwv.googlegroups.com> References: <1146104350.843046.186230@v46g2000cwv.googlegroups.com> Message-ID: <1146146791.931624.314570@y43g2000cwc.googlegroups.com> Posting that error message would be helpful From jzgoda at o2.usun.pl Thu Apr 20 16:38:08 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Thu, 20 Apr 2006 22:38:08 +0200 Subject: the whole 'batteries included' idea In-Reply-To: References: Message-ID: John Salerno napisa?(a): > So my question is, what is the difference between Python's 'batteries' > (standard modules), and C#'s framework? I know nothing of Java, but I > assume it has its own rich (and confusing) set of classes as well. Is > there something different about other languages' libraries/frameworks > that makes Python's different, and worthy of being touted as 'batteries > included'? I can speak only for Java -- its batteries are not included, you have to download jakarta-commons plus (since Python 2.5) JDOM to get the effect similar to Python's stdlib. Java library only seems to be complete (i.e. when looking on included classes), but its support for common programming tasks is just inadequate. -- Jarek Zgoda http://jpa.berlios.de/ From sjmachin at lexicon.net Thu Apr 6 18:56:09 2006 From: sjmachin at lexicon.net (John Machin) Date: 6 Apr 2006 15:56:09 -0700 Subject: Unicode, command-line and idle In-Reply-To: <44359427.6080805@v.loewis.de> References: <1144321375.901932.161330@v46g2000cwv.googlegroups.com> <1144333536.440072.13830@i40g2000cwc.googlegroups.com> <44359427.6080805@v.loewis.de> Message-ID: <1144364169.004219.164980@i39g2000cwa.googlegroups.com> The docs say that the encoding attribute is "New in version 2.3". Python 2.2's IDLE produces exactly the exception reported by the OP. Cheers, John From martin at v.loewis.de Mon Apr 24 03:03:43 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 24 Apr 2006 09:03:43 +0200 Subject: MS VC++ Toolkit 2003, where? In-Reply-To: <1he9m4m.9d8okx1x7mxeaN%aleaxit@yahoo.com> References: <1he8pss.1yk7ug81rv7pw2N%aleaxit@yahoo.com> <1145811839.042394.73260@t31g2000cwb.googlegroups.com> <1he8sbx.dqqp3q10n5thaN%aleaxit@yahoo.com> <1145849491.347970.112150@e56g2000cwe.googlegroups.com> <1he9m4m.9d8okx1x7mxeaN%aleaxit@yahoo.com> Message-ID: <444C784F.3000502@v.loewis.de> Alex Martelli wrote: > Can anybody suggest where to get a Framework SDK 1.1., or any other > legal way to get "the core msvcrt.lib for msvcr71.dll against which to > link your extensions. This is critically important"...??? From http://www.microsoft.com/downloads/details.aspx?familyid=9b3a2ca6-3647-4070-9f41-a333c6b9181d&displaylang=en > I'm sure my Windows-loving > colleagues in the PSF (who got several free copies of VS 2003 from > Microsoft, I believe -- at the time, I had zero Windows installations > and zero interest in Windows, so I didn't sign up for one) have fully > considered this recurring drama, and come to the decision of sticking > with VS 2003 (avoiding any free-as-in-beer compilers such as VS 2005 or > mingw) with thorough and wise deliberation. Not sure whether this mark was meant to be sarcastic: but why you don't want to use mingw to build extensions on Windows, I cannot understand. Regards, Martin From kylotan at gmail.com Thu Apr 20 12:16:34 2006 From: kylotan at gmail.com (Ben Sizer) Date: 20 Apr 2006 09:16:34 -0700 Subject: How protect proprietary Python code? (bytecode obfuscation?, what better?) In-Reply-To: <1he30cu.1akaa40fe3fwpN%aleaxit@yahoo.com> References: <1145293384.791678.14450@v46g2000cwv.googlegroups.com> <4444c777$0$9453$626a54ce@news.free.fr> <1145450399.254863.234380@i40g2000cwc.googlegroups.com> <44466dd9$0$20865$636a55ce@news.free.fr> <1145541967.959650.305600@z34g2000cwc.googlegroups.com> <1he30cu.1akaa40fe3fwpN%aleaxit@yahoo.com> Message-ID: <1145549793.941082.78030@e56g2000cwe.googlegroups.com> Alex Martelli wrote: > Ben Sizer wrote: > > > I don't know. In terms of copy protection, popular off-the-shelf > > software is going to get cracked whether it's written in Python or x86 > > ASM, that much is true. But in terms of perhaps protecting innovative > > algorithms from competitors, or something similar, compilation into > > native code does a great job of hiding your work. Not a perfect job, > > but a good enough job. > > If they're truly worth protecting, they're worth reverse engineering. It's a sliding scale though. You don't need to be able to stop everybody to make it worthwhile. > Remember, the competition includes excellent programmers working in > countries where $10 an hour's salary is luxury and IP law enforcements > non-existent, so the cost to reveng is not as high as you might think. Whether $10 is a lot or a little is not as important as whether that $10 could be better spent. It's easy to drill down far enough to break copy protection but nowhere near as easy to derive a high level algorithm from the assembly language. So in the latter case, a little protection goes a long way. > > I know some people talk a lot about using web services to keep the > > proprietary data behind a secure server, but there is a large number of > > Ah yes, that would be me;-). Except that I don't limit my advice to > proprietary DATA -- it also applies to CODE worth keeping secret. Code is data, data is code. :) I meant it to refer to all information stored that way. > > applications where this is not practical - eg. image/audio processing, > > computer games, artificial intelligence, or several other applications > > with heavy real-time or cpu-intensive requirements, or embedded systems > > that don't have web access. > > Fewer and fewer systems "intrinsically lack" net access. For example, > good (costly) computer games more and more need net access to be played > in the best way (multiplayer etc). Sure, but there's still many, many programs that don't fit that criteria. Nor are people generally happy about being compelled to use online services to 'activate' their games. > "CPU intensive" is a weird reason to want to avoid keeping in a well > protected environment any code that's really worth money -- if it IS > worth that much you're no doubt charging enough for it to afford > supplying the CPU power to your customers (whatever your business model, > say pay-per-use or subscription levels with different maxima, etc etc). Maybe I wasn't making myself clear - I just meant that you can't be doing round-trips to a web server for per-pixel calculations. -- Ben Sizer From bignose+hates-spam at benfinney.id.au Sat Apr 1 01:04:20 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 01 Apr 2006 16:04:20 +1000 Subject: Exception handling....dumb question? References: <1143849093.457940.294150@g10g2000cwb.googlegroups.com> Message-ID: <877j697rx7.fsf@rose.polar.local> "kbperry" writes: > In Python, > When using the default except (like following) > > try: > some code that might blow up > > except: > print "some error message" This will catch *every* exception, and throw it away before it gets to your "print" statement. This is almost never a good idea. You should catch *specific* exceptions that you know you can deal with at that point in the code. import logging try: foo = 12 / 0 except ZeroDivisionError, e: print "You *knew* this was going to happen: '%s'" % e logging.error(str(e)) This allows all other exceptions to propogate back through the call stack. More information on 'try': -- \ "When we call others dogmatic, what we really object to is | `\ their holding dogmas that are different from our own." -- | _o__) Charles Issawi | Ben Finney From cretin at des.alpes.ch Thu Apr 6 10:36:48 2006 From: cretin at des.alpes.ch (Azolex) Date: Thu, 06 Apr 2006 16:36:48 +0200 Subject: pre-PEP: The create statement In-Reply-To: <1144310059.925361.36780@t31g2000cwb.googlegroups.com> References: <59Wdnbd8EazRCqnZnZ2dnUVZ_vudnZ2d@comcast.com> <1144310059.925361.36780@t31g2000cwb.googlegroups.com> Message-ID: <4435278c_2@news.bluewin.ch> Michele Simionato wrote: > Steven Bethard wrote: >> The PEP is based on a suggestion [1]_ from Michele Simionato on the >> python-dev list. > > True, but I would also mention that the idea of the 'create' keyword > come from > Nick Coghlan: > > http://mail.python.org/pipermail/python-dev/2005-October/057531.html > > > Michele Simionato > I'd advocate for the shortest possible keyword, and - maybe because English is not my native language - I'd thus prefer "make" if any is really required. From david at boddie.org.uk Tue Apr 11 18:38:46 2006 From: david at boddie.org.uk (David Boddie) Date: 11 Apr 2006 15:38:46 -0700 Subject: Removing an item from a QListView in PyQt In-Reply-To: <1144772606.340377.290120@i40g2000cwc.googlegroups.com> References: <1144769597.763389.67500@j33g2000cwa.googlegroups.com> <1144772606.340377.290120@i40g2000cwc.googlegroups.com> Message-ID: <1144795125.986445.296270@t31g2000cwb.googlegroups.com> To summarize my previous misformatted post: removeChild() is a QScrollView method. You can call it because QListView inherits it from QScrollView, but you need to call your QListView instance's takeItem() method with the item you want to remove as the argument. Hope this helps, David From boyee118 at gmail.com Tue Apr 11 10:24:43 2006 From: boyee118 at gmail.com (boyeestudio) Date: Tue, 11 Apr 2006 22:24:43 +0800 Subject: the mysql for python cann't be install from the source! Help!! Message-ID: I install the mysqldb module for python,I use: python setup.py build but it tell me "cann't find include file my_conf.h' I search the mysql directory but gain none of it! Please help me with it! Thanks a lot! -------------- next part -------------- An HTML attachment was scrubbed... URL: From steven.bethard at gmail.com Thu Apr 6 00:21:31 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 05 Apr 2006 22:21:31 -0600 Subject: pre-PEP: The create statement Message-ID: <59Wdnbd8EazRCqnZnZ2dnUVZ_vudnZ2d@comcast.com> The PEP below should be mostly self explanatory. I'll try to keep the most updated versions available at: http://ucsu.colorado.edu/~bethard/py/pep_create_statement.txt http://ucsu.colorado.edu/~bethard/py/pep_create_statement.html PEP: XXX Title: The create statement Version: $Revision: 1.4 $ Last-Modified: $Date: 2003/09/22 04:51:50 $ Author: Steven Bethard Status: Draft Type: Standards Track Content-Type: text/x-rst Created: 05-Apr-2006 Python-Version: 2.6 Post-History: 05-Apr-2006 Abstract ======== This PEP proposes a generalization of the class-declaration syntax, the ``create`` statement. The proposed syntax and semantics parallel the syntax for class definition, and so:: create : is translated into the assignment:: = ("", , ) where ```` is the dict created by executing ````. The PEP is based on a suggestion [1]_ from Michele Simionato on the python-dev list. Motivation ========== Class statements provide two nice facilities to Python: (1) They are the standard Python means of creating a namespace. All statements within a class body are executed, and the resulting local name bindings are passed as a dict to the metaclass. (2) They encourage DRY (don't repeat yourself) by allowing the class being created to know the name it is being assigned. Thus in a simple class statement like:: class C(object): x = 1 def foo(self): return 'bar' the metaclass (``type``) gets called something like:: C = type('C', (object,), {'x':1, 'foo':}) The class statement is just syntactic sugar for the above assignment statement, but clearly a very useful sort of syntactic sugar. It avoids not only the repetition of ``C``, but also simplifies the creation of the dict by allowing it to be expressed as a series of statements. Historically, type instances (a.k.a. class objects) have been the only objects blessed with this sort of syntactic support. But other sorts of objects could benefit from such support. For example, property objects take three function arguments, but because the property type cannot be passed a namespace, these functions, though relevant only to the property, must be declared before it and then passed as arguments to the property call, e.g.:: class C(object): ... def get_x(self): ... def set_x(self): ... x = property(get_x, set_x, ...) There have been a few recipes [2]_ trying to work around this behavior, but with the new create statement (and an appropriate definition of property), the getter and setter functions can be defined in the property's namespace like:: class C(object): ... create property x: def get(self): ... def set(self): ... The definition of such a property callable could be as simple as:: def property(name, args, namespace): fget = namespace.get('get') fset = namespace.get('set') fdel = namespace.get('delete') doc = namespace.get('__doc__') return __builtin__.property(fget, fset, fdel, doc) Of course, properties are only one of the many possible uses of the create statement. The create statement is useful in essentially any situation where a name is associated with a namespace. So, for example, sub-modules could be created as simply as:: create module mod: "This creates a sub-module named mod with an f1 function" def f1(): ... and named, nested hierarchies like XML documents could be created like:: create ETobject html: "This statement would generate an ElementTree object" create ETobject head: "generate the head" ... create ETobject body: "generate the body" ... If Python acquires interfaces, given an appropriately defined ``interface`` callable, the create statement can support interface creation through the syntax:: create interface C(...): ... which would mean that interface systems like that of Zope would no longer have to abuse the class syntax to create proper interface instances. Specification ============= Python will translate a create statement:: create : into the assignment:: = ("", , ) where ```` is the dict created by executing ````. The ```` expression is optional; if not present, an empty tuple will be assumed. A patch is available implementing these semantics [3]_. Optional Extensions =================== Remove the create keyword ------------------------- It might be possible to remove the create keyword so that such statements would begin with the callable being called, e.g.: module mod: def f1(): ... def f2(): ... interface C(...): ... However, this would probably add some complexity in the grammar and so far I (Steven Bethard) have not been able to implement the feature without the keyword. Deprecating __metaclass__ in Python 3000 ---------------------------------------- As a side-effect of its generality, the create statement mostly eliminates the need for the ``__metaclass__`` attribute in class objects. Thus in Python 3000, instead of:: class : __metaclass__ = metaclasses could be supported by using the metaclass as the callable in a create statement:: create : Removing the ``__metaclass__`` hook would simplify the BUILD_CLASS opcode a bit. References ========== .. [1] Michele Simionato's original suggestion (http://mail.python.org/pipermail/python-dev/2005-October/057435.html) .. [2] Namespace-based property recipe (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/442418) .. [3] Create Statement patch (http://ucsu.colorado.edu/~bethard/py/create_stmt.patch) Copyright ========= This document has been placed in the public domain. .. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 End: From michele.simionato at gmail.com Thu Apr 6 12:17:59 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 6 Apr 2006 09:17:59 -0700 Subject: updated pre-PEP: The create statement In-Reply-To: References: Message-ID: <1144340279.327270.240750@i40g2000cwc.googlegroups.com> Steven Bethard wrote: > I've updated the PEP based on a number of comments on comp.lang.python. > The most updated versions are still at: > > http://ucsu.colorado.edu/~bethard/py/pep_create_statement.txt > http://ucsu.colorado.edu/~bethard/py/pep_create_statement.html > > In this post, I'm especially soliciting review of Carl Banks's point > (now discussed under Open Issues) which asks if it would be better to > have the create statement translated into: > > = ("", *, **) > > instead of the current: > > = ("", , ) > > The former allows the create statement to be applied to a wider variety > of callables; the latter keeps a better parallel with the class statement. Maybe I am thick this evening, but how that would work? It would break for classes if we do not follow the signature of 'type'. -1 unless you explain me what I am missing. Michele Simionato From esj at harvee.org Wed Apr 12 12:37:13 2006 From: esj at harvee.org (Eric S. Johansson) Date: Wed, 12 Apr 2006 12:37:13 -0400 Subject: drag and drop to icon Message-ID: I have a small problem that may be best solved by dragging and dropping a mail message to an icon. But I'm honestly not sure what the data will look like from different e-mail clients. Since most of my programming experience is something a user rarely sees, I'm not even sure where to start creating a test case. I would appreciate pointers to documentation (and yes I did Google before asking) how to create an icon on a desktop (Macintosh and Windows) and have that icon act on something which has been dropped on it. many thanks for any assistance ---eric From flexx at jerasoft.net Mon Apr 10 03:55:37 2006 From: flexx at jerasoft.net (Flexx) Date: Mon, 10 Apr 2006 10:55:37 +0300 Subject: Python 2.5 licensing: stop this change In-Reply-To: References: <442E2FC1.6090600@hathawaymix.org> Message-ID: <1144655689.124533@isa.mirotel.net> Steve Holden >> It was an April Fool's joke. It's not actually true. >> > To try and ensure this thread dies for ever, I have added a note to the > blog entry at > > http://pyfound.blogspot.com/2006/04/python-25-licensing-change.html > > noting the fact that this was indeed an April Fool's joke. "Python Software Foundation News: Python 2.5 Licensing Change Saturday, April 01, 2006 Python 2.5 Licensing Change" Look at the date =) From no-spam at no-spam-no-spam.com Wed Apr 26 08:38:47 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Wed, 26 Apr 2006 14:38:47 +0200 Subject: Introspection Class/Instance Name In-Reply-To: References: Message-ID: *binarystar* wrote: > Hello there, > > what method would you use to return the name of the class and/or > instance introspectively eg. > > class Bollocks: > > def __init__( self ): > > print self.__method_that_returns_class_name__() > print self.__method_that_returns_instance_name__() > > > instance_of_bollocks = Bollocks() > > # Which outputs > > 'Bollocks' > 'instance_of_bollocks' > self.__class__ is good for getting instance's top class yet Python is weak on introspecting the namespace of its definitions - funcs and classes. it stops at sys._getframe().f_code.co_name thus, e.g. for things like super() you need always to re-type the class name where you just write in!? maybe Py3K brings more ? Maybe There could be compiler-variables like __CLASS__ , __FUNC__ for things like super(), recursion etc. (compare http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/491265 ) -robert From cygnus at cprogrammer.org Mon Apr 17 17:33:20 2006 From: cygnus at cprogrammer.org (Jonathan Daugherty) Date: Mon, 17 Apr 2006 14:33:20 -0700 Subject: Missing interfaces in Python... In-Reply-To: <1145309327.456488.18280@i39g2000cwa.googlegroups.com> References: <20060417210541.GV7561@vulcan.cprogrammer.org> <1145309327.456488.18280@i39g2000cwa.googlegroups.com> Message-ID: <20060417213320.GY7561@vulcan.cprogrammer.org> # Thanks for the responses...Looks like I might have opened Pandora's # box here. Could I accomplish the above with an abstract class? Zope 3 has an interface system which is good. I recommend you look at that. -- Jonathan Daugherty http://www.parsed.org From michael1cat at yahoo.com Wed Apr 12 11:58:15 2006 From: michael1cat at yahoo.com (Michael Paoli) Date: 12 Apr 2006 08:58:15 -0700 Subject: symbolic links, aliases, cls clear References: <1143672131.167324.36920@i39g2000cwa.googlegroups.com> <1144844223.094969.82870@t31g2000cwb.googlegroups.com> <87r7430x2t.fld@apaflo.com> Message-ID: <1144857495.630085.116020@i40g2000cwc.googlegroups.com> Floyd L. Davidson wrote: > af.dingo at gmail.com wrote: > >If I may recommend an alternative, > >print "\033[H\033[J" > Unfortunately, it is poor practice to hard code such sequences. > Instead the proper sequence should be obtained from the > appropriate database (TERMINFO or TERMCAP), and the easy way to > do that is, > tput clear Or clear(1), as also mentioned earlier. Yes, definitely don't want to hardcode the sequence. Definitely do use the appropriate terminal capabilities database (terminfo or termcap) in the appropriate manner (e.g. clear(1) or tput clear will handle that in the simple case of shell accessible means to clear the screen). Most UNIX(/LINUX/BSD/...) implementations support a large number of terminal types. E.g. on my system, I check and find that there are 1470 unique terminal types (descriptions) supported - and that's not including multiple aliases for the same terminal type/description (but it does count distinct names/files which have differing configurations, even if they are for the same terminal - such as changing certain options or behavior of a terminal, or using the terminal in distinct modes). Among those terminal types on my system, I find 154 distinct means of clearing the screen. Just for illustrative purposes, here are the top 10 I find, with count of how many distinct types (descriptions) use that particular sequence: 236 clear=\E[H\E[J, 120 clear=^L, 120 clear=\E[H\E[2J, 64 clear=\EH\EJ, 61 clear=\E[2J, 42 clear=\E[H\E[J$<156>, 38 clear=^Z, 36 clear=\E[H\E[J$<50>, 31 clear=\E[H\E[J$<40>, 29 clear=\E[2J\E[H, And of course, sending the wrong sequence (e.g. like trying some to see what works) can be highly problematic - it can do very nasty things to some terminals. E.g. I own one terminal, which among sequences it supports, is one which effectively says interpret the following hexadecimal character pairs as bytes, load them into RAM, and execute them - a relatively sure-fire way to crash the terminal if it is sent garbage (I used to run into that and other problems with some BBS systems that would presume everyone must be running something ANSI capable or that it was safe to do other tests such as see if certain sequences would render a blue square on one's screen). references: "system" call/function, in various programming languages clear(1) tput(1) terminfo(5) termcap(5) news:1143672131.167324.36920 at i39g2000cwa.googlegroups.com news:1143707753.031675.111630 at v46g2000cwv.googlegroups.com From skip at pobox.com Sat Apr 22 15:31:46 2006 From: skip at pobox.com (skip at pobox.com) Date: Sat, 22 Apr 2006 14:31:46 -0500 Subject: repr() for Perl? In-Reply-To: References: Message-ID: <17482.33954.622656.386885@montanaro.dyndns.org> >> Does Perl have something like Python's repr() function? Mirco> Have a look at this: ... Thanks, I'm getting set up to try it just for the exercise. I went with John Lee's Data::Dumper suggestion simply because I already had it installed and have neither String::Escape nor Inline::Python installed. Skip From flamesrock at gmail.com Tue Apr 4 19:42:10 2006 From: flamesrock at gmail.com (flamesrock) Date: 4 Apr 2006 16:42:10 -0700 Subject: Python Decompilers? Message-ID: <1144194130.731253.170930@t31g2000cwb.googlegroups.com> Hi, Are there any good decompilers for python? -Thanks From a.schmolck at gmail.com Wed Apr 5 08:55:58 2006 From: a.schmolck at gmail.com (Alexander Schmolck) Date: 05 Apr 2006 13:55:58 +0100 Subject: Dice probability problem References: Message-ID: Tomi Lindberg writes: > # Adds another die to results. > def add_dice(sums, die): > # If first die, all values appear once I'd add something like sums = sums or {} because otherwise your function will sometimes mutate sums and sometimes return a fresh object, which usually is a very bad thing as it can easily lead to quite nasty bugs. > if not sums: > for face in die: > sums[face] = 1 > # Calculating the number of appearances for additional > # dice > else: > new_sums = {} > for k in sums.keys(): > for f in die: > if new_sums.has_key(k+f): > new_sums[k+f] += sums[k] > else: > new_sums[k+f] = sums[k] > sums = new_sums > return sums 'as From steve at REMOVETHIScyber.com.au Sun Apr 9 03:02:28 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 09 Apr 2006 17:02:28 +1000 Subject: how to print without blank? References: <1144562057.796460.277900@e56g2000cwe.googlegroups.com> Message-ID: On Sat, 08 Apr 2006 22:54:17 -0700, Ju Hui wrote: > I want to print 3 numbers without blank. [snip] > how to print > 012 > ? Method one: accumulate your numbers into a single string, then print it in one go. >>> L = [] >>> for x in range(3): ... L.append(str(x)) ... >>> print ''.join(L) 012 >>> Or even: >>> print ''.join(map(str, range(3))) 012 >>> Or use a list comprehension: >>> print ''.join([str(x) for x in range(3)]) 012 >>> Method two: don't use the print statement, but write directly to standard output. >>> import sys >>> for x in range(3): ... sys.stdout.write(str(x)) ... 012>>> But notice how this does not write a newline when you are done -- you will have to remember to do it yourself with sys.stdout.write('\n'). Also, print will work with any object, but sys.stdout.write will only work with strings: >>> print 6 6 >>> sys.stdout.write(6) Traceback (most recent call last): File "", line 1, in ? TypeError: argument 1 must be string or read-only character buffer, not int >>> -- Steven. From hitesh287 at gmail.com Mon Apr 24 18:45:08 2006 From: hitesh287 at gmail.com (Hitesh Joshi) Date: 24 Apr 2006 15:45:08 -0700 Subject: What am I doing wrong here In-Reply-To: References: <1145916134.764210.235250@t31g2000cwb.googlegroups.com> Message-ID: <1145918708.831606.243250@u72g2000cwu.googlegroups.com> Thank you all for the quick replies. It worked! Truely appriciated. I am python novice and still learning.... I hope to contribute to this group someday :) Hitesh From grflanagan at yahoo.co.uk Thu Apr 27 06:27:10 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 27 Apr 2006 03:27:10 -0700 Subject: can anyone advise me References: <1146131326.328919.285430@t31g2000cwb.googlegroups.com> Message-ID: <1146133630.147211.77540@g10g2000cwb.googlegroups.com> micklee74 at hotmail.com wrote: > why the output of this code : > x = 0 > while x < 10: > z = 0 > print x > x = x + 1 > while z < x: > print z, > z = z + 1 > > is > > 0 > 0 1 > 0 1 2 > 0 1 2 3 > 0 1 2 3 4 > 0 1 2 3 4 5 > 0 1 2 3 4 5 6 > 0 1 2 3 4 5 6 7 > 0 1 2 3 4 5 6 7 8 > 0 1 2 3 4 5 6 7 8 9 > 0 1 2 3 4 5 6 7 8 9 < ---extra > > > instead of : > 0 > 0 1 > 0 1 2 > 0 1 2 3 > 0 1 2 3 4 > 0 1 2 3 4 5 > 0 1 2 3 4 5 6 > 0 1 2 3 4 5 6 7 > 0 1 2 3 4 5 6 7 8 > 0 1 2 3 4 5 6 7 8 9 > Does the following help? x = 0 while x < 10: print 'x' x = x + 1 z = 0 while z < x: print z, z = z + 1 x 0 x 0 1 x 0 1 2 x 0 1 2 3 x 0 1 2 3 4 x 0 1 2 3 4 5 x 0 1 2 3 4 5 6 x 0 1 2 3 4 5 6 7 x 0 1 2 3 4 5 6 7 8 x 0 1 2 3 4 5 6 7 8 9 x = 0 while x < 10: print x = x + 1 z = 0 while z < x: print z, z = z + 1 0 0 1 0 1 2 0 1 2 3 0 1 2 3 4 0 1 2 3 4 5 0 1 2 3 4 5 6 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 8 0 1 2 3 4 5 6 7 8 9 Gerard From johnny at johnnydebris.net Fri Apr 21 03:30:21 2006 From: johnny at johnnydebris.net (Johnny deBris) Date: Fri, 21 Apr 2006 09:30:21 +0200 Subject: py.test munging strings in asserts? In-Reply-To: References: Message-ID: <124h2ghloco0v6c@corp.supernews.com> Timothy Grant wrote: > > granted the left side of that equality could be messed up due to > create_output() NOT doing the right thing. But the right side is > simply the contents of the variable "text" so WHY is the first part of > the path being substituted with "..."? > Some grepping on '...' revealed that there's some string munging going on in py/code/safe_repr.py, In py/test/terminal/terminal.py, in TerminalSession, there's a method 'repr_locals' that uses it, I guess you have to override that or something if you want to change this behaviour... Cheers, Guido Wesdorp From edeveaud at pasteur.fr Thu Apr 13 04:20:14 2006 From: edeveaud at pasteur.fr (Eric Deveaud) Date: Thu, 13 Apr 2006 08:20:14 +0000 (UTC) Subject: Initializing defaults to module variables References: <87psjm3ef4.fsf@gmail.com> Message-ID: Burton Samograd wrote: > Hi, > > I'm writing an app that stores some user configuration variables in a > file ~/.program/config, which it then imports like so: > > import sys > from posix import environ > sys.path.append(environ["HOME"]+"/.program") > import config > > I can then access the configuration through code like: > > login(config.username) better use some plain text configuration file check ConfigParser documentation. > So I guess the real question is: > > Is there a way to create a module namespace and populate it > before sourcing the file? if you take a look at how naming space is affected by the variants "from module import *" and his conterpart "import module", you will have your answer. shortly if you use "import foo" all the variables/class/functions comming from the module foo are located in a globlal space dictionary named foo if you use "form foo import *" all variables/class/functions comming from the foo module are located in gloabal space naming dictionary. try this -=-=-=-=-=-=- consider module foo.py -=-=-=-=-=-=- my_var = "my var from foo" -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- hebus:~/tmp > python Python 2.4.2 (#1, Mar 22 2006, 12:59:23) [GCC 3.3.5 (Debian 1:3.3.5-5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import foo >>> print my_var Traceback (most recent call last): File "", line 1, in ? NameError: name 'my_var' is not defined and now hebus:~/tmp > python Python 2.4.2 (#1, Mar 22 2006, 12:59:23) [GCC 3.3.5 (Debian 1:3.3.5-5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from foo import * >>> print my_var my var from foo this will lead to a solution regarding your problem hebus:~/tmp > python Python 2.4.2 (#1, Mar 22 2006, 12:59:23) [GCC 3.3.5 (Debian 1:3.3.5-5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> my_var = 'some default value' >>> from foo import * >>> print my_var my var from foo once again, I bet your best choice will be to have some plain text config file Eric -- Je voudrais savoir s'il existe un compteur de vitesse (?) pour savoir ? quelle vitesse on est r?ellement connect? au FAI et surtout si une telle b?te existe... o? la trouver. -+- RJ in: Guide du Neuneu d'Usenet - Baisse la t?te et p?dale -+- From luismgz at gmail.com Wed Apr 12 14:37:05 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 12 Apr 2006 11:37:05 -0700 Subject: New Karrigel page in Wikipedia Message-ID: <1144867025.095969.92870@e56g2000cwe.googlegroups.com> For those interested in the simplest, easiest and most pythonic web framework out there, there's a new page in Wikipedia: http://en.wikipedia.org/wiki/Karrigell From cretin at des.alpes.ch Wed Apr 5 20:33:16 2006 From: cretin at des.alpes.ch (Azolex) Date: Thu, 06 Apr 2006 02:33:16 +0200 Subject: efficiency of range() and xrange() in for loops In-Reply-To: References: Message-ID: <443461d7$1_2@news.bluewin.ch> Steve R. Hastings wrote: > On Thu, 06 Apr 2006 09:08:45 +1000, Steven D'Aprano wrote: >> Yes, the above example is a good use case for xrange. Did you think that >> anyone denied that there were good cases for it? > > I am now officially sorry for starting this thread. Don't. It's quite funny, thanks. From fulvio at pc.jaring.my Thu Apr 6 06:13:58 2006 From: fulvio at pc.jaring.my (Fulvio) Date: Thu, 6 Apr 2006 18:13:58 +0800 Subject: how to convert string In-Reply-To: <1144284671.748880.187060@j33g2000cwa.googlegroups.com> References: <1144261976.640631.9280@e56g2000cwe.googlegroups.com> <1144284671.748880.187060@j33g2000cwa.googlegroups.com> Message-ID: <200604061813.58405.fulvio@pc.jaring.my> Alle 08:51, gioved? 06 aprile 2006, swami426 at yahoo.com ha scritto: > for x in range(10): > ????????sys.stdout.write(x) > ????????sys.stdout.write(" ") BTW, how to write a number repeatly in the same line and position, without let the printout to scroll down. F From tim.peters at gmail.com Mon Apr 10 23:31:27 2006 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 10 Apr 2006 23:31:27 -0400 Subject: TypeError + generator + str.join(): Bug or user error? In-Reply-To: <1144724066.286814.264480@i40g2000cwc.googlegroups.com> References: <1144724066.286814.264480@i40g2000cwc.googlegroups.com> Message-ID: <1f7befae0604102031k19fd9708w4f486b146b5116cd@mail.gmail.com> [Paul Du Bois] > Using win32 python 2.4.1, I have a minimal test program: > > def generate(): > raise TypeError('blah') > yield "" > > print "\n".join((generate())) > > Executing the program gives: > > Traceback (most recent call last): > File "", line 5, in ? > TypeError: sequence expected, generator found > > replacing TypeError with Exception gives what I would have expected: a > traceback starting from the raise statement. I'm not relying on one > behavior or the other, but I had a TypeError in a generator, and the > funny exception slowed me down finding it. I don't really think of it as "a bug" or a "user error". Instead it's a consquence of intractable complexity <0.5 wink>. What can you pass to join()? "An iterable object" is the answer. So what's "an iterable object"? Well, many things, but you can't always tell for sure without _trying_ to iterate over it. If the internal _attempt_ to iterate raises TypeError, the 2.4 join() interprets that as meaning "ah, so this object doesn't support iteration after all -- let's raise a TypeError of our own, explaining why we failed". That's usually a good thing to do, but sometimes (as in your case) it turns out it wasn't. The internals got fiddled in 2.5 so that your test case produces: Traceback (most recent call last): File "pd.py", line 5, in print "\n".join((generate())) File "pd.py", line 2, in generate raise TypeError('blah') TypeError: blah instead. Since only God knows whether that makes some other test case worse (probably not, but ...), and it's a change in visible behavior regardless, that won't be backported to the 2.4 line. From franz.steinhaeusler at gmx.at Tue Apr 11 07:09:52 2006 From: franz.steinhaeusler at gmx.at (Franz Steinhaeusler) Date: Tue, 11 Apr 2006 13:09:52 +0200 Subject: wxStyledTextCtrl - Dead? References: <4438efbb$0$60784$157c6196@dreader1.cybercity.dk> <1144702358.186240.161950@e56g2000cwe.googlegroups.com> <443b5144$0$67257$157c6196@dreader2.cybercity.dk> Message-ID: <4h3n329vu1lhgkn0vrvhig8qtft3bm4aof@4ax.com> On Tue, 11 Apr 2006 06:58:28 -0400, Peter Hansen wrote: >David Rasmussen wrote: >> I am trying to make a programmer's editor (and later a full IDE), and I >> want things like syntax highlighting etc. I could of course roll my own >> fancy editing control, but if STC could solve my problem and is flexible >> enough, then I'll use that for now :) > >There are at least two (that I know of) editors written in Python and >based on the STC. Going from memory, PyPE is one, and the other is ... > um... well, it's too early in the morning to recall but I'm sure it >wouldn't be hard to find. No, it's not hard. :) for example: Boa Constructor, DrPython, spe and newedit. From sybrenUSE at YOURthirdtower.com.imagination Tue Apr 4 10:31:48 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Tue, 4 Apr 2006 16:31:48 +0200 Subject: CD Burning References: Message-ID: Albert Leibbrandt enlightened us with: > Can anybody tell me which windows API or python module they are > using for writing cd's / dvd's with python? I'd install cygwin and use cdrecord. That seems the easiest way to go about burning disks to me. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From michele.simionato at gmail.com Tue Apr 11 05:54:12 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 11 Apr 2006 02:54:12 -0700 Subject: updated pre-PEP: The create statement In-Reply-To: References: <443a9c60$1_1@news.bluewin.ch> Message-ID: <1144741586.861381.190350@z34g2000cwc.googlegroups.com> Steven Bethard wrote: > Azolex wrote: > > Steven Bethard wrote: > >> and named, nested hierarchies like XML documents could be created > >> like:: > >> > >> create ETobject html: > >> "This statement would generate an ElementTree object" > >> > >> create ETobject head: > >> "generate the head" > >> ... > >> > >> create ETobject body: > >> "generate the body" > >> ... > > > > I think this is is a most important eventual use-case, and would like to > > see it better worked out - or else declared outside the scope of the > > proposed statement. As far as I can see, this does not cut it, since xml > > and html allow /sequencial repetition/ of tags and the results of the > > statement suites are passed as unordered namespaces/dicts. > > Good point. The code above would only work if you didn't care about the > order of elements. I'm half inclined to pull the example, but the > original was due to Michele Simionato, and I haven't quite convinced > myself yet that you couldn't hack it to have ETObject append to an > internal list somehow to keep order. Michele? Did you have a plan for > how this would work? > > STeVe Honestly, I don't want the 'create' statement to be used to write XML in Python. I think this would be a misuse of the functionality. OTOH I believe that the main selling point for the 'create' statements is that it make it easy to implement declarative minilanguages, so I have given an XML example. To solve the ordering issue one should change the internals of Python, in such a way to pass an ordered dict to the 'create' statement instead of an usual dictionary. I think the main use case for 'create' would be in things like object-relational-mappers, not in XML generation. You can pull out the example in the official PEP, if you like. It was just matter for thought. Michele Simionato From russandheather at gmail.com Wed Apr 26 14:07:23 2006 From: russandheather at gmail.com (Russell Warren) Date: 26 Apr 2006 11:07:23 -0700 Subject: Speed of shutil.copy vs os.system("copy src dest") in win32 Message-ID: <1146074843.891044.279310@g10g2000cwb.googlegroups.com> I just did a comparison of the copying speed of shutil.copy against the speed of a direct windows copy using os.system. I copied a file that was 1083 KB. I'm very interested to see that the shutil.copy copyfileobj implementation of hacking through the file and writing a new one is significantly faster... any clue as to why this is? I figure I'm missing something here. Does os.system launch a cmd shell every time? >>> import timeit >>> timeit.Timer(stmt= r'shutil.copy(r"c:\windows\ntbtlog.txt", r"c:\temp")',setup="import shutil").repeat(repeat=5,number=100) [0.99285104671434965, 0.68337121058721095, 0.84528340892575216, 0.87780765432398766, 0.8709894693311071] >>> timeit.Timer(stmt= r'os.system(r"copy c:\windows\ntbtlog.txt c:\temp")',setup="import os").repeat(repeat=5,number=100) [2.8546278926514788, 2.3763950446300441, 2.4444609580241377, 2.4392499605455669, 2.4446956247265916] From nelson1977 at gmail.com Sat Apr 1 07:36:35 2006 From: nelson1977 at gmail.com (nelson) Date: Sat, 01 Apr 2006 14:36:35 +0200 Subject: COM Server & wxPython Message-ID: <442e73d1$0$36926$4fafbaef@reader3.news.tin.it> Hi all, i'm doing a COM server that have to expose some graphics (panels and configuration controls), that would be embedded in an application through OLE. I was wondering if I can do this using wxPython. Another question is if my COM server would inherits from one of the wxPython class. If it's true, from which? wx.App, wx.Frame, wx.Panel. The important thing is that i would to have the same effect that you have when you the calendar OLE control on a Delphi or VB form (you see the graphics ;) ) thanks, nelson From chris.lasher at gmail.com Wed Apr 12 08:59:17 2006 From: chris.lasher at gmail.com (Chris Lasher) Date: 12 Apr 2006 05:59:17 -0700 Subject: Regular expression intricacies: why do REs skip some matches? In-Reply-To: <1144798732.127411.244680@t31g2000cwb.googlegroups.com> References: <1144795311.560566.4190@j33g2000cwa.googlegroups.com> <1144798732.127411.244680@t31g2000cwb.googlegroups.com> Message-ID: <1144846756.984153.12460@v46g2000cwv.googlegroups.com> Diez, John, Tim, and Ben, thank you all so much. I now "get it". It makes logical sense now that the difficulty was actually in the implementation of findall, which does non-overlapping matches. It also makes sense, now, that one can get around this by using a lookahead assertion. Thanks a bunch, guys; this really helped! Chris From let0-pasdespam at free.fr Sun Apr 9 15:28:00 2006 From: let0-pasdespam at free.fr (Olivier P) Date: Sun, 09 Apr 2006 21:28:00 +0200 Subject: 32-bit python on Opteron, Solaris 10? References: Message-ID: <44396040$0$20300$626a54ce@news.free.fr> Gary Robinson wrote: > I'm in the market for a server to run some python code which is > optimized via psyco. > > Sun T2100 servers come with Solaris 10, which comes with python > pre-installed. You can always install a 32bits version of Linux or Solaris on the X2100 yourself. The X2100 is even certified to run on it . cf http://www.sun.com/servers/entry/x2100/os.jsp From Serge.Orlov at gmail.com Wed Apr 26 18:52:34 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 26 Apr 2006 15:52:34 -0700 Subject: not quite 1252 In-Reply-To: <444f5e6b$1@usenet.zapto.org> References: <444f5e6b$1@usenet.zapto.org> Message-ID: <1146091954.352996.16600@i40g2000cwc.googlegroups.com> Anton Vredegoor wrote: > I'm trying to import text from an open office document (save as .sxw and > read the data from content.xml inside the sxw-archive using > elementtree and such tools). > > The encoding that gives me the least problems seems to be cp1252, > however it's not completely perfect because there are still characters > in it like \93 or \94. Has anyone handled this before? I'd rather not > reinvent the wheel and start translating strings 'by hand'. I extracted content.xml from a test file and the header is: So any xml library should handle it just fine, without you trying to guess the encoding. From leonardodiserpierodavinci at gmail.com Thu Apr 27 05:35:50 2006 From: leonardodiserpierodavinci at gmail.com (Leonardo da Vinci) Date: 27 Apr 2006 02:35:50 -0700 Subject: How to align the text of a Listbox to the right Message-ID: <1146130550.583881.149820@g10g2000cwb.googlegroups.com> Greetings gentlemen and ladies, I have a question: in Tkinter, how to align a Listbox entry (i.e. a line of text) to the right? Google did not show up the answer to my request. Thanks very much. L From mmanns at gmx.net Wed Apr 12 22:41:49 2006 From: mmanns at gmx.net (Martin Manns) Date: Thu, 13 Apr 2006 02:41:49 GMT Subject: Numpy and cPickle Message-ID: Hi If I cPickle a numpy array under Linux and un-cPickle it under Solaris 10, my arrays seem to be transposed. Is there any way to get the same behavior on both platforms without testing which platform the python script runs on and then transposing the array? I am using python 2.4.2 and numpy 0.9.6 on both machines. Thanks in advance Martin From reply.in.the.newsgroup at my.address.is.invalid Fri Apr 7 10:13:52 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Fri, 07 Apr 2006 16:13:52 +0200 Subject: Characters contain themselves? References: Message-ID: <2ksc32h3ub58gh11umf9nrc2ur4aqpnijg@4ax.com> WENDUM Denis 47.76.11 (agent): >While testing recursive algoritms dealing with generic lists I stumbled >on infinite loops which were triggered by the fact that (at least for my >version of Pyton) characters contain themselves. No, strings contain characters. And 'a' is a string consisting of one character. "The items of a string are characters. There is no separate character type; a character is represented by a string of one item." http://docs.python.org/ref/types.html (One item of what type, one might ask) -- Ren? Pijlman From robert.kern at gmail.com Sun Apr 30 18:03:34 2006 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 30 Apr 2006 17:03:34 -0500 Subject: How to efficiently read binary files? In-Reply-To: <125acgep357kbd8@corp.supernews.com> References: <125acgep357kbd8@corp.supernews.com> Message-ID: Grant Edwards wrote: > On 2006-04-30, David Lees wrote: > >>I want to process large binary files (>2GB) in Python. I have played >>around with prototypes in pure Python and profiled the code. Most of >>the time seems to be spent converting back and forth to and from strings >>using the struct module. Is there a way to directly read into an array >>of integers in Python? > > Perhaps the numarray module? numpy for new code, please. In particular, numarray is limited by 32-bit APIs even on 64-bit platforms, so a >2GB file will be difficult to process even when using mmap. numpy removed this restriction on 64-bit platforms. 32-bit users will still have to split up the file into <2GB chunks, though. http://numeric.scipy.org/ https://lists.sourceforge.net/lists/listinfo/numpy-discussion -- Robert Kern robert.kern at gmail.com "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From vivainio at gmail.com Tue Apr 11 11:01:20 2006 From: vivainio at gmail.com (Ville Vainio) Date: 11 Apr 2006 08:01:20 -0700 Subject: list.clear() missing?!? Message-ID: <1144767680.583085.310160@v46g2000cwv.googlegroups.com> I tried to clear a list today (which I do rather rarely, considering that just doing l = [] works most of the time) and was shocked, SHOCKED to notice that there is no clear() method. Dicts have it, sets have it, why do lists have to be second class citizens? From gaochongnan at gmail.com Wed Apr 12 03:51:35 2006 From: gaochongnan at gmail.com (gcn) Date: 12 Apr 2006 00:51:35 -0700 Subject: A bug of httplib? Message-ID: <1144828295.035770.150380@i40g2000cwc.googlegroups.com> Hello, The HTTPSConnection class in httplib overload the connect method of HTTPConnection, but it can only deals with IPv4: def connect(self): "Connect to a host on a given (SSL) port." sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((self.host, self.port)) ssl = socket.ssl(self.sock, self.key_file, self.cert_file) self.sock = FakeSocket(self.sock, ssl) Is it a bug or I should use other method? Thanks. From fredrik at pythonware.com Sat Apr 15 05:11:41 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 15 Apr 2006 11:11:41 +0200 Subject: nested functions References: <1145014674.717433.75100@t31g2000cwb.googlegroups.com> Message-ID: Lawrence D'Oliveiro wrote: > >BUT 'b' and 'c' simply do not exist outside the 'a' world. > > It's worth distinguishing between the _names_ 'b' and 'c' and the > _functions_ referred to by those names. The _names_ certainly do not > exist outside of the scope of the function referred to by 'a' (any > occurrences of 'b' and 'c' outside that scope refer to _different_ > names), but the _functions_ they refer to certainly do exist. that's a bit misleading. "def" is an executable statement, and it *creates* a function object when it's executed. that object is handled in exactly the same way as any other object. in the following example, the function referred to by "c" doesn't exist before a call to "a", and it doesn't exist after the function has returned: def a(): def c(): print "c" c() if you call the function again, a new function object is created. From nnorwitz at gmail.com Fri Apr 28 13:37:11 2006 From: nnorwitz at gmail.com (Neal Norwitz) Date: Fri, 28 Apr 2006 10:37:11 -0700 Subject: Summer of Code mailing list Message-ID: There's a new SoC mailing list. soc2006 at python.org You can sign up here: http://mail.python.org/mailman/listinfo/soc2006 This list is for any SoC discussion: mentors, students, idea, etc. Student can submit applications starting May 1, so now is the time to get students interested in your ideas! Please pass this information along. Cheers, n From peter at engcorp.com Wed Apr 12 15:30:41 2006 From: peter at engcorp.com (Peter Hansen) Date: Wed, 12 Apr 2006 15:30:41 -0400 Subject: Regular Expressions In-Reply-To: <9583ed900604121205o5da84b0crd2ae671c0b6a4395@mail.gmail.com> References: <9583ed900604121205o5da84b0crd2ae671c0b6a4395@mail.gmail.com> Message-ID: david brochu jr wrote: > I am trying to grab the following string out of a text file using > regular expression (re module): Why do you have to use a regular expression? > "DcaVer"=dword:00000640 Is all your other input pretty much identical in form? Specifically, the number of interest is the last thing on the line, and always preceded by a colon? > What I need to do with that string is trim down " "DcaVer"=dword:" and > convert the remaining number from hex to dec. What does "trim down" mean? Do you need something out of the string, or are you just discarding/ignoring it? > I have been trying to figure this out for a while..I am fairly new so > please any help would be greatly appreciated. s = '"DcaVer"=dword:00000640' value = int(s.split(':')[-1], 16) (In other words, split on colons, take the last field and, treating it as a hex value, convert to an integer.) -Peter From pmartin at snakecard.com Fri Apr 14 17:17:20 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Fri, 14 Apr 2006 16:17:20 -0500 Subject: Passing a packed C structure to a c module References: <3OP%f.811$9c6.333@dukeread11> <443fcb63$0$3177$9b622d9e@news.freenet.de> <443fd8f2$0$470$9b622d9e@news.freenet.de> <443ff364$0$6341$9b622d9e@news.freenet.de> Message-ID: I misslead you: it is a smart card-style ioctl ... Philippe "Martin v. L?wis" wrote: > Philippe Martin wrote: >> The call actually is an IOCtl: depending on the control code, the >> structure has a different format. > > Ah. In that case, I recommend to use the ioctl module; you won't need a > C wrapper, then. > >> Although the number of control codes/structures is finite, it would make >> the wrapper function fairly large. > > *Some* code to handle this will be very large, regardless of how you > write it. > >> You seem to think that building the structure from python would be a >> mistake: why is that ? > > It's very error-prone. You have to match the C structure layout of the > compiler precisely, and you even have to get the alignment right, > something that can't be done reliably in Python. > >> PS: the wrapper also has to work under multiple OSs > > That makes it worse: now you not only have to match the C compiler's > expectation on a single processor, but on different ones. > > Perhaps you should be using ctypes. > > Regards, > Martin From see_signature_for_reply-to at ccrl-nece.de Fri Apr 7 08:56:06 2006 From: see_signature_for_reply-to at ccrl-nece.de (Joachim Worringen) Date: Fri, 07 Apr 2006 14:56:06 +0200 Subject: performance degradation when looping through lists In-Reply-To: <44365e67$0$7086$626a54ce@news.free.fr> References: <4436575e$0$11070$9b4e6d93@newsread4.arcor-online.net> <44365e67$0$7086$626a54ce@news.free.fr> Message-ID: <44366179$0$18270$9b4e6d93@newsread2.arcor-online.net> bruno at modulix wrote: > Joachim Worringen wrote: >> I need to process large lists (in my real application, this is to parse >> the content of a file). > > Then you probably want to use generators instead of lists. The problem > with large lists is that they eat a lot of memory - which can result in > swapping . The effect also shows up in tiny examples (as the one posted) which surely don't swap on a 512MB machine. Also, I only read parts of the file into memory to avoid that memory becomes exhausted. Of course, using less memory is always a good idea - do you have a pointer on how to use generators for this application (basically, buffering file content in memory for faster access)? BTW, the effect also shows up with the linecache module. >> I noticed that the performance to access the >> individual list elements degrades over runtime. > > I leave this point to gurus, but it may have to do with swapping. Also, > this is not real-time, so variations may have to do with your OS tasks > scheduler. See above for the swapping. And the OS scheduler may create variations in runtime, but not monotone degradation. I don't think these two effect come into play here. -- Joachim - reply to joachim at domain ccrl-nece dot de Opinion expressed is personal and does not constitute an opinion or statement of NEC Laboratories. From steven.bethard at gmail.com Tue Apr 11 16:28:29 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 11 Apr 2006 14:28:29 -0600 Subject: pre-PEP: The create statement In-Reply-To: References: <59Wdnbd8EazRCqnZnZ2dnUVZ_vudnZ2d@comcast.com> <1144328362.729594.173160@z34g2000cwc.googlegroups.com> <13B*uLudr@news.chiark.greenend.org.uk> <1144335440.387962.250960@u72g2000cwu.googlegroups.com> Message-ID: John J. Lee wrote: > "Michele Simionato" writes: > [...] >> This agrees with my scan (except I also found an occurrence of 'create' >> in Tkinter). >> BTW, I would be curious to see the script you are using for the >> scanning. Are you >> using tokenize too? In am quite fond of the tokenize module ;) > > Having seen Sion's (non-existent) script, how about posting yours? I > regularly grep for things in Python code, and it hadn't occurred to me > that I could instead use module tokenize. > > Module tokenize looks pretty simple, but would be nice to see some > code that has already been used. Michele's code: http://groups.google.com/group/comp.lang.python/msg/e84e36ad10d78303 My derivative: http://groups.google.com/group/comp.lang.python/msg/ed6dd53c267c7c77 STeVe From maa_subscriptions at sinn.ru Tue Apr 11 06:56:06 2006 From: maa_subscriptions at sinn.ru (Alexander Myodov) Date: Tue, 11 Apr 2006 14:56:06 +0400 Subject: RIIA in Python 2.5 alpha: "with... as" Message-ID: <178359972.20060411145606@sinn.ru> Hello, Having heard that Python 2.5 offers some kind of RIIA concept via PEP343, got it downloaded (Windows version) and tried. But it did not work as expected and as wanted. For the time since I first learned Python, the only reason why I just could not use it was inability to localize the lifetime of some variables inside some syntactical "blocks", especially ones in "for"/"while"/"if" statements, but possibly in any "manually generated" block (say, like if I would create a "{}" block in C/C++ just to separate one part of the function from another). I mean the cases like for k in a1: pass print "k: %s" % k where "k" lives long after the actual need in it was lost, and even list comprehensions: b1 = [l for l in a1] print "l: %s" % l . So, with 2.5, I tried to utilize "with...as" construct for this, but unsuccessfully: from __future__ import with_statement with 5 as k: pass print k - told me that "AttributeError: 'int' object has no attribute '__context__'". So, does this mean that we still don't have any kind of RIIA in Python, any capability to localize the lifetime of variables on a level less than a function, and this is indeed not gonna happen to change yet? -- With best regards, Alexander mailto:maa_subscriptions at sinn.ru From fredrik at pythonware.com Thu Apr 27 10:42:12 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 27 Apr 2006 16:42:12 +0200 Subject: Twisted and Tkinter References: <1146104350.843046.186230@v46g2000cwv.googlegroups.com><1146146791.931624.314570@y43g2000cwc.googlegroups.com> <1146147995.608638.245540@u72g2000cwu.googlegroups.com> Message-ID: "Chris" wrot: > Sorry. The error message is normally AttributeError: 'NoneType' object > has no attribute 'sendLine'" please post the *entire* traceback, including the part that lists filenames, line numbers, and source code lines. From tmp1 at reifenberg.de Tue Apr 4 14:26:00 2006 From: tmp1 at reifenberg.de (Nebur) Date: 4 Apr 2006 11:26:00 -0700 Subject: PEP 343 == small-sized aspect orientation ? Message-ID: <1144175160.590378.317640@e56g2000cwe.googlegroups.com> I started learning PEP 343 , and it made me feel unsure how much I really comprehend. Can somebody explain which benefit it provides, compared with usual Aspect Orientation ? The latter looks more generic to me (and doesn't need the "with" keyword). Do I miss something apparent ? Nebur From alacrite at gmail.com Mon Apr 17 23:03:26 2006 From: alacrite at gmail.com (alacrite at gmail.com) Date: 17 Apr 2006 20:03:26 -0700 Subject: Ironpython book? Message-ID: <1145329406.419299.12780@i40g2000cwc.googlegroups.com> Anyone know if there is a book for Ironpython in the works? A good knowledge of .NET and Python is enough to get started but just poking around Ironpython homepage it seems like there are some new language features added to handle some quirks with working within the CLR. Although I could be wrong. Thanks -Jake From dananrg at yahoo.com Thu Apr 6 05:55:54 2006 From: dananrg at yahoo.com (dananrg at yahoo.com) Date: 6 Apr 2006 02:55:54 -0700 Subject: Using PythonWin32 to copy text to Windoze Clipboard for Unix-style random .sig rotator? Message-ID: <1144317354.546106.167500@v46g2000cwv.googlegroups.com> Can you tell I miss Unix? I want to write a Python script that, when launched, will choose a random .sig (from a list of about 30 cool ones I've devised), and store the .sig text in the Windows Clipboard, so I can then paste it into any Windows application. This way, it'll work for Outlook e-mails, Yahoo, Gmail, etc. Also, could I use Python to programmatically set key combos to do certain things? Should I buy the Python on Win32 book? Are all my answers there? Or is there a good PyWin32 FAQ where all (that I'm interested in with this particular e-mail) will be revealed? Spammity-spam, y'all. Thanks. Dana From godoy at ieee.org Wed Apr 19 14:47:58 2006 From: godoy at ieee.org (Jorge Godoy) Date: Wed, 19 Apr 2006 15:47:58 -0300 Subject: multiline comments References: <1145425311.771598.140970@i40g2000cwc.googlegroups.com> <2Ak1g.72509$dW3.31324@newssvr21.news.prodigy.com> <2145108.A1WUCsNlIN@jupiter.g2ctech> <4446799a$0$12109$ba624c82@nntp02.dk.telia.net> Message-ID: <1824939.HMKUP9guAi@jupiter.g2ctech> rx wrote: > > "Jorge Godoy" wrote in message > news:2145108.A1WUCsNlIN at jupiter.g2ctech... >> Edward Elliott wrote: >> > >> >> You can use either """ or '''. I don't keep changing them in my code, so >> I >> can always use the other type (usually I use " so for commenting things >> out >> I'd use ') to do that. >> > > Try that on this code: > > a=3 > a=a*a > b='''This is a > very long > long > text''' > print a > > > like: > > a=3 > ''' > a=a*a > b='''This is a > very long > long > text''' > ''' > print a > > > > raises SyntaxError Of course! You should have used """ since you already used ''' in your triple-quoted text. But I'm just repeating what I already said (and kept above so that you can see it again). -- Jorge Godoy "Quidquid latine dictum sit, altum sonatur." - Qualquer coisa dita em latim soa profundo. - Anything said in Latin sounds smart. From sleytr at gmail.com Thu Apr 6 02:05:54 2006 From: sleytr at gmail.com (sleytr at gmail.com) Date: 5 Apr 2006 23:05:54 -0700 Subject: =?iso-8859-1?q?Re:_urllib.urlencode_wrongly_encoding_=B1_character?= In-Reply-To: <1144292226.017425.97420@i40g2000cwc.googlegroups.com> References: <1144287250.071811.296390@i39g2000cwa.googlegroups.com> <1144292226.017425.97420@i40g2000cwc.googlegroups.com> Message-ID: <1144303554.167469.173540@t31g2000cwb.googlegroups.com> you are right. but when I capture traffic in firefox via livehttpheaders extension, it shows me that ? is encoded to %B1. Addition to that, I found lots of page about urlencoding they have a conversation tables or scripts. All of them defines ? as %B1 . realy confused? I can copy and use urlencoded values from firefox, but I'm realy want to do things with right way. From Serge.Orlov at gmail.com Thu Apr 20 04:27:44 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 20 Apr 2006 01:27:44 -0700 Subject: UDP performance In-Reply-To: <444741dc$0$31652$e4fe514c@news.xs4all.nl> References: <44473787$0$31643$e4fe514c@news.xs4all.nl> <1145519675.476745.119480@g10g2000cwb.googlegroups.com> <444741dc$0$31652$e4fe514c@news.xs4all.nl> Message-ID: <1145521664.857759.247400@i39g2000cwa.googlegroups.com> Paul Sijben wrote: > Serge Orlov wrote: > > Paul Sijben wrote: > >> I am stumped by the following problem. I have a large multi-threaded > >> server accepting communications on one UDP port (chosen for its supposed > >> speed). > >> > >> I have been profiling the code and found that the UDP communication is > >> my biggest drain on performance! Communication where the client and the > >> server are on the same machine still takes 300ms or sometimes much more > >> per packet on an Athlon64 3000+ running Linux (Fedora Core 5 x64). > > > > [snip] > > > >> buf, address = socket.recvfrom(8192) > > > > I'm not an expert here, but I AFAIK UDP packet size should be kept > > below 512 bytes otherwise it can cause fragmentation and hence all the > > slow stuff like acknoledgements, timeouts, etc... > > > good point in general but in practice they are in this case. but this is > less of a problem on the loopback interface anyway. Isn't it still controlled by MTU even on the loopback? What is your MTU on the loopback? From deets at nospam.web.de Mon Apr 24 10:40:39 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 24 Apr 2006 16:40:39 +0200 Subject: Twisted/wxPython Problem... References: <1145888878.330009.154320@u72g2000cwu.googlegroups.com> Message-ID: <4b46b9Fv7pfaU1@uni-berlin.de> PeterG wrote: > Hi, > > I am relatively new to Python, and am learning it as part of a > university > module... > > Im currently undertaking a project to create an IM server and IM gui > client. > > I have a very basic server, and a basic gui client. I can get my > client to > connect to my server, but cant get it to disconnect or send messages to > the > server. > > I am getting the following error when I click on the 'Disconnect' > button - > AttributeError: 'NoneType' object has no attribute 'loseConnection' It seems that your client inherits from two classes, but doesn't invoke their respective constructors. That makes python only call the first classes constructor, as this simple experiment shows: class A(object): def __init__(self): print "I'm A" class B(object): def __init__(self): print "I'm B" class C(A,B): pass C() -> I'm A so - create a constructor, invoke both constructors of your super-classes either explicitly or using super (make sure you understand super!) Regards, Diez From hugonz at gmail.com Tue Apr 4 18:56:17 2006 From: hugonz at gmail.com (hugonz at gmail.com) Date: 4 Apr 2006 15:56:17 -0700 Subject: CD Burning References: Message-ID: <1144191377.191980.184050@j33g2000cwa.googlegroups.com> Hi, I used cdrecord, albeit on Linux, to do it. Someone already suggested to use Cygwin for that. I'll just drop a piece of code I wrote for getting the percentage of advance when recording sound, with cdrecord. Here it is (wraps cdrecord): #!/usr/bin/env python """ Canonizer: will open up a program and try to canonize its output. Output is program dependent (different information is needed) but always canonical (messages are one line long, and parsable through splitting) Currently only cdrecord will be implemented, but will be tailored for anything. Usage: canonizer.py """ import re import sys import os track_regexp = re.compile(r"^Track\s+(\d+):\s+(\d+)\s+of\s+(\d+)") total_regexp = re.compile(r"^Total size:\s+(\d+)") fixating_regexp = re.compile(r"^Fixating\.") done_regexp = re.compile(r"^Fixating time") def loop_cdrecord(filep): """Loop over cdrecord's output""" mycharbuf = "" exitstatus = "" burning = 0 #progress in Mbytes progress = 0 newinterval = oldinterval = 0 while True: data = filep.read(1) if not data: return exitstatus mycharbuf+= data if mycharbuf.endswith("\n") or mycharbuf.endswith("\r"): #sys.stdout.write(mycharbuf) #sys.stdout.flush() mycharbuf = mycharbuf[:-1] if not burning: try: totalsize = int(total_regexp.match(mycharbuf).group(1)) burning = 1 except: pass else: if (track_regexp.search(mycharbuf)): reobj = track_regexp.match(mycharbuf) mytrack, mynum, mydem = reobj.group(1, 2, 3) oldinterval = newinterval newinterval = int(mynum) if (oldinterval <= newinterval): progress += newinterval - oldinterval else: oldinterval = 0 print "CAN_PERCENT = %d"%((progress*98)/totalsize) elif (fixating_regexp.search(mycharbuf)): print "CAN_PERCENT = %d"%(98) print "CAN_FIXATING" elif (done_regexp.search(mycharbuf)): progress = 100 print "CAN_PERCENT = %d"%(100) exitstatus = "ok" print "CAN_DONE" sys.stdout.flush() mycharbuf = "" commandline = "" #for i in sys.argv: # print i #Get the intended commandline for i in sys.argv[1:]: commandline += " " + i pipe_filep = os.popen (commandline, "r") exitstatus = loop_cdrecord(pipe_filep) if (exitstatus != "ok"): print "CAN_ERROR" From brochu121 at gmail.com Thu Apr 13 15:00:53 2006 From: brochu121 at gmail.com (david brochu jr) Date: Thu, 13 Apr 2006 15:00:53 -0400 Subject: Remove Whitespace Message-ID: <9583ed900604131200n5c43829ckeb01ba4503763954@mail.gmail.com> Hi again, Trying to remove whitespace from a string in a text file. the string is: D c a V e r " = d w o r d : 0 0 0 0 0 6 4 0 how would i go about doing this? -------------- next part -------------- An HTML attachment was scrubbed... URL: From rob.haswell at gmail.com Sun Apr 23 17:17:30 2006 From: rob.haswell at gmail.com (rob.haswell at gmail.com) Date: 23 Apr 2006 14:17:30 -0700 Subject: getattr from local scope Message-ID: <1145827050.347326.84980@t31g2000cwb.googlegroups.com> Hey there My question is pretty simple - I want to use something like getattr to grab a symbol from the local scope from a string. Basically my application has a scheduler which stores names of functions defined in the "schedule" module in a database, to be run on certain days. Every night I call schedule.RunSchedule, which grabs all the rows on the database that have to be run now, and I want to call the function defined the same module according to that string. I know I can use eval, but I've always been told that if you're using eval, you're doing it wrong. Also not using eval limits the scope damage that can be caused by any errors in my application which could cause the database to be poisoned. Cheers for any help :-) -Rob From michele.simionato at gmail.com Thu Apr 6 12:11:52 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 6 Apr 2006 09:11:52 -0700 Subject: pre-PEP: The create statement In-Reply-To: <1144302248.639529.161700@j33g2000cwa.googlegroups.com> References: <59Wdnbd8EazRCqnZnZ2dnUVZ_vudnZ2d@comcast.com> <1144302248.639529.161700@j33g2000cwa.googlegroups.com> Message-ID: <1144339912.936273.208170@j33g2000cwa.googlegroups.com> Carl Banks wrote: > My biggest concern with this is the special arguments of the caller. > It breaks my heart that we couldn't do something like this: > > create dict keymap: > A = 1 > B = 2 > > And it'll probably confuse people as well. We ought to keep that in > mind. > > > > Of course, properties are only one of the many possible uses of the > > create statement. The create statement is useful in essentially any > > situation where a name is associated with a namespace. So, for > > example, sub-modules could be created as simply as:: > > > > create module mod: > > "This creates a sub-module named mod with an f1 function" > > > > def f1(): > > ... > > Let's not do this, really. A module should be one-to-one with a file, > and you should be able to import any module. Having in-line modules > complicates everything. And it becomes a misnomer. So, please, let's > get a better example. If you must, call it a scope or namespace. You are right, I think I am responsible for the wrong choice of the name. What I had in mind was a namespace or, if you wish, a named dictionary. An simple-minded implementation could be class Namespace(object): def __init__(self, name, args, dic): self.__name__ = name self.__dict__.update(dic) create Namespace keymap: A = 1 B = 2 and nothing forbids to have the Namespace class in some module of the standard library ;) Michele Simionato From fatal.serpent at gmail.com Sat Apr 15 10:36:30 2006 From: fatal.serpent at gmail.com (fatal.serpent) Date: 15 Apr 2006 07:36:30 -0700 Subject: Help with python output redirection In-Reply-To: References: <1145059153.392141.145360@u72g2000cwu.googlegroups.com> Message-ID: <1145111789.969239.270260@i40g2000cwc.googlegroups.com> Thank you. Also this script is PublicDomain right? Steven D'Aprano wrote: > On Fri, 14 Apr 2006 16:59:13 -0700, fatalserpent wrote: > > > Here is the basic code (yes, I know its tiny). > > > > x = ['print "x =", x', 'for m in x: print m'] > > print "x =", x > > for m in x: print m > > > > I want to modify this so it will output to a file called 1. What I want > > is to have that file direct its output to a file called 2 and 2 direct > > to 3 and so on. Hopefully this will be an easy-to-answer question. THX > > in advance. > > From the shell, you are probably doing something like this: > > $ python mymodule.py > > Change it to this: > > $ python mymodule.py > 2 > $ python 2 > 3 > $ python 3 > 4 > > and so on. > > Alternatively, you can do this: > > x = ['f = file("2", "w")', 'print >>f, "x =", x', > 'for m in x: >>f, print m'] > print >>f, "x =", x > for m in x: print >>f, m > > I'll leave changing the file name from "2" to "3" etc. as an exercise for > you. > > > -- > Steven. From no_spam at tilanus.com Fri Apr 28 02:17:56 2006 From: no_spam at tilanus.com (Winfried Tilanus) Date: Fri, 28 Apr 2006 08:17:56 +0200 Subject: can i set up a mysql db connection as a class ? In-Reply-To: References: <1146183359.932904.298760@g10g2000cwb.googlegroups.com> <1146199764.328276.241320@j33g2000cwa.googlegroups.com> Message-ID: <4451b394$0$31649$e4fe514c@news.xs4all.nl> On 04/28/2006 07:54 AM, *binarystar* wrote: Just wondering: is there any risk of two threads accessing the Execute function at the same time and getting something like this on the same cursor object: thread_1: self.cursor.Execute( sql_statement ) thread_2: self.cursor.Execute( sql_statement ) thread_1: return self.cursor.FetchAll() thread_2: return self.cursor.FetchAll() In that case the queries would seriously be messed up. My intuition says this would need some locking or a 'cursor-pool'. best wishes, Winfried > your on the right track ... create something like this ( hope the > formatting doesn't go to hay wire ) > > class DB_Connector(object): > > """ Humble Database Connection Class """ > def __init__(self, host="localhost", > user="MyUser",passwd="MyPassword", **other_db_arguments): > self.host = host > self.user = user > self.passwd = passwd > # Unpack Other Database Arguments Here > self.CreateConnection() > def CreateConnection( self ): > self.cursor = MySQLdb.connect(self.host, self.user, > self.passwd) > def DestroyConnection( self ): > self.cursor.close() > def Execute( self, sql_statement ): > self.cursor.Execute( sql_statement ) > return self.cursor.FetchAll() > Then when you run your program create an instance of the object > > db_connection = DB_Connector( 'localhost', 'administrator', > 'betelgeuse99', auto_commit=1, other_keyword_arg="yes" ) > > now when you pass the db_connection instance to other classes, a copy > will be made automagically > > thread_1_instance = ThreadingClass( db_connection ) > thread_2_instance = ThreadingClass( db_connection ) > thread_3_instance = ThreadingClass( db_connection ) > > should work .. > I hope this is useful From enleverlesX.XmcX at XmclaveauX.com Mon Apr 3 07:35:04 2006 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI) Date: Mon, 3 Apr 2006 13:35:04 +0200 Subject: beautiful GUI References: <1144062388.699313.138160@j33g2000cwa.googlegroups.com> Message-ID: <443133c6$0$18315$8fcfb975@news.wanadoo.fr> Hi! Two ideas : - WindowsBlind - Internet-Explorer + DHTML - Flash, like GUI Oups, there are three ideas.... Sorry @-salutations -- Michel Claveau From mwilson-to at sympatico.ca Fri Apr 21 15:39:29 2006 From: mwilson-to at sympatico.ca (Mel Wilson) Date: Fri, 21 Apr 2006 15:39:29 -0400 Subject: lambda In-Reply-To: <1145642409.389741.39680@g10g2000cwb.googlegroups.com> References: <1145642409.389741.39680@g10g2000cwb.googlegroups.com> Message-ID: rubbishemail at web.de wrote: > Hello, > > I need your help understanding lambda (and doing it a better way > without). > > f = lambda x : x*x [ ... ] > # the idea is now to give the definition of the multiplication of > functions and integers > # (f * c)(xx) := f(x)*c > [lambda xx: f(xx)*y for y in range(1,5)][0](1) > # returns 4 > # I would expect 1*x*x = 1 I think you have to get the value of y at definition time, not at call time: >>> z=[lambda xx, yy=y: (f(xx)*yy) for y in xrange(1,5)] >>> z[0](1) 1 Mel. From jUrner at arcor.de Fri Apr 7 14:41:58 2006 From: jUrner at arcor.de (jUrner at arcor.de) Date: 7 Apr 2006 11:41:58 -0700 Subject: how you know you're a programming nerd In-Reply-To: References: <3GuZf.1940$No6.41580@news.tufts.edu> <1144429942.206807.178070@v46g2000cwv.googlegroups.com> Message-ID: <1144435318.718778.59390@i39g2000cwa.googlegroups.com> Keep on coding. It'll just go away.. From sturlamolden at yahoo.no Fri Apr 28 15:42:35 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 28 Apr 2006 12:42:35 -0700 Subject: MinGW and Python In-Reply-To: <1146248734.511062.115290@j73g2000cwa.googlegroups.com> References: <1146248734.511062.115290@j73g2000cwa.googlegroups.com> Message-ID: <1146253355.564139.147500@j73g2000cwa.googlegroups.com> Ross Ridge wrote: > You'd have to point people who don't already have it to Microsoft's > download site. Is there a download site? I have not been able to localise one. > I think that having current versions of Python also linked MSVCRT.DLL, > whether compiled with MinGW or MSVC 6, 7 or 8, could be over all be a > better solution than using a CRT DLL specific to one version of > Microsoft's compiler. It would make it possible to build extentions > with any version of MSVC, instead of just the one that Python was built > with. I am not sure it is good enough. For two reasons: 1. msvcrt.dll is intended for future use by system level components only. 2. you need an import library for msvcrt.dll, if your VS don't ship with one you are lost. http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_crt_c_run.2d.time_libraries.asp What is the difference between msvcrt.dll and msvcr71.dll? The msvcrt.dll is now a "known DLL," meaning that it is a system component owned and built by Windows. It is intended for future use only by system-level components. An application should use and redistribute msvcr71.dll, and it should avoid placing a copy or using an existing copy of msvcr71.dll in the system directory. Instead, the application should keep a copy of msvcr71.dll in its application directory with the program executable. Any application built with Visual C++ .NET using the /MD switch will necessarily use msvcr71.dll. From nomail at nixmail.com Sun Apr 30 05:26:31 2006 From: nomail at nixmail.com (DarkBlue) Date: Sun, 30 Apr 2006 17:26:31 +0800 Subject: Unpacking of query result References: <44547588@127.0.0.1> Message-ID: <445482c7@127.0.0.1> Thank you Mission accomplished. Have a nice sunday Db From phddas at yahoo.com Thu Apr 20 03:47:02 2006 From: phddas at yahoo.com (Gary Wessle) Date: 20 Apr 2006 17:47:02 +1000 Subject: charting Message-ID: <87zmigheo9.fsf@localhost.localdomain> Dear python users I am just wondering if python is the language to use to build a custom charting package which is live updated from live data stream coming through a socket. as well as dynamically execute data analysis code on the data being fed. I have been looking at SpecTix. thank you From python.list at tim.thechases.com Sun Apr 16 11:38:56 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 16 Apr 2006 10:38:56 -0500 Subject: Unified web API for CGI and mod_python? In-Reply-To: References: <1138116339.781705.67960@f14g2000cwb.googlegroups.com> Message-ID: <44426510.9080509@tim.thechases.com> >>root at rubbish# cd ~tim/WebStack-1.1.2 >>root at rubbish# python2.3 setup.py install >>running install >>error: invalid Python installation: unable to open >>/usr/lib/python2.3/config/Makefile (No such file or directory) > > apt-get install python2.3-dev Worked like a charm, and the WebStack install took place uneventfully. Only took half an hour to download the .deb packages over dialup :-/ Thanks for your help! -tim From SSchukat at dspace.de Wed Apr 19 13:26:48 2006 From: SSchukat at dspace.de (Stefan Schukat) Date: Wed, 19 Apr 2006 18:26:48 +0100 Subject: Help needed on COM issue Message-ID: <1B3F2E002D9AD04BBC1A27B370F29EB9022DA2@exchange2003.dspace.de> Hi, the feature you expierenced are parameterized properties. This is only supported by VB and could only be emulated in python. If you use makepy/gencache to generate a wrapper the appropriate Set methods are created: oR.SetItem(1,2, "4") Stefan > -----Original Message----- > From: python-list-bounces+sschukat=dspace.de at python.org > [mailto:python-list-bounces+sschukat=dspace.de at python.org] On > Behalf Of Mike Howard > Sent: Wednesday, April 12, 2006 1:12 AM > To: python-list at python.org > Subject: Help needed on COM issue > > I'm doing some conversion of vb code to python code and I > have a problem with a COM object > > Specifically in VB I can do > Set oR = oA.Action > debug.print oR.Item(1,2) > [returns say "1"] > oR.Item(1,2)="4" > debug.print oR > [returns "4"] > > In Python I need to do .. > > oR=oA.Action() > print oR.Item(1,2)[0] > [returns say "1"] > oR.Update > [saves the record with the new item] > > But when I ty to update the value > > oR.Item(1,2)[0]="4" > > I get a TypeError : object doesn't support item assignment. > > I presume this is because Python is returning oR as a tupe - > hence the need to refer to Item(1,2)[0] - but I can't figure > out the equivalent method to update the value I need. > > Any help appreciated. > > -- > http://mail.python.org/mailman/listinfo/python-list > From mahs at telcopartners.com Fri Apr 21 20:29:51 2006 From: mahs at telcopartners.com (Michael Spencer) Date: Fri, 21 Apr 2006 17:29:51 -0700 Subject: How to create a dictionary from a string? In-Reply-To: <1145664416.562678.113720@i40g2000cwc.googlegroups.com> References: <1145664416.562678.113720@i40g2000cwc.googlegroups.com> Message-ID: Clodoaldo Pinto wrote: > Is there a simple way to build a dictionary from a string without using > eval()? > >>>> s = '{"a":1}' >>>> d = eval(s) >>>> d > {'a': 1} > > Regards, Clodoaldo Pinto > Here is a discussion about one way to do it: http://tinyurl.com/o8mmm HTH Michael From sambo at void.com Sat Apr 22 15:14:57 2006 From: sambo at void.com (Sambo) Date: Sat, 22 Apr 2006 15:14:57 -0400 Subject: Problem calling math.cos() Message-ID: <3ev2g.9680$%97.5795@newsfe15.lga> I have the following module: ------------------------------- import math def ac_add_a_ph( amp1, ph1, amp2, ph2 ): amp3 = 0.0 ph3 = 0.0 ac1 = ( 0, 0j ) ac2 = ( 0, 0j ) ac3 = ( 0, 0j ) ac1 = complex( amp1 * math.cos( math.radians( ph1 ) ), amp1 * math.sin( math.radians( ph1 ) ) ) ac2 = complex( amp2 * math.cos( math.radians( ph2 ) ), amp2 * math.sin( math.radians( ph2 ) ) ) ac3 = ac1 + ac2 amp3 = math.abs( ac3 ) ph3 = math.atan( ac3.imag / ac3.real ) return [amp3, ph3] -------------------------------------- when I import it (electronics) in python.exe in windows2000 and try to use it, it croaks. ??? >>> import math >>> import electronics >>> print electronics.ac_add_a_ph( 10, 0 , 6 , 45 ) Traceback (most recent call last): File "", line 1, in ? File "f:\devel\python\electronics.py", line 10, in ac_add_a_ph ac1 = complex( amp1 * math.cos( math.radians( ph1 ) ), amp1 * math.sin( math .radians( ph1 ) ) ) NameError: global name 'cos' is not defined >>> global?? huh? what does abs stand for? why is that not absolute value? hmmm. Hmm, complex numbers, cool I don't even have any idea where C stands on this. From nid_oizo at yahoo.com_removethe_ Fri Apr 14 12:47:06 2006 From: nid_oizo at yahoo.com_removethe_ (Nicolas Fleury) Date: Fri, 14 Apr 2006 12:47:06 -0400 Subject: PEP 359: The "make" Statement In-Reply-To: References: Message-ID: Felipe Almeida Lessa wrote: > Em Sex, 2006-04-14 ?s 09:31 -0600, Steven Bethard escreveu: >> [1] Here's the code I used to test it. >> >> >>> def make(callable, name, args, block_string): >> ... try: >> ... make_dict = callable.__make_dict__ >> ... except AttributeError: >> ... make_dict = dict >> ... block_dict = make_dict() >> ... exec block_string in block_dict >> ... return callable(name, args, block_dict) >> ... >> >>> (snip) > > I think it would be nice not to put those ">>>" and "..." to make copy > and paste easier. Okay, I know we can do "".join(line[4:] for line in > text), but that's just my humble opinion. > Note that there's a "special paste" in wxPython PyShell, with which you can copy/paste these lines. Nicolas From tzot at sil-tec.gr Wed Apr 12 09:52:12 2006 From: tzot at sil-tec.gr (Christos Georgiou) Date: Wed, 12 Apr 2006 16:52:12 +0300 Subject: Compleated Begginers Guide. Now What? References: <1144497870.999295.162450@i39g2000cwa.googlegroups.com> Message-ID: On Tue, 11 Apr 2006 07:37:23 -0400, rumours say that Steve Holden might have written: >James Stroud wrote: >> Mirco Wahab wrote: >>>Jay wrote: >>>Malchick, you cracked your veshchs to classes, which is >>>not that gloopy. So rabbit on them and add class methods >>>that sloosh on beeing called and do the proper veshchs >>>to the gulliwuts of their classes. >> Brillig! >But neither helpful nor sympathetic. Neither sympythetic, too (where ?sympythetic? is the typical behaviour on c.l.py) -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From bignose+hates-spam at benfinney.id.au Tue Apr 18 18:48:36 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 19 Apr 2006 08:48:36 +1000 Subject: indirect import of standard module References: <1145386200.076643.253740@u72g2000cwu.googlegroups.com> <1145393476.931506.9650@e56g2000cwe.googlegroups.com> Message-ID: <87mzeih54r.fsf@benfinney.id.au> "alisonken1" writes: > Unless you override some of os.* functions in foo, you want to > import os into foo and bar separately. > > Python does not reimport the module a second time (create a second > instance of os) More accurately, it *does* import it twice, into two separate namespaces; but loads and executes the code only the first time. -- \ "God forbid that any book should be banned. The practice is as | `\ indefensible as infanticide." -- Dame Rebecca West | _o__) | Ben Finney From cyberco at gmail.com Fri Apr 7 17:38:30 2006 From: cyberco at gmail.com (cyberco) Date: 7 Apr 2006 14:38:30 -0700 Subject: mod_python + apache + winxp => nogo Message-ID: <1144445910.877992.80210@v46g2000cwv.googlegroups.com> And I thought this would be trivial...getting mod_python to run within apache on windows XP. ============= mod_python 3.2.8 apache 2.0.55 python2.4 winxp ============= After adding: "LoadModule python_module modules/mod_python.so" to apache's httpd.conf, apache refuses to start, saying: "cannot load c://mod_python.so into server: the specified module could not be found" 'mod_python.so' is in the modules folder under apache, though. I've searched everywhere, but could not find a solution. Anybody here that has been successful in getting this combo to work? From walter at livinglogic.de Thu Apr 6 09:50:00 2006 From: walter at livinglogic.de (=?ISO-8859-1?Q?Walter_D=F6rwald?=) Date: Thu, 06 Apr 2006 15:50:00 +0200 Subject: HTMLParser fragility In-Reply-To: References: Message-ID: <44351C88.7000800@livinglogic.de> Rene Pijlman wrote: > Lawrence D'Oliveiro: >> I've been using HTMLParser to scrape Web sites. The trouble with this >> is, there's a lot of malformed HTML out there. Real browsers have to be >> written to cope gracefully with this, but HTMLParser does not. > > There are two solutions to this: > > 1. Tidy the source before parsing it. > http://www.egenix.com/files/python/mxTidy.html > > 2. Use something more foregiving, like BeautifulSoup. > http://www.crummy.com/software/BeautifulSoup/ You can also use the HTML parser from libxml2 or any of the available wrappers for it. Bye, Walter D?rwald From harry.g.george at boeing.com Mon Apr 10 07:24:47 2006 From: harry.g.george at boeing.com (Harry George) Date: Mon, 10 Apr 2006 11:24:47 GMT Subject: best way to install python modules on linux References: Message-ID: Fabian Braennstroem writes: > Hi, > > I am pretty new to python and will use it mainly in > combination with scientific packages. I am running ubuntu > breezy right now and see that some packages are out of date. > Do you have any suggestion, how I can get/keep the latest > python modules (e.g. scipy, numpy,...) on my ubuntu system? > I.e. does there exist any script/program, which downloads > and installs automatically the latest stable releases of selected > modules? It would be nice, if the program can remove the > installed modules, too!? > > Or would it be easier to stick to apt/deb and create own > packages ... > > > Greetings! > Fabian > I find it helpful to leave the as-delivered Python (e.g., /usr/bin/python) as-is. It is being used to run your basic Linux system. Screwing around with it can have nasty side effects. Instead I build a new one at /usr/local, give it a unique name, and upgrade/hack that one to my heart's content. E.g., if the base system is using Python 2.2, you can be running Python 2.4 as /usr/local/bin/py24, and add all the numerical packages you wish at use/local/lib/python2.4/site-packages. Also, make sure root doesn't have /usr/local/bin on its PATH (which is a good rule anyway). -- Harry George PLM Engineering Architecture From sperlle at yahoo.com Sun Apr 16 11:01:51 2006 From: sperlle at yahoo.com (Michael Sperlle) Date: 16 Apr 2006 15:01:51 -0000 Subject: Using Python To Create An Encrypted Container Message-ID: Is it possible? Bestcrypt can supposedly be set up on linux, but it seems to need changes to the kernel before it can be installed, and I have no intention of going through whatever hell that would cause. If I could create a large file that could be encrypted, and maybe add files to it by appending them and putting in some kind of delimiter between files, maybe a homemade version of truecrypt could be constructed. Any idea what it would take? From peter at engcorp.com Fri Apr 7 19:54:38 2006 From: peter at engcorp.com (Peter Hansen) Date: Fri, 07 Apr 2006 19:54:38 -0400 Subject: minidom + wxPython woes In-Reply-To: <1144448617.018935.112660@e56g2000cwe.googlegroups.com> References: <1144448449.586601.293480@v46g2000cwv.googlegroups.com> <1144448617.018935.112660@e56g2000cwe.googlegroups.com> Message-ID: Lonnie Princehouse wrote: > Oops, I missed a bracket... that should read: > > testxml = '' > > But it still crashes ;-) Maybe missing a question mark still too? (It's like a processing instruction, not an element.) -Peter From felipe.lessa at gmail.com Sat Apr 22 00:19:13 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Sat, 22 Apr 2006 01:19:13 -0300 Subject: Generate a sequence of random numbers that sum up to 1? In-Reply-To: References: Message-ID: <1145679553.3758.0.camel@kenshin.CASA> Em S?b, 2006-04-22 ?s 03:16 +0000, Edward Elliott escreveu: > If that level of accuracy > matters, you might consider generating your rands as integers and then > fp-dividing by the sum (or just store them as integers/fractions). Or using decimal module: http://docs.python.org/lib/module-decimal.html -- Felipe. From szabolcs.berecz at gmail.com Fri Apr 14 08:10:17 2006 From: szabolcs.berecz at gmail.com (Szabolcs Berecz) Date: Fri, 14 Apr 2006 14:10:17 +0200 Subject: nested functions In-Reply-To: <1145014674.717433.75100@t31g2000cwb.googlegroups.com> References: <1145014674.717433.75100@t31g2000cwb.googlegroups.com> Message-ID: On 14 Apr 2006 04:37:54 -0700, micklee74 at hotmail.com wrote: > def a(): > def b(): > print "b" > def c(): > print "c" > > how can i call c() ?? Function c() is not meant to be called from outside function a(). That's what a nested function is for: localizing it's usage and prevent cluttering the global namespace Szabi From johnjsal at NOSPAMgmail.com Mon Apr 10 22:31:48 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 10 Apr 2006 22:31:48 -0400 Subject: Best Python web-hosting? In-Reply-To: <1144710859.872630.297820@u72g2000cwu.googlegroups.com> References: <1144605832.364688.305300@j33g2000cwa.googlegroups.com> <4439870a$0$4206$c3e8da3@news.astraweb.com> <1144710859.872630.297820@u72g2000cwu.googlegroups.com> Message-ID: <443b15dd$0$11701$c3e8da3@news.astraweb.com> walterbyrd wrote: > And they have mod_python. You sure about that? I've learned to be skeptical, because a lot of hosts don't even seem to understand the difference between supporting "Python" (which in reality is just CGI for them) and mod_python. In fact, I've even been told that a host *does* have mod_python installed, and it took several emails to find out that, no, they really don't, they just support CGI. All I see on this site is "Python 2.3.4", no mention of mod_python. I have an email in to them to inquire, but I'm not getting my hopes up. From iddw at hotmail.com Tue Apr 18 16:09:59 2006 From: iddw at hotmail.com (Dave Hansen) Date: Tue, 18 Apr 2006 15:09:59 -0500 Subject: How do you guys print out a binary tree? References: <1145343415.809363.116280@i39g2000cwa.googlegroups.com> Message-ID: On Tue, 18 Apr 2006 08:17:22 -0700 (PDT) in comp.lang.python, Anthony Liu wrote: > > >--- bayerj wrote: > >> Hi, >> >> > 1 2 3 4 5 >> > 0 7 8 9 10 >> > 0 0 13 14 15 >> > 0 0 0 19 20 >> > 0 0 0 0 25 >> > Look at the triangle represented by the non-zero >> > integers. This triangle is a binary tree if we >> take 5 >> > as the root and walk down on both sides. >> >> Are you sure? Is 9 a child of 4 or 10? A binary >> tree can have up to >> 2^n - 1 nodes. A matrix can have up to n^2 values, >> in your case of a >> half-empty matrix about (n-1)^2. >> > >Thanks. I am not concerned about the shape of binary >tree. So, let's forget about binary tree. > >Given a triangle like that, it does not matter which >is whose children. How do we nicely present it as >tree in an ascii console? Something like the following might work. Quick 2-minute script. Probably needs tweaking to be generally useful import sys def print_tri(t): n = len(t) cell = 0 for line in t: tw = max(map(lambda x:len(str(x)), line)) if tw > cell: cell = tw for p in range(n,0,-1): sys.stdout.write("%*s"%(((cell+1)/2)*(2*p),"")) x = 0 y = p-1 while y References: <1145895732.963584.231100@j33g2000cwa.googlegroups.com> Message-ID: <1146072411.253848.108770@e56g2000cwe.googlegroups.com> Fredrik, thanks alot. Your preposition worked like a charm, plus I got to learn how to reverse an inner for loop using list comprehensions :) What I don't understand is what are you doing with *(...), this is supposed to pack its contents as a list? From ldo at geek-central.gen.new_zealand Mon Apr 10 03:33:22 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 10 Apr 2006 19:33:22 +1200 Subject: can't pass command-line arguments References: <1144636890.976327.253000@i39g2000cwa.googlegroups.com> <1144637633.814788.150270@i40g2000cwc.googlegroups.com> Message-ID: In article <1144637633.814788.150270 at i40g2000cwc.googlegroups.com>, "BartlebyScrivener" wrote: >I was used to being able to run scripts by just typing the script name, >even without the .py extension, but > >findmyfiles d:/notes notes*.* does not work The MS-DOS foundation on which Windows is built only supports a small number of extensions for "executable" files (.COM, .EXE and .BAT), with no provision for any extensions to these. From nobody at 127.0.0.1 Tue Apr 25 17:38:00 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Tue, 25 Apr 2006 21:38:00 GMT Subject: MinGW and Python References: <1145861223.509630.247350@y43g2000cwc.googlegroups.com> <444C79D7.4060007@v.loewis.de> <444DC62B.7000702@v.loewis.de> <1145985979.369429.114040@i39g2000cwa.googlegroups.com> <444e7d85$0$12131$9b622d9e@news.freenet.de> Message-ID: "Martin v. L?wis" wrote: > Well, you are not compiling with neither mingw, nor cygwin; you are > compiling with gcc in either case. touche, mr. pedant. :) > Well, there is no native C library on Microsoft Windows: the system > simply doesn't include an official C library (I know there is crtdll.dll > and msvcrt.dll, but these aren't "endorsed" system C libraries). don't know what you mean by "endorsed". does it lack features of the C89 ANSI standard? > For Windows, that would require not to use any of the standard C > functionality, since the system doesn't provide that functionality out > of the box. That would be a problem then. So what happens when you compile python with msvc, and why can't mingw just replicate that? From digitalorganics at gmail.com Mon Apr 3 15:24:18 2006 From: digitalorganics at gmail.com (Cloudthunder) Date: Mon, 3 Apr 2006 15:24:18 -0400 Subject: Merging Objects In-Reply-To: <443163F3.20205@python.org.ve> References: <443163F3.20205@python.org.ve> Message-ID: Sorry, I don't understand, how does this solve my problem? On 4/3/06, Jesus Rivero - (Neurogeek) wrote: > > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > >>> help(getattr) help(setattr) > > Regards, > > Jesus Rivero - (Neurogeek) > > Cloudthunder wrote: > > > Question: how do I merge two objects? I would like to be able to > > have an instance of Foo and an instance of Boo and then be able to > > add them together and create a new object that has the methods and > > properties of both objects. I am going to be doing a lot of this > > and I don't want to have to dynamically (or otherwise) create a > > whole bunch of classes that inherit from both Foo and Boo then > > create instances of those new children classes. In fact, this > > wouldn't work for me anyway because I am going to have an instance > > of Foo which will be used within my algorithm for sometime then > > later I will want to merge it with a fresh instance of Boo or > > otherwise give it all the methods and properties of the Boo class. > > Am I making any sense here? > > > > Thanks. > > > > - OP > > > > P.S. I also noticed that we can no long use the __members__ > > property to get a tuple of all a class's methods. How can I get the > > same info from dir()? Dir(), I understand, tells you about all > > properties and you can't tell it to just list the methods. > > > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.1 (GNU/Linux) > Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org > > iD8DBQFEMWPzdIssYB9vBoMRAnkLAJ4mkUTlB9POlOyE5MeHukAJ5LeawQCghtoQ > Dsn33bw0LYFsNS2AYStPLdU= > =Dt4g > -----END PGP SIGNATURE----- > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From none at no.chance Wed Apr 19 07:02:37 2006 From: none at no.chance (Peter Tillotson) Date: Wed, 19 Apr 2006 12:02:37 +0100 Subject: multiline comments In-Reply-To: References: <1145425311.771598.140970@i40g2000cwc.googlegroups.com> Message-ID: Ben Finney wrote: > "Atanas Banov" writes: > >> Edward Elliott wrote: >>> Saying coders shouldn't use multiline comments to disable code >>> misses the point. Coders will comment out code regardless of the >>> existence of multiline comemnts. There has to be a better >>> argument for leaving them out. >> i beg to differ: you'd be surprised how much effect can little >> inconveniences have. >> >> want to comment block of code? use tripple-quotes. does not nest? >> ahhh, maybe it's time to get rid of that block you commented out a >> month ago "just in case the new code doesnt work". > > Indeed. Using revision control means never needing to comment out > blocks of code. > > If your revision control system is so inconvenient to use that you'd > rather have large blocks of commented-out code, it's time to start > using a better RCS -- perhaps a distributed one, so you can commit to > your own local repository with abandon while trying out changes. > I'm not sure I agree, revision control is great but not the only answer. In multi-developer teams working on the trunk, it its kind of inconvenient if someone checks in broken code. It also blocks critical path development if the person responsible for the code you conflict with happens to be out on holiday. Block commenting is a clear flag to that developer that something has changed - ideally he'd notice, see sensible revision control comments, see the flag on the wiki or you would remember to tell him. But if all of that fails, if it is commented in the code it should get picked up at a code review. Personally, I prefer clear code, minimally commented with good high level descriptions of particularly complex section / algorithms. The later doesn't always fit neatly on one line. There is an argument that these should go into their own functions and be commented at the function level. Again I'm not sure I agree entirely - function comments that are auto extracted to create api docs (sorry Java background :-)) need only outline What a function does. There is a place for multiline comments to describe How that is achieved. Having said all that, I generally don't like comments, they are often maintained poorly, too numerous, too verbose (red rag :-)) - so i'm undecided whether they should be made easier for developers or discouraged except where vital. Perhaps we should make them really hard and elegant - mandate latex/mathml markup so good editors can display the equations we are implementing :-) From simon at brunningonline.net Tue Apr 11 07:06:39 2006 From: simon at brunningonline.net (Simon Brunning) Date: Tue, 11 Apr 2006 12:06:39 +0100 Subject: Web Service SOAP - Unknown element v1 In-Reply-To: References: Message-ID: <8c7f10c60604110406n20b5b5b6xa00e3f717b9b15c8@mail.gmail.com> On 4/11/06, Jesus.Javier.Masa.Lledo at dmr-consulting.com wrote: > > This is the result of doing: setDVD(title="BenHur") > > *** Outgoing SOAP ****************************************************** > > SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" > xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" > xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance" > xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" > xmlns:xsd="http://www.w3.org/1999/XMLSchema" > > > > > BENHUR > > > > ************************************************************************ Clearly it isn't. Your Python snippet uses the keyword "title", whereas the outgoing SOAP message uses "titulo". What does the WSDL say it needs? Have you looked at the Java side, as I suggested? BTW, please reply to the list rather than to me personally. Thanks. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From first180 at gmail.com Sun Apr 16 12:33:15 2006 From: first180 at gmail.com (Jay) Date: 16 Apr 2006 09:33:15 -0700 Subject: Tkinter In-Reply-To: References: <1145198499.259375.90030@i39g2000cwa.googlegroups.com> Message-ID: <1145205195.820055.153410@z34g2000cwc.googlegroups.com> I still dont quite get it, is their sum kind of way you can [def Newdef + i()] for example so that the def is different from the string, all the buttons now have numbers on If I am not mistaken Fredrik Lundh rote the tutorial Learning to program (Python) www.freenetpages.co.uk/hp/alan.gauld/ and www.effbot.org If this is the same person then thank you for everything I no about python it seams what ever I try and learn about Python it is always you who helps or has wrote docs to help Newbie's and well everyone really. ---code--- from Tkinter import * class App: def __init__(self, root): self.DisplayAreaListsFrame = Frame(root) self.DisplayAreaListsFrame.pack() Lists = ["A1","B2","C3","D4"] for i in Lists: def i(): print i self.DisplayAreaListButton = Button( self.DisplayAreaListsFrame, text=i, command=i) self.DisplayAreaListButton.pack(side=LEFT,padx=10) root = Tk() app = App(root) root.mainloop() From bitprophet at gmail.com Thu Apr 6 23:07:24 2006 From: bitprophet at gmail.com (Jeff) Date: 6 Apr 2006 20:07:24 -0700 Subject: Training/conventions featuring non-introductory Python Message-ID: <1144379244.793406.231750@g10g2000cwb.googlegroups.com> Hey all, I'm looking around to see how best to spend the training monies allocated me by my employer for this year, and haven't really ever done this sort of thing before. I work primarily with Python (Django, Zope, and assorted small apps and scripts) so what would be best is something that is primarily or partially concerned with the language we all know and love. To a lesser extent, anything development or Web related would also work (piggyback question, I guess :)). In addition, I'm looking mostly on the West Coast of the United States since I have other reasons to travel there this year. Thus far I've found only one Python-specific course that is not an introductory one, namely Wes Chun's advanced Python course in San Francisco. As for conventions, there's O'Reilly's OSCON and (to a lesser extent) their Lots O' Hype--excuse me, Web 2.0--conference, in Portland and SF respectively. Before I commit to one of those, I'd like to make sure there's nothing else I'm missing out on. Thanks for any tips or pointers, Jeff From tjreedy at udel.edu Thu Apr 13 17:18:25 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 13 Apr 2006 17:18:25 -0400 Subject: List comp bug? References: <1144923444.813998.61650@v46g2000cwv.googlegroups.com> Message-ID: wrote in message news:1144923444.813998.61650 at v46g2000cwv.googlegroups.com... > [f() for f in [lambda: t for t in ((1, 2), (3, 4))]] > is giving me > [(3, 4), (3, 4)] > > The equivalent using a generator expression: List comps were originally designed to be equivalent to for loops with nested for loops and if blocks. Generator expressions are know to be slightly different and *not* exactly equivalent due to the new local namespace. > [f() for f in (lambda: t for t in ((1, 2), (3, 4)))] > is giving me > [(1, 2), (3, 4)] Since, when there is a difference, as above, the genex behavior is more often the right or expected behavior (as above), Guido is considering making the diference go away in 3.0 by making [stuff] == list((stuff)) (ie, listcomp == list(genex)). Terry Jan Reedy From gherron at islandtraining.com Wed Apr 5 14:59:27 2006 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 05 Apr 2006 11:59:27 -0700 Subject: how to convert string In-Reply-To: <1144261976.640631.9280@e56g2000cwe.googlegroups.com> References: <1144261976.640631.9280@e56g2000cwe.googlegroups.com> Message-ID: <4434138F.2030409@islandtraining.com> diffuser78 at gmail.com wrote: >I want to print number 0 to 9 in one line like this >0 1 2 3 4 5 6 7 8 9 > >if I do like this, it prints in different lines > >for i in xrange(10): > print i > > A comma at the end of the print will do what you want: for i in xrange(10): print i, >so i tried like this > >str = "" >for i in xrange(10): > str = i + " " >print str > >but i want to know how convert int i to string. > > str(i) will do what you want and so will the "%" operator. However, you sample code masks the builtin "str" function by creating a variable with the same name (plus you had another error in that line), so try this: s = "" for i in xrange(10): s = s + str(i) + " " print s A shortcut for the line in the loop is s += str(i) + " " Also note that appending to string is slow while appending to lists is not. So try build a list and turning it into a string with the string "join" method like this l = [] for i in xrange(10): l.append(str(i) print " ".join(l) Finally, you can build the list with a list comprehension construct l = [str(i) for i in xrange(10)] print " ".join(l) You could also combine the above two lines into one -- that would be shorter, but probably not clearer. Cheers, Gary Herron >Every help is appreciate. > > > From newsgroup_mail... at ...binarystar.org Fri Apr 28 02:19:50 2006 From: newsgroup_mail... at ...binarystar.org (*binarystar*) Date: Fri, 28 Apr 2006 16:19:50 +1000 Subject: append function problem? In-Reply-To: <1146196184.408569.197960@i40g2000cwc.googlegroups.com> References: <1146196184.408569.197960@i40g2000cwc.googlegroups.com> Message-ID: # Try This seed = [2, 3, 4, 5] next = [7] seed1 = seed + next randomtalk at gmail.com wrote: > hello, recently i tried to use list.append() function in seemingly > logical ways, however, i cannot get it to work, here is the test code: > >>>> seed = [2, 3, 4, 5] >>>> next = 7 >>>> seed1 = seed.append(next) >>>> seed1 >>>> print(str(seed1)) > None >>>> def test(lst): > ... print(str(lst)) > ... >>>> test(seed.append(next)) > None > > I'm using Activestate python (latest) on win xp sp2.. > > I'm not sure why seed1 and the function doesn't recognize the list.. > > If anyone can point out where i'm going wrong would be much > appreciated! > Thanks in advance! > From shejo284 at gmail.com Mon Apr 24 08:50:56 2006 From: shejo284 at gmail.com (Sheldon) Date: 24 Apr 2006 05:50:56 -0700 Subject: GRIB to images Message-ID: <1145883056.639668.214920@t31g2000cwb.googlegroups.com> Hi, I am interesseted on reading some GRIB files using python and then converting the fields to gif images. Does anyone know if this is possible or have a program that does this? /Sheldon From imecs2006 at iaeng.org Tue Apr 4 11:55:56 2006 From: imecs2006 at iaeng.org (imecs2006 at iaeng.org) Date: 4 Apr 2006 08:55:56 -0700 Subject: Final Call for Papers: IAENG International Workshop on Software Engineering (in IMECS 2006) Message-ID: <1144166155.974502.242090@u72g2000cwu.googlegroups.com> Final CFP From: IAENG: International Association of Engineers (http://www.iaeng.org) Engineering Letters (http://www.engineeringletters.com) The 2006 IAENG International Workshop on Software Engineering (Part of The International MultiConference of Engineers and Computer Scientists IMECS 2006) IMECS 2006: 20-22 June, 2006, Hong Kong http://www.iaeng.org/IMECS2006/IWSE2006.html The IWSE'06 workshop is held as part of the International MultiConference of Engineers and Computer Scientists 2006. The IMECS 2006 is organized by the International Association of Engineers (IAENG), and serves as good platforms for the engineering community members to meet with each other and to exchange ideas. Extended version of the papers under this workshop can be included in the special issue of our journal Engineering Letters. And, further extended version can also be included in a book called "Current Trends in Software Engineering " to be published by IAENG. The IMECS 2006 multiconference has the focus on the frontier topics in the theoretical and applied engineering and computer science subjects. It consists of 14 workshops (see the details at IMECS website: www.iaeng.org/IMECS2006). The multiconference serves as good platforms for the engineering community members of different disciplines to meet with each other and to exchange ideas. The current conference committee of the IMECS 2006 includes over 140 workshop co-chairs and committee members of mainly research center heads, department heads, professors, research scientists from over 20 countries, while a few of the committee members are also experienced software development directors and engineers. All submitted papers will be under peer review and accepted papers will be published in the conference proceeding (ISBN: 988-98671-3-3). The abstracts will be indexed and available at major academic databases. The Technology Research Databases (TRD) of CSA (Cambridge Scientific Abstracts), DBLP and Computer Science Bibliographies have promised to index the print proceeding in advance of its publication. And after the publication of the proceeding, print copies will also be sent to databases like IEE INSPEC, Engineering Index (EI) and ISI Thomson Scientific for indexing. The accepted papers will also be considered for publication in the special issues of the journal Engineering Letters. Some participants may also be invited to submit extended version of their conference papers for considering as book chapters (soon after the conference). The topics of the workshop include, but not limited to, the following: Software requirements engineering Software architecture design Software reusable components Software testing and analysis Software processes and workflows Software safety, security and reliability Software maintenance Reverse engineering Grid software Software economics Distribution systems Programming languages Embedded software systems And their applications ========= Submission: Prospective authors are invited to submit their draft paper in abstract format (one page) or in full paper format to imecs at iaeng.org by 12 March, 2006. The submitted file can be in MS Word format, PS format, or PDF formats. The first page of the draft paper should include: ? Title of the paper; ? Name, affiliation and e-mail address for each author; ? A maximum of 5 keywords of the paper; Also, the name of the workshop session that the paper is being submitted to should be stated in the email. ============= Important Dates: Proposals for special conference sessions and tutorials deadline: 30 December, 2005 Draft Manuscript / Abstract Submission Deadline (extended): 6 April, 2006 Camera-Ready papers & Pre-registration Due (extended): 13 April, 2006 IMECS 2006: 20-22 June, 2006 More details about the IWSE 2006 can be found at: http://www.iaeng.org/IMECS2006/IWSE2006.html IWSE Workshop Co-chairs and Committee Members: Chin-Chen Chang IEEE Fellow, IEE Fellow Chair Professor in Department of Information Engineering and Computer Science, Feng Chia University, Taiwan Zonghua Gu (co-chair) Assistant Professor Dept. of Computer Science, Hong Kong University of Science and Technology, HK Pao-Ann Hsiung Associate Professor, Institute of Computer Science and Information Engineering National Chung Cheng University, Taiwan Quah Tong Seng (co-chair) Professor of Information Communication Institute of Singapore (ICIS) Nanyang Technological University, Singapore Chen-Hua She (co-chair) Assistant Professor, Department of Mechanical and Automation Engineering Da-Yeh University, Taiwan ******** It will be highly appreciated if you can circulate these calls for papers to your colleagues. From felipe.lessa at gmail.com Sun Apr 16 19:29:59 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Sun, 16 Apr 2006 20:29:59 -0300 Subject: filling today's date in a form In-Reply-To: References: Message-ID: <1145230199.14257.3.camel@kenshin.CASA> Em Dom, 2006-04-16 ?s 19:22 -0400, Kun escreveu: > i have a form Which kind of form? Which toolkit? > which takes in inputs for a mysql query. one of the inputs > is 'date'. normally, a user has to manually enter a date, Enter the date in which kind of control? > but i am > wondering if there is a way to create a button which would automatically > insert today's date in the date form field if the user chooses to use > today's date. Almost 100% sure that there is, but I can't tell you if or how if you don't tell us how you are doing what you are doing. -- Felipe. From floyd at apaflo.com Wed Apr 12 15:09:29 2006 From: floyd at apaflo.com (Floyd L. Davidson) Date: Wed, 12 Apr 2006 11:09:29 -0800 Subject: symbolic links, aliases, cls clear References: <1143672131.167324.36920@i39g2000cwa.googlegroups.com> <1144844223.094969.82870@t31g2000cwb.googlegroups.com> <87r7430x2t.fld@apaflo.com> Message-ID: <87ek021uhi.fld@apaflo.com> Keith Thompson wrote: >floyd at apaflo.com (Floyd L. Davidson) writes: >> af.dingo at gmail.com wrote: >>>If I may recommend an alternative, >>> >>>print "\033[H\033[J" >>> >>>the ansi sequence to clear the screen. >> >> Or so you would hope (however, that is *not* what you have listed!). >> >> Unfortunately, it is poor practice to hard code such sequences. >> Instead the proper sequence should be obtained from the >> appropriate database (TERMINFO or TERMCAP), and the easy way to >> do that is, >> >> tput clear > >(Or "clear".) But /clear/ merely uses "tput clear". >On the other hand, I think it's been at least a decade since I've used >a terminal or emulator that's not VT100-compatible (i.e., accepts ANSI >control sequences). > >Of course, I'll run into one the day after I start writing code that >depends on that assumption. However, if you check out the various TERMINFO database entries for an assortment of "VT100-compatible" terminals, you *will* find variation! Plus, if a user has customized a terminal database, for who knows what reason... -- Floyd L. Davidson Ukpeagvik (Barrow, Alaska) floyd at apaflo.com From sjmachin at lexicon.net Tue Apr 25 07:21:23 2006 From: sjmachin at lexicon.net (John Machin) Date: Tue, 25 Apr 2006 21:21:23 +1000 Subject: Counting elements in a list wildcard In-Reply-To: <1145962281.870457.161150@j33g2000cwa.googlegroups.com> References: <1145921582.526072.120480@u72g2000cwu.googlegroups.com> <1145953610.077361.320290@y43g2000cwc.googlegroups.com> <444DEEC8.7000001@lexicon.net> <1145962281.870457.161150@j33g2000cwa.googlegroups.com> Message-ID: <444e064c$1@news.eftel.com> On 25/04/2006 8:51 PM, Iain King wrote: > John Machin wrote: >> On 25/04/2006 6:26 PM, Iain King wrote: >>> hawkesed wrote: >>>> If I have a list, say of names. And I want to count all the people >>>> named, say, Susie, but I don't care exactly how they spell it (ie, >>>> Susy, Susi, Susie all work.) how would I do this? Set up a regular >>>> expression inside the count? Is there a wildcard variable I can use? >>>> Here is the code for the non-fuzzy way: >>>> lstNames.count("Susie") >>>> Any ideas? Is this something you wouldn't expect count to do? >>>> Thanks y'all from a newbie. > > snip > >>> steven = re.compile("Ste(v|ph|f)(e|a)n") >> What about Steffan, Etienne, Esteban, Istv?n, ... ? >> > > well, obviously these could be included: > "(Ste(v|ph|f)(e|a)n|Steffan|Etienne|Esteban)", but the OP never said he > wanted to translate anything into another language. Neither did I. But if you have to cope with a practical situation like where the birth certificate says Istv?n and the job application says Steven and the foreman calls him Steve, you won't be stuffing about with hand-crafted REs, one per popular given name. Could be worse: the punter could have looked up a dictionary and changed his surname from Kov?cs to Smith; believe me -- it happens. Oh and if you cast your net as wide as the Pacific islands, chuck in Sitiveni. That's enough examples. We won't go near Benjamin :-) From reply.in.the.newsgroup at my.address.is.invalid Tue Apr 18 14:38:31 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Tue, 18 Apr 2006 20:38:31 +0200 Subject: Missing interfaces in Python... References: <1145306373.781129.305840@z34g2000cwc.googlegroups.com> <1145382654.423527.265160@v46g2000cwv.googlegroups.com> Message-ID: olsongt at verizon.net: >If it looks like a duck, and quacks like a duck, then for all practical >purposes it supports the 'duck' interface. The problem with that of course, is that there's much more to being a duck than being called 'duck'. public interface JarFile { void explode(); } public interface NuclearBomb { void explode(); } http://www.beust.com/weblog/archives/000269.html -- Ren? Pijlman From felipe.lessa at gmail.com Sat Apr 1 06:12:25 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Sat, 01 Apr 2006 08:12:25 -0300 Subject: Should any() and all() take a key= argument? In-Reply-To: References: Message-ID: <1143889945.3990.1.camel@kenshin> Em S?b, 2006-04-01 ?s 20:44 +1000, Steven D'Aprano escreveu: > Here's another way of doing it: > > lst = [2, 4, 42] > any(map(lambda x: x==42, lst)) In fact, as we're talking about Python 2.5 anyway, it would be better not to waste memory and use: any(x == 42 for x in lst) -- Felipe. From eoinrogers at gmail.com Sat Apr 8 11:34:05 2006 From: eoinrogers at gmail.com (Byte) Date: 8 Apr 2006 08:34:05 -0700 Subject: Working with decimal points In-Reply-To: <1144510250.788190.317860@i39g2000cwa.googlegroups.com> References: <1144509666.471858.55160@v46g2000cwv.googlegroups.com> <1144510250.788190.317860@i39g2000cwa.googlegroups.com> Message-ID: <1144510445.223313.247010@u72g2000cwu.googlegroups.com> That dosnt work either: sum = 0.1+1/4 print sum Just returns 0.1 From luigipaioro at libero.it Mon Apr 3 11:36:50 2006 From: luigipaioro at libero.it (Luigi) Date: 3 Apr 2006 08:36:50 -0700 Subject: can I get the index number in for x in y loop? References: <1144078372.411795.21570@i39g2000cwa.googlegroups.com> Message-ID: <1144078610.231423.38670@v46g2000cwv.googlegroups.com> Try this: >>> a='String' >>> i=0 >>> for x in a: ... print i, x ... i+=1 ... 0 S 1 t 2 r 3 i 4 n 5 g From paul at boddie.org.uk Fri Apr 7 13:03:49 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 7 Apr 2006 10:03:49 -0700 Subject: UnicodeDecodeError help please? References: Message-ID: <1144429429.350233.212330@g10g2000cwb.googlegroups.com> Robin Haswell wrote: > Okay I'm getting really frustrated with Python's Unicode handling, I'm > trying everything I can think of an I can't escape Unicode(En|De)codeError > no matter what I try. If you follow a few relatively simple rules, the days of Unicode errors will be over. Let's take a look! > Could someone explain to me what I'm doing wrong here, so I can hope to > throw light on the myriad of similar problems I'm having? Thanks :-) > > Python 2.4.1 (#2, May 6 2005, 11:22:24) > [GCC 3.3.6 (Debian 1:3.3.6-2)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import sys > >>> sys.getdefaultencoding() > 'utf-8' Note that this only specifies the encoding assumed to be used in plain strings when such strings are used to create Unicode objects. For some applications this is sufficient, but where you may be dealing with many different character sets (or encodings), having a default encoding will not be sufficient. This has an impact below and in your wider problem. > >>> import htmlentitydefs > >>> char = htmlentitydefs.entitydefs["copy"] # this is an HTML © - a copyright symbol > >>> print char > ? It's better here to use repr(char) to see exactly what kind of object it is (or just give the name of the variable at the prompt). For me, it's a plain string, despite htmlentitydefs defining the each name in terms of its "Unicode codepoint". Moreover, for me the plain string uses the "Latin-1" (or more correctly iso-8859-1) character set, and I imagine that you get the same result. > >>> str = u"Apple" > >>> print str > Apple > >>> str + char > Traceback (most recent call last): > File "", line 1, in ? > UnicodeDecodeError: 'utf8' codec can't decode byte 0xa9 in position 0: unexpected code byte Here, Python attempts to make a Unicode object from char, using the default encoding (which is utf-8) and finds that char is a plain string containing non-utf-8 character values, specifically a single iso-8859-1 character value. It consequently complains. This is quite unfortunate since you probably expected Python to give you the entity definition either as a Unicode object or a plain string of your chosen encoding. Having never used htmlentitydefs before, I can only imagine that it provides plain strings containing iso-8859-1 values in order to support "legacy" HTML processing (given that semi-modern HTML favours &#xx; entities, and XHTML uses genuine character sequences in the stated encoding), and that getting anything other than such strings might not be particularly useful. Anyway, what you'd do here is this: str + unicode(char, "iso-8859-1) Rule #1: if you have plain strings and you want them as Unicode, you must somewhere state what encoding those strings are in, preferably as you convert them to Unicode objects. Here, we can't rely on the default encoding being correct and must explicitly state a different encoding. Generally, stating the encoding is the right thing to do, rather than assuming some default setting that may differ across environments. Somehow, my default encoding is "ascii" not "utf-8", so your code would fail on my system by relying on the default encoding. [...] > Basically my app is a search engine - I'm grabbing content from pages > using HTMLParser and storing it in a database but I'm running in to these > problems all over the shop (from decoding the entities to calling > str.lower()) - I don't know what encoding my pages are coming in as, I'm > just happy enough to accept that they're either UTF-8 or latin-1 with > entities. Rule #2: get your content as Unicode as soon as possible, then work with it in Unicode. Once you've made your content Unicode, you shouldn't get UnicodeDecodeError all over the place, and the only time you then risk an UnicodeEncodeError is when you convert your content back to plain strings, typically for serialisation purposes. Rule #3: get acquainted with what kind of encodings apply to the incoming data. If you are prepared to assume that the data is either utf-8 or iso-8859-1, first try making Unicode objects from the data stating that utf-8 is the encoding employed, and only if that fails should you consider it as iso-8859-1, since an utf-8 string can quite happily be interpreted (incorrectly) as a bunch of iso-8859-1 characters but not vice versa; thus, you have a primitive means of validation. > Any help would be great, I just hope that I have a brainwave over the > weekend because I've lost two days to Unicode errors now. It's even worse > that I've written the same app in PHP before with none of these problems - > and PHP4 doesn't even support Unicode. Perhaps that's why you never saw any such problems, but have you looked at the quality of your data? Paul From steve at REMOVETHIScyber.com.au Fri Apr 14 06:46:25 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Fri, 14 Apr 2006 20:46:25 +1000 Subject: List of all syntactic sugar? References: <1145008451.273827.293680@v46g2000cwv.googlegroups.com> Message-ID: On Fri, 14 Apr 2006 02:54:11 -0700, Bas wrote: > Hi group, > > just out of curiosity, is there a list of all the syntactic sugar that > is used in python? If there isn't such a list, could it be put on a > wiki somewhere? The bit of sugar that I do know have helped me a lot in > understanding the inner workings of python. That kind of depends on what you mean by syntactic sugar. For instance, I wouldn't call any of your examples syntactic sugar. The problem with (e.g.) calling x[i] syntactic sugar for x.__getitem__(i) is that it gets the relationship backwards: x[i] _is_ the syntax, it isn't the sugar. Magic methods like __getitem__ are there as a mechanism to allow custom classes to use the same syntax as built-in classes. However, I would call these syntactic sugar: "hello" " " "world" -> "hello world" # literal string concatenation r'raw strings' x[-n] -> x[len(x)-n] x[:] -> x[0:len(x)] print obj -> sys.stdout.write(str(obj) + '\n') print obj, -> sys.stdout.write(str(obj)) s.find(target) -> try: return s.index(target) except IndexError: return -1 # not really syntax, perhaps "method sugar" is a better name? import a, b, c -> import a; import b; import c raise Exception, string -> raise Exception(string) Of course, one person's syntactic sugar is another person's essential syntactic carbohydrates. -- Steven. From invalidemail at aerojockey.com Fri Apr 7 00:22:04 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 6 Apr 2006 21:22:04 -0700 Subject: updated pre-PEP: The create statement In-Reply-To: References: Message-ID: <1144383724.490548.149840@v46g2000cwv.googlegroups.com> Steven Bethard wrote: > I've updated the PEP based on a number of comments on comp.lang.python. > The most updated versions are still at: > > http://ucsu.colorado.edu/~bethard/py/pep_create_statement.txt > http://ucsu.colorado.edu/~bethard/py/pep_create_statement.html > > In this post, I'm especially soliciting review of Carl Banks's point > (now discussed under Open Issues) which asks if it would be better to > have the create statement translated into: > > = ("", *, **) > > instead of the current: > > = ("", , ) > > The former allows the create statement to be applied to a wider variety > of callables; the latter keeps a better parallel with the class statement. Meh. I don't think the args, kwargs is a good idea at all, and wasn't suggesting that. For this construction not to apply to type objects would be a mistake. I wanted us to consider whether it was a problem for it not to work in certain useful cases (such as dicts), and whether it was deal-breaking, and what to do about it if not. Off the top of my head, a simple way to make this work for both types and dicts is to have a special static method called __make__ (or __create__) that is called by this syntax. For type objects, __make__ is a synonym for __new__. For dict, it can call __new__ with the third argument. Carl Banks From sxn02 at yahoo.com Thu Apr 27 13:15:45 2006 From: sxn02 at yahoo.com (Sori Schwimmer) Date: Thu, 27 Apr 2006 10:15:45 -0700 (PDT) Subject: How to align the text of a Listbox to the right Message-ID: <20060427171545.87820.qmail@web34107.mail.mud.yahoo.com> For a listbox, I would give a width and go with string formatting. In your case, I guess that what I'll do is to limit the width to something acceptable, and show only the tail of the line. Say, your width is w, then I'll show only the last w-4 chars, preceded by '... ' (ellipsis+space). It might be nice to put a label on top of your listbox and dynamically change it's text attribute to the complete version of your selection in the listbox, broken in lines of appropriate length. Hope this helps, Sorin Schwimmer __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From fetofs at gmail.com Mon Apr 17 20:37:58 2006 From: fetofs at gmail.com (Fetofs Ashu) Date: Mon, 17 Apr 2006 21:37:58 -0300 Subject: Schedule Message-ID: I want to create a work schedule; I will have to input some names (in alphabetical order) and the days they can't be working because they have a license, are in vacation or are doing special services. Then, using that information, the program would assign, from a Monday specified onwards, from two weeks to two weeks for a period of 3 months (12 weeks), one person to the morning and two to the afternoon, following the order. However, if the person is not available in any day of that two weeks (input given earlier); it is not allocated to that two weeks of work. Instead, it is still the first of the list (it will be assigned in the future to the next two weeks when there's nothing to impede the work). Then the program will output the schedule to a file or the screen (preferrably a file). I've included an example of only one period. The impediment list is optional, but highly recommended if you can do it.If anyone would want to program it for me, I'd be pleased. However, if you just want to help me, I'll post the code and the problem: day = int(raw_input("day: ")) month = int(raw_input("month: ")) year = int(raw_input("year: ")) for week in range(5): if day in calendar.monthcalendar(ano, mes)[week]: startweek = week def definsemana(): monthcalendar = calendar.monthcalendar(year, month) t1s = monthcalendar[startweek] if t1s[-1] == 0: startweek = 0 if month < 12: month += 1 for i in range(7): if t1s[i] == 0: t1s[i] = calendar.monthcalendar(year, month)[startweek][i] startweek = 1 else: month = 2 year += 1 for day in t1s: print day, '\t', This SHOULD get the day specified and output the week following it, however it seems that it's outputting the first week of the month, regardless of the input date (try 26 December 2005 as an example). Where's the problem? -------------- next part -------------- An HTML attachment was scrubbed... URL: From Serge.Orlov at gmail.com Mon Apr 17 15:21:17 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 17 Apr 2006 12:21:17 -0700 Subject: How protect proprietary Python code? (bytecode obfuscation?, what better?) In-Reply-To: <1145293384.791678.14450@v46g2000cwv.googlegroups.com> References: <1145293384.791678.14450@v46g2000cwv.googlegroups.com> Message-ID: <1145301677.615715.56600@g10g2000cwb.googlegroups.com> seberino at spawar.navy.mil wrote: > How can a proprietary software developer protect their Python code? > People often ask me about obfuscating Python bytecode. They don't want > people to easily decompile their proprietary Python app. > > I suppose another idea is to rewrite entire Python app in C if compiled > C code > is harder to decompile. > > Any ideas? Shuffle opcode values in random order, recompile Python, recompile stdlib, recompile py2exe (or whatever you use for bundling). It will keep attacker busy for several hours From gry at ll.mit.edu Mon Apr 10 21:36:00 2006 From: gry at ll.mit.edu (gry at ll.mit.edu) Date: 10 Apr 2006 18:36:00 -0700 Subject: how to pipe to variable of a "here document" In-Reply-To: References: <1144641459.230416.104590@v46g2000cwv.googlegroups.com> <87fykmm1bt.fsf@gmail.com> Message-ID: <1144719360.369388.130610@z34g2000cwc.googlegroups.com> http://www.python.org/doc/topics/database/ From fredrik at pythonware.com Thu Apr 6 10:45:35 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 6 Apr 2006 16:45:35 +0200 Subject: urllib.urlencode wrongly encoding ± character References: <1144287250.071811.296390@i39g2000cwa.googlegroups.com><1144315212.179762.108490@t31g2000cwb.googlegroups.com> <1144327797.796852.192050@i40g2000cwc.googlegroups.com> Message-ID: Evren Esat Ozkan wrote: > when I remove "# -*- coding: utf-8 -*-" line from start of the script > it worked properly. So I moved variable decleration to another file and > imported than it worked too. the coding directive controls how *unicode* literals in the *source code* are parsed into unicode string objects. it has absolutely nothing to do with how urlencode works. if would help if you posted a short self-contained code snippet, so we don't have to keep guessing. From bokr at oz.net Sun Apr 23 18:12:01 2006 From: bokr at oz.net (Bengt Richter) Date: Sun, 23 Apr 2006 22:12:01 GMT Subject: Why new Python 2.5 feature "class C()" return old-style class ? References: <1144752553.305591.88050@j33g2000cwa.googlegroups.com> <1144756774.177225.311120@z34g2000cwc.googlegroups.com> <443ba5a9$0$14281$626a54ce@news.free.fr> <1144763398.243329.231380@g10g2000cwb.googlegroups.com> <443bbdbe$0$15517$626a54ce@news.free.fr> Message-ID: <444befc6.251077400@news.oz.net> On Tue, 11 Apr 2006 16:30:10 +0200, bruno at modulix wrote: >looping wrote: >> bruno at modulix wrote: >> >>>looping wrote: >>> >>>>Peter Hansen wrote: >>>> >>>> >>>>>Georg Brandl wrote: >>>>> >>>>> >>>>>>class C(): >>>>>> >>>>>>is meant to be synonymous with is meant by whom, and according to what rationale? >>>>>> >>>>>>class C: >>>>>> >>>>>>and therefore cannot create a new-style class. >>>>> >>>>>I think "looping" understands that, but is basically asking why anyone >>>>>is bothering with a change that involves a part of the language that is >>>>>effectively deprecated. In other words, class(): never used to be >>>>>valid, so why make it valid now? Because it it consistent with passing an empty bases-tuple to type, which is where a non-empty bases-tuple goes. (See more on metaclass logic below). >>>>> >>>>>-Peter >>>> >>>> >>>>Exact. >>>>But I think that if we make "class C():" a synonym of "class >>>>C(object):", it will save lot of keystrokes ;-) >>> +1 >>>Since the class statement without superclass actually creates an >>>old-style class, I'd expect the "class MyClass():" variant to behave >>>the same. Sacrifying readability and expliciteness just to save half a >>>dozen keystrokes is not pythonic IMHO. >>> >> >> >> I don't think readability suffer > >It does. The statement "class X():" imply there's no superclass, so it >definitiveley should behave the same as "class X:". > I'm not sure what you mean by "no superclass," comparing >>> class X: pass ... >>> x = X() >>> type(x).mro() [, ] with >>> class Y(object): pass ... >>> y = Y() >>> type(y).mro() [, ] The way I look at it, in new-style-capable Python, class X: pass is really effectively sugar for class X: __metaclass__ = types.ClassType and class X(bases): pass is sugar for class X(bases): __metaclass__ = type so class X(): pass ought to be sugar for class X(): __metaclass__ = type I.e., "old-style classes" really inherit methods from a metaclass that overrides the methods of object, so that new-style descriptor logic can be tweaked to provide the old behaviors for classes not having type as metaclass. >> and expliciteness could sometimes be >> sacrified to simplify the life of developer: ex "abcd"[0:3] -> >> "abcd"[:3]. > >Here there's no ambiguity. > >> And for newbies, the somewhat magic behavior of the "object" superclass >> is not so clear even that it is very explicit. > >There's no magic involved here. And I really doubt that having >inconsistant behaviour for "class X():" wrt/ "class X:" will help here. > Again, IMO any bases-tuple including empty should be sugar for __metaclass__ = type, i.e., class X(): pass should be consistent with the empty parens in X = type("X",(),{}), not with the backwards-compatibility cleverness (really) of effectively switching default metaclass to X = types.ClassType("X",(),{}) using an empty and valid base class tuple as a flag for the switcheroo. Note that the code erroneously creates an empty tuple for class X:pass, as if it were class X():pass. (IMO the proper way to indicate the you don't have a tuple is to use None or some other sentinel, not abuse a perfectly legal tuple value). >>> dis.dis(compile('class X:pass','','exec')) 1 0 LOAD_CONST 0 ('X') <<--+-- ought to be LOAD_CONST 0 (None) 3 BUILD_TUPLE 0 <<--' 6 LOAD_CONST 1 () 9 MAKE_FUNCTION 0 12 CALL_FUNCTION 0 15 BUILD_CLASS 16 STORE_NAME 0 (X) 19 LOAD_CONST 2 (None) 22 RETURN_VALUE vs code for class x(something):pass >>> dis.dis(compile('class X(object):pass','','exec')) 1 0 LOAD_CONST 0 ('X') 3 LOAD_NAME 0 (object) 6 BUILD_TUPLE 1 9 LOAD_CONST 1 () 12 MAKE_FUNCTION 0 15 CALL_FUNCTION 0 18 BUILD_CLASS 19 STORE_NAME 1 (X) 22 LOAD_CONST 2 (None) 25 RETURN_VALUE IMO generating an empty tuple for class X():pass is a natural variation of the immediately above. What is un-natural is using an empty tuple as a logical flag for old-style classes (implementing the latter by selecting types.ClassType as the metaclass instead of type) for what would othewise work perfectly normally with the default metaclass of type. Code generation would need to provide something other than an empty tuple on the stack for class X:pass (IWT None would work?) as the logic flag for old-style classes, and build_class in ceval.c would have to be changed to recognize the new flag value (None?) for calling types.ClassType, and pass tuples (including empty) through to type. >> When I write script I don't use new-style class > >You should. > >> cause is bother me to >> type "(object)" when I don't need their features. so for now put __metaclass__ = type once at the top of your module source, and all your class X: ... will be interpreted as class X: __metaclass__ = type ... instead of implicitly as class X: __metaclass__ = types.ClassType ... > >Please repeat this 101 times each morning: >"thou shall not use old-style classes for they are deprecated". > >(snip) > >> So this new syntax is a good way to boost their uses without bother >> with compatibility of existing code IMHO. > >It's mostly a good way to add inconsistency and confusion to a situation >that's already confusing enough for newbies. I don't agree with your idea of inconsistency. IMO it would be better to explain that a legal basetuple value (empty tuple) is currently being abused as a logical flag to call types.ClassType(clsname, basestuple, clsdict) instead of type(clsname, basestuple, clsdict), and explain that it will be corrected, so that class X():pass will now call the latter, consistent with class X(bases):pass. Bottom line: IMO class C():pass should create a new-style class, and the parens serve well as a reminder of which kind it is, whether empty or not, until py3k. I.e., make it easy for newbies: parens means new-style, no parens means old-style, until py3k. Pontificating pushes my counter-pontificating button; that's the only explanation I have for doing this. I was going to stop wasting time, but find myself unable as yet fully to abandon scanning clp and python-dev ;-/ Regards, Bengt Richter From paul at boddie.org.uk Wed Apr 5 06:14:35 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 5 Apr 2006 03:14:35 -0700 Subject: Python Decompilers? References: <1144194130.731253.170930@t31g2000cwb.googlegroups.com> Message-ID: <1144232075.368019.147340@z34g2000cwc.googlegroups.com> flamesrock wrote: > > Are there any good decompilers for python? I've had some success with decompyle, which seems to be principally available as a Debian package, for which the sources can be obtained here: http://packages.debian.org/stable/source/decompyle Paul From gaz082 at gmail.com Fri Apr 21 19:22:32 2006 From: gaz082 at gmail.com (Gaz) Date: 21 Apr 2006 16:22:32 -0700 Subject: Pythonesque interface. In-Reply-To: <1145656794.388937.60580@e56g2000cwe.googlegroups.com> References: <1145639147.524042.260220@z34g2000cwc.googlegroups.com> <4asil8FuicdvU1@uni-berlin.de> <1145640417.247970.116480@v46g2000cwv.googlegroups.com> <1145656794.388937.60580@e56g2000cwe.googlegroups.com> Message-ID: <1145661752.254875.232980@i40g2000cwc.googlegroups.com> OP? From __peter__ at web.de Fri Apr 7 09:25:32 2006 From: __peter__ at web.de (Peter Otten) Date: Fri, 07 Apr 2006 15:25:32 +0200 Subject: performance degradation when looping through lists References: <4436575e$0$11070$9b4e6d93@newsread4.arcor-online.net> Message-ID: Joachim Worringen wrote: > I need to process large lists (in my real application, this is to parse > the content of a file). I noticed that the performance to access the > individual list elements degrades over runtime. > > This can be reproduced easily using this code: > > import time > > N=100000 > p=10000 > > A=[] > for i in range(N): > A.append(str(i)) > > j = 0 > t = time.clock() > for i in range(len(A)): > j += int(A[i]) > if i % p == 0: > t = time.clock() - t > print t > > (the string conversion only servers to increase the duration of each > iteration; you can observer the same effect with ints, too). > > When running this, I get output like this: > 0.0 > 0.37 > 0.03 > 0.4 > 0.06 > 0.43 > 0.09 > 0.46 > 0.13 > 0.49 > > I use Python 2.3.4 (#1, Sep 3 2004, 12:08:45) > [GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-110)] on linux2 > > I wonder why > 1. The execution times alternate between "fast" and "slow" (I observe the > same effect in my much more complex application) Your timing code is buggy. Change it to import time N=100000 p=10000 A=[] for i in range(N): A.append(str(i)) j = 0 start = time.clock() for i in range(len(A)): j += int(A[i]) if i % p == 0: end = time.clock() print end - start start = end Does the problem persist? I hope not. Peter From duncan.booth at invalid.invalid Thu Apr 27 16:03:36 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 27 Apr 2006 20:03:36 GMT Subject: OOP techniques in Python References: <1146158190.320947.108480@t31g2000cwb.googlegroups.com> <4I6dnWIRt762kMzZnZ2dnUVZ_sOdnZ2d@comcast.com> Message-ID: Philippe Martin wrote: > Steven Bethard wrote: >> [Please don't top-post] > > OK I won't, is that a general rule? (I've been top posting for quite some > time now and it is the first time I see that warning) Yes. Other suggestions you might get are not to bottom post, and certainly not (as you did elsewhere) to post your response as a signature (i.e. following a line containing only two dashes and a space). The accepted way to follow up is to trim the post to which you are responding so as to maintain sufficient context to make the post intelligible on its own, but not to quote the entire post: most newsreader programs will help you in this by either warning or indeed refusing to post responses which have too many quoted lines compared with new content. It is perfectly reasonable if you are making several points to intersperse your comments with other quoted sections. Some newsgroups use a different convention and expect top-posting without trimming of the quoted posts, but these very much are in the minority. From sjmachin at lexicon.net Tue Apr 11 16:46:15 2006 From: sjmachin at lexicon.net (John Machin) Date: 11 Apr 2006 13:46:15 -0700 Subject: RegExp question References: <1144781090.622493.252460@t31g2000cwb.googlegroups.com> Message-ID: <1144788374.953808.184320@i39g2000cwa.googlegroups.com> Precise? The OP asked for "tokens". #>>> re.search(r"(and|or|xor)\s*#", "a = the_operand # gotcha!") #<_sre.SRE_Match object at 0x00AE6620> Try this: #>>> re.search(r"\b(and|or|xor)\s*#", "a = the_operand # should fail") #>>> re.search(r"\b(and|or|xor)\s*#", "and # OK") #<_sre.SRE_Match object at 0x00AE6E60> #>>> re.search(r"\b(and|or|xor)\s*#", "blah blah and # OK") #<_sre.SRE_Match object at 0x00AE66E0> From kent at kentsjohnson.com Tue Apr 11 07:02:33 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Tue, 11 Apr 2006 07:02:33 -0400 Subject: Sorting a list of objects by multiple attributes In-Reply-To: <1144718963.906712.131510@t31g2000cwb.googlegroups.com> References: <1144718377.331845.56390@z34g2000cwc.googlegroups.com> <1144718963.906712.131510@t31g2000cwb.googlegroups.com> Message-ID: <443b874e$1_3@newspeer2.tds.net> gry at ll.mit.edu wrote: > For multiple keys the form is quite analogous: > > L.sort(key=lambda i: (i.whatever, i.someother, i.anotherkey)) > > I.e., just return a tuple with the keys in order from your lambda. > Such tuples sort nicely. In Python 2.5 you can do this with operator.attrgetter(): L.sort(key=operator.attrgetter('whatever', 'someother', 'anotherkey')) Kent From qscomputing at gmail.com Fri Apr 28 06:55:57 2006 From: qscomputing at gmail.com (qscomputing at gmail.com) Date: 28 Apr 2006 03:55:57 -0700 Subject: Non-web-based templating system Message-ID: <1146221757.653214.115090@g10g2000cwb.googlegroups.com> Hi, I'm creating a small application in Python that uses lists and dictionaries to create a rudimentary database. I'd like to create some "fill-in-the-blanks" reports from this data, ideally by taking an RTF or plaintext file as a template and replacing placeholder tags with my data. Are there any good pre-written systems that would allow me to do this? Thanks, - QS Computing. From mateom at gmail.com Tue Apr 18 15:48:48 2006 From: mateom at gmail.com (Mateo) Date: 18 Apr 2006 12:48:48 -0700 Subject: Mouse control in OS X Message-ID: <1145389728.419328.109680@i40g2000cwc.googlegroups.com> Hi, I'd like to be able to use python to control the mouse cursor in OS X. ( i.e. programmatically move it around, click things, etc...) Anyone know the best way to do it on a Mac? Thanks. From cfbolz at gmx.de Mon Apr 3 06:08:58 2006 From: cfbolz at gmx.de (Carl Friedrich Bolz) Date: Mon, 03 Apr 2006 12:08:58 +0200 Subject: Obtaining the Python Control Flow Graph In-Reply-To: <1144041360.431388.187650@i40g2000cwc.googlegroups.com> References: <1144041360.431388.187650@i40g2000cwc.googlegroups.com> Message-ID: <4430F43A.6070701@gmx.de> Hi! brianlum at gmail.com wrote: > I have been looking for a good way to convert python code into a > control flow graph. > > I know of Python functions that will convert an expression into an > abstract syntax tree (i.e. ast = parser.expr('(x+5)*5') then t = > ast.totuple() then t), but I am not sure how to obtain a CFG. > > I've gone through the compiler and it has code that converts the AST > into a CFG (described here: > http://www.python.org/doc/peps/pep-0339/#ast-to-cfg-to-bytecode). > Basically, PyAST_Compile() in Python/compile.c coverts the AST to a CFG > and outputs final bytecode from the CFG by calling two functions: > PySymtable_Build() in Python/symtable.c and compiler_mod() in > Python/compile.c. PySymtable_Build() will build a symtable and > compiler_mod() will create the CFG. > > PyPy also offers a way to obtain a control flow graph: > http://codespeak.net/pypy/dist/pypy/doc/objspace.html#the-flow-model (Disclaimer: I am a PyPy developer) This works quite well in most cases but not in all, e.g. generators are not supported. It has other problems: The result will be (due to the used approach) in SSA form, which might be good or bad, depending on what you want. I don't know the CPython compiler well enough to say whether it is easy to get a CFG out of it. I know of no other easy method to get a CFG graph from Python code. > I was wondering if anyone had any advice on the best way to obtain a > control flow graph. I need the control flow graph because I am trying > figure out if there is a way to bound the integer ranges and list > lengths at compile time. This might be quite hard, for generic Python code. You might possibly (depending again on what your exact plans are) also look into the type inference part of PyPy: http://codespeak.net/pypy/dist/pypy/doc/translation.html#the-annotation-pass Feel free to also contact the PyPy mailing list (pypy-dev at codespeak.net) if you have PyPy-specific questions. Cheers, Carl Friedrich Bolz From fredrik at pythonware.com Sun Apr 2 15:24:03 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 2 Apr 2006 21:24:03 +0200 Subject: Assignment in a while? References: <123071lnngm15da@corp.supernews.com><1144004544.270588.24720@t31g2000cwb.googlegroups.com> <12308kqngr3m5b7@corp.supernews.com> Message-ID: "none <"@bag.python.org> wrote: > So it seems that I stumbled on the idiomatic way of doing this then. > Well, as they say, "When in Rome..." :). Thanks for pointing out the > FAQ. I'll be reading up on it. the idiomatic way to loop in Python is to use iterators/generators. if you have a callable that fetches data from some resource and returns a "sentinel" when you get to the end, you can use the iter function to turn it into an iterator: >>> help(iter) Help on built-in function iter in module __builtin__: iter(...) iter(collection) -> iterator iter(callable, sentinel) -> iterator Get an iterator from an object. In the first form, the argument must supply its own iterator, or be a sequence. In the second form, the callable is called until it returns the sentinel. given this, your loop can be written: for result in iter(std.fetchone, None): print result From ldo at geek-central.gen.new_zealand Thu Apr 27 03:41:18 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 27 Apr 2006 19:41:18 +1200 Subject: OOP / language design question References: <1145961248.794496.80220@j33g2000cwa.googlegroups.com> <444e0e97$0$2052$626a54ce@news.free.fr> <1145969107.837185.212970@e56g2000cwe.googlegroups.com> Message-ID: In article <1145969107.837185.212970 at e56g2000cwe.googlegroups.com>, "Carl Banks" wrote: >bruno at modulix wrote: >> cctv.star at gmail.com wrote: >> > I was wondering, why you always have to remember to call bases' >> > constructors >> >> >> s/constructors/__init__/ >> >> the __init__() method is *not* the constructor. Object's instanciation >> is a two-stage process: __new__() is called first, then __init__(). >> > >You know, Python's __init__ has almost the same semantics as C++ >constructors (they both initialize something that's already been >allocated in memory, and neither can return a substitute object). I >actually think constructors are misnamed in C++, they should be called >initializers (and destructors finalizers). "Constructor" is also the term used for the corresponding method in Java. Is there any OO language that does not use "constructor" in this sense? I don't think there is one. This is standard OO terminology. From sjmachin at lexicon.net Fri Apr 28 00:06:39 2006 From: sjmachin at lexicon.net (John Machin) Date: Fri, 28 Apr 2006 14:06:39 +1000 Subject: append function problem? In-Reply-To: <1146196184.408569.197960@i40g2000cwc.googlegroups.com> References: <1146196184.408569.197960@i40g2000cwc.googlegroups.com> Message-ID: <445194CF.4040206@lexicon.net> On 28/04/2006 1:49 PM, randomtalk at gmail.com wrote: > hello, recently i tried to use list.append() function in seemingly > logical ways, however, i cannot get it to work, here is the test code: > >>>> seed = [2, 3, 4, 5] >>>> next = 7 >>>> seed1 = seed.append(next) >>>> seed1 >>>> print(str(seed1)) > None (1) Try this: print seed (2) Read the documentation (especially the HEADING and the FIRST sentence): http://docs.python.org/lib/typesseq-mutable.html (3) Work your way through the Python Tutorial; here's the section on lists, which covers your problem: http://docs.python.org/tut/node5.html#SECTION005140000000000000000 >>>> def test(lst): > ... print(str(lst)) > ... >>>> test(seed.append(next)) > None > > I'm using Activestate python (latest) on win xp sp2.. > > I'm not sure why seed1 and the function doesn't recognize the list.. I'm not sure what "doesn't recognize the list" means. > > If anyone can point out where i'm going wrong would be much > appreciated! > Thanks in advance! > From fuzzyman at gmail.com Sat Apr 1 03:37:26 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 1 Apr 2006 00:37:26 -0800 Subject: Python 2.5 licensing: stop this change In-Reply-To: References: Message-ID: <1143880645.973457.105300@t31g2000cwb.googlegroups.com> Steve Holden wrote: > As the only director of the Python Software Foundation to vote against a > recent Board motion to implement the change in licensing terms described in > > http://pyfound.blogspot.com/2006/04/python-25-licensing-change.html > > I would like to place on record my protest against this change. I think > it will harm the Python language and ultimately be counter-productive, > reducing the user base and discouraging open source programmers from > contributing to the code base. > > If you disagree with this proposed change it's not too late to do > something about it. If this change goes ahead it will be the end of > Python as we know it. > Can I ask for clarification. The charge applies to any commercial use of a derivative work based on the Python source code ? Normal applications that use Python, including bunding the standard CPython as an executable, using tools like py2exe, won't be covered. Right ? Does this cover commercial applications that embed the Python interpreter ? (Looks like it will) All the best, Fuzzyman http://www.voidspace.org.uk/python/index.shtml > regards > Steve > -- > Steve Holden +44 150 684 7255 +1 800 494 3119 > Holden Web LLC/Ltd www.holdenweb.com > Love me, love my blog holdenweb.blogspot.com From fredrik at pythonware.com Sat Apr 15 07:17:42 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 15 Apr 2006 13:17:42 +0200 Subject: Why new Python 2.5 feature "class C()" return old-style class ? References: <1144752553.305591.88050@j33g2000cwa.googlegroups.com> <443bbdbe$0$15517$626a54ce@news.free.fr> <443c22d1$0$11341$636a55ce@news.free.fr> <443E4204.2020003@freakmail.de> Message-ID: Wildemar Wildenburger wrote: > But I guess I'll just keep adding the (object) appendix even after that, > so all my class definitions get syntax highlighting. why are you using an IDE that doesn't understand Python syntax ? From rrr at ronadam.com Sat Apr 8 04:20:15 2006 From: rrr at ronadam.com (Ron Adam) Date: Sat, 08 Apr 2006 03:20:15 -0500 Subject: calculating system clock resolution In-Reply-To: References: <1144434899.840346.220780@z34g2000cwc.googlegroups.com> <1144444527.376016.73100@i40g2000cwc.googlegroups.com> <1144453180.713760.12870@v46g2000cwv.googlegroups.com> Message-ID: Steven D'Aprano wrote: > On Fri, 07 Apr 2006 16:39:40 -0700, jUrner wrote: > >> Maybe it was not too clear what I was trying to point out. >> >> I have to calculate the time time.time() requires to return the next >> tick of the clock. >> Should be about 0.01ms but this may differ from os to os. > > I suspect that Python isn't quite fast enough to give an accurate measure > for this, but I could be wrong. >>>> import time >>>> >>>> calc_time_res() > 2.50339508057e-05 >>>> calc_time_res() > 2.59876251221e-05 >>>> calc_time_res() > 2.59876251221e-05 >>>> calc_time_res() > 2.59876251221e-05 >>>> calc_time_res() > 2.40802764893e-05 Trying this on my win xp gives the following. 0.0150001049042 # time.time() 2.23492091872e-006 # time.clock() 2.7936511484e-006 1.95555580388e-006 #<- lowest value for time.clock() 1.95555580388e-006 1.95555580388e-006 3.35238137808e-006 1.95555580388e-006 1.95555580388e-006 1.95555580388e-006 2.23492091872e-006 But I think this is going to vary from system to system as well as what os is used. And it may be effected by other tasks as well so checking multiple times is probably needed. def calc_time_res(): now = time.time start = now() x = start while start == x: x = now() print x - start def calc_time_res2(): now = time.clock start = now() x = start while start == x: x = now() print x - start def calc_time_res3(): now = time.clock r = range(10) times = [now() for x in r] start = times[0] for x in times[1:]: print x-start start = x calc_time_res() print calc_time_res2() print calc_time_res3() From aleaxit at yahoo.com Thu Apr 27 23:15:29 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 27 Apr 2006 20:15:29 -0700 Subject: Type-Def-ing Python References: <1146041765.423121.106840@i39g2000cwa.googlegroups.com> <1hefehe.gyyjap1my3zj0N%aleaxit@yahoo.com> Message-ID: <1hegxcc.10xccas9an4etN%aleaxit@yahoo.com> Aahz wrote: > In article <1hefehe.gyyjap1my3zj0N%aleaxit at yahoo.com>, > Alex Martelli wrote: > > wrote: > > ... > >> Brett Cannon's thesis in which he tweaks the compiler and shows that > >> type-defing python would not help the compiler achieve a 5% performace > >> increase. > >> > >> Brett Cannon, "Localized Type Inference of Atomic Types in Python": > >> http://www.ocf.berkeley.edu/~bac/thesis.pdf > >> > >> I was wondering if anyone had his contact information so that I could > >> might ask him for his source code and try to use type-defing as a > >> bug-finder. > > > >Brett is active on Python-Dev, so post there and you're likely to get a > >response from him -- your subject is not OT for that list, anyway! > > Oh, so this is why we got an off-topic post on python-dev. Shouldn't you > have told him to use Google?... ;-) I don't think that applying type-inferencing to such task as debugging (and possibly applying minor tweaks to Python to help out with that) is OT for python-dev. Alex From bdesth.quelquechose at free.quelquepart.fr Thu Apr 20 22:11:01 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 21 Apr 2006 04:11:01 +0200 Subject: search a string In-Reply-To: References: <9583ed900604201423k5671242en7d4345e695ea7000@mail.gmail.com> <44480380$0$30095$636a55ce@news.free.fr> Message-ID: <444810e2$0$14295$626a54ce@news.free.fr> Carl J. Van Arsdall a ?crit : (snip) > With a file object, to iterate through the lines in a file don't you > have to use readlines()? Nope - no more, should I say. The file object is now an iterable. file.readlines() try and read all the file and returns it as a list. It's ok for small files, but can lead to problem with huge ones... using the file as an iterator, you have a lazy read - just like you would with the older file.readline() idiom: line = f.readline() while line: do_something_with(line) line = f.readline() but with much less hassle : for line in f: do_something_with(line) From g.brandl-nospam at gmx.net Wed Apr 12 12:03:55 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Wed, 12 Apr 2006 18:03:55 +0200 Subject: just one more question about the python challenge In-Reply-To: References: Message-ID: John Salerno wrote: > Georg Brandl wrote: > >> Have you found the file? You'll have to distribute that file bytewise >> in 5 "piles". > > No, I haven't figured out anything for this puzzle. It seems I might > have to change the filename of the image to something else, but I don't > know what. But even after I find the image, I won't know what to do from > there. I don't know what it means to distribute a file bytewise, but if > I knew exactly which modules/functions to use, I'd be more than happy > reading up on them myself. I just hate not knowing where to go to begin > with (even though I know I probably won't know enough about images to > use the right module properly either, but I can try). If you give me the URL of that level, maybe I'll recall what to do. Georg From steve at aol.com Sat Apr 1 05:10:21 2006 From: steve at aol.com (steve) Date: Sat, 1 Apr 2006 18:10:21 +0800 Subject: DO NOT USE JAVA BECAUSE IT IS NOT OPEN SOURCE References: <1143867556.814290.321740@i40g2000cwc.googlegroups.com> Message-ID: On Sat, 1 Apr 2006 13:06:52 +0800, Luc The Perverse wrote (in article ): > wrote in message > news:1143867556.814290.321740 at i40g2000cwc.googlegroups.com... >> Programing Languiges Are Ment to be free. That is why i am starting The >> Coo De Tar thats french for Blow of state it is a flash/java >> alternative and if you are going to use a server side languige use >> Perl,Python or better yet Ruby. What is the point of a languige without >> a standerd and without a open source distrabution. Coo De Tar will be >> released as a api for perl,python and ruby. Java sucks because it IS >> NOT FREE. I AM A GNU GUY I BELEVE THAT SOFTWARE MUST AND SHALL BE >> FREE!!!!!!!!!!!!!! do not use java because it is an oxymoron >> > > Dear Mr Troll, > > There are GNU implementations of JVM and compiler. > > And just because Sun's Java is not GNU does not mean it is not free. > > Now go get a life. > > -- > LTP > >>> > > it's April 1st remember -- NewsGuy.Com 30Gb $9.95 Carry Forward and On Demand Bandwidth From steve at holdenweb.com Sat Apr 1 21:27:26 2006 From: steve at holdenweb.com (Steve Holden) Date: Sat, 01 Apr 2006 21:27:26 -0500 Subject: Python 2.5 licensing: stop this change In-Reply-To: <122t31idovvdc65@corp.supernews.com> References: <122t31idovvdc65@corp.supernews.com> Message-ID: Grant Edwards wrote: > On 2006-04-01, Steve Holden wrote: > >>As the only director of the Python Software Foundation to vote against a >>recent Board motion to implement the change in licensing terms described in >> >> http://pyfound.blogspot.com/2006/04/python-25-licensing-change.html > > > Good one Steve. > > I particularly liked the Comments section. > > :) > Yes, lots of people joined in the spirit of the original post - the comments were added by others. Thanks for pointing them out: I hadn't noticed, having been out all day at a Make Beer Free rally. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd www.holdenweb.com Love me, love my blog holdenweb.blogspot.com From zmason at gmail.com Wed Apr 5 19:18:13 2006 From: zmason at gmail.com (zmason at gmail.com) Date: 5 Apr 2006 16:18:13 -0700 Subject: A way to read shelves quickly? Message-ID: <1144279093.716621.42330@t31g2000cwb.googlegroups.com> I have a collection of about 5M shelves, each consisting of string->int mappings with on the order of 500 entries per shelf. I want to iterate through them rapidly and get the contents of each. But calling items() on each of them is slow - on the order of 1 or 2 seconds. Is there any way I can speed up this process? thanks Zach From brian at rkspeed-rugby.dk Tue Apr 25 06:49:43 2006 From: brian at rkspeed-rugby.dk (Brian Elmegaard) Date: Tue, 25 Apr 2006 12:49:43 +0200 Subject: MinGW and Python References: <1145861223.509630.247350@y43g2000cwc.googlegroups.com> <444C79D7.4060007@v.loewis.de> <444DC62B.7000702@v.loewis.de> Message-ID: "Martin v. L?wis" writes: > It would certainly be possible to distribute a gcc-compiled python. > However, what is the point in doing so? Cygwin already includes > a gcc-compiled Python, for Windows: Interesting. > That is simply not true. Actually, you answered me then too. I misunderstood after reading http://sebsauvage.net/python/mingw.html. Is the information on that page not correct? Has it never been? > You can build the entire Python interpreter with Cygwin (but you > don't need to, because there is a precompiled version), and you can > build extensions for the python.org binary using MingW. Great, then I tend to agree that there is no reason for building it with mingw. -- Brian (remove the sport for mail) http://www.et.web.mek.dtu.dk/Staff/be/be.html http://www.rugbyklubben-speed.dk From deets at nospam.web.de Fri Apr 28 07:22:20 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 28 Apr 2006 13:22:20 +0200 Subject: Non-web-based templating system References: <1146221757.653214.115090@g10g2000cwb.googlegroups.com> Message-ID: <4bec7mF10pfe5U1@uni-berlin.de> qscomputing at gmail.com wrote: > Hi, > > I'm creating a small application in Python that uses lists and > dictionaries to create a rudimentary database. I'd like to create some > "fill-in-the-blanks" reports from this data, ideally by taking an RTF > or plaintext file as a template and replacing placeholder tags with my > data. > Are there any good pre-written systems that would allow me to do this? Maybe the built-in string interpolation is sufficient? print "Hello %(name)s" % dict(name="Peter Pan") diez From pythonic at seehart.com Mon Apr 3 15:42:27 2006 From: pythonic at seehart.com (Ken Seehart) Date: Mon, 03 Apr 2006 12:42:27 -0700 Subject: Registration Code In-Reply-To: References: Message-ID: <44317AA3.7040709@seehart.com> Math wrote: > Hello, > > I wonder if I can ask this particular question here... > I'm writing this piece of Python Software and I'm almost done...:-) > But now I want the end-user to register this software with a > registration code or perhaps something like an evaluation demo version > which expires after some period of time... > Is this the right place to ask or does anybody know where to look for > more on the subject? > > Thanks > One thing I tried some time ago: I encypted the bytecode of a few important functions with a key based on information required from the user. Without the key, these functions can't be decrypted. This is somewhat more secure than just testing the key with an "if" statement since the latter could easily be bypassed by a hacker. To encrypt the function, I saved the bytecode of the target function to a file. Then, in the version to be shipped, I substituted the encrypted version of bytecode for the original bytecode. The rest of the program (including the part that asks for the authentication information) works fine. If the authentication passes, the encrypted function(s) are decrypted. Normally the encrypted functions are never executed of course (if authentication fails, the user is notified). If a hacker bypasses the authentication test, the program will crash when the program attempts to executed the encypted bytecode. How to determine the key depends on your application. You may choose to include hardware serial numbers, for example. - Ken From ldo at geek-central.gen.new_zealand Mon Apr 3 05:21:20 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 03 Apr 2006 21:21:20 +1200 Subject: datetime, tzinfo ... strange conversion? References: Message-ID: In article , Tino Lange wrote: >--> Why is GMT (3) wrong? At a guess, it's because there's nothing in the parameters passed to indicate that daylight saving is currently in effect. Tip: always do your date/time calculations as far as possible in UTC. Only convert to local time at the last possible step, before displaying results to the user. From felipe.lessa at gmail.com Tue Apr 11 21:57:48 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Tue, 11 Apr 2006 22:57:48 -0300 Subject: list.clear() missing?!? In-Reply-To: References: <1144767680.583085.310160@v46g2000cwv.googlegroups.com> <443BE426.20501@v.loewis.de> Message-ID: <1144807068.8392.6.camel@kenshin.CASA> Em Qua, 2006-04-12 ?s 11:36 +1000, Steven D'Aprano escreveu: > On Tue, 11 Apr 2006 19:15:18 +0200, Martin v. L?wis wrote: > > > Felipe Almeida Lessa wrote: > >> I love benchmarks, so as I was testing the options, I saw something very > >> strange: > >> > >> $ python2.4 -mtimeit 'x = range(100000); ' > >> 100 loops, best of 3: 6.7 msec per loop > >> $ python2.4 -mtimeit 'x = range(100000); del x[:]' > >> 100 loops, best of 3: 6.35 msec per loop > >> $ python2.4 -mtimeit 'x = range(100000); x[:] = []' > >> 100 loops, best of 3: 6.36 msec per loop > >> $ python2.4 -mtimeit 'x = range(100000); del x' > >> 100 loops, best of 3: 6.46 msec per loop > >> > >> Why the first benchmark is the slowest? I don't get it... could someone > >> test this, too? > > > > In the first benchmark, you need space for two lists: the old one and > > the new one; > > Er, what new list? I see only one list, x = range(100000), which is merely > created then nothing done to it. Have I missed something? He's talking about the garbage collector. Talking about the GC, do you want to see something *really* odd? $ python2.4 -mtimeit -s 'from gc import collect' 'collect(); x = range(100000); ' 100 loops, best of 3: 13 msec per loop $ python2.4 -mtimeit -s 'from gc import collect' 'collect(); x = range(100000); del x[:]' 100 loops, best of 3: 8.19 msec per loop $ python2.4 -mtimeit -s 'from gc import collect' 'collect(); x = range(100000); x[:] = []' 100 loops, best of 3: 8.16 msec per loop $ python2.4 -mtimeit -s 'from gc import collect' 'collect(); x = range(100000); del x' 100 loops, best of 3: 8.3 msec per loop But in this case I got the answer (I think): - When you explicitly delete the objects, the GC already know that it can be collected, so it just throw the objects away. - When we let the "x" variable continue to survive, the GC has to look at all the 100001 objects to see if they can be collected -- just to see that it can't. Also, IIRC "del x" is slower than "x = []" because removing a name from the namespace is more expensive than just assigning something else to it. Right? > I understood Felipe to be asking, why does it take longer to just create a > list, than it takes to create a list AND then do something to it? I see dead people... ;-) -- Felipe. From onurb at xiludom.gro Fri Apr 7 08:42:06 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 07 Apr 2006 14:42:06 +0200 Subject: performance degradation when looping through lists In-Reply-To: <4436575e$0$11070$9b4e6d93@newsread4.arcor-online.net> References: <4436575e$0$11070$9b4e6d93@newsread4.arcor-online.net> Message-ID: <44365e67$0$7086$626a54ce@news.free.fr> Joachim Worringen wrote: > I need to process large lists (in my real application, this is to parse > the content of a file). Then you probably want to use generators instead of lists. The problem with large lists is that they eat a lot of memory - which can result in swapping . > I noticed that the performance to access the > individual list elements degrades over runtime. I leave this point to gurus, but it may have to do with swapping. Also, this is not real-time, so variations may have to do with your OS tasks scheduler. My 2 cents -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From martin.sand.christensen at gmail.com Sat Apr 8 10:56:53 2006 From: martin.sand.christensen at gmail.com (Martin Christensen) Date: Sat, 08 Apr 2006 16:56:53 +0200 Subject: How can I reduce the number of queries to my PostgreSQL database? References: <1144489087.794505.277930@v46g2000cwv.googlegroups.com> Message-ID: <87fykonmiy.fsf@fangorn.rev.stofanet.dk> >>>>> "SR" == writes: SR> Scenario: I have a python script which creates web page listing SR> all books in the database, and all authors for each book. My SR> python script does essentially three things: SR> 1. retrieve a list of all book_ids and book_titles. SR> 2. for each book_id, query the bookauthors table and retrieve all SR> author names for that book_id. SR> 3. display it all out as an html table on a web page. That's one query, if you're willing to make it advanced enough, although you need to make an aggregate to enable PostgreSQL to concatenate and comma separate author names. However, this aggregate will typically need more than one database function. Such an aggregate could be as follows: CREATE OR REPLACE FUNCTION author_agg_sfunc(TEXT, authors.name%TYPE) RETURNS TEXT AS ' SELECT $1 || '', '' || $2; ' LANGUAGE sql; CREATE OR REPLACE FUNCTION author_agg_ffunc(TEXT) RETURNS TEXT AS ' SELECT trim(trailing '', '' from $1); ' LANGUAGE sql; CREATE AGGREGATE author_agg ( basetype = VARCHAR(100), sfunc = author_agg_sfunc, stype = TEXT, finalfunc = author_agg_ffunc, initcond = '' ); Then you could use it as follows: SELECT author_agg(authors.name), foo, bar FROM authors, writes, books WHERE authors.id = writes.author_id AND writes.book_id = books.id GROUP BY foo, bar; This is the solution that I would use after working nearly a decade with databases. It is neither simple nor obvious to the novice, but it's the Right Way To Do It. For a learning exercise, this is way over the top, but I thought you might benefit from seeing that - so long as you only need information that would reasonably fit in one table on a web page or the equivalent - one query is always enough. Or perhaps that should be One Query Is Always Enough. :-) Learn at your own pace, though, but you might want to keep this in mind for future reference. Martin From kevin.bell at slcgov.com Wed Apr 19 17:04:33 2006 From: kevin.bell at slcgov.com (Bell, Kevin) Date: Wed, 19 Apr 2006 15:04:33 -0600 Subject: send pdf or jpg to printer Message-ID: <2387F0EED10A4545A840B231BBAAC7226082AA@slcimail1.slcgov.com> Does anyone have any suggestions on printing pdf's? These pdf's don't change much, so if it be more straight forward to convert them to jpgs, or another format, then that'd be fine too. Thanks in advanced, Kevin From alexandre_irrthum at yahoo.com Fri Apr 7 09:39:15 2006 From: alexandre_irrthum at yahoo.com (alexandre_irrthum at yahoo.com) Date: 7 Apr 2006 06:39:15 -0700 Subject: ImageDraw line inconsistent ? (repost) Message-ID: <1144417155.889030.47290@j33g2000cwa.googlegroups.com> Hi there, Sorry to repost this, but I didn't get any answer one month ago. In essence, it seems that the ImageDraw line function draws lines one pixel shorter in some circumstances. This could be very annoying for some applications where precise geometry does matter. Below I test this function on a 3x3 image and show schematic representations of obtained images (where o means a drawn pixel) import Image, ImageDraw im = Image.new("L", (3,3)) draw = ImageDraw.Draw(im) draw.line((0,0,2,2), fill=255) im.tostring() Gives: o-- -o- --- So the last pixel of the line is not drawn. Similarly, draw.line((0,2,2,0), fill=255) gives: --- -o- o-- And draw.line((1,0,1,2), fill=255) gives: -o- -o- --- But, surprisingly, draw.line((0,1,2,1), fill=255) gives: --- ooo --- Where the last pixel of the line -is- drawn, as I expected it would be for all lines. This seems to be true for various image sizes and line angles: the last pixel is never drawn unless the line is horizontal. Any clues ? Thanks alex From g.brandl-nospam at gmx.net Wed Apr 5 18:59:01 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Thu, 06 Apr 2006 00:59:01 +0200 Subject: efficiency of range() and xrange() in for loops In-Reply-To: References: Message-ID: Alan Morgan wrote: > In article , > Giovanni Bajo wrote: >>Steve R. Hastings wrote: >> >>>> in Python 2.X, range is defined to return a list. if you start >>>> returning something else, you'll break stuff. >>> >>> Perhaps I'm mistaken here, but I don't see how this optimization could >>> possibly break anything. >> >>Because you assume that the only use-case of range() is within a for-loop. >>range() is a builtin function that can be used in any Python expression. For >>instance: >> >>RED, GREEN, BLUE, WHITE, BLACK = range(5) > > Hmmm, this worked fine when I used xrange as well. Am I missing something? > Obviously there *are* differences, viz: Just _look_ at the objects: >>> range(5) [0, 1, 2, 3, 4] >>> xrange(5) xrange(5) >>> range is giving you a real list, while xrange is giving you an xrange object. Have you tried to slice an xrange object? Or using .append on it? Georg From deets at nospam.web.de Mon Apr 3 12:34:25 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 03 Apr 2006 18:34:25 +0200 Subject: Convertion of Unicode to ASCII NIGHTMARE References: <1144079830.734516.8390@z34g2000cwc.googlegroups.com> Message-ID: <49d197FntisqU1@uni-berlin.de> > Don't. You can't. Those characters don't exist in the ASCII character set. > SQLite 3.0 deals with UTF-8 encoded SQL statements, though. That is not entirely correct - one can, if losing information is ok. The OPs code that normalized UTF-8 to NFKD, an umlaut like ? is transformed to a two-character-sequence basically saying "a with two dots on top". With 'ignore' specified as parameter to the encoder, this should be result in the letter a. Regards, Diez From peter.mosley at talk21.com Sun Apr 23 12:33:37 2006 From: peter.mosley at talk21.com (peter) Date: 23 Apr 2006 09:33:37 -0700 Subject: How I learned Tkinter Message-ID: <1145810017.100862.215950@j33g2000cwa.googlegroups.com> I've been trying to teach myself Tkinter programming over the last few months (in a strictly amateur way), and have made a number of requests for help in this newsgroup and elsewhere. I've now (sort of) got there - in that I have used Tkinter for some programs for personal use - and I've written up my experiences at http://www.aqzj33.dsl.pipex.com/how_i_learned_tkinter/contents.htm In general I found that while Frederik Lundh's tutorial is comprehensive and well written, there is little else around to help the newcomer working without the benefit of more experienced colleagues, and that in places the documentation is too sparse to be of much help. Any thoughts? Is my experience typical? Peter From Serge.Orlov at gmail.com Mon Apr 24 11:19:26 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 24 Apr 2006 08:19:26 -0700 Subject: need a thread to keep a socket connection alive? References: <1145718638.526525.235090@i39g2000cwa.googlegroups.com> <1145885130.140370.166490@t31g2000cwb.googlegroups.com> Message-ID: <1145891966.658138.31310@i40g2000cwc.googlegroups.com> Roy Smith wrote: > Serge Orlov wrote: > > sockobj.settimeout(550) > > [...] > > Also, as other people pointed out, you'd better make buffered socket > > with .makefile() socket method. > > If I understand the docs for the socket module correctly, these two > suggestions are mutually incompatable. Perhaps this restriction was lifted? >>> s = socket.socket() >>> s.settimeout(15) >>> s.connect(("www.python.org", 80)) >>> f = s.makefile() >>> f.readline() Traceback (most recent call last): File "", line 1, in -toplevel- f.readline() File "C:\Python24\lib\socket.py", line 340, in readline data = self._sock.recv(self._rbufsize) timeout: timed out >>> From g.brandl-nospam at gmx.net Thu Apr 13 04:05:26 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Thu, 13 Apr 2006 10:05:26 +0200 Subject: list.clear() missing?!? In-Reply-To: References: <1144870852.886477.238570@u72g2000cwu.googlegroups.com> Message-ID: Duncan Booth wrote: > Peter Hansen wrote: > >>> * learning slices is basic to the language (this lesson shouldn't be >>> skipped) >> >> And yet it doesn't appear to be in the tutorial. I could have missed > Both of these talk about ways to remove slices from a list. Perhaps the > wording could be clearer to make it obvious that they can also be used to > clear a list entirely (using the word 'clear' would certainly help people > Googling for the answer). So maybe 'this can even change the size of the > list or clear it completely' would be a good change for 3.1.4. I added two examples of clearing a list to the section about slice assignment and del. Georg From fatal.serpent at gmail.com Fri Apr 14 19:59:13 2006 From: fatal.serpent at gmail.com (fatalserpent) Date: 14 Apr 2006 16:59:13 -0700 Subject: Help with python output redirection Message-ID: <1145059153.392141.145360@u72g2000cwu.googlegroups.com> Here is the basic code (yes, I know its tiny). x = ['print "x =", x', 'for m in x: print m'] print "x =", x for m in x: print m I want to modify this so it will output to a file called 1. What I want is to have that file direct its output to a file called 2 and 2 direct to 3 and so on. Hopefully this will be an easy-to-answer question. THX in advance. From qscomputing at gmail.com Fri Apr 28 08:53:16 2006 From: qscomputing at gmail.com (qscomputing at gmail.com) Date: 28 Apr 2006 05:53:16 -0700 Subject: Non-web-based templating system References: <1146221757.653214.115090@g10g2000cwb.googlegroups.com> <4bec7mF10pfe5U1@uni-berlin.de> <4452073b$0$23034$626a54ce@news.free.fr> Message-ID: <1146228796.731058.54280@u72g2000cwu.googlegroups.com> Thanks, it looks like empy is what I need. From kylotan at gmail.com Thu Apr 27 04:23:14 2006 From: kylotan at gmail.com (Ben Sizer) Date: 27 Apr 2006 01:23:14 -0700 Subject: Events in Python? In-Reply-To: <1146079344.627176.27280@e56g2000cwe.googlegroups.com> References: <1146065995.016939.187440@i40g2000cwc.googlegroups.com> <1146071232.275024.5310@e56g2000cwe.googlegroups.com> <1146079344.627176.27280@e56g2000cwe.googlegroups.com> Message-ID: <1146126193.558593.157630@e56g2000cwe.googlegroups.com> redefined.horizons at gmail.com wrote: > It seems like Python doesn't have a "standard" implementation of an > event or messaging system. That is really what I was curious about. I > wanted to check before I implemented something of my own. What are you comparing it to? Does Java have standard event or messaging systems? I thought there were only such systems as part of the GUI libraries. Perhaps you're referring to the Observer interface? Sometimes a solution that is necessary in Java would be an overcomplication in Python, and full-blown Observers is probably one such example. -- Ben Sizer From thn at mail.utexas.edu Sun Apr 9 16:02:50 2006 From: thn at mail.utexas.edu (Thomas Nelson) Date: 9 Apr 2006 13:02:50 -0700 Subject: "The World's Most Maintainable Programming Language" In-Reply-To: <44331897$0$12009$c3e8da3@news.astraweb.com> References: <44331897$0$12009$c3e8da3@news.astraweb.com> Message-ID: <1144612970.670345.62000@u72g2000cwu.googlegroups.com> I thought the paragraph about provability was interesting. Presumably the author refers to proofs in the spirit of "A Discipline of Programming" from Djikstra, 1976. Unfortunately, I don't think anyone has writting much about this since the 70s. I'd be interested to learn if anyone's tried to write "weakest precondition" style specifications for python (builtin functions, for, lambda, etc). Or perhaps there's some easier to understand medium? It's worth noting that the author makes proving correctness sound like a trivial task, which of course it's not. Consider def collatz(n,i=0): if n==1: return i elif (n%2)==0: return collatz(n/2,i+1) else: return collatz((3*n+1)/2,i+1) It is currently unknown whether this even terminates in all cases. From sll_noSpamlicious_z_XXX_m at cc.usu.edu Sat Apr 1 20:57:32 2006 From: sll_noSpamlicious_z_XXX_m at cc.usu.edu (Luc The Perverse) Date: Sat, 1 Apr 2006 18:57:32 -0700 Subject: DO NOT USE JAVA BECAUSE IT IS NOT OPEN SOURCE References: <1143867556.814290.321740@i40g2000cwc.googlegroups.com> Message-ID: <8ln3g3xo0c.ln2@loki.cmears.id.au> "steve" wrote in message news:e0ljid01frd at news4.newsguy.com... > On Sat, 1 Apr 2006 13:06:52 +0800, Luc The Perverse wrote > (in article ): > >> wrote in message >> news:1143867556.814290.321740 at i40g2000cwc.googlegroups.com... >>> Programing Languiges Are Ment to be free. That is why i am starting The >>> Coo De Tar thats french for Blow of state it is a flash/java >>> alternative and if you are going to use a server side languige use >>> Perl,Python or better yet Ruby. What is the point of a languige without >>> a standerd and without a open source distrabution. Coo De Tar will be >>> released as a api for perl,python and ruby. Java sucks because it IS >>> NOT FREE. I AM A GNU GUY I BELEVE THAT SOFTWARE MUST AND SHALL BE >>> FREE!!!!!!!!!!!!!! do not use java because it is an oxymoron >>> >> >> Dear Mr Troll, >> >> There are GNU implementations of JVM and compiler. >> >> And just because Sun's Java is not GNU does not mean it is not free. >> >> Now go get a life. >> >> -- >> LTP >> >>>> >> >> > > it's April 1st remember Ah! Thank you -- LTP :) From steve at REMOVETHIScyber.com.au Fri Apr 14 22:09:17 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 15 Apr 2006 12:09:17 +1000 Subject: Help with python output redirection References: <1145059153.392141.145360@u72g2000cwu.googlegroups.com> Message-ID: On Fri, 14 Apr 2006 16:59:13 -0700, fatalserpent wrote: > Here is the basic code (yes, I know its tiny). > > x = ['print "x =", x', 'for m in x: print m'] > print "x =", x > for m in x: print m > > I want to modify this so it will output to a file called 1. What I want > is to have that file direct its output to a file called 2 and 2 direct > to 3 and so on. Hopefully this will be an easy-to-answer question. THX > in advance. >From the shell, you are probably doing something like this: $ python mymodule.py Change it to this: $ python mymodule.py > 2 $ python 2 > 3 $ python 3 > 4 and so on. Alternatively, you can do this: x = ['f = file("2", "w")', 'print >>f, "x =", x', 'for m in x: >>f, print m'] print >>f, "x =", x for m in x: print >>f, m I'll leave changing the file name from "2" to "3" etc. as an exercise for you. -- Steven. From pythor at gmail.com Tue Apr 4 13:14:17 2006 From: pythor at gmail.com (Pythor) Date: 4 Apr 2006 10:14:17 -0700 Subject: how do you use pickle? In-Reply-To: References: <1144167350.837406.172430@i39g2000cwa.googlegroups.com> <1144169459.630621.240510@i40g2000cwc.googlegroups.com> Message-ID: <1144170857.069178.115440@i39g2000cwa.googlegroups.com> John Salerno wrote: > Pythor wrote: > > John Salerno wrote: > >> Pythor wrote: > >>> John Salerno wrote: > >>> > >>>> I'm sorry, but I'm terribly confused. Nothing seems to be working for > >>>> me. I *think* what I need to pickle is an image file, > >>> SNIP > >>> > >>> Hint: Read the source for that page more carefully. > >>> > >> Hmmm...the source doesn't say much. Is there more to do with the source > >> beyond using it to figure out what 'peak hell' means? > > > > Yes... It mentions a whole different file, which you need to use pickle > > on. > > > > Yikes, I even took a second look at that after you said re-read the > source and then I ignored it! Thanks! Whis is why I said carefully ;) I missed it several times myself when I was working on the challenge. From kelvie at ieee.org Fri Apr 21 20:22:20 2006 From: kelvie at ieee.org (Kelvie Wong) Date: Fri, 21 Apr 2006 17:22:20 -0700 Subject: Raising a specific OSError In-Reply-To: <94ccbe710604211710gcce5028t87e387e268ebb6e7@mail.gmail.com> References: <1145659457.805754.129340@u72g2000cwu.googlegroups.com> <44496345.3090407@ilm.com> <94ccbe710604211710gcce5028t87e387e268ebb6e7@mail.gmail.com> Message-ID: <94ccbe710604211722m13f1feb1tbb7bcd7fe956eacb@mail.gmail.com> Looking at the Python docs.. I found this: http://docs.python.org/ext/errors.html """ Another useful function is PyErr_SetFromErrno(), which only takes an exception argument and constructs the associated value by inspection of the global variable errno. The most general function is PyErr_SetObject(), which takes two object arguments, the exception and its associated value. You don't need to Py_INCREF() the objects passed to any of these functions. """ So, in a C extension, to raise a a specific OSError... errno = ENOENT; PyErr_SetFromErrno(PyExc_OSError); should work... On 4/21/06, Kelvie Wong wrote: > I do not see the point in doing so (why not just copy+paste that > string?), but the errno (specifically ENOENT) corresponds to the > POSIX.1 error number, and the string "No such file or directory" is > done in C via strerror(ENOENT); (check errno(3) and strerror(3)). > > I doubt there is something that does this in the standard library > (just checked, there's an errno module, but it is quite sparse), but a > simple C extension would be trivial to write. > > However, the best way is just to copy and paste that text into your > program, I mean, why not? > > raise OSError("[Errno 2] No such file or directory") > > On 4/21/06, David Hirschfield wrote: > > I wasn't clear enough in my original post. > > > > I know how to raise a basic OSError or IOError, but what if I want to raise > > specifically an "OSError: [Errno 2] No such file or directory"? > > Somehow it must be possible to raise the error with the correct information > > to bring up the standard message, but where do I find the right values to > > give? > > > > Thanks, > > -Dave > > > > > > > > alisonken1 wrote: > > To raise a specific error, just find the error that you want to raise, > > then give the error a text string to print: ex. > > > > raise IOError("This raises an IO error") > > > > On the stderr output, when the routine hits this line, you will get: > > > > > > > > > > > > raise IOError("This raises an IOError") > > > > Traceback (most recent call last): > > File "", line 1, in ? > > IOError: This raises an IOError > > > > > > Just be sure of the error that you want to raise, since some of them > > will do stuff like closing open file descriptors as well. > > > > > > > > > > -- > > Presenting: > > mediocre nebula. > > > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > > > -- > Kelvie > -- Kelvie From nobody at 127.0.0.1 Wed Apr 19 02:24:14 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 19 Apr 2006 06:24:14 GMT Subject: multiline comments In-Reply-To: References: Message-ID: Ben Finney wrote: > And/or switch to an editor that can perform editing operations on a > range of lines. I'm not unsympathetic to this point of view, as I would feel hamstrung without my vim. It's more that I object to the paternalism of telling people they have to use such an editor. There are times when notepad is all that's available. On top of that, the expressive power of nested comments seems greater than an endless string of ^#s. Sometimes it's just easier to see what's going on. From brian at rkspeed-rugby.dk Fri Apr 14 05:23:15 2006 From: brian at rkspeed-rugby.dk (Brian Elmegaard) Date: Fri, 14 Apr 2006 11:23:15 +0200 Subject: Upgrading and modules Message-ID: Hi, Every time I upgrade python I also have to download all packages and reinstall them. http://www.voidspace.org.uk/python/articles/upgrading_python.html tells me that this is only a problem on windows for some reasons that have to do with binary distributions, compiling and more. This leads me to the questions: 1: Isn't there a better way? 2: Why is compilation needed for installation of a package? 3: Why isn't python backwards compatible so reinstallation is unneeded? 4: Would it help if python was compiled with gcc/mingw so installation would be the same as on other systems? 5: What about a package repository and a manager like miktex has? regards, -- Brian (remove the sport for mail) http://www.et.web.mek.dtu.dk/Staff/be/be.html http://www.rugbyklubben-speed.dk From hnt20 at msn.com Sat Apr 15 17:43:24 2006 From: hnt20 at msn.com (HNT20) Date: Sat, 15 Apr 2006 21:43:24 GMT Subject: How to Convert a string into binary In-Reply-To: <1145132538.384947.4560@v46g2000cwv.googlegroups.com> References: <1145132538.384947.4560@v46g2000cwv.googlegroups.com> Message-ID: <0Od0g.92827$9I5.50222@tornado.ohiordc.rr.com> bearophileHUGS at lycos.com wrote: > If (assuming this is correct, you can do more tests) the given strings > are many and/or long, this can be a fast version. With Psyco this same > version can become quite faster. > Bye, > bearophile > > > from array import array > > class ToBinary(object): > """ToBinary: class to convert a given string to a binary string.""" > def __init__(self): > _nibbles = {"0":"0000", "1":"0001", "2":"0010", "3":"0011", > "4":"0100", "5":"0101", "6":"0110", "7":"0111", > "8":"1000", "9":"1001", "A":"1010", "B":"1011", > "C":"1100", "D":"1101", "E":"1110", "F":"1111"} > self._bytes = ["".join(_nibbles[h] for h in "%X"%i).zfill(8) > for i in xrange(256)] > def conv(self, s): > if s: > result = [self._bytes[el] for el in array("B", s)] > result[0] = result[0].lstrip("0") > return "".join(result) > else: > return "0" > > # Tests > Conv2 = ToBinary() > data = ["", "a", "b", "ab", "hello", "123456789"] > for s in data: > print s, Conv2.conv(s) > Thanks you very much, i will give this code a try. i hope it will work. From fredrik at pythonware.com Sun Apr 23 13:41:57 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 23 Apr 2006 19:41:57 +0200 Subject: check whether a value is scalar References: <1145738972.246620.317070@i40g2000cwc.googlegroups.com> Message-ID: "Eli" wrote: > The issue is I want to keep a set of values to share among several > applications in different languages, and only scalar values can be > shared. Since objects are not the same in all languages, it's possible > to share only simple values. I can assure you that people who've implemented various kinds of RPC protocols and cross-language bindings would be rather surprised to hear that you've discovered that it's impossible to do what they've done. I'm not entirely convinced that you know what you're talking about, really. Maybe you should spend a little more time studying prior art ? From johnjsal at NOSPAMgmail.com Wed Apr 5 14:48:21 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 05 Apr 2006 18:48:21 GMT Subject: PIL question about crop method Message-ID: I might be way off target even looking into this method for what I need to do, but I'm still a little confused about the description of it: crop im.crop(box) => image Returns a rectangular region from the current image. The box is a 4-tuple defining the left, upper, right, and lower pixel coordinate. I'm probably just being a little dense again, but how exactly do you write the tuple? Wouldn't a coordinates parameter be a tuple of tuples? It sounds like here you only need four numbers, but I don't understand what 'left, upper, right, and lower pixel coordinate' means. It doesn't seem like it's asking for a set of coordinates for each corner of the box, or for a set at all. How do four separate numbers make up coordinates? Thanks. From ldo at geek-central.gen.new_zealand Fri Apr 7 16:47:23 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 08 Apr 2006 08:47:23 +1200 Subject: python on Mac References: <1144284073.446005.53950@t31g2000cwb.googlegroups.com> <1hdc51n.1qgtjne1mduk7gN%aleaxit@yahoo.com> <1144291572.151260.56700@j33g2000cwa.googlegroups.com> <1144293362.889863.146200@i39g2000cwa.googlegroups.com> Message-ID: In article <1144293362.889863.146200 at i39g2000cwa.googlegroups.com>, "pierreth" wrote: >You removed /usr/bin/python! This is a really bad idea Is there any way to put it back, short of a full system reinstall? From ove.svensson at ericsson.com Wed Apr 19 02:53:20 2006 From: ove.svensson at ericsson.com (Ove Svensson) Date: 19 Apr 2006 08:53:20 +0200 Subject: Queue can result in nested monitor deadlock References: <1145284326.177062.230120@v46g2000cwv.googlegroups.com> <1145292096.906390.254280@e56g2000cwe.googlegroups.com> <1145306244.336966.113470@e56g2000cwe.googlegroups.com> <2ht842lakluo2gmorqncrtcd4shjngdvd8@4ax.com> <1145388959.865294.183820@j33g2000cwa.googlegroups.com> Message-ID: "Jonathan Amsterdam" writes: > No redesign necessary. I simply make M be the Queue's mutex, via the > LQueue class I posted. I am making the modest suggestion that this > feature be documented and exposed in the Queue class. > Even though LQueue is the correct sollution to the problem, why not fix Queue.Queue? Fixing Queue.Queue would not break any existing code and we don't have to pollute the namespace with yet another class. From bdesth.quelquechose at free.quelquepart.fr Fri Apr 7 18:33:55 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 08 Apr 2006 00:33:55 +0200 Subject: Characters contain themselves? In-Reply-To: References: Message-ID: <4436baef$0$14290$626a54ce@news.free.fr> WENDUM Denis 47.76.11 (agent) a ?crit : > > While testing recursive algoritms dealing with generic lists I stumbled > on infinite loops which were triggered by the fact that (at least for my > version of Pyton) characters contain themselves. There is *no* character type in Python. 'a' is a string, and of course the string 'a' is a substring of string 'a'. From Andreas.Ames at comergo.com Fri Apr 28 12:53:32 2006 From: Andreas.Ames at comergo.com (Ames Andreas) Date: Fri, 28 Apr 2006 18:53:32 +0200 Subject: MinGW and Python Message-ID: <552B6B925278EF478EA8887D7F9E5AC3894D28@tndefr-ws00024.tenovis.corp.lan> > -----Original Message----- > From: "Martin v. L?wis" [mailto:martin at v.loewis.de] > Sent: Friday, April 28, 2006 6:20 PM > Subject: Re: MinGW and Python > > It all depends on what CRT version you link Python with. If you > use mingw32 to link Python with msvcr71.dll, nothing would change > for pywin32 compared to Python 2.4. OTOH, nothing would change > for anybody else, either. I'm more concerned that it might expose some C++ code (symbols) to other python code but I haven't looked at pywin32's implementation so I can't really tell. If it does, one shouldn't use it with _any_ compiler other than the one used to build pywin32. Even a mix of different ms-compilers would be dangerous, IMHO. cheers, aa -- Andreas Ames | Programmer | Comergo GmbH | Voice: +49 69 7505 3213 | ames AT avaya . com From godoy at ieee.org Thu Apr 27 13:17:46 2006 From: godoy at ieee.org (Jorge Godoy) Date: Thu, 27 Apr 2006 14:17:46 -0300 Subject: finding IP address of computer References: <1146150198.737288.37640@i40g2000cwc.googlegroups.com> <1146150983.359961.7160@i39g2000cwa.googlegroups.com> <1146151668.000022.153540@e56g2000cwe.googlegroups.com> Message-ID: <3667287.QCcezcacLV@jupiter.g2ctech> Chris wrote: > hehe, works a charm, cheers mate. Beware that if you have a different entry in your hosts file you can match a different name. Test it: - add "127.0.0.2 yourhost.yourdomain yourhost" to /etc/hosts - rerun the code. You'll see "127.0.0.2" as the result. So take that into account. -- Jorge Godoy "Quidquid latine dictum sit, altum sonatur." - Qualquer coisa dita em latim soa profundo. - Anything said in Latin sounds smart. From tim at thechases.com Tue Apr 18 11:31:39 2006 From: tim at thechases.com (Tim Chase) Date: Tue, 18 Apr 2006 10:31:39 -0500 Subject: Uniquifying a list? Message-ID: <4445065B.6000700@thechases.com> Is there an obvious/pythonic way to remove duplicates from a list (resulting order doesn't matter, or can be sorted postfacto)? My first-pass hack was something of the form >>> myList = [3,1,4,1,5,9,2,6,5,3,5] >>> uniq = dict([k,None for k in myList).keys() or alternatively >>> uniq = list(set(myList)) However, it seems like there's a fair bit of overhead here...creating a dictionary just to extract its keys, or creating a set, just to convert it back to a list. It feels like there's something obvious I'm missing here, but I can't put my finger on it. Thanks... -tkc From vincenzo.cacciatore at gmail.com Mon Apr 3 04:31:22 2006 From: vincenzo.cacciatore at gmail.com (LabWINC) Date: 3 Apr 2006 01:31:22 -0700 Subject: How can i design a band-pass filter with scipy? Message-ID: <1144053082.053806.301650@z34g2000cwc.googlegroups.com> Hi all, i would like to design a high pass filter with scipy.signal module. This is the code i'm using to: import scipy.signal as signal import scipy #first of all i design the lowpass fir filter. This is a 10 taps filter with cutoff frequency =1 (as help tell me to do) lpwindow=signal.firwin(10,1) #with the following instruction i'm creating a band pass filter from the low pass one bpwindow=signal.lp2bp(lpwindow,1,0.5,0.2) My problem is that the band-pass filter obtained with lp2bp function is 16 taps one! How is it possible?? thanks, Vincenzo From fulvio at pc.jaring.my Thu Apr 13 07:11:40 2006 From: fulvio at pc.jaring.my (Fulvio) Date: Thu, 13 Apr 2006 19:11:40 +0800 Subject: Figure out month number from month abbrievation In-Reply-To: References: <1144873227.982973.18720@i40g2000cwc.googlegroups.com> Message-ID: <200604131911.40313.fulvio@pc.jaring.my> Alle 04:41, gioved? 13 aprile 2006, Fredrik Lundh ha scritto: > but it also looks as if the meaning of the word "localized" isn't clear to > you; if you changed the locale, those names will be translated Mine behave strangely. Linux localized for Italian, but Python (or its calander is in english) ?? F From rpdooling at gmail.com Tue Apr 18 14:50:00 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 18 Apr 2006 11:50:00 -0700 Subject: indirect import of standard module Message-ID: <1145386200.076643.253740@u72g2000cwu.googlegroups.com> I know this must have been answered a hundred times, but I must be searching on the wrong terminology. Let's say I have a module foo.py that imports os. I make another script called bar.py that imports foo.py and now I want to use, say, os.walk in bar.py. Which is faster or more correct or whatever: Do I import os at the top of bar.py and use foo's functions? Or do I call os.walk by writing foo.os.walk? Sorry for lack of proper terminology. I read the module parts of the Tutorial but couldn't find it there. Rick From antonyliu2002 at yahoo.com Mon Apr 17 23:44:27 2006 From: antonyliu2002 at yahoo.com (Anthony Liu) Date: Mon, 17 Apr 2006 20:44:27 -0700 (PDT) Subject: Slicing matrix In-Reply-To: Message-ID: <20060418034427.95197.qmail@web35805.mail.mud.yahoo.com> Hi, James, I just realized that my English is so good that I can joke with slangs. Hopefully it isn't that offensive. Otherwise, I am sorry. --- James Stroud wrote: > Anthony Liu wrote: > > I figure it out, too. NumArray is so flexible, > it's > > like cutting the cheese. > > Some idioms do not translate so well. > > > -- > James Stroud > UCLA-DOE Institute for Genomics and Proteomics > Box 951570 > Los Angeles, CA 90095 > > http://www.jamesstroud.com/ > -- > http://mail.python.org/mailman/listinfo/python-list > __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From anon Wed Apr 26 16:14:00 2006 From: anon (Mark Thomas) Date: Wed, 26 Apr 2006 21:14:00 +0100 Subject: (was Re: Xah's Edu Corner: Criticism vs Constructive Criticism) In-Reply-To: <1146079773.910552.217390@y43g2000cwc.googlegroups.com> References: <1145992903.834316.198370@u72g2000cwu.googlegroups.com> <4GM3g.3084$TT.1768@twister.nyroc.rr.com> <1146079773.910552.217390@y43g2000cwc.googlegroups.com> Message-ID: <444fd488$0$33924$ed2619ec@ptn-nntp-reader03.plus.net> Xah Lee wrote: > Dear John Bokma, > > This is a public notice that what you are trying to do is getting close > to harrassment from the law's perspective. > > Thanks. > > Xah > xah at xahlee.org > ? http://xahlee.org/ > > > John Bokma wrote: >> Eli Gottlieb wrote: >> >>> Oh, God, not another one. >> Instead of cross posting more garbage, do as follows: >> >> Email a complaint to the email addresses you can look up yourself and >> include the entire message of Xah: >> >> http://www.spamcop.net/sc?track=72.231.179.135 posting host >> http://www.spamcop.net/sc?track=xahlee.org spamvertized site >> >> >> If enough people complain with both, it might stop one day. > Ooooh! (Waggles fingers beneath chin) Mark From jaywgraves at gmail.com Mon Apr 10 16:58:33 2006 From: jaywgraves at gmail.com (jay graves) Date: 10 Apr 2006 13:58:33 -0700 Subject: Python Shell window References: <1144693672.676045.193680@i40g2000cwc.googlegroups.com> Message-ID: <1144702713.136121.186230@e56g2000cwe.googlegroups.com> Jay wrote: > Is their any way of setting wear the Python Shell window appears on the > screen when I run my program? > > I am testing a full screen program with no Window Frame on a comp with > 2 monitors and I have to keep pressing the Key to bring the > Shell to the front and then moving it manually to the other screen > every time I restart the program. > > I would like it to just appear on the other screen from the start. > > Any ideas 1. Do you really want the CMD prompt to show up? If not, rename your file from .py to .pyw and it will be hidden. You'll miss all of the STD* streams though. 2. Find the window and move it to the right place. Here is a script I use to launch PuTTY (which has the unfortunate problem of 'hiding' its title bar below my 'Start' bar which I keep at the top of my screen). It's convient for me to launch PuTTY from this script but I don't see any reason why you couldn't add this code to your main function and find the errand CMD prompt and move it. (For this you need the win32 extension installed) ------------------------------------------------ import win32gui,os,sys,time command = r"start putty -load %s" def moveWindow(hwnd, ignored): x = win32gui.GetWindowText(hwnd) if x.find('PuTTY') >= 0: left,top,right,bottom = win32gui.GetWindowRect(hwnd) if top < 30: width = right - left height = bottom - top win32gui.MoveWindow(hwnd,left,top+30,width,height,1) try: p1 = sys.argv[1] except IndexError: #print "you must provide a valid machine name" p1 = "opus" os.system(command % (p1,)) time.sleep(1.0) win32gui.EnumWindows(moveWindow, None) ------------------------------------------------ HTH.. Jay From bones17 at gmail.com Sat Apr 1 03:57:21 2006 From: bones17 at gmail.com (bones17 at gmail.com) Date: 1 Apr 2006 00:57:21 -0800 Subject: Python 2.4.3 Documentation: Bad link In-Reply-To: References: <1143879203.136199.32840@e56g2000cwe.googlegroups.com> Message-ID: <1143881841.044273.221050@g10g2000cwb.googlegroups.com> Now, it works well... I really don't know why it before report 404 Not Found... I was tested it 5x... I'm sorry for unwanted false bug report. From da.martian at gmail.com Mon Apr 3 11:57:10 2006 From: da.martian at gmail.com (ChaosKCW) Date: 3 Apr 2006 08:57:10 -0700 Subject: Convertion of Unicode to ASCII NIGHTMARE Message-ID: <1144079830.734516.8390@z34g2000cwc.googlegroups.com> Hi I am reading from an oracle database using cx_Oracle. I am writing to a SQLite database using apsw. The oracle database is returning utf-8 characters for euopean item names, ie special charcaters from an ASCII perspective. I get the following error: > SQLiteCur.execute(sql, row) >UnicodeDecodeError: 'ascii' codec can't decode byte 0xdc in position 12: ordinal not in >range(128) I have googled for serval days now and still cant get it to encode to ascii. I encode the SQL as follows: sql = "insert into %s values %s" % (SQLiteTable, paramstr) sql.encode('ascii', 'ignore') I then code each of the row values returned from Oracle like this: row = map(encodestr, row) SQLiteCur.execute(sql, row) where encodestr is as follows: def encodestr(item): if isinstance(item, types.StringTypes): return unicodedata.normalize('NFKD', unicode(item, 'utf-8', 'ignore')).encode('ASCII', 'ignore') else: return item I have tried a thousand of similiar functions to the above, permitations of the above from various google searches. But I still get the above exception on the line: SQLiteCur.execute(sql, row) and the exception is reslated to the data in one field. Int the end I resorted to using oracles convert function in the SQL statement but would like to understand why this is happening and why its so hard to convert the string in python. I have read many complaints about this from other people some of whom have written custom stripping routines. I havent tried a custom routine yet, cause I think it should be possilble in python. Thanks, From dmh2000 at gmail.com Thu Apr 6 11:58:18 2006 From: dmh2000 at gmail.com (dmh2000) Date: 6 Apr 2006 08:58:18 -0700 Subject: Difference in Python and Ruby interactive shells References: <1144159204.450444.297870@t31g2000cwb.googlegroups.com> Message-ID: <1144339098.067261.147800@i40g2000cwc.googlegroups.com> Thanks all for the responses. Extra kudos to Steve J and Michele S. that cleared it up for me. the context of my question comes from reading up on Lisp in "Loving Lisp - the Savy Programmer's Secret Weapon", http://www.markwatson.com/opencontent/lisp_lic.htm, where the author described building up a large system during test, that took a long to to load. He was showing one reason why a dynamic language was more productive than a statically compiled language. From tzot at sil-tec.gr Mon Apr 10 08:48:19 2006 From: tzot at sil-tec.gr (Christos Georgiou) Date: Mon, 10 Apr 2006 15:48:19 +0300 Subject: Decorators, Identity functions and execution... References: <87fykm7qud.fsf@ieee.org> Message-ID: On Sun, 09 Apr 2006 11:42:34 -0300, rumours say that Jorge Godoy might have written: >Indeed. This is correct. Fredrick's comment was related to the lack of >indentation in your code. His code was indented fine, as you maybe noticed later on. The actual problem was that he had tabs, so Fredrik's Outlook Express (and I guess other newsreaders too) did not show indentation. Fredrik suggested already the typical "use spaces, not tabs"; I just thought that "lack of indentation" was unfair for the OP. -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From richard.hsu at gmail.com Tue Apr 11 21:39:15 2006 From: richard.hsu at gmail.com (Richard Hsu) Date: 11 Apr 2006 18:39:15 -0700 Subject: finish_endtag in sgmllib.py [Python 2.4] In-Reply-To: <1144804382.736878.309380@g10g2000cwb.googlegroups.com> References: <1144802230.446613.297980@i39g2000cwa.googlegroups.com> <1144804382.736878.309380@g10g2000cwb.googlegroups.com> Message-ID: <1144805955.218026.193070@u72g2000cwu.googlegroups.com> thank you Ben. not only did i learn something about my question, i learnt the 'truth' :-) From fe5259gm.bbs at bbs.wretch.cc Fri Apr 14 02:50:04 2006 From: fe5259gm.bbs at bbs.wretch.cc (fe5259gm.bbs at bbs.wretch.cc) Date: 14 Apr 2006 06:50:04 GMT Subject: [=?big5?Q?=BCs=A7i]=BCx=A4H~=AD=DD=C2=BE=A4u=A7@=A5=FE=C2=BE=A6=AC=A4J(=A5i=A6b=AEa=A4u=A7@)?= Message-ID: <4NXGWS$BvY@bbs.wretch.cc> Part-time job Full-time income ??????????????????????? ??????,??2~3??,??1?~3? http://www.moonnini.com/w/nica/ ??????????? ????????????????? -- ????????????????????????????????????? ????????????????????????????????????? ????????????????????????????????????? ????????????????????????????????????? ??????????????????? 220-137-106-136.dynamic.hinet.net? From cctv.star at gmail.com Tue Apr 25 06:34:08 2006 From: cctv.star at gmail.com (cctv.star at gmail.com) Date: 25 Apr 2006 03:34:08 -0700 Subject: OOP / language design question Message-ID: <1145961248.794496.80220@j33g2000cwa.googlegroups.com> I was wondering, why you always have to remember to call bases' constructors explicitly from the derived class constructor? Why hasn't this been enforced by the language? From alex.buell at munted.org.uk Wed Apr 26 20:12:48 2006 From: alex.buell at munted.org.uk (Alex Buell) Date: Thu, 27 Apr 2006 01:12:48 +0100 Subject: Xah's Edu Corner: Criticism vs Constructive Criticism References: <1145992903.834316.198370@u72g2000cwu.googlegroups.com> Message-ID: <20060427011248.517fc1ca.alex.buell@munted.org.uk> On 25 Apr 2006 12:21:43 -0700 "Xah Lee" waved a wand and this message magically appeared: > Criticism versus Constructive Criticism GO AWAY. Noone wants to see this drivel. Put it on a website if you must. Otherwise shut the fuck up and leave us alone! -- http://www.munted.org.uk Take a nap, it saves lives. From lucaberto at libero.it Mon Apr 3 04:34:10 2006 From: lucaberto at libero.it (luca72) Date: 3 Apr 2006 01:34:10 -0700 Subject: wx.checklistbox In-Reply-To: <1143922446.596030.299380@i40g2000cwc.googlegroups.com> References: <1143815725.730867.324970@j33g2000cwa.googlegroups.com> <1143900250.243912.309390@v46g2000cwv.googlegroups.com> <1143922446.596030.299380@i40g2000cwc.googlegroups.com> Message-ID: <1144053250.212944.76140@i40g2000cwc.googlegroups.com> Hello Frefrik It works but sometimes it insert a blank row so the file is like: item1 item2 item3 item4 etc.. I don't inderstand why. But supposing that we can't solve this, is it possible to delete blanlk items in the checkListBox? From tagore at tagoresmith.com Sat Apr 29 02:54:21 2006 From: tagore at tagoresmith.com (Tagore Smith) Date: 28 Apr 2006 23:54:21 -0700 Subject: (was Re: Xah's Edu Corner: Criticism vs Constructive Criticism) In-Reply-To: References: <1145992903.834316.198370@u72g2000cwu.googlegroups.com> <4GM3g.3084$TT.1768@twister.nyroc.rr.com> <1146231280.733609.143230@e56g2000cwe.googlegroups.com> <1146276319.504694.218970@v46g2000cwv.googlegroups.com> <1146285809.127897.24070@j33g2000cwa.googlegroups.com> Message-ID: <1146293661.242855.307580@j73g2000cwa.googlegroups.com> John Bokma wrote: > "Tagore Smith" wrote: > > > Try > > sending mail to abuse at (any of my) desmesne(s). You won't get a > > response- in fact, no-one will read your mail. > > Then you come close to being RFC ignorant IMO. Couldn't be bothered to > check it out. I don't care much about the RFC. I'd like to actually handle abusive users. But people report abuse for all kinds of strange reasons. It seems that believing in "Darwinism" is a form of abuse... go figure. That's actually my point. You are helping to ensure that abuse is tolerated. We stopped reading the abuse account for a reason. > > I'm not sure that Xah's post was offtopic, and I am not sure how to > > determine that objectively. > > An excessive crosspost is hardly ever on topic. Now you are just being dishonest. > > I am sure that it was excessively > > crossposted. I also know that Xah was posting to Usenet a long time > > before you, > > Could be, oldest post I could find of myself: > dmode=source> > > But is this a pissing contest? No- if it were you would no longer have internet access. From felipe.lessa at gmail.com Fri Apr 14 01:49:21 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Fri, 14 Apr 2006 02:49:21 -0300 Subject: reading files in small chunks? In-Reply-To: <47a726d60604132245s32fc4d55r3279e8e4372d720a@mail.gmail.com> References: <47a726d60604132245s32fc4d55r3279e8e4372d720a@mail.gmail.com> Message-ID: <1144993761.17836.9.camel@kenshin.CASA> Em Sex, 2006-04-14 ?s 13:45 +0800, Rajesh Sathyamoorthy escreveu: > I wanted to know why it is more efficient to read a file in smaller > chunks ( using file() or open() )? It's more efficient in some cases, and worse on others. It also depends on how you implement the read loop. I won't elaborate too much here, there are loads of sites and books that talk about this topic. > If this is not done, will this lead to errors in the data read or just > results in slower performance? It doesn't corrupt anything, unless you have a buggy hardware. -- Felipe. From jjl at pobox.com Tue Apr 11 19:52:47 2006 From: jjl at pobox.com (John J. Lee) Date: 11 Apr 2006 23:52:47 +0000 Subject: I wanna use urllib2 to get a page with a socks 5 proxy, who can give me a sample code ? References: <1144593748.272792.133830@e56g2000cwe.googlegroups.com> Message-ID: <871ww38yb4.fsf@pobox.com> "Ju Hui" writes: > I wanna use urllib2 to get a page with a socks 5 proxy,who can give me > a sample code ? [...] I haven't used it myself (though curiously, ftplib knows about this module and will use it if present -- and urllib2 uses ftplib to fetch ftp: URLs), but you could try this http://www.w3.org/People/Connolly/drafts/socksForPython.html And monkeypatch urllib2 (and everything else that uses module socket!) something like so (UNTESTED): import sys, os os.environ['SOCKS_SERVER'] = 'joe:password at proxy.example.org' import SOCKS from socket import getfqdn SOCKS.getfqdn = getfqdn sys.modules['socket'] = SOCKS del getfqdn, SOCKS import urllib2 then just use urllib2 normally... John From NOatkinwSPAM at rpi.edu Fri Apr 28 13:41:02 2006 From: NOatkinwSPAM at rpi.edu (Bill Atkins) Date: Fri, 28 Apr 2006 13:41:02 -0400 Subject: No subject References: <1145992903.834316.198370@u72g2000cwu.googlegroups.com> <4GM3g.3084$TT.1768@twister.nyroc.rr.com> <1146231280.733609.143230@e56g2000cwe.googlegroups.com> <4452258e$0$655$bed64819@news.gradwell.net> <1146235544.218219.71430@j73g2000cwa.googlegroups.com> Message-ID: <87psj1ionl.fsf@rpi.edu> John Bokma writes: > > Isn't it crazy that one person is allowed to create such a huge mess > everytime he posts? Isn't it crazy that one person willfully creates such a mess every time Xah posts? Shush! -- This is a song that took me ten years to live and two years to write. - Bob Dylan From blais at furius.ca Mon Apr 24 12:16:41 2006 From: blais at furius.ca (Martin Blais) Date: Mon, 24 Apr 2006 12:16:41 -0400 Subject: i18n hell In-Reply-To: <1145864322.901596.122290@i40g2000cwc.googlegroups.com> References: <1145853400.436212.26190@u72g2000cwu.googlegroups.com> <1145864322.901596.122290@i40g2000cwc.googlegroups.com> Message-ID: <8393fff0604240916l2187a1d7p2fe2a703561f1b43@mail.gmail.com> On 24 Apr 2006 00:38:42 -0700, Serge Orlov wrote: > fyleow wrote: > > I just spent hours trying to figure out why even after I set my SQL > > table attributes to UTF-8 only garbage kept adding into the database. > > Apparently you need to execute "SET NAMES 'utf8'" before inserting into > > the tables. > > > > Does anyone have experience working with other languages using Django > > or Turbogears? I just need to be able to retrieve and enter text to > > the database from my page without it being mangled. I know these > > frameworks employ ORM so you don't need to write SQL and that worries > > me because I tried this on Rails and it wouldn't work. > > Frequently asked question to people who are burning in i18n hell: are > you using unicode strings or byte strings? Unicode string means that > type(your_string) is unicode, it does not mean you keep utf-8 encoded > text in python byte strings. I used to live i18n hell, a while ago, until I understood this: everytime you keep a reference to some kind of string object, ALWAYS ALWAYS ALWAYS be AWARE of whether it is not encoded (a unicode object) or an encoding string (a str object), and if so, which encoding it is in. Then deal with the conversion between the two domains EXPLICITLY (e.g. encode(), decode()). If you hold onto a str or unicode object and you don't know which it is, you are inevitably bound to face unicode hell at some point. You can use a prefix convention if that makes it easier for you, but the point is that you CANNOT just "wing it". Python makes it too easy to just "wing it" and that creates a lot of surprises, especially since some methods hide the conversions, e.g. str.join. w.r.t. to DB storage, that depends on the specific database you're using and the DBAPI module you're using, read up on it, write a few tests on your corresponding DBAPI (simple tests, easy peasy), know what kinds of strings you're sending in and reading back. I'm using PostgreSQL often and my configuration always stores strings in UTF-8 in the database. I have a lightweight mapping module that disambiguiates and does the encoding/decoding automatically in a consistent way (that decision belongs in the client code for now, unfortunately, but is centralized using my table declaration that lists the desired conversions for each column). See http://furius.ca/antiorm/ for something simple that works well. cheers, -- Martin Furius Python Training -- http://furius.ca/training/ From fredrik at pythonware.com Wed Apr 19 14:06:53 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 19 Apr 2006 20:06:53 +0200 Subject: Ironpython book? References: <1145329406.419299.12780@i40g2000cwc.googlegroups.com><1he15xj.1dy2h0vzbebqmN%aleaxit@yahoo.com><1he18dm.e64uky1urr3n0N%aleaxit@yahoo.com> Message-ID: John Salerno wrote: > But it sounds like, from Fred's post, that work is still being done on > it. My main point in asking was just that I hadn't heard as much about > it as IronPython lately, and I was just curious what the community would > think about two competing .NET implementations, since a big part of > Python is having one main way to do everything (I think). are we talking about two different things here, perhaps ? the "Python for .Net" tool I'm talking about is an integration tool that lets you use CPython and CPython extensions together with CLR stuff, while IronPython is a pure-CLR implementation of Python. there was also, once upon a time, an experimental Python compiler for the .Net platform: http://starship.python.net/~skippy/dotnet/index.html but that project was abandoned years ago. From felipe.lessa at gmail.com Fri Apr 14 00:16:22 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Fri, 14 Apr 2006 01:16:22 -0300 Subject: PEP 359: The "make" Statement In-Reply-To: References: Message-ID: <1144988182.17836.0.camel@kenshin.CASA> Em Qui, 2006-04-13 ?s 23:17 -0400, Nicolas Fleury escreveu: > The callable could have something like a __namespacetype__ that could be > use instead of dict. That type would have to implement __setitem__. Or the namespace variable could be a list of tuples. -- Felipe. From johnjsal at NOSPAMgmail.com Mon Apr 10 09:49:55 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 10 Apr 2006 13:49:55 GMT Subject: how relevant is C today? In-Reply-To: <1144644611.512055.193260@i39g2000cwa.googlegroups.com> References: <44381ee4$0$4209$c3e8da3@news.astraweb.com> <44382711.10403@v.loewis.de> <44393fbe$0$19226$c3e8da3@news.astraweb.com> <44398651$0$4206$c3e8da3@news.astraweb.com> <1144644611.512055.193260@i39g2000cwa.googlegroups.com> Message-ID: <7ot_f.1948$No6.42663@news.tufts.edu> Ray wrote: > John Salerno wrote: >>> At which level in the 'python challenge' did >>> you get stuck - and why? >> Ugh, don't remind me! :) >> >> I'm stuck on level 12, which is yet another image processing puzzle. I'm >> getting tired of those, and I think it's really a shame that there is a > > This is EXACTLY why I am still stuck on level 12 for many months. The > first few ones are fun. That sequence thing is also particularly fun. > > But after a while, it seems that it's an image after image after image > after image. I just got sick of PIL :) > > > And it is surprisingly difficult to find solutions anywhere! People really want to keep them a secret! :) From rpdooling at gmail.com Fri Apr 21 12:17:52 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 21 Apr 2006 09:17:52 -0700 Subject: proposed Python logo In-Reply-To: References: <1145615455.477800.74730@i39g2000cwa.googlegroups.com> Message-ID: <1145636272.363143.208410@i40g2000cwc.googlegroups.com> >> I'd like some variation of used as a logo. That has real potential, but I bet it's trademarked. rick From jstroud at ucla.edu Mon Apr 17 23:09:55 2006 From: jstroud at ucla.edu (James Stroud) Date: Mon, 17 Apr 2006 20:09:55 -0700 Subject: Slicing matrix In-Reply-To: References: Message-ID: Anthony Liu wrote: > I figure it out, too. NumArray is so flexible, it's > like cutting the cheese. Some idioms do not translate so well. -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From imdognuts at yahoo.com Mon Apr 17 19:57:37 2006 From: imdognuts at yahoo.com (imdognuts at yahoo.com) Date: 17 Apr 2006 16:57:37 -0700 Subject: Freeze without a binary Message-ID: <1145318257.444166.245430@j33g2000cwa.googlegroups.com> I want to use freeze to create the .o's to then include in a library that will be distributed. When I use freeze it creates a binary and a main, and the main calls some frozenmain func. Obviously I dont want a main() in this code. Do I need to extract the code that was generated by freeze in main like Py_FrozenMain() and call this from somewhere else? This was created in the main() function: extern int Py_FrozenMain(int, char **); PyImport_FrozenModules = _PyImport_FrozenModules; return Py_FrozenMain(argc, argv); In my code i have C funcs that call py file functions which call C funcs. I dont want to ship the py files, but include it in a library with the other .o's Thanks. From robin at alldunn.com Tue Apr 4 14:13:38 2006 From: robin at alldunn.com (Robin Dunn) Date: Tue, 04 Apr 2006 11:13:38 -0700 Subject: ANNOUNCE: wxPython 2.6.3.2 In-Reply-To: <4432B4D8.4000404@wordtech-software.com> References: <4432B4D8.4000404@wordtech-software.com> Message-ID: <4432B752.5080408@alldunn.com> Kevin Walzer wrote: > Is the new build of wxPython-Mac a universal binary? > No, not yet. There is still some more work to do for that. -- Robin Dunn Software Craftsman http://wxPython.org Java give you jitters? Relax with wxPython! From sushant.sirsikar at gmail.com Mon Apr 3 02:31:32 2006 From: sushant.sirsikar at gmail.com (sushant.sirsikar at gmail.com) Date: 2 Apr 2006 23:31:32 -0700 Subject: Get the input from user Message-ID: <1144045891.952385.176780@v46g2000cwv.googlegroups.com> hi, I am doing example of address book.when user enter stop and presses enter my loop should stop.But there is some prob in my loop.It is accepting \r after pressing Enter key.How do i check end of input : addressbook={} name = raw_input("Enter Name (stop to Finish)") name = EnterAddress(addressbook) ShowAddress(name, addressbook) def ShowAddress(name, addressbook): name = raw_input("Enter Name for Address ") print "Address of %s is %s" %(name,addressbook[name]) def EnterAddress(addressbook): while name != "stop": entry = raw_input("Enter the address") addressbook[name]=entry name = raw_input("Enter Name (Leave blank to Finish)") return name thanks Sushant From martin at v.loewis.de Sun Apr 23 03:13:45 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 23 Apr 2006 09:13:45 +0200 Subject: How can I call a python method from the XML-RPC client in Java? In-Reply-To: <1145557883.584164.97830@t31g2000cwb.googlegroups.com> References: <1145557883.584164.97830@t31g2000cwb.googlegroups.com> Message-ID: <444b292a$0$31328$9b622d9e@news.freenet.de> evelyne0510 at gmail.com wrote: > Hi all, I have created a XML-RPC model (with server and client) > written in Java. I want to call the methods in another XML-RPC model > written in Python. I know that in Java, I can use like > "xmlrpc_client.excute("handler_name.method", param)" to call the > methods in my xml-rpc server written in java. But how can I call the > methods in Python? I cannot creat a handler in my Python XML-RPC > server..... > > Is there anyone able to help me? I would be very appreciate! It's not clear to me what you are trying to do: Do you want to know how to write certain Java code (as the subject line suggests), or how to write certain Python code (as "I cannot create a handle in my Python XML-RPC server" suggests"). I'm going by the subject: As a first step, please try calling the demo server in SimpleXMLRPCServer in Java. To do this, start the demo servre, point your Java client to http://localhost:8000/RPC2, and invoke xmlrpc_client("add", new args[]{1, 2}) (or some such, I'm not sure how parameter passing in your library works). You are right that there typically is no "handler" in Python, so you just omit the handler_name part of the method string. Regards, Martin From mtobis at gmail.com Wed Apr 12 16:30:57 2006 From: mtobis at gmail.com (Michael Tobis) Date: 12 Apr 2006 13:30:57 -0700 Subject: iPython and doctest Message-ID: <1144873857.232532.119160@t31g2000cwb.googlegroups.com> It appears that doctest does not work straightforwardly within iPython. I would like to be able to use doctest within a file conditionally, so that I can develop it within ipython and test it otherwise. It would seem that this would work: Python 2.4.1 (#2, Mar 31 2005, 00:05:10) [GCC 3.3 20030304 (Apple Computer, Inc. build 1666)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import testme >>> testme._test() >>> but it doesn't (the test above fails, but reports nothing) I am finding the documentation for doctest ironically impenetrable and **would** be interested in adding some examples and explanatory text to it, but I need to understand what is going on rather better than I do. Meanwhile I am settling for this: # testme.py def foo(): """ Should return 42 >>> foo() 42 """ return 43 def _test(): import doctest doctest.testmod() if __name__ == "__main__": try: __IP # check if we are in iPython except: _test() print "ok" #### Then In [4]:!python testme.py works (reports the error) just fine! So I don't even have to bail out of iPython to run the tests. mt From sjmachin at lexicon.net Thu Apr 13 02:17:19 2006 From: sjmachin at lexicon.net (John Machin) Date: Thu, 13 Apr 2006 16:17:19 +1000 Subject: Regular Expression: Matching substring In-Reply-To: <1144895624.539696.322960@e56g2000cwe.googlegroups.com> References: <1144895624.539696.322960@e56g2000cwe.googlegroups.com> Message-ID: <443ded05$1@news.eftel.com> On 13/04/2006 12:33 PM, Kevin CH wrote: > Hi, > > I'm currently running into a confusion on regex and hopefully you guys > can clear it up for me. > > Suppose I have a regular expression (0|(1(01*0)*1))* and two test > strings: 110_1011101_ and _101101_1. (The underscores are not part of > the string. They are added to show that both string has a substring > that matches the pattern.) Applying a match() function on the first > string returns true while false for the second. Perhaps you are using grep, or you have stumbled on the old deprecated "regex" module and are using that instead of the "re" module. Perhaps not as you are using only 2 plain vanilla RE operations which should work the same way everywhere. Perhaps you are having trouble with search() versus match() -- if so, read the section on this topic in the re docs. It's rather hard to tell what you are doing without seeing the code you are using. > The difference is the > first one has unmatched chunk in the beginning With re's match(), the whole string matches. > while the second at the > end. With re's match(), the part you marked with underscores (at the *beginning*) matches. > How's the regex rule work here? Let's abbreviate your pattern as (0|X)* This means 0 or more occurrences of strings that match either 0 or X. Case 1 gives us 11 matching X [it's a 1 followed by zero occurrences of (01*0) followed by a 1], then a 0, then 1011101 matching X [it's a 1 foll. by 1 occ. of (01110) followed by a 1]. Case 2 gives us 101101 matching X [it's a 1 foll. by 1 occ of (0110) foll by a 1] -- then there's a 1 that doesn't match anything. Here's some code and its output: C:\junk>type kevinch.py import re rx = re.compile(r"(0|(1(01*0)*1))*") def doit(n, s): print "Case", n m = rx.match(s) if m: print "0123456789" print s for k in range(4): print "span(%d) -> %r" % (k, m.span(k)) else: print "... no match" s1 = "110_1011101_".replace('_', '') s2 = "_101101_1".replace('_', '') doit(1, s1) doit(2, s2) C:\junk>kevinch.py Case 1 0123456789 1101011101 span(0) -> (0, 10) span(1) -> (3, 10) span(2) -> (3, 10) span(3) -> (4, 9) Case 2 0123456789 1011011 span(0) -> (0, 6) span(1) -> (0, 6) span(2) -> (0, 6) span(3) -> (1, 5) HTH, John From konrad.hinsen at laposte.net Thu Apr 13 12:27:43 2006 From: konrad.hinsen at laposte.net (Konrad Hinsen) Date: Thu, 13 Apr 2006 18:27:43 +0200 Subject: Looking for thoughts on PyMPI In-Reply-To: <443E7044.4040709@mvista.com> References: <443E7044.4040709@mvista.com> Message-ID: On Apr 13, 2006, at 17:37, Carl J. Van Arsdall wrote: > Hey, anyone use the PyMPI suite: http://sourceforge.net/projects/ > pympi/ ?? > > I am an engineer doing research with MPI and thought I'd do some > digging > to see if any scripting languages had adopted it yet. I was just > looking for general comments and reviews from the community on this > project, thanks! There is also PyPAR which is quite similar: http://datamining.anu.edu.au/~ole/pypar/ Both are high-level interfaces to MPI, i.e. they propose an MPI-like message passing interface with the main added value being communication of arbitrary Python objects. There is also a more low-level MPI interface in my ScientificPython library: http://dirac.cnrs-orleans.fr/ScientificPython/ScientificPythonManual/ Scientific_27.html It handles only strings and arrays, but with almost no overhead. Its strong point is its C interface, which makes it possible to write parallelized mixed C-Python code and to integrate parallelized C libraries into Python projects. Finally, if you are looking for parallel programming in Python but not necessarily an MPI-like approach, consider my BSP interface: http://dirac.cnrs-orleans.fr/ScientificPython/BSP_Tutorial.pdf This is what I personally consider the most convenient interface for parallel programming in Python. It is built on the BSP (Bulk Synchronous Processing) model that works at a higher level than message passing: the programmer does not have to worry about synchronization, which is a major source of hard-to-track- down bugs. Konrad. -- --------------------------------------------------------------------- Konrad Hinsen Laboratoire L?on Brillouin, CEA Saclay, 91191 Gif-sur-Yvette Cedex, France Tel.: +33-1 69 08 79 25 Fax: +33-1 69 08 82 61 E-Mail: konrad.hinsen at cea.fr --------------------------------------------------------------------- From bdesth.quelquechose at free.quelquepart.fr Mon Apr 24 21:23:16 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 25 Apr 2006 03:23:16 +0200 Subject: Can you create an instance of a subclass with an existing instance of the base class? In-Reply-To: <1145801642.764905.30020@v46g2000cwv.googlegroups.com> References: <1145650105.664762.321560@j33g2000cwa.googlegroups.com> <1145736124.831082.34550@v46g2000cwv.googlegroups.com> <1145801642.764905.30020@v46g2000cwv.googlegroups.com> Message-ID: <444d4b92$0$7905$636a55ce@news.free.fr> Sandra-24 a ?crit : > Lawrence D'Oliveiro wrote: > >>In article <1145736124.831082.34550 at v46g2000cwv.googlegroups.com>, >> "Sandra-24" wrote: >> >> >>>Now that is a clever little trick. I never would have guessed you can >>>assign to __class__, Python always surprises me in it's sheer >>>flexibility. >> >>That's because you're still thinking in OO terms. > > It's not quite as simple as all that. I agree that people, escpecially > people with a Java (ew) background overuse OO, when there's often > simpler ways of doing things. Nope. I mean : they don't overuse OO, they overuse *classes*. AFAIK, OO means *object* oriented - not class oriented. There are OO languages that don't even have a notion of class. > However in this case I'm simply getting an object (an mp_request object > from mod_python) passed into my function, and before I pass it on to > the functions that make up and individual web page it is modified by > adding members and methods to add functionality. Which is a well-known design pattern called "decorator". (snip) > Sadly I'm unable to create it as a python object first, because it's > created by the time my code comes into play. So I have to resort to > using the new module to add methods. This is OK IMHO. > It works, but it has to be redone for every request, Is this really a problem ? > I thought moving > the extra functionality to another object would simplify the task. > > A > better way might be to contain the mp_request within another object and > use __getattr__ to lazily copy the inner object. I'd probably have to > first copy those few fields that are not read-only or use __setattr__ > as well. Why copy ? You could as well just use composition/delegation (also using __getattr__ - and BTW, this is another possible implementation of the decorator pattern). From Serge.Orlov at gmail.com Fri Apr 28 09:31:11 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 28 Apr 2006 06:31:11 -0700 Subject: not quite 1252 In-Reply-To: <445214a1$1@usenet.zapto.org> References: <444f5e6b$1@usenet.zapto.org> <444f8781@usenet.zapto.org> <44507F68.7080804@lexicon.net> <4450e193$1@usenet.zapto.org> <1146228498.056632.168360@j73g2000cwa.googlegroups.com> <445214a1$1@usenet.zapto.org> Message-ID: <1146231071.769740.46120@j73g2000cwa.googlegroups.com> Anton Vredegoor wrote: > Serge Orlov wrote: > > > Anton Vredegoor wrote: > >> In fact there are a lot of printable things that haven't got a text > >> attribute, for example some items with tag (xxxx)s. > > > > In my sample file I see , is that you're talking > > about? Since my file is small I can say for sure this tag represents > > two space characters. > > Or for example in firefox: > > > in Amsterdam > > > So, probably yes. If it doesn't have a text attribrute if you iterate > over it using OOopy for example: > > o = OOoPy (infile = fname) > c = o.read ('content.xml') > for x in c.getiterator(): > if x.text: > > Then we know for sure you have recreated my other problem. I'm tweaking a small test file and see that is one space character is two space characters is three space characters From skip at pobox.com Sun Apr 23 22:05:40 2006 From: skip at pobox.com (skip at pobox.com) Date: Sun, 23 Apr 2006 21:05:40 -0500 Subject: MySQLdb In-Reply-To: <1145843959.890656.218710@i40g2000cwc.googlegroups.com> References: <1145843959.890656.218710@i40g2000cwc.googlegroups.com> Message-ID: <17484.12916.40906.745976@montanaro.dyndns.org> placid> Does anyone have binary for MySQLdb (python 2.4.3, MySQL 5.0a) ? Platform? Last I checked a few weeks ago, MySQLdb didn't yet work with MySQL 5.0. Skip From johnjsal at NOSPAMgmail.com Tue Apr 18 17:08:46 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 18 Apr 2006 21:08:46 GMT Subject: difference between class and static methods? In-Reply-To: References: Message-ID: Marc 'BlackJack' Rintsch wrote: > If you call `B.from_file('spam.xyz')` now, the `from_file()` method > inherited from class `A` is called but with `B` as the first argument so > it returns an instance of `B`. > > A staticmethod is just a function attached to a class without any "magic". So a class method is specifically for using the class name itself as an object in the method? If that's the case, then it makes some sense now. I guess the reason I didn't get it before is that this is a feature of dynamic languages, right? And something that couldn't have been done in C# anyway? From roy at panix.com Mon Apr 24 08:27:03 2006 From: roy at panix.com (Roy Smith) Date: Mon, 24 Apr 2006 08:27:03 -0400 Subject: need a thread to keep a socket connection alive? References: <1145718638.526525.235090@i39g2000cwa.googlegroups.com> Message-ID: nephish at xit.net wrote: > hey there, > > i have a script that waits for message packets from a data server over > a socket. > it goes a little like this: > > while 1: > x+=1 > databack = sockobj.recv(158) > if databack: > > print 'caught a message %s bytes ' % len(databack) > if len(databack) > 120: > message = databack[3:-3] #strip stx and enx > print '\n\n%s' % message > else: > break > print 'end data ack' You need to go review how TCP works. All that it guarantees is that you will receive bytes in the same order they were sent. It says nothing about maintaining record boundaries. Just because you did a send(n) at one end, it doesn't mean that you can expect to read n bytes in a single recv() call at this end. Multiple send() calls could have their contents accumlated into a single recv() call, or a single send() could get broken up into several recv() calls. If you want to read fixed-length messages (as you appear to be trying to do with your recv(158)), you need to build a buffering layer which reads from the socket into a buffer and then doles out messages to a higher layer from that buffer. > it works fine for a while, but the server requires that i send a > heartbeat ping every 600 seconds or it will terminate the connection. > > so i also need something like > while 1: > sockobj.send(ping) > ping_acknowlage = sockobj.recv(48) > time.sleep(550) This needs to be burried in a lower layer as well. You want to build some kind of bufferedConnection class which hides all this gunk from your application. You probably will want sendMessage() and recvMessage() methods for your class. You probably want to have this class create a thread to handle the low-level I/O asyncronously, and put the heatbeat processing in there. This is not a trivial problem. By the time you're done with it, you will have learned a lot about how to communicate over a network. From maria.kgn at gmail.com Sun Apr 16 06:03:57 2006 From: maria.kgn at gmail.com (MK) Date: 16 Apr 2006 03:03:57 -0700 Subject: sort in Excel Message-ID: <1145181837.674909.273600@e56g2000cwe.googlegroups.com> Hello, Does anyone knows how can I From anton.vredegoor at gmail.com Fri Apr 28 15:32:58 2006 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Fri, 28 Apr 2006 21:32:58 +0200 Subject: not quite 1252 In-Reply-To: <4450587D.6060103@v.loewis.de> References: <444f5e6b$1@usenet.zapto.org> <444FAA49.1000909@v.loewis.de> <444fe3e2$1@usenet.zapto.org> <4450587D.6060103@v.loewis.de> Message-ID: <44526dac$1@usenet.zapto.org> Martin v. L?wis wrote: > So if that is the case: What is the problem then? If you interpret > the document as cp1252, and it contains \x93 and \x94, what is > it that you don't like about that? In yet other words: what actions > are you performing, what are the results you expect to get, and > what are the results that you actually get? Well, where do these cp1252 codes come from? The xml-file claims it's utf-8. I just tried out some random decodings and cp1252 seemed to work. I don't like to have to guess this way. I think John wouldn't even allow it :-) Anton From andrew at trevorrow.com Tue Apr 25 00:51:53 2006 From: andrew at trevorrow.com (Andrew Trevorrow) Date: Tue, 25 Apr 2006 14:51:53 +1000 Subject: MS VC++ Toolkit 2003, where? References: <1he8pss.1yk7ug81rv7pw2N%aleaxit@yahoo.com> <1145811839.042394.73260@t31g2000cwb.googlegroups.com> <1he8sbx.dqqp3q10n5thaN%aleaxit@yahoo.com> <1145849491.347970.112150@e56g2000cwe.googlegroups.com> <1he9m4m.9d8okx1x7mxeaN%aleaxit@yahoo.com> <444C7896.9040104@v.loewis.de> <1heagzk.1pzfash1awhj3eN%aleaxit@yahoo.com> <1hebe5h.18mseq84cf1khN%aleaxit@yahoo.com> Message-ID: aleaxit at yahoo.com (Alex Martelli) wrote: > Andrew Trevorrow wrote: > > Or maybe someone is willing to make their VCToolkitSetup.exe available > > temporarily... > > I suggest any such offers be made privately, since I'm pretty sure > they'd be illegal (at least in the US, dunno 'bout Oz law). Oh, absolutely -- private offers only please. If it helps ease the conscience af any prospective benefactors, I *did* have a copy of VCToolkitSetup.exe at one point. I downloaded it about a year ago and installed it on Win2000 under Virtual PC, but later trashed it without making a backup, so that'll teach me. Failing any offers of help, I guess my options are: - Wait for Parallels to allow importing VPC disk images (I asked them about this but it's not going to happen soon). - Extract all the VC++ 2003 stuff from my VPC Win2000 system and copy it over to my Parallels system. Sounds like fun... - Look on ebay for a cheap copy of Visual Studio with VC++ 2003. - Download VC++ 2005 Express. I'm not planning to build extensions so I guess I don't really have to use VC++ 2003. Andrew From nogradi at gmail.com Wed Apr 12 05:53:11 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Wed, 12 Apr 2006 11:53:11 +0200 Subject: Problem with spawning an external process In-Reply-To: <1144834879.3376.39.camel@notamc2.snetsys.co.za> References: <1144834050.3376.35.camel@notamc2.snetsys.co.za> <1144834879.3376.39.camel@notamc2.snetsys.co.za> Message-ID: <5f56302b0604120253u2705a0fdo837a981d9930a635@mail.gmail.com> > > I want to execute a command (in this case, and it seems to be > > significant, a Java program) in a thread in Python. When I execute the > > java binary in the main python thread, everything runs correctly. But > > when I try and execute java in a thread, java segfaults. I am using > > Python 2.3.3 and trying to run the java binary from the 1.4.2 SDK from > > Sun. > > Here is the output that I get on my machine: > > [nico@ script]$ python testcrash2.py > > In main thread > > > > PID: 32107 signal: 0 return code: 1 > > In Thread > > PID: 32116 signal: 11 return code: 0 Your code works fine here both in the main and the new thread. Here is the output: In main thread PID: 5990 signal: 0 return code: 1 In Thread Waiting...PID: 5999 signal: 0 return code: 1 ...Finished So I guess the problem is somewhere else. From fredrik at pythonware.com Sun Apr 2 01:07:00 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 2 Apr 2006 08:07:00 +0200 Subject: Python 2.5 licensing: stop this change References: <1143917997.566424.231930@v46g2000cwv.googlegroups.com> Message-ID: "walterbyrd" wrote: > Please post a link to the original article. Not just a post to a blog. the pyfound blog is the official PSF blog; it's linked from the PSF:s homepage: http://www.python.org/psf/ From ladasky at my-deja.com Fri Apr 7 19:30:16 2006 From: ladasky at my-deja.com (John Ladasky) Date: 7 Apr 2006 16:30:16 -0700 Subject: Newbie wxPython questions. In-Reply-To: <1144438889.111109.20490@u72g2000cwu.googlegroups.com> References: <1144431488.217852.132790@j33g2000cwa.googlegroups.com> <1144438889.111109.20490@u72g2000cwu.googlegroups.com> Message-ID: <1144452616.480474.75100@i40g2000cwc.googlegroups.com> diffuser78 at gmail.com wrote: > I am also a newbie and learning like you are. I was wondering if do you > know any wxPython forum just for GUIs ? > Good luck with your project and hope that some guru helps us out. If you are reading this via Usenet, you can subscribe to the newsgroup comp.soft-sys.wxwindows. You will find people there who use the wxWidgets port in many different forms, including wxPython. You can also visit wxpython.org and subscribe to the mailing list. The mailing list is mirrored to the Usenet group. Good luck! +-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-+ | Ladasky Home Solar, Inc.: blowing sunshine up your | | power grid since March 24, 2005. Fiat lux! | +-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-+ | Uptime Downtime kWh generated kWh consumed | | 374 days none 6608 7143 | +-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-+ From onurb at xiludom.gro Wed Apr 26 05:36:26 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 26 Apr 2006 11:36:26 +0200 Subject: OOP / language design question In-Reply-To: References: <1145961248.794496.80220@j33g2000cwa.googlegroups.com> <1145963311.348482.15080@i40g2000cwc.googlegroups.com> <444e0dec$0$27071$626a54ce@news.free.fr> <444e38e9$0$29686$636a55ce@news.free.fr> <1hedc5l.toeunc1twg6bsN%aleaxit@yahoo.com> Message-ID: <444f3f6f$0$27980$626a54ce@news.free.fr> Duncan Booth wrote: > Alex Martelli wrote: > > >>>What I think I'm trying to get at is that I believe that most >>>situations where someone actually tries to do something in the base >>>initialiser which requires calling a virtual method are probably also >>>cases where the initialiser is doing too much: i.e. separating the >>>construction/initialisation from actually doing something is usually >>>a good idea. >> >>But why should that be? Template Method is perhaps the MOST generally >>useful design pattern -- why would it be any less useful in >>initialization than elsewhere?! >> > > Because it is error prone? Programming *is* error prone. > Any method which is called from the constructor/initialiser has to operate > correctly any method has to operate correctly anyway !-) > on an object which at that point is not fully > constructed/initialised. In Python, when the __init__ method is called, the object is at least fully constructed. > So instead of having to write a method on a Foo > object, your template method has to operate on a partial Foo. The danger is > that you haven't clearly defined the partial Foo interface sufficiently and > the method tries to use other parts of the object which haven't yet been > set up. If so, the worse thing that can happen is an exception - and you'll surely spot the problem really soon. > That situation gets worse when you have a class hierarchy as the > subclass needs to know that it has to do complete its own initialisation > before constructing the base class instead of afterwards, and if you are > going to document that requirement, why not do it properly and split the > construction in two? It's *already* split : __new__ construct the object, __init__ initialize it. > That's why I would go for the 2-phase construction: But that's already what you have. > after the first phase > you have an object which is fully initialised, just not yet > used/connected/running. For example httplib.HTTPConnection does this: you > construct the object with a host and port, but the actual connection is > triggered by a separate object. If you look at file objects, they do try and open the file at init time. Is a net or db connection that different ? (snip) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From ray_usenet at yahoo.com Sun Apr 9 23:32:07 2006 From: ray_usenet at yahoo.com (Ray) Date: 9 Apr 2006 20:32:07 -0700 Subject: Python 3.0 or Python 3000? In-Reply-To: References: <4439aba9$0$18019$c3e8da3@news.astraweb.com> Message-ID: <1144639927.634478.319420@v46g2000cwv.googlegroups.com> Dennis Lee Bieber wrote: > Or... just to save "3000" as a "time way down the road"... The next > major version of Python will be: Python PI (and each build will add > another digit... "3.1, 3.14, 3.141, ...") I like this idea a lot. This way, people ALWAYS know what the next release's name will be. > -- > > ============================================================== < > > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > > wulfraed at dm.net | Bestiaria Support Staff < > > ============================================================== < > > Home Page: < > > Overflow Page: < From steve at REMOVETHIScyber.com.au Wed Apr 12 19:15:22 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Thu, 13 Apr 2006 09:15:22 +1000 Subject: list.clear() missing?!? References: <1144767680.583085.310160@v46g2000cwv.googlegroups.com> <1144792144.168802.146310@i39g2000cwa.googlegroups.com> <1144870852.886477.238570@u72g2000cwu.googlegroups.com> Message-ID: On Wed, 12 Apr 2006 12:40:52 -0700, Raymond Hettinger wrote: > Something this small doesn't need a PEP. I'll just send a note to > Guido asking for a pronouncement. Raymond, if you're genuinely trying to help get this sorted in the fairest, simplest way possible, I hope I speak for everyone when I say thank you, your efforts are appreciated. But there is this: > * the request is inane, the underlying problem is trivial, and the > relevant idiom is fundamental (api expansions should be saved for rich > new functionality and not become cluttered with infrequently used > redundant entries) Is this sort of editorialising fair, or just a way of not-so-subtly encouraging Guido to reject the whole idea, now and forever? Convenience and obviousness are important for APIs -- that's why lists have pop, extend and remove methods. The only difference I can see between a hypothetical clear and these is that clear can be replaced with a one-liner, while the others need at least two, e.g. for extend: for item in seq: L.append(item) Here is another Pro for your list: A list.clear method will make deleting items from a list more OO, consistent with almost everything else you do to lists, and less procedural. This is especially true if clear() takes an optional index (or two), allowing sections of the list to be cleared, not just the entire list. -- Steven. From edeveaud at pasteur.fr Thu Apr 13 05:41:19 2006 From: edeveaud at pasteur.fr (Eric Deveaud) Date: Thu, 13 Apr 2006 09:41:19 +0000 (UTC) Subject: Iterating command switches from a data file - have a working solution but it seems inefficient References: <123r6925duev9b2@corp.supernews.com> <443e0edc$0$20655$636a55ce@news.free.fr> <123s5qm84atdf5d@corp.supernews.com> Message-ID: News wrote: > bruno at modulix wrote: > > > > Have you looked at optparse ? > > > I have. > > The module optparse seemed to be aimed at reading from commandline > versus pulling attributes from a read line. hummmm .... lets see optparse seems to be reading from commandline. that's not false but not really true ;-) point 1: remember that commandline reading is done thru sys.argv wich provide a a list of strings point 2 now consider pulling datas from readline, wich return a string. if you split this string you'll have a list of string. point 3 optparse is designed for reading from a list of strings I let the conclusion to your imagination ;-)) Eric -- Salut,Je m'appele sed.je suis etudiant en communication, j'ai lu votre message.je viens vous dire un petiit bonjour,et vous laisser mon m?l: vous pouvez me repondre maintenant si vous ?tez conecter. -+-Guide du Neuneu d'Usenet - La com', elle ne passera pas par moi -+- From fuzzyman at gmail.com Sun Apr 9 12:31:31 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 9 Apr 2006 09:31:31 -0700 Subject: I wanna use urllib2 to get a page with a socks 5 proxy, who can give me a sample code ? In-Reply-To: <1144593748.272792.133830@e56g2000cwe.googlegroups.com> References: <1144593748.272792.133830@e56g2000cwe.googlegroups.com> Message-ID: <1144600290.971425.11090@i40g2000cwc.googlegroups.com> Ju Hui wrote: > I wanna use urllib2 to get a page with a socks 5 proxy,who can give me > a sample code ? > > example, > the proxy server is :123.123.123.123 > and the port is :1080 > and the username/password is : user/pass > I want to open http://www.google.com > > how to write this kind of script? I'm pretty sure that urllib2 doesn't work with SOCKS proxies of any kind. I think you'll have to use pycurl (extension library - not in standard lib). This is mcuh more powerful, but not so simple to use. All the best, Fuzzyman http://www.voidspace.org.uk/python/index.shtml > thanks. From kelvie at ieee.org Wed Apr 19 12:13:09 2006 From: kelvie at ieee.org (Kelvie Wong) Date: Wed, 19 Apr 2006 09:13:09 -0700 Subject: semi-[OT]: adding a reply-to line to these mails? In-Reply-To: <444641BE.9050601@freakmail.de> References: <4444CD12.7080807@freakmail.de> <87r73uh594.fsf@benfinney.id.au> <444641BE.9050601@freakmail.de> Message-ID: <94ccbe710604190913g42b0cb30s1cbce853092f5678@mail.gmail.com> Is there not a "Reply to all" function in Thunderbird? (and I'd go shopping for plugins for TB, if not) (Sorry, Wildemar, looks like I didn't click Reply to all :d) On 4/19/06, Wildemar Wildenburger wrote: > Ben Finney wrote: > > Wildemar Wildenburger writes: > > > > > >> I've noticed that I replied to individual posters' private addresses > >> several times now ... > >> > > > > That's a much preferable, and much more easily corrected, error than > > the alternative: replying to the entire group what was intended only > > for the individual in private. > > > > > >> So a quick note to the admin(s): see topic ;) > >> > > > > The Reply-To header field is to be set by an individual on their own > > messages, to indicate where a *private* reply should go. > > > > > > I guess that means no, huh? > > :) > -- > http://mail.python.org/mailman/listinfo/python-list > -- Kelvie From aleaxit at yahoo.com Mon Apr 24 00:15:23 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 23 Apr 2006 21:15:23 -0700 Subject: MS VC++ Toolkit 2003, where? References: <1he8pss.1yk7ug81rv7pw2N%aleaxit@yahoo.com> <1145811839.042394.73260@t31g2000cwb.googlegroups.com> <1he8sbx.dqqp3q10n5thaN%aleaxit@yahoo.com> <1145849491.347970.112150@e56g2000cwe.googlegroups.com> Message-ID: <1he9m4m.9d8okx1x7mxeaN%aleaxit@yahoo.com> AIM wrote: > The site comes back with a message saying ... > > "The download you requested is unavailable. If you continue to see this > message when trying to access this download, go to the "Search for a > Download" area on the Download Center home page." > > Does anyone have any other ideas of where to look? As suggested to me by David Rushby 10 hours ago, http://www.microsoft.com/downloads/details.aspx?FamilyId=272BE09D-40BB-4 9FD-9CB0-4BFA122FA91B&displaylang=en does work. But, there's another problem -- helloworld.c compiles fine, but linking doesn't find MSVCRT.LIB -- apparently, the 2.0 .NET Framework SDK does NOT include this file for x86 (there _are_ a couple of versions under a64 and some other parallel directory, but I doubt they're good to use with an x86!-). As the already-quoted crucial URL mentions: """ # .NET Framework SDK Version 1.1 Provides the core msvcrt.lib for msvcr71.dll against which to link your extensions. This is critically important, as without it you are going to wind up linking against the wrong run-time and will see crashes whenever a core object such as a file is shared across run-time barriers. The 2.0 beta also works according to reports, and may be required to build Numpy 23.6 (whereas 23.1 seems to work without it). """ Whether the 2.0 beta also worked, the current definitive 2.0 seems NOT to work. Can anybody suggest where to get a Framework SDK 1.1., or any other legal way to get "the core msvcrt.lib for msvcr71.dll against which to link your extensions. This is critically important"...??? And, as an aside...: It's sure an interesting reflection, that impecunious or thrifty developers (ones not willing to shell out mucho $$$ to MS for a pro VS 2003) must go through such gyrations as these in order to be able to build Python extensions on Windows. I'm sure my Windows-loving colleagues in the PSF (who got several free copies of VS 2003 from Microsoft, I believe -- at the time, I had zero Windows installations and zero interest in Windows, so I didn't sign up for one) have fully considered this recurring drama, and come to the decision of sticking with VS 2003 (avoiding any free-as-in-beer compilers such as VS 2005 or mingw) with thorough and wise deliberation. The optimizer in the C compiler used to build Python in Windows *IS* impressive: just today, I ran (and posted to it.comp.macintosh) pybench on Python 2.4.3 on iBook G4 12", Macbook Pro 2.0 GHz, and Parallels Workstation VM with Win2000 on the same Macbook -- while the Macbook is 4 times as fast as the iBook, the Windows version, despite the slight overhead of running under Parallels' virtualization, is an impressive 12%+ _faster_ than the "native" MacOSX Python 2.4.3 (I'm not quite sure about how good Parallels' virtualization IS, but even if it's as impressive as a mere 3% overhead, this still means that the Windows version of Python on identical HW must be at least 15% faster than the MacOSX version, compiled with gcc). I can see the stance that such a speedup warrants using Microsoft's costly VS 2003 and imposing endless gyrations on developers trying to get it on the cheap -- being one of the latter developers, I'm inclined nevertheless to grumble, right now, of course;-)... Alex From richard.hsu at gmail.com Wed Apr 5 23:53:48 2006 From: richard.hsu at gmail.com (richard.hsu at gmail.com) Date: 5 Apr 2006 20:53:48 -0700 Subject: slicing question: rawdata[j:j+1] == 'xx' #will this ever be true ?? Message-ID: <1144295628.022719.166970@e56g2000cwe.googlegroups.com> I am new to python language and most of my python programming has been done with IronPython. I was looking at the source of markupbase.py which is included with Python 2.4 and came across the following line of code:- if rawdata[j:j+1] == '--': #comment i was confused because based on my understanding of the slicing syntax, rawdata[j:j+1] will either yield a string with ONE character or an empty string, therefore this boolean comparison will always be False because we are checking if it will be equal to a string with 2 characters! am I missing something here ? thank you in advance for educating me. From jjl at pobox.com Wed Apr 12 18:41:41 2006 From: jjl at pobox.com (John J. Lee) Date: 12 Apr 2006 22:41:41 +0000 Subject: Python editing with emacs/wordstar key bindings. References: Message-ID: <87bqv6quvu.fsf@pobox.com> "Thomas Bartkus" writes: [...] > > 1) When I load a .py file, emacs automatically overrides my wordstar-mode > with python-mode, forcing all the keybindings back to emacs native keys. > Why? > > Why should a python-mode care what key bindings are in use? No idea. Quite odd. > 2) We get for block indentation instead of the spaces I prefer. That's odd, I get four spaces unless I'm editing an existing file that already uses some other convention, in which case python-mode is usuall smart enough to figure that out. I don't use wordstar-mode. > Is there a better python-mode script I should be using other than the > default that came with emacs? I assume you're using X/Emacs, then, rather than GNU Emacs? IIRC, there's a separate sourceforge project for python-mode now, so you could give that version a try. John From steve at REMOVETHIScyber.com.au Thu Apr 13 22:46:32 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Fri, 14 Apr 2006 12:46:32 +1000 Subject: Remove Whitespace References: <9583ed900604131200n5c43829ckeb01ba4503763954@mail.gmail.com> Message-ID: On Thu, 13 Apr 2006 12:09:32 -0700, Kelvie Wong wrote: > try this: > > string = 'D c a V e r " = d w o r d : 0 0 0 0 0 6 4 0' > import re > re.sub("\s", "", string) Why would you want to call in the heavy sledgehammer of regular expressions for cracking this peanut? old_s = 'D c a V e r " = d w o r d : 0 0 0 0 0 6 4 0' new_s = old_s.replace(" ", "") And if you want to remove all whitespace: new_s = "".join(old_s.split()) -- Steven. From michele.petrazzo at TOGLIunipex.it Mon Apr 24 09:03:44 2006 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Mon, 24 Apr 2006 15:03:44 +0200 Subject: GRIB to images In-Reply-To: <1145883056.639668.214920@t31g2000cwb.googlegroups.com> References: <1145883056.639668.214920@t31g2000cwb.googlegroups.com> Message-ID: <444cccae$0$29111$5fc30a8@news.tiscali.it> Sheldon wrote: > Hi, > > I am interesseted on reading some GRIB files using python and then > converting the fields to gif images. > > Does anyone know if this is possible or have a program that does this? Yes of course with PIL. http://www.pythonware.com/products/pil/ http://effbot.org/imagingbook/format-grib.htm > > /Sheldon > Michele From walterbyrd at iname.com Tue Apr 11 22:12:32 2006 From: walterbyrd at iname.com (walterbyrd) Date: 11 Apr 2006 19:12:32 -0700 Subject: Application Generators In-Reply-To: <1144771837.976918.177800@i39g2000cwa.googlegroups.com> References: <1143917722.208117.223790@e56g2000cwe.googlegroups.com> <1144770265.241893.115810@j33g2000cwa.googlegroups.com> <1144771837.976918.177800@i39g2000cwa.googlegroups.com> Message-ID: <1144807951.936179.253100@g10g2000cwb.googlegroups.com> Thanks. It does look good. The personal editon costs less than phprunner. And it seems much more powerful than PHPRunner. From ldo at geek-central.gen.new_zealand Wed Apr 12 01:18:21 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 12 Apr 2006 17:18:21 +1200 Subject: Decorators, Identity functions and execution... References: <1144597938.664642.133100@v46g2000cwv.googlegroups.com> <1144742379.824131.299990@t31g2000cwb.googlegroups.com> Message-ID: In article <1144742379.824131.299990 at t31g2000cwb.googlegroups.com>, "Ben Sizer" wrote: >Lawrence D'Oliveiro wrote: >> In article <1144597938.664642.133100 at v46g2000cwv.googlegroups.com>, >> "Carl Banks" wrote: >> >> >Always use spaces when posting, and use them in your code as well. >> >Spaces are the current recommended practice, and in the future tabs >> >might become illegal. I'd prefer tabs myself, but it's more important >> >to respect community standards than to stick to some silly preference >> >you have. >> >> Tab stops every 4 columns. What's silly about that? Any other definition >> is silly, or at best antiquated. > >Every day I come across people or programs that use tab stops every 2 >or 8 columns. I am another fan of tabs every 4 columns, but >unfortunately this isn't standard, so spaces in Python it is. All we have to do is keep using and promoting 4-column tabs every chance we get. I've been using them myself for about 18 years. Eventually they'll become accepted as the standard. From foobarbazqux at ftml.net Wed Apr 12 16:20:28 2006 From: foobarbazqux at ftml.net (Bill) Date: 12 Apr 2006 13:20:28 -0700 Subject: Figure out month number from month abbrievation Message-ID: <1144873227.982973.18720@i40g2000cwc.googlegroups.com> Hello -- I'm parsing the output of the finger command, and was wondering something...If I'm given a month abbrievation (such as "Jan"), what's the best way to figure out the month number? I see that there's something called "month_abbr" in the calendar module. However, when I try to do calendar.month_abbr.index("Jan"), I get "_localized_month instance has no attribute 'index'." So it seems that month_abbr isn't a regular list. I'm currently doing it this way: def month_number(monthabbr): """Return the month number for monthabbr; e.g. "Jan" -> 1.""" for index, day in enumerate(calendar.month_abbr): if day == monthabbr: return index which works well enough but isn't very clever. I'm pretty new to Python; what am I missing here? Thanks -- Bill. From lennart at kommunicera.umea.se Mon Apr 3 15:28:20 2006 From: lennart at kommunicera.umea.se (lennart at kommunicera.umea.se) Date: 3 Apr 2006 12:28:20 -0700 Subject: overloading constructor in python? Message-ID: <1144092500.618489.204740@e56g2000cwe.googlegroups.com> This is probably a really stupid question, but I cant seem to find a satisfying answer by myself so here it goes. In for example java we could create a class dummie with several constructors, say one that takes an int, and one that takes a String as argument. In python it doesnt seem possible to have several __init__ methods ( and I assume if we could there would be some problem to determine which __init__ to use). So my question is how this is normally solved in python? I dont really like the idea of using neither def __init__(self, o): if type(o) is ... nor subclasses for the baseclass, but I cant think of another way. Any thoughts anyone? Thanx /Lennart From kruhftREMOVE at gmail.com Mon Apr 17 14:59:52 2006 From: kruhftREMOVE at gmail.com (Burton Samograd) Date: 17 Apr 2006 12:59:52 -0600 Subject: C FFI: easy conversion from list to argv? References: <87vet8awyw.fsf@gmail.com> Message-ID: <87r73wauzb.fsf@gmail.com> Burton Samograd writes: > I'm trying to update the fuse python bindings to my app and I was > curious if there were any C utility functions that would turn a > sys.argv into a C style argv array, or am I going to have to write > those myself? Following up to myself again...found the solution: ---------------------------------------------------------------------- PyObject *argv; /* value from PyArg_ParseTupleAndKeywords elsewhere */ int _argc = PySequence_Length(argv); char **_argv = malloc(_argc*sizeof(char**)); int i; for(i=0;i<_argc;i++) _argv[i] = PyString_AsString(PyList_GetItem(argv, i)); ---------------------------------------------------------------------- Could probabaly use some error checking but it works... -- burton samograd kruhft .at. gmail kruhft.blogspot.com www.myspace.com/kruhft metashell.blogspot.com From gry at ll.mit.edu Fri Apr 7 14:20:03 2006 From: gry at ll.mit.edu (gry at ll.mit.edu) Date: 7 Apr 2006 11:20:03 -0700 Subject: glob and curly brackets In-Reply-To: References: Message-ID: <1144434003.468127.290910@t31g2000cwb.googlegroups.com> This would indeed be a nice feature. The glob module is only 75 lines of pure python. Perhaps you would like to enhance it? Take a look. From robert.kern at gmail.com Thu Apr 6 12:02:53 2006 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 06 Apr 2006 11:02:53 -0500 Subject: python on Mac In-Reply-To: <1144337441.565462.202030@v46g2000cwv.googlegroups.com> References: <1144284073.446005.53950@t31g2000cwb.googlegroups.com> <1144330655.771606.275130@v46g2000cwv.googlegroups.com> <1144337441.565462.202030@v46g2000cwv.googlegroups.com> Message-ID: Thomas Nelson wrote: > Well, as I stated in post, I've already replaced the link at > /usr/bin/python. I'm not clear why that's unhealthy. The FAQ describes why it's unhealthy in detail. "FAQ 5.7 Describe Apple's Framework implementation of Python and how that affects me adding new Python implementations" http://pythonmac.org/wiki/FAQ#head-392d16c2e6e49d6de6555634fc94759989464b5a > Should I change > it back to whatever it was before? I guess maybe it was > /System/Library/Frameworks/Python.framework/Versions/Current/bin/python > ? [src]$ ls -l /usr/bin/python lrwxr-xr-x 1 root wheel 9 May 1 2005 /usr/bin/python -> python2.3 [src]$ ls -l /usr/bin/python2.3 lrwxr-xr-x 1 root wheel 72 May 1 2005 /usr/bin/python2.3 -> ../../System/Library/Frameworks/Python.framework/Versions/2.3/bin/python -- Robert Kern robert.kern at gmail.com "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From olsongt at verizon.net Tue Apr 18 13:50:54 2006 From: olsongt at verizon.net (olsongt at verizon.net) Date: 18 Apr 2006 10:50:54 -0700 Subject: Missing interfaces in Python... References: <1145306373.781129.305840@z34g2000cwc.googlegroups.com> Message-ID: <1145382654.423527.265160@v46g2000cwv.googlegroups.com> redefined.horizons at gmail.com wrote: > I'm coming from a Java background, so please don't stone me... > > I see that Python is missing "interfaces". The concept of an interface > is a key to good programming design in Java, but I've read that they > aren't really necessary in Python. I am wondering what technique I can > use in Python to get the same benefits to a program design that I would > get with interfaces in Java. > > For example, if I want to have a program with a Car object, and a Bus > object. I want both of these objects to present a common group of > methods that can be used by Mechanic objects, but slightly different > methods that can be used by Driver objects. > > In Java I would accomplish this by defining an IFixable interface that > would be implemented by both the Car and Bus objects. Mechanic objects > would work with any object implementing this interface. > > How would I approach this problem in Python? I think I would use an > abstract class instead of an interface for IFixable, since Python > supports multiple inheritance, but I'm not sure this is correct. > > Thanks for any suggestions. > > Scott Huey Everyone is getting off track here. Java has interfaces because it doesn't support multiple inheritance. Python supports MI, so you don't need to use the seperate concept of an interface. You're right that an abstract class is the equivilent of an interface. Just create a ABC that raises NotImplementedExceptions for each of the methods, and use that class as one of the base classes. Of course, like a lot of stuff in python, this won't throw an exception at 'compile-time', only when you try to invoke a method that has no implemenation. The general wisdom is that Abstract Base Classes aren't pythonic though. If you want to be pythonic, just implement the methods for your 'interface', and (if necessary) check for their existance with hasattr before calling (or even just call the method and you'll get an attribute error anyway). This is referred to as duck-typing. If it looks like a duck, and quacks like a duck, then for all practical purposes it supports the 'duck' interface. From tjreedy at udel.edu Wed Apr 12 21:14:41 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 12 Apr 2006 21:14:41 -0400 Subject: list.clear() missing?!? References: <1144767680.583085.310160@v46g2000cwv.googlegroups.com> <1144792144.168802.146310@i39g2000cwa.googlegroups.com> <1144870852.886477.238570@u72g2000cwu.googlegroups.com> Message-ID: "Peter Hansen" wrote in message news:e1k6ev$42c$1 at sea.gmane.org... > It's not even clear that extend needs two lines: > > >>> s = range(5) > >>> more = list('abc') > >>> s[:] = s + more > >>> s > [0, 1, 2, 3, 4, 'a', 'b', 'c'] This is not the same as list.extend because it makes a separate intermediate list instead of doing the extension completely in place. However, the following does mimic .extend. >>> s=range(5) >>> s[len(s):] = list('abc') >>> s [0, 1, 2, 3, 4, 'a', 'b', 'c'] So. at the cost of writing and calling len(s), you are correct that .extend is not necessary. Terry Jan Reedy From cygnus at cprogrammer.org Tue Apr 25 23:26:43 2006 From: cygnus at cprogrammer.org (Jonathan Daugherty) Date: Tue, 25 Apr 2006 20:26:43 -0700 Subject: 345 free programming books In-Reply-To: References: <1146020222.383927.319890@i40g2000cwc.googlegroups.com> Message-ID: <20060426032643.GS7561@vulcan.cprogrammer.org> # http://ttcom.blogspot.com/2006/04/345-free-online-programming-books.html It seems this has been making the rounds today. The Practical PostgreSQL link is also broken; OpenDocs Publishing ceased to exist starting several months ago. -- Jonathan Daugherty http://www.parsed.org From rpdooling at gmail.com Mon Apr 10 09:48:05 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 10 Apr 2006 06:48:05 -0700 Subject: can't pass command-line arguments References: Message-ID: <1144676885.317592.21780@e56g2000cwe.googlegroups.com> Tim, No conflicting bat file. Script name cbfindfiles.py import os import fnmatch import sys def all_files(root, patterns='*', single_level=False, yield_folders=False): """walks the directory tree starting at root and finds all files matching patterns""" # Expand patterns from semicolon-separated string to list patterns = patterns.split(';') for path, subdirs, files in os.walk(root): if yield_folders: files.extend(subdirs) files.sort() for name in files: for pattern in patterns: if fnmatch.fnmatch(name, pattern): yield os.path.join(path, name) break if single_level: break if __name__ == "__main__": print sys.argv for path in all_files(sys.argv[1], sys.argv[2]): print path If I run cbfindfiles.py d:/ *emacs* from the command prompt I get: ['d:\\python\\cbfindfiles.py', 'd:/', '*emacs*'] followed by a list of matching files If I run cbfindfiles d:/ *emacs* If get an empty command prompt back. Oh, well. Not worth troubling over. Thank you again. Rick From dausha at gmail.com Wed Apr 19 13:46:42 2006 From: dausha at gmail.com (Ben Wilson) Date: 19 Apr 2006 10:46:42 -0700 Subject: Better way to sift parts of URL . . . In-Reply-To: <7pd1g.46$0Z4.8@tornado.texas.rr.com> References: <1145392079.720766.122310@z34g2000cwc.googlegroups.com> <7pd1g.46$0Z4.8@tornado.texas.rr.com> Message-ID: <1145468802.471081.209840@u72g2000cwu.googlegroups.com> This is what I ended up with. Slightly different approach: import urlparse def sUrl(s): page = group = '' bits = urlparse.urlsplit(s) url = '//'.join([bits[0],bits[1]]) + '/' query = bits[2].split('/') if '' in query: query.remove('') if len(query) > 1: page = query.pop() if len(query) > 0 and query[-1] == query[-1].capitalize(): group = query.pop() if len(query): url += '/'.join(query) + '/' if page == '': page = 'Main' if group == '': group = 'Main' page = '.'.join([group,page]) print " URL: (%s) PAGE: (%s)" % (url, page) urls = [ "http://www.example.org/test/Main/AnotherPage", # (page = Main/AnotherPage) "http://www.example.org/test/Main", # (page = Main + '/' + default_page) "http://www.example.org/test", # (page = default_group + '/' + default_page) "http://www.example.org/test/", # (page = default_group + '/' + default_page) "http://www.example.org/", # (page = default_group + '/' + default_page) "http://www.example.org/Main/AnotherPage", ] for u in urls: print "Testing:",u sUrl(u) From steve at REMOVETHIScyber.com.au Wed Apr 12 07:09:23 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Wed, 12 Apr 2006 21:09:23 +1000 Subject: list.clear() missing?!? References: <1144767680.583085.310160@v46g2000cwv.googlegroups.com> <443BE426.20501@v.loewis.de> <1144827208.841644.148130@v46g2000cwv.googlegroups.com> Message-ID: On Wed, 12 Apr 2006 00:33:29 -0700, Serge Orlov wrote: > > Felipe Almeida Lessa wrote: >> Em Qua, 2006-04-12 ?s 11:36 +1000, Steven D'Aprano escreveu: >> > On Tue, 11 Apr 2006 19:15:18 +0200, Martin v. L?wis wrote: >> > >> > > Felipe Almeida Lessa wrote: >> > >> I love benchmarks, so as I was testing the options, I saw something very >> > >> strange: >> > >> >> > >> $ python2.4 -mtimeit 'x = range(100000); ' >> > >> 100 loops, best of 3: 6.7 msec per loop >> > >> $ python2.4 -mtimeit 'x = range(100000); del x[:]' >> > >> 100 loops, best of 3: 6.35 msec per loop >> > >> $ python2.4 -mtimeit 'x = range(100000); x[:] = []' >> > >> 100 loops, best of 3: 6.36 msec per loop >> > >> $ python2.4 -mtimeit 'x = range(100000); del x' >> > >> 100 loops, best of 3: 6.46 msec per loop >> > >> >> > >> Why the first benchmark is the slowest? I don't get it... could someone >> > >> test this, too? >> > > >> > > In the first benchmark, you need space for two lists: the old one and >> > > the new one; >> > >> > Er, what new list? I see only one list, x = range(100000), which is merely >> > created then nothing done to it. Have I missed something? >> >> He's talking about the garbage collector. > > To be exact the reason for two array is timeit.py. It doesn't place the > code to time into a separate namespace but injects it into a for loop, > so the actual code timed is: > for _i in _it: > x = range(100000) > and that makes two arrays with 100.000 items exist for a short time > starting from second iteration. But that is precisely the same for the other timeit tests too. for _i in _it: x = range(100000) del x[:] etc. The question remains -- why does it take longer to do X than it takes to do X and then Y? -- Steven. From mahs at telcopartners.com Sat Apr 8 18:49:11 2006 From: mahs at telcopartners.com (Michael Spencer) Date: Sat, 08 Apr 2006 15:49:11 -0700 Subject: how to make a generator use the last yielded value when it regains control In-Reply-To: <4435e96d$0$17970$c3e8da3@news.astraweb.com> References: <4435cde3$0$11677$c3e8da3@news.astraweb.com> <1144383206.576767.192570@g10g2000cwb.googlegroups.com> <4435e96d$0$17970$c3e8da3@news.astraweb.com> Message-ID: John Salerno wrote: > Ben Cartwright wrote: > >> Definitely go for (1). The Morris sequence is a great candidate to >> implement as a generator. As a generator, it will be more flexible and >> efficient than (2). > > Actually I was just thinking about this and it seems like, at least for > my purpose (to simply return a list of numbers), I don't need a > generator. My understanding of a generator is that you do something to > each yielded value before returning to the generator (so that you might > not return at all), but since I'm not handling the individual numbers, > just getting a list, it seems I don't need them to be yielded. Of > course, a generator would allow the process to be done over and over, I > suppose, which is what I wanted, I just couldn't figure out how to keep > using the new values. itertools.groupby makes this very straightforward: >>> from itertools import groupby ... >>> def lookandsay(seed): ... seed = str(seed) ... while 1: ... seed = "".join("%s%s" % (len(list(group)), item) ... for item, group in groupby(seed)) ... yield seed ... >>> >>> seq = lookandsay(1) >>> seq.next() '11' >>> seq.next() '21' >>> seq.next() '1211' >>> seq.next() '111221' >>> seq.next() '312211' If you want to get just part of the infinite series, use itertools.islice: >>> from itertools import islice >>> list(islice(lookandsay(1),10)) ['11', '21', '1211', '111221', '312211', '13112221', '1113213211', '31131211131221', '13211311123113112211', '11131221133112132113212221'] >>> list(islice(lookandsay(1),10,20)) ['3113112221232112111312211312113211', '1321132132111213122112311311222113111221131221', '11131221131211131231121113112221121321132132211331222113112211', '311311222113111231131112132112311321322112111312211312111322212311322113212221', '132113213221133112132113311211131221121321131211132221123113112221131112311332111213211322211312113211', '11131221131211132221232112111312212321123113112221121113122113111231133221121321132132211331121321231231121113122113322113111221131221', '31131122211311123113321112131221123113112211121312211213211321322112311311222113311213212322211211131221131211132221232112111312111213111213211231131122212322211331222113112211', '1321132132211331121321231231121113112221121321132122311211131122211211131221131211132221121321132132212321121113121112133221123113112221131112311332111213122112311311123112111331121113122112132113213211121332212311322113212221', '11131221131211132221232112111312111213111213211231132132211211131221131211221321123113213221123113112221131112311332211211131221131211132211121312211231131112311211232221121321132132211331121321231231121113112221121321133112132112312321123113112221121113122113121113123112112322111213211322211312113211', '311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122211311122122111312211213211312111322211213211321322113311213212322211231131122211311123113223112111311222112132113311213211221121332211211131221131211132221232112111312111213111213211231132132211211131221232112111312211213111213122112132113213221123113112221131112311311121321122112132231121113122113322113111221131221'] >>> HTH Michael From sjuranic at gmail.com Tue Apr 25 10:54:06 2006 From: sjuranic at gmail.com (Steve Juranich) Date: Tue, 25 Apr 2006 07:54:06 -0700 Subject: Zope 3 References: <1145965796.432891.274310@i39g2000cwa.googlegroups.com> Message-ID: Derick van Niekerk wrote: > I love Python! Then I was introduced to Zope by freak accident. While > Zope looked like the answer to my dillemma, I still can't get my head > wrapped around it. Is it because I don't know Python well enough? Or is > it just that difficult to learn? I've been hacking Python now for 6 years. I just picked up Zope last month and found the learning curve to be quite steep. It's not just you. There's a lot of stuff there. > I would like to start my next web project (a database of demographic > info on scientists in Africa) on Zope 3. Could anybody point me in the > right direction? Where should I start? After you look through the tutorial (which is simply a Zope product you can add from the main page of the ZMI (Zope Management Interface), have a peek at the Zope book (http://www.zope.org/Documentation/Books/ZopeBook/2_6Edition/view). Don't worry about the version (2.6) of the book. It's the latest they have (I think they're working on a new one for z3). You can skip the bits about DTML, but keep them handy. You should also take a look at the Zope user list: http://mail.zope.org/mailman/listinfo/zope Hope this all helps. -- Steve Juranich Tucson, AZ USA From sandravandale at yahoo.com Sat Apr 22 16:02:04 2006 From: sandravandale at yahoo.com (Sandra-24) Date: 22 Apr 2006 13:02:04 -0700 Subject: Can you create an instance of a subclass with an existing instance of the base class? References: <1145650105.664762.321560@j33g2000cwa.googlegroups.com> Message-ID: <1145736124.831082.34550@v46g2000cwv.googlegroups.com> Now that is a clever little trick. I never would have guessed you can assign to __class__, Python always surprises me in it's sheer flexibility. In this case it doesn't work. TypeError: __class__ assignment: only for heap types I suspect that's because this object begins its life in C code. The technique of using the __class__.__subclasses__ also fails: TypeError: cannot create 'B' instances This seems more complex than I thought. Can one do this for an object that beings it's life in C? Thanks, -Sandra Peter Otten wrote: > Sandra-24 wrote: > > > Can you create an instance of a subclass using an existing instance of > > the base class? > > > > Such things would be impossible in some languages or very difficult in > > others. I wonder if this can be done in python, without copying the > > base class instance, which in my case is a very expensive object. > > You can change the class of an instance by assigning to the __class__ > attribute. The new class doesn't even need to be a subclass of the old: > > >>> class A(object): > ... def __init__(self, name): > ... self.name = name > ... def show(self): print self.name > ... > >>> a = A("alpha") > >>> a.show() > alpha > >>> class B(object): > ... def show(self): print self.name.upper() > ... > >>> a.__class__ = B > >>> a.show() > ALPHA > > Peter From ldo at geek-central.gen.new_zealand Sun Apr 16 19:07:56 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 17 Apr 2006 11:07:56 +1200 Subject: Async Sleep? References: Message-ID: In article , "Aleksandar Cikota" wrote: >How to check this every 10 sec, but that the CPU is free? Or better still, why not set a notification on the directory, so you're woken up every time something happens to it? Look up the inotify mechanism, which was added in version 2.6.13 of the Linux kernel. From kent at kentsjohnson.com Tue Apr 11 12:14:44 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Tue, 11 Apr 2006 12:14:44 -0400 Subject: Sorting a list of objects by multiple attributes In-Reply-To: <443bcef4@nntp0.pdx.net> References: <1144718377.331845.56390@z34g2000cwc.googlegroups.com> <1144718963.906712.131510@t31g2000cwb.googlegroups.com> <443b874e$1_3@newspeer2.tds.net> <443bcef4@nntp0.pdx.net> Message-ID: <443bd077$1_2@newspeer2.tds.net> Scott David Daniels wrote: > Kent Johnson wrote: >> In Python 2.5 you can do this with operator.attrgetter(): >> L.sort(key=operator.attrgetter('whatever', 'someother', 'anotherkey')) > > Note: this is also available in Python 2.4 No, the ability to specify more than one attribute name, making a getter that returns a tuple, is a Python 2.5 enhancement. In 2.4: In [1]: import operator In [2]: operator.attrgetter('whatever', 'someother', 'anotherkey') ------------------------------------------------------------ Traceback (most recent call last): File "", line 1, in ? TypeError: attrgetter expected 1 arguments, got 3 Kent From chris.cavalaria at free.fr Fri Apr 14 09:26:54 2006 From: chris.cavalaria at free.fr (Christophe) Date: Fri, 14 Apr 2006 15:26:54 +0200 Subject: Why new Python 2.5 feature "class C()" return old-style class ? In-Reply-To: References: <1144752553.305591.88050@j33g2000cwa.googlegroups.com> <1144763219.936992.219110@g10g2000cwb.googlegroups.com> Message-ID: <443fa3c3$0$27959$626a54ce@news.free.fr> Aahz a ?crit : > In article , > Felipe Almeida Lessa wrote: > >>Em Ter, 2006-04-11 ? s 07:17 -0700, Aahz escreveu: >> >>>Can, yes. But should it? The whole point of adding the () option to >>>classes was to ease the learning process for newbies who don't >>>understand why classes have a different syntax from functions. Having >>> >>>class C(): pass >>> >>>behave differently from >>> >>>class C: pass >>> >>>would be of no benefit for that purpose. >> >>Why should a newbie use an old-style class? > > > Because that's the default. Because lots of existing code still uses > classic classes, so you need to learn them anyway. Because you can't use > new-style classes in code intended for 2.1 or earlier; because of the > changes made in 2.3, I don't particularly recommend new-style classes for > 2.2. Because even the second edition of _Learning Python_ (targeted at > Python 2.3) doesn't cover new-style classes much, so I'm certainly not > alone in believing that new-style classes are better avoided for newbies. Well, old-style classes are perfect to confuse the newbie. After all, there's nothing like adding a "property" in a class and wondering why it does not work as expected. What would be a language without horrible pitfalls ? Newbies would have it easy and they have no right for an easy language ! From jg.lists at sympatico.ca Fri Apr 7 18:32:56 2006 From: jg.lists at sympatico.ca (Jim Gallacher) Date: Fri, 07 Apr 2006 18:32:56 -0400 Subject: mod_python + apache + winxp => nogo In-Reply-To: <1144447790.070964.295880@g10g2000cwb.googlegroups.com> References: <1144445910.877992.80210@v46g2000cwv.googlegroups.com> <1144447790.070964.295880@g10g2000cwb.googlegroups.com> Message-ID: <4436E898.6020809@sympatico.ca> Fuzzyman wrote: > cyberco wrote: > >>And I thought this would be trivial...getting mod_python to run within >>apache on windows XP. >> >>============= >>mod_python 3.2.8 >>apache 2.0.55 >>python2.4 >>winxp >>============= >> >>After adding: >>"LoadModule python_module modules/mod_python.so" >> > > > I'm no expert - having never tried that combination (but I have heard > of it and you should try the mod_python mailing list). > > However, if IIRC then a '.so' file is a UNIX type library file. > (Possibly the equivalent of a dll on windows). This sounds awry to me. It's an apache thing. Apache loadable modules have the same suffix on all platforms, so mod_python.so is correct. Jim From johnjsal at NOSPAMgmail.com Fri Apr 7 00:22:26 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 07 Apr 2006 00:22:26 -0400 Subject: how to make a generator use the last yielded value when it regains control In-Reply-To: <1144383206.576767.192570@g10g2000cwb.googlegroups.com> References: <4435cde3$0$11677$c3e8da3@news.astraweb.com> <1144383206.576767.192570@g10g2000cwb.googlegroups.com> Message-ID: <4435e96d$0$17970$c3e8da3@news.astraweb.com> Ben Cartwright wrote: > Definitely go for (1). The Morris sequence is a great candidate to > implement as a generator. As a generator, it will be more flexible and > efficient than (2). Actually I was just thinking about this and it seems like, at least for my purpose (to simply return a list of numbers), I don't need a generator. My understanding of a generator is that you do something to each yielded value before returning to the generator (so that you might not return at all), but since I'm not handling the individual numbers, just getting a list, it seems I don't need them to be yielded. Of course, a generator would allow the process to be done over and over, I suppose, which is what I wanted, I just couldn't figure out how to keep using the new values. From webraviteja at gmail.com Wed Apr 5 06:03:55 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 5 Apr 2006 03:03:55 -0700 Subject: Standalone Python functions in UML? In-Reply-To: <44338852$0$9464$626a54ce@news.free.fr> References: <1144145349.186395.44890@z34g2000cwc.googlegroups.com> <1144198593.264275.131480@i39g2000cwa.googlegroups.com> <44338852$0$9464$626a54ce@news.free.fr> Message-ID: <1144231435.786747.227660@u72g2000cwu.googlegroups.com> > Well, you can have a lot of things happening during the import stage. Is this 'runtime' or not ?-) Runtime. > And you can actually *create* (not 'change') classes at runtime too. Yes sir! By now I am quite well aware what 'dynamic typing' means. Once again, round trip tools today model program structure/code/text, not runtime magic - all the stuff a dynamically typed language such as Python does differently from statically typed languages like Java. So this does not affect them much. Languages like Python with metaclasses and other dynamic aspects do present an interesting case for modelling but what I am talking about is round trip tools, not the full scope of modelling and UML. Round trip implementations today get at class and package diagrams (structural), not object diagrams and collaboration diagrams. Class and Package diagrams are concerned with the layout, not intricate runtime behaviour, mutations and mutilations of classes and packages. That would be the domain of behavioural diagrams of which I made no assertions. There isn't much magical about Python as far as code layout is concerned. Metaclasses can for example change the very behaviour of the class construct but modelling that is not the purpose of a class or package diagram. Rather than going hypothetical and us miscommunicating in the abstract plane, could you just tell me why you could not draw a class or package diagram for your last project? That will probably make me see what I am missing from your points. From keith.b.perry at gmail.com Fri Apr 21 15:56:20 2006 From: keith.b.perry at gmail.com (kbperry) Date: 21 Apr 2006 12:56:20 -0700 Subject: win32com.client.constants - AttributeError In-Reply-To: <1145631219.159431.105040@g10g2000cwb.googlegroups.com> References: <1145565829.143096.75510@e56g2000cwe.googlegroups.com> <1145590250_3749@sp6iad.superfeed.net> <1145631219.159431.105040@g10g2000cwb.googlegroups.com> Message-ID: <1145649380.169565.71990@z34g2000cwc.googlegroups.com> Please help! Anyone else know? From itayyy at gmail.com Tue Apr 18 17:37:54 2006 From: itayyy at gmail.com (itay_k) Date: 18 Apr 2006 14:37:54 -0700 Subject: http request with cookie sending Message-ID: <1145396274.746861.40330@i39g2000cwa.googlegroups.com> Hi, I want to send a cookie on some http request (with urllib2), so I created a Cookie but I cant associate it with CookieJar object. for example: import Cookie import cookielib, urllib2 C = Cookie.SimpleCookie() C["a"] = "b" cj = cookielib.CookieJar() cj.set_cookie(C) in the last line I got: Traceback (most recent call last): File "", line 1, in ? File "C:\Python24\lib\cookielib.py", line 1593, in set_cookie if cookie.domain not in c: c[cookie.domain] = {} AttributeError: 'SimpleCookie' object has no attribute 'domain' why? maybe.. there is any code example for sending cookie with some http request operation? thanks alot, Itay. From jjl at pobox.com Sat Apr 29 14:37:31 2006 From: jjl at pobox.com (John J. Lee) Date: 29 Apr 2006 18:37:31 +0000 Subject: Using a browser as a GUI: which Python package References: <1146267924.602318.238640@j73g2000cwa.googlegroups.com> Message-ID: <87zmi4rzx0.fsf@pobox.com> "Andr?" writes: [...] > I would like to use a browser (e.g. Firefox) as a simple GUI > "framework". Note that this is to be done on a single user machine, so > the question of sandboxing is not really relevant here. [...] > My ultimate goal would be to port the main features of two > wxPython-based apps I wrote (rur-ple and Lightning Compiler, both found > at https://sourceforge.net/project/showfiles.php?group_id=125834) > within a standard browser. If you can stick to Firefox, you might find XUL useful. There are various different styles of development that use XUL and Python -- a bit of Googling and reading should find them. John From roy at panix.com Tue Apr 4 15:00:03 2006 From: roy at panix.com (Roy Smith) Date: Tue, 4 Apr 2006 19:00:03 +0000 (UTC) Subject: Strange problem when running python code References: <1144175959.412184.187110@g10g2000cwb.googlegroups.com> Message-ID: ishtar2020 wrote: >I've been writing my very first application in Python and everything is >running smoothly, except for a strange problem that pops up every once >in a while. I'm sure is the kind >of newbie thing every seasoned programmer knows. Nobody here has a crystal ball. Please post your code, tell us what changes you made, and cut-and-paste the entire error message and the associated stack trace. From anikin#remove_this# at vstu.ru Mon Apr 3 04:32:04 2006 From: anikin#remove_this# at vstu.ru (Dmitry Anikin) Date: Mon, 3 Apr 2006 12:32:04 +0400 Subject: Can't detect EOF from stdin on windows console Message-ID: <4430ec0e$0$20103$834e42db@reader.greatnowhere.com> I want to read stdin in chunks of fixed size until EOF I want to be able (also) to supply data interactively in console window and then to hit Ctrl+Z when finished So what I do is: while True: s = sys.stdin.read(chunk_size) if not s: break # do something with s if stdin is standard console input (on windows xp), here what happens: (suppose, chunk_size = 3) input: 123^Z --- s gets "123" but reading doesn't end input: ^Z --- now s is empty and loop breaks, so you have to press Ctrl-Z TWICE to end the loop worse still: input: 12^Z --- EOF is there, but there's only TWO chars instead of requested THREE, so stdin.read() doesn't even return yet input: ^Z --- s gets "12" but reading doesn't end input: ^Z --- only now loop breaks so you have to press Ctrl-Z THRICE to end the loop I haven't discovered any EOF function in python which could tell me if eof was encountered. As you see, testing for empty string or for len(s) = chunk_size doesn't improve the situation, anyone can suggest a workaround? Also I think the latter case is a straightaway bug, doc says: read( [size]) Read at most size bytes from the file (less if the read hits EOF before obtaining size bytes). According to that, stdin.read(3), when supplied with "12^Z" should return immediately with two-character string instead of waiting for third character after EOF. By the way, if I enter something between ^Z's that will be treated as vaild input and ^Z's will be completely ignored. From paul at boddie.org.uk Mon Apr 3 12:18:57 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 3 Apr 2006 09:18:57 -0700 Subject: Convertion of Unicode to ASCII NIGHTMARE References: <1144079830.734516.8390@z34g2000cwc.googlegroups.com> Message-ID: <1144081137.137744.253790@i39g2000cwa.googlegroups.com> ChaosKCW wrote: > Hi > > I am reading from an oracle database using cx_Oracle. I am writing to a > SQLite database using apsw. > > The oracle database is returning utf-8 characters for euopean item > names, ie special charcaters from an ASCII perspective. And does cx_Oracle return those as Unicode objects or as plain strings containing UTF-8 byte sequences? It's very important to distinguish between these two cases, and I don't have any experience with cx_Oracle to be able to give advice here. > I get the following error: > > SQLiteCur.execute(sql, row) > >UnicodeDecodeError: 'ascii' codec can't decode byte 0xdc in position 12: ordinal not > > in range(128) It looks like you may have Unicode objects that you're presenting to sqlite. In any case, with earlier versions of pysqlite that I've used, you need to connect with a special unicode_results parameter, although later versions should work with Unicode objects without special configuration. See here for a thread (in which I seem to have participated, coincidentally): http://mail.python.org/pipermail/python-list/2002-June/107526.html > I have googled for serval days now and still cant get it to encode to > ascii. This is a tough thing to find out - whilst previous searches did uncover some discussions about it, I just tried and failed to find the enlightening documents - and I certainly didn't see many references to it on the official pysqlite site. Paul From sjdevnull at yahoo.com Wed Apr 19 15:16:27 2006 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 19 Apr 2006 12:16:27 -0700 Subject: Java Developer Exploring Python In-Reply-To: <1145290449.735642.120860@i40g2000cwc.googlegroups.com> References: <1145290449.735642.120860@i40g2000cwc.googlegroups.com> Message-ID: <1145474187.047800.110170@e56g2000cwe.googlegroups.com> redefined.horizons at gmail.com wrote: > Is Python actively developed and supported on Linux? Yes. In fact, Red Hat's installation and administration tools are written in Python and have been for a decade (give or take a year or two). From timr at probo.com Wed Apr 19 02:44:05 2006 From: timr at probo.com (Tim Roberts) Date: Wed, 19 Apr 2006 06:44:05 GMT Subject: removing cgi fieldstorage keys References: Message-ID: Kun wrote: > >i don't know what happened but all of a sudden, my cgi.fieldstorage has >two extra keys, 'x' and 'y', does anyone know how i can remove them in >python? If this is coming from a web site that you created, then you darned well better figure out where they're coming from! Did you add any fields? Did you add an image map? On the other hand, why do you want to remove them? -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From fredrik at pythonware.com Tue Apr 4 14:59:33 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 4 Apr 2006 20:59:33 +0200 Subject: Strange problem when running python code References: <1144175959.412184.187110@g10g2000cwb.googlegroups.com> Message-ID: "ishtar2020" wrote: > Sometimes a receive strange Syntax Errors from parts of code that > worked perfectly minutes ago. What's even more puzzling is that those > errors are pointed to another part of the module when I do some random, > innofensive changes in the code (like inserting a line or deleting some > comments). Sometimes those changes are enough to make the error > dissapear. Python 2.4.1 has a bug where this can happen if you're 1) using coding directives, and 2) your module is relatively large. I suggest upgrading to 2.4.3. From steve at REMOVETHIScyber.com.au Sun Apr 16 10:20:59 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Mon, 17 Apr 2006 00:20:59 +1000 Subject: Help with python output redirection References: <1145059153.392141.145360@u72g2000cwu.googlegroups.com> <1145111789.969239.270260@i40g2000cwc.googlegroups.com> Message-ID: On Sun, 16 Apr 2006 12:16:39 +0200, Fredrik Lundh wrote: > Steven D'Aprano wrote: > >> So, let me say firstly that I wish the following code to be put into >> the public domain > > so you're taking the work by others ("for m in x", "print m", and so on) > and think that by posting it to usenet as if you wrote it yourself, you > can release it into the public domain ? ??? You're joking, right? Look, I'm not having a good run at the moment telling when folks are being funny, so if you trying to introduce a note of levity into the discussion, ha ha I laughed so much my sides burst. But if you are being serious, and for the benefit of anyone else out there who doesn't get the joke and thinks there is something of substance to your claim: (1) If I didn't already have the copyright to the code, I simply can't transfer ownership to it or reassign copyright no matter what I say; (2) If you read my post, I think it is abundantly clear that my intention was not to claim copyright on it at all; (3) Only because the Original Poster appeared to be concerned about copyright on the code I posted, I released it, simply to reassure the OP; (4) As far as me posting individual Python statements (like for, print etc.) as if I wrote them myself, that's ludicrous. A writer's copyright on a work does not imply copyright on the individual words; likewise a programmer's copyright on a program does not mean he claims copyright on the language itself. So, just so there is no misunderstanding: - I did not write the Python language, I do not have ownership of the copyright to the Python language, and it is not my intention to transfer copyright of the Python language (in whole or in part) to the public domain, even if I were able to, which I am not. - I do not have copyright on any code not written by me, consequently I'm not releasing the copyright on any code not written by me. - I am, however, explicitly releasing from copyright the code written by me in the earlier message with the subject line "Re: Help with python output redirection" dated Sat, 15 Apr 2006 12:09:17 +1000, and then re-posted as quoted text in a message with the same subject line dated Sun, 16 Apr 2006 11:35:04 +1000. - In the event that the appropriate laws do not allow me to release from copyright the code, I offer it to anyone who wants to copy such a trivial few lines of code into their own work with an unlimited, non-exclusive, transferable, warranty-less licence. - None of this is a substitute for paying a lawyer many hundreds of dollars to be told that no judge is going to rule copyright infringement for copying such a trivial work, and that this whole exercise was an utter waste of time. Sheesh. I have to deal with enough legal waffle at work, I didn't think I'd be held to such pedantic standards about a trivial four-line piece of code on Usenet. Oh, Fredrik, if your intention was to demonstrate just what a PITA overly strict copyright law is, you're preaching to the converted brother. -- Steven. From kent at kentsjohnson.com Tue Apr 4 11:57:53 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Tue, 04 Apr 2006 11:57:53 -0400 Subject: scraping nested tables with BeautifulSoup In-Reply-To: <1144165142.767043.70100@g10g2000cwb.googlegroups.com> References: <1144142334.695498.293650@u72g2000cwu.googlegroups.com> <4432753a$1_2@newspeer2.tds.net> <1144165142.767043.70100@g10g2000cwb.googlegroups.com> Message-ID: <44329229$1_3@newspeer2.tds.net> Gonzillaaa at gmail.com wrote: > Hey Kent, > > thanks for your reply. how did you exactly save the file in firefox? if > I save the file locally I get the same error. I think I right-clicked on the page and chose "Save page as..." Here is a program that shows where BS is choking. It finds the last leaf node in the parse data by descending the last child of each node: from urllib import urlopen from BeautifulSoup import BeautifulSoup data = urlopen('http://www.findaproperty.com/regi0018.html').read() soup = BeautifulSoup(data) tag = soup while hasattr(tag, 'contents') and tag.contents: tag = tag.contents[-1] print type(tag) print tag It prints: Looking at the saved file, Firefox has clearly done some cleanup. So I think you have to look at why BS is not processing the original data the way you want. It seems to be choking on something. Kent From paddy3118 at netscape.net Thu Apr 20 02:05:48 2006 From: paddy3118 at netscape.net (Paddy) Date: 19 Apr 2006 23:05:48 -0700 Subject: Lamdba forms References: <1145492986.738200.229690@i39g2000cwa.googlegroups.com> Message-ID: <1145513148.200209.9170@i40g2000cwc.googlegroups.com> To expand on the above, Python does not have statements in its lambda forms, but that does not stop pythoneers from getting the job done. I use a named function for that, but if you have an issue with that, it really is worth following Terry's advice as the subject has been tackled at great length before. - Cheers, Paddy. From http Sat Apr 29 19:39:24 2006 From: http (Paul Rubin) Date: 29 Apr 2006 16:39:24 -0700 Subject: String Exceptions (PEP 352) References: <4450d844$0$27293$626a54ce@news.free.fr> Message-ID: <7xhd4ckl3n.fsf@ruckus.brouhaha.com> bruno at modulix writes: > What's wrong with: > > assert foo and bar and i > 10, \ > "if foo and bar i must not be greater than 10" It doesn't necessarily do anything. With optimization enable, assert is a no-op. From theller at python.net Wed Apr 26 09:49:29 2006 From: theller at python.net (Thomas Heller) Date: Wed, 26 Apr 2006 15:49:29 +0200 Subject: Importing modules through directory shortcuts on Windows In-Reply-To: <444F7747.3060201@sweetapp.com> References: <444F7747.3060201@sweetapp.com> Message-ID: Brian Quinlan wrote: > Recently, I became responsible for maintaining some Python code, which > was organized as follows: > > user/pylib > ui > ... > project2/pylib > ui > ... > project3/pylib > ui > ... > python-packages/user => /user/pylib > project2 => /project2/pylib > project3 => /project3/pylib > > The idea is that "python-packages" is added to sys.path and then every > project can import the library package from every other project. NOTE: I > think that this structure is crazy but I'm just the poor maintenance > programmer. > > Anyway, the problem is that Windows does not have a symlink facility to > accommodate this (AFAIK) and the Python import mechanism does not > resolve shortcuts. > > Therefore, I wrote a very simple import hook to get around that problem. > If you are interested, the code is here: > http://www.sweetapp.com/shortcut/shortcutimporter.py > > BTW, does anyone else think that this functionality should be part of > core Python? I wonder (but haven't yet figured out) if something similar can be achived with pkgutil and one or more .pkg files. Thomas From heidiweber at freenet.de Sun Apr 9 10:29:12 2006 From: heidiweber at freenet.de (HeidiWeber) Date: 9 Apr 2006 07:29:12 -0700 Subject: Round In-Reply-To: <1144583035.135712.307920@i40g2000cwc.googlegroups.com> References: <1144583035.135712.307920@i40g2000cwc.googlegroups.com> Message-ID: <1144592952.443440.78050@g10g2000cwb.googlegroups.com> thank you very much to you i wish you a nice sunday... cu Heidi From gry at ll.mit.edu Thu Apr 13 11:12:55 2006 From: gry at ll.mit.edu (gry at ll.mit.edu) Date: 13 Apr 2006 08:12:55 -0700 Subject: list.clear() missing?!? In-Reply-To: <1144937913.006463.241520@j33g2000cwa.googlegroups.com> References: <1144767680.583085.310160@v46g2000cwv.googlegroups.com> <1144937913.006463.241520@j33g2000cwa.googlegroups.com> Message-ID: <1144941175.861800.200720@v46g2000cwv.googlegroups.com> A perspective that I haven't seen raised here is inheritance. I often say mylist = [] if I'm done with the current contents and just want a fresh list. But the cases where I have really needed list.clear [and laboriously looked for it and ended up with del l[:] were when the object was my own class that inherits from list, adding some state and other functionality. Of course I *could* have added my own 'clear' function member, but I *wanted* it to behave like a standard python list in it's role of maintaining a sequence of processing steps. So, I end up doing del current_process[:] which, IMO, looks a bit queer, especially when current_process object is a fairly elaborate data object. From broek at cc.umanitoba.ca Sun Apr 23 19:05:28 2006 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Sun, 23 Apr 2006 18:05:28 -0500 Subject: PYTHONPATH In-Reply-To: References: <1145535721.138411.145790@z34g2000cwc.googlegroups.com> <44478f30$0$12862$626a54ce@news.free.fr> Message-ID: <444C0838.5040309@cc.umanitoba.ca> Edward Elliott said unto the world upon 23/04/06 04:28 PM: > Brian van den Broek wrote: > >>The suggestions above appear not to work for me: >> >>brian at Cedric:~$ cat /etc/profile | grep 'export PYTHONPATH' >>export PYTHONPATH="~/PythonFiles" >>brian at Cedric:~$ cat .bash_profile | grep 'export PYTHONPATH' >>export PYTHONPATH="~/PythonFiles" > > > Those files are only read when you start the shell. I'm guessing you made > those changes from the currently running shell. To fix it you have 3 choices: > 1. Close the shell and start a new one > 2. Type 'bash -l' at the prompt to invoke a new login shell > 3. Type '. .bash_profile' to read the changes into your current shell Edward, thanks for the reply. I'm going to not worry about exposing my ignorance in what follows :-) I ought to have specified that I did indeed think to invoke a new shell after I made the changes. However, trying (2) and (3) as you specified shed some light. Early on, (probably miss-)following something I read on the net, I'd put a block into my .bash_profile that read: if 1; then somestuff Trying (3) gave brian at Cedric:~$ . .bash_profile bash: 1: command not found Commenting out the bad block in .bash_profile, if I open a shell and things are somewhat better. Only somewhat, as if I open a brand new shell: brian at Cedric:~$ python Python 2.4.2 (#2, Sep 30 2005, 21:19:01) [GCC 4.0.2 20050808 (prerelease) (Ubuntu 4.0.1-4ubuntu8)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from sys import path >>> path[0:3] ['', '/usr/lib/python24.zip', '/usr/lib/python2.4'] >>> brian at Cedric:~$ . .bash_profile brian at Cedric:~$ python Python 2.4.2 (#2, Sep 30 2005, 21:19:01) [GCC 4.0.2 20050808 (prerelease) (Ubuntu 4.0.1-4ubuntu8)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from sys import path >>> path[0:3] ['', '/home/brian/PythonFiles', '/usr/lib/python24.zip'] >>> So, it seems that I currently have to invoke '. .bash_profile' manually with each new shell opened for this to have effect. (Trained by Bill, I even rebooted to be sure that the invocation of '. .bash_profile' is needed.) But, still it is closer :-) I still haven't managed to coerce lines in /etc/profile exporting PYTHONPATH to have an effect. >>I don't know where to look for more information; I'm assuming that >>ubuntu isn't doing it the standard way bruno referred to above. Could >>some ubuntu user cast light, please? > > > This information bruno gave is correct. I didn't mean to suggest bruno was wrong, but instead that perhaps ubuntu was a distro falling under his phrase: > but this may vary according to your distro and your shell such that the instructions he gave would not work without modification. Apologies if I gave a different impression. > You might want to google for "bash shell tutorial" and familiarize yourself > with how bash shells work. It can be somewhat confusing at first, but it's > a very powerful way to interact with your system. Thanks for the suggestions. With luck, I'll get the remaining issue sorted. Thanks for the help, Brian vdB From tagore at tagoresmith.com Fri Apr 28 09:34:40 2006 From: tagore at tagoresmith.com (Tagore Smith) Date: 28 Apr 2006 06:34:40 -0700 Subject: (was Re: Xah's Edu Corner: Criticism vs Constructive Criticism) In-Reply-To: References: <1145992903.834316.198370@u72g2000cwu.googlegroups.com> <4GM3g.3084$TT.1768@twister.nyroc.rr.com> Message-ID: <1146231280.733609.143230@e56g2000cwe.googlegroups.com> John Bokma wrote: > Eli Gottlieb wrote: > > > Oh, God, not another one. > > Instead of cross posting more garbage, do as follows: > > Email a complaint to the email addresses you can look up yourself and > include the entire message of Xah: > > http://www.spamcop.net/sc?track=72.231.179.135 posting host > http://www.spamcop.net/sc?track=xahlee.org spamvertized site Xah Lee has been around for a long time. I don't claim to understand him, but I don't think he is a troll- I think he is sincere in his postings, even if they are gibberish to everyone else. The only thing he is doing that should be considered abuse is crossposting to several groups (and he should certainly stop doing that). But he is only crossposting to about eight or so groups- hardly a Dave Rhodes incident. The great thing about Usenet is that it gives everyone a soapbox, even the slightly warped. Xah Lee should stop crossposting, but the fact that he is incoherent should not bar him from posting messages. He is actually a pretty interesting fellow when it comes to certain aspects of mathematics- I don't know if he still maintains his site about knot theory, but it was quite interesting, last time I looked. It's much easier to use a killfile than to complain to an ISP, and I think that that should be the preferred response to messages you don't like. Complaints to ISPs should be reserved for egregious abuse of the Usenet infrastructure. From ericcngan at gmail.com Mon Apr 24 16:57:11 2006 From: ericcngan at gmail.com (vduber6er) Date: 24 Apr 2006 13:57:11 -0700 Subject: Can my python script return a value to the c program executing it? In-Reply-To: References: <1145646392.037236.105750@u72g2000cwu.googlegroups.com> Message-ID: <1145912231.262845.10480@g10g2000cwb.googlegroups.com> That link seemed to do the trick with a little bit of edits. Thanks a lot Philippe! Eric From girodt at gmail.com Wed Apr 26 10:14:14 2006 From: girodt at gmail.com (TG) Date: 26 Apr 2006 07:14:14 -0700 Subject: Inherit from array In-Reply-To: References: <1146057315.721573.196140@u72g2000cwu.googlegroups.com> <444f79a8$0$5191$626a54ce@news.free.fr> Message-ID: <1146060853.950843.108950@i39g2000cwa.googlegroups.com> Obviously, there is something I didn't catch in python's inheritance. from array import array class Vector(array): def __init__(self,size): print self.typecode array.__init__(self,'f') >>> v = Vector('c') c Here, it says the typecode is 'c' - I thought such an information was initalized during the array.__init__(self,'f') but obviously I was wrong. Maybe the typecode is defined before, during the call to __new__ method ... But here i'm getting lost. From tim.hochberg at cox.net Sat Apr 15 12:39:35 2006 From: tim.hochberg at cox.net (Tim Hochberg) Date: Sat, 15 Apr 2006 09:39:35 -0700 Subject: PEP 359: The "make" Statement In-Reply-To: <44403893.3060909@ieee.org> References: <44403893.3060909@ieee.org> Message-ID: <444121C7.4030208@cox.net> Tim Hochberg wrote: > Steven Bethard wrote: > >> Steven Bethard wrote: >> >>> Tim Hochberg wrote: >>> >>>> Steven Bethard wrote: >>>> >>>>> Steven Bethard wrote: >>>>> >>>>>> Duncan Booth wrote: >>>>>> >>>>>>> make Element html: >>>>>>> make Element body: >>>>>>> make Element p: >>>>>>> text('But this ') >>>>>>> make Element strong: >>>>>>> text('could') >>>>>>> text(' be made to work') >>>>>> >>>>>> >>>>>> This is nice. I'll have to play around with it a bit to see how >>>>>> hard it would be to make it work. >>>>> >>>>> >>>>> Okay, I think it'll work[1]. I'm going to update this section to >>>>> something more like: >>>>> >>>>> >>>>> Open Issues >>>>> =========== >>>>> >>>>> ... >>>>> >>>>> Should users of the make statement be able to determine in which dict >>>>> object the code is executed? This would allow the make statement to >>>>> be used in situations where a normal dict object would not suffice, >>>>> e.g. if order and repeated names must be allowed. Allowing this sort >>>>> of customization could allow XML to be written like:: >>>> >>>> >>>> I think this PEP is going off the rails. It's primary virtue was >>>> that it was a simpler, clearer way to write: >>>> >>>> class Foo(args): >>>> __metaclass__ = some_metaclass >>>> #... >>>> >>>> Once it starts calling secret magic methods behind the scenes it's >>>> losing that virture. And for what? Supporting some use cases that >>>> have reasonable solutions already? >>> >>> >>> That's why it's in the Open Issues section. I expect most of these >>> open issues to be resolved by rejection. (At least, that's my >>> preferred resolution.) But since they people have brought them up, >>> I think they need to be addressed as completely as possible. >>> >>> But I think you make a good point that this particular case can be >>> just as easily done using a with-statement (I think). I'll add that >>> to this part of the PEP (once I'm sure it works). >> >> >> >> Hmm... Actually, while the with-statement can probably help out with >> the nesting, it doesn't help out with the DRY; you still have to >> repeat the element name (once for the call to Element, and once as >> the name that Element object is bound to). > > > > I don't think that's correct. I think that with a suitably designed > HtmlDocument object, the following should be possible: > > with HtmlDocument("Title") as doc: > with doc.element("body"): > doc.text("before first h1") > with doc.element("h1", style="first"): > doc.text("first h1") > # I don't understand the point of tail, but you could do that too > doc.text("after first h1") > with doc.element("h1", style="second"): > doc.text("second h1") > doc.text("after second h1") > Here's code to do this. It would be probably be better to use elment tree or some such instead of pushing out the HTML directly, but this should get the idea across (testing using 2.5a1): class HtmlTag(object): def __init__(self, document, type, attribs): self.document = document self.type = type self.attribs = attribs def __context__(self): return self def _format_attribs(self): if not self.attribs: return '' return ' ' + ' '.join('%s="%s"' % (k,v) for k, v in self.attribs.items()) def __enter__(self): self.document.entities.append('<%s%s>' % (self.type, self._format_attribs())) return self def __exit__(self, type, value, traceback): self.document.entities.append('' % self.type) def add(self): self.document.entities.append('<%s%s/>' % (self.type, self._format_attribs())) class HtmlDocument(object): def __init__(self): self.entities = [] def tag(self, type, **atribs): return HtmlTag(self, type, atribs) def text(self, value): self.entities.append(value) def tostring(self): return ''.join(self.entities) def __context__(self): return self def __enter__(self): self.entities.append('') return self def __exit__(self, type, value, traceback): if not (type is value is traceback is None): raise type(value) self.entities.append('') And here are some simple examples: with HtmlDocument() as doc: with doc.tag("body"): doc.text("before first h1") with doc.tag("h1", style="first"): doc.text("first h1") doc.text("after first h1") with doc.tag("h1", style="second"): doc.text("second h1") doc.text("after second h1") expected = '''\ \ \ before first h1\

first h1

\ after first h1\

second h1

\ after second h1\ \ \ ''' print doc.tostring() == expected some_list = ["foo", "bar", 'bazz', "froodle"] with HtmlDocument() as doc: with doc.tag("body"): with doc.tag("h1"): doc.text("An ordered list") with doc.tag("ol"): for value in some_list: with doc.tag('li'): doc.text(value) print doc.tostring() Regards, -tim > That seems reasonably DRY compliant. Doc would simply stack and > unstack the attributes on the way in and out of the with blocks. This > arguably maps better to the underlying HTML as well. > > I'd like to reiterate my point that, as far as I can tell, the make > statement won't actually work for creating HTML in all but the most > trivial of cases. Consider: > > with HtmlDocument("Title Here") as doc: > with doc.element("body"): > with doc.element("h1"): > doc.text("An ordered list") > with doc.element("ol"): # Ordered list > for value in some_list: > doc.listitem(value) > > If I try to translate this to make syntax, I get into trouble. I end > up with 'value' getting set as an element over and over again. Not at > all what I want! I suppose you could filter your expression so that > only things that subtype some marker class get added, but that's > piling weirdness on top of confusion; and good sign that the whole > idea is better off abandoned. > > -tim > > > > > > > From aleaxit at yahoo.com Mon Apr 24 22:30:01 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 24 Apr 2006 19:30:01 -0700 Subject: MS VC++ Toolkit 2003, where? References: <1he8pss.1yk7ug81rv7pw2N%aleaxit@yahoo.com> <1145811839.042394.73260@t31g2000cwb.googlegroups.com> <1he8sbx.dqqp3q10n5thaN%aleaxit@yahoo.com> <1145849491.347970.112150@e56g2000cwe.googlegroups.com> <1he9m4m.9d8okx1x7mxeaN%aleaxit@yahoo.com> Message-ID: <1hebbvz.18xp69i9wogskN%aleaxit@yahoo.com> Edward Elliott wrote: > Alex Martelli wrote: > > the Windows version, despite the slight > > overhead of running under Parallels' virtualization, is an impressive > > 12%+ _faster_ than the "native" MacOSX Python 2.4.3 (I'm not quite sure > > about how good Parallels' virtualization IS, but even if it's as > > impressive as a mere 3% overhead, this still means that the Windows > > version of Python on identical HW must be at least 15% faster than the > > MacOSX version, compiled with gcc). > > Can you post the complete benchmark results from both systems on the > Macbook? My understanding is that virtualization overhead is not a OK, I've placed on http://www.aleax.it/Python/ the files that pybench writes (with the -file option) for each machines, the names are onmbp.txt and onwin2k.txt -- just 20k each (I'm not sure their format is documented, but I guess that, worst case, one just needs to study pybench's sources). > builder knew about, etc. I think Apple switched to the Intel compiler for > x86 macs, was python built with that or with gcc? The compiler Apple distributes freely is still gcc -- the intel compiler (rumored to have better optimization) costs hundreds of dollars, so Apple couldn't possibly distribute it for free with XCode. > In short, your results are interesting but I'm not sure what to make of > them yet. Consider me available if you need some other tests and don't have other easy access to OSX and Windows running on the same HW. Alex From flamesrock at gmail.com Thu Apr 6 19:33:18 2006 From: flamesrock at gmail.com (flamesrock) Date: 6 Apr 2006 16:33:18 -0700 Subject: Can't Delete a Thread Message-ID: <1144366398.071761.64370@u72g2000cwu.googlegroups.com> I have the following two threads, called from a method: def uploading_region: uploading_region = AddRegionToServerThread(self,self.SESSION,create_region) while uploading_region.UPLOADING: pass #escape method when uploading_region thread is false class AddRegionToServerThread(Thread): def __init__(self, window, session, dict): Thread.__init__(self) self.SESSION = session self.DICT = dict #contains dbuser,password, etc self.STATUS = 'Uploading the region. Please wait...' self.WINDOW = window self.dlg = wx.ProgressDialog('Please Wait...', self.STATUS, 100, self.WINDOW, wx.PD_AUTO_HIDE | wx.PD_APP_MODAL) self.RETICULATE = ReticulateSplines(self.dlg) self.UPLOADING = True self.start() def run(self): self.STATUS = 'Adding cities to database. Almost done...' #create database .... self.RETICULATE._Thread__delete() time.sleep(3) #give some extra time self.UPLOADING = False class ReticulateSplines(Thread): def __init__(self,dialog): Thread.__init__(self) self.random_messages=[ 'reticulating splines','hiring code monkeys','are you still watching this?', 'a penny saved is a penny earned','use this as an opportunity to go outside', 'mmm water','drinking decaff coffee','neutering excess bits', 'starting improbability drive','delousing edmontonians'] self.dialog = dialog self.x=1 self.start() def run(self): self.x += 2 self.dialog.Update(self.x,self.random_messages[random.randrange(len(self.random_messages))]) time.sleep(3) self.__init__(self.dialog) Now for some reason, I can't delete the thread 'ReticulateSplines' in the run() function of AddRegionToServerThread(). I call it, but the dialog window doesn't actually close, while, for some reason I am able to terminate AddRegionToServerThread. Any ideas on why? I've tried a combination of things and yet nothing works. Any help would be greatly appreciated. -Thanks Flamesrock From jarrells at jarrells.cjb.net Sat Apr 22 11:15:03 2006 From: jarrells at jarrells.cjb.net (jarrells at jarrells.cjb.net) Date: 22 Apr 2006 08:15:03 -0700 Subject: proposed Python logo In-Reply-To: <1145585399.871299.31900@t31g2000cwb.googlegroups.com> References: <1145585399.871299.31900@t31g2000cwb.googlegroups.com> Message-ID: <1145718903.823375.257470@i39g2000cwa.googlegroups.com> Mike, Excellent artwork! I don't like reinventing the wheel so I propose we reuse someone else's work. I propose something like: http://www.dvdweb.co.uk/reviewgfx/bompfc1.jpg which symbolizes Python's ability to quickly implement many coding ideas or: http://www.phill.co.uk/comedy/python/python15.jpg which symbolizes Python's ability to squash the competition for quick coding or: http://imagecache2.allposters.com/images/CMAG/939-009.jpg which symbolizes Python's place as the pick of the litter. They also symbolize the fact that coder's shouldn't take life too seriously. Happy coding! Mike Michael Tobis wrote: > "Is this the right room for an argument?" > > http://geosci.uchicago.edu/~tobis/snake.png > > ok, so my execution is pretty crude, but you can at least see my idea. > I trust you to imagine it professionally executed in cheerful colors. > > Advantages of proposed logo over existing logo > > Much as it would be an ego-boost for me to have some version of this > idea used for the language, I'm almost as happy with repurposing the > most excellent PyCon logo if that is OK with everyone involved. But imo > we can't fully promote the power of Python with tadpoles. > > mt From antroy at gmail.com Thu Apr 27 04:38:30 2006 From: antroy at gmail.com (Ant) Date: 27 Apr 2006 01:38:30 -0700 Subject: begging for a tree implementation In-Reply-To: <1146091386.013265.153660@v46g2000cwv.googlegroups.com> References: <1146091386.013265.153660@v46g2000cwv.googlegroups.com> Message-ID: <1146127110.773347.222270@e56g2000cwe.googlegroups.com> I was looking for a tree implementation a while back, but got no real pointers. Seems that there are no tree data model modules out there - which surprises me, since it is such a fundamental data structure. I ended up using a very basic tree data class - I didn't need all of the methods you mentioned. Here it is in case that helps at all: class Node (object): def __init__(self, data, parent=None): self.data = data self.parent = parent self.children = [] def add_child(self, child): self.children.append(child) child.parent = self Some of those methods you mentioned would be trivial to implement: def is_root(self): return not self.parent def is_leaf(self): return not self.children It may also be more pythonic to have 'walk' methods for traversing trees. I may start a tree data structure project - it's something I've been thinking about for a while, and now it's clear that it's not just me who uses trees as data structures! From arv.nntp at gmail.com Fri Apr 21 17:49:18 2006 From: arv.nntp at gmail.com (Alexis Roda) Date: Fri, 21 Apr 2006 23:49:18 +0200 Subject: lambda In-Reply-To: References: <1145642409.389741.39680@g10g2000cwb.googlegroups.com> Message-ID: Ben C escribi?: > On 2006-04-21, Ben C wrote: > Having said that, I attempted to confirm this using def rather than > lambda, and encountered something I cannot explain at all-- it appears > that the functions are getting redefined whenever they are called, to > effect a kind of "dynamic scoping" behaviour. I would appreciate any > explanation anyone can give of this: > > fns = [] > for y in range(2): > def fn(): > yy = y # exactly the same with yy = int(y) > print "defining fn that returns", yy > return yy > print "Appending at", y > print fn, fn() > fns.append(fn) yy = y does assign y's current value (current == fn call time, not fn definition time). To return 0 and 1 as expected you should create a "different/private" y for every fn's definition. ---------------------------------------- fns = [] for y in range(2): def fn(y=y): yy = y print "defining fn that returns", yy return yy print "Appending at", y print fn, fn() fns.append(fn) ---------------------------------------- fns = [] def factory(y) : def fn() : yy = y print "defining fn that returns", yy return yy return fn for y in range(2) : fn = factory(y) print "Appending at", y print fn, fn() fns.append(fn) ---------------------------------------- HTH From phpbird at gmail.com Tue Apr 18 20:43:16 2006 From: phpbird at gmail.com (Ju Hui) Date: 18 Apr 2006 17:43:16 -0700 Subject: how to use socks5 proxy in pycurl? In-Reply-To: <1145344870.973387.65290@v46g2000cwv.googlegroups.com> References: <1145344870.973387.65290@v46g2000cwv.googlegroups.com> Message-ID: <1145407396.687892.214750@j33g2000cwa.googlegroups.com> No one use this function? From brandon.mcginty at gmail.com Fri Apr 14 20:37:11 2006 From: brandon.mcginty at gmail.com (brandon.mcginty at gmail.com) Date: Fri, 14 Apr 2006 17:37:11 -0700 Subject: ping In-Reply-To: <9583ed900604141704x39542865ie71665c071aaf571@mail.gmail.com> Message-ID: <02cd01c66024$bd90f240$6400a8c0@D1FWTS61> Try this: import os pinginfo=os.popen("ping www.google.com") #opens file object with output of the ping to google print pinginfo.read(-1) #reads the ping information from the abuv file object pinginfo.close() #closes the pinginfo object, as you would do for a standard file object Note that pinginfo is actually a file object, and as such, you must treat it as you would any file you are reading to, readlines, read, etc. HTH, Brandon McGinty ---------- Feel free to contact me for technical support, or just to chat; I always have time to talk and help, and an open ear. Email:Brandon.mcginty at gmail.com Skype:brandon.mcginty Msn:brandon_mcginty at hotmail.com Aim:brandonmcginty (Not currently available.) Cell:4802025790 (Weekends and nights only, please.) "Kindness is a language that the deaf can hear and the blind can see." Mark Twain -----Original Message----- From: python-list-bounces+brandon.mcginty=gmail.com at python.org [mailto:python-list-bounces+brandon.mcginty=gmail.com at python.org] On Behalf Of david brochu jr Sent: Friday, April 14, 2006 5:04 PM To: python-list at python.org Subject: re: ping Thanks, Unfortunately substituting os.system with os.popen results in the output being: instead of giving me the ping stats "pinging etc etc, packets sent 4 recienved 4 etc) Any idea around this? -- No virus found in this incoming message. Checked by AVG Free Edition. Version: 7.1.385 / Virus Database: 268.4.1/312 - Release Date: 4/14/2006 -- No virus found in this outgoing message. Checked by AVG Free Edition. Version: 7.1.385 / Virus Database: 268.4.1/312 - Release Date: 4/14/2006 -------------- next part -------------- An HTML attachment was scrubbed... URL: From see at signature.invalid Thu Apr 27 01:40:58 2006 From: see at signature.invalid (Nigel Rowe) Date: Thu, 27 Apr 2006 15:40:58 +1000 Subject: Xah's Edu Corner: Criticism vs Constructive Criticism References: <1145992903.834316.198370@u72g2000cwu.googlegroups.com> Message-ID: Ari Johnson wrote: > "Xah Lee" writes: >> >> Xah >> xah at xahlee.org >> ? http://xahlee.org/ > > (This isn't constructive criticism, but just a question:) Are you the > sum of your web page? Yes he is, the total value is zero. -- Nigel Rowe A pox upon the spammers that make me write my address like.. rho (snail) swiftdsl (stop) com (stop) au From fredrik at pythonware.com Sat Apr 8 04:17:25 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 8 Apr 2006 10:17:25 +0200 Subject: How to change the docs - a case study References: <4434fcb8$1_3@newspeer2.tds.net> <44350be9$1_1@newspeer2.tds.net> Message-ID: Kent Johnson wrote: > >> Here is an example. This morning I noticed a minor discrepancy in the > >> docs for the 'rot13' encoding. I posted a bug to SourceForge at 10:05 > >> GMT. At 10:59 someone commented that maybe the code was broken rather > >> than the docs. At 11:18 another poster responded that the code should > >> stay the same. At 11:25, less than two hours after my original report, a > >> fixed was checked in. > > > > how many manhours did this take, in total ? did you clock your own efforts ? > > It took a few minutes of my time. Maybe a minute to verify that there > was no similar bug report, a few minutes to write up my findings and > submit them. I don't know how much time the other posters spent but the > total clock time from OP to fix was 1 hour 20 minutes so that gives you > an upper bound. now that the developer documentation has been updated, have you verified that the fix is correct ? if you have, how long did it take (in clock time) be- fore you got around to do that ? > the 2.4.3 doc is still broken: > > http://docs.python.org/lib/standard-encodings.html for the record, it's still broken. and there's no sign that there's a known bug on that page. I've written a little more about this here: http://pytut.infogami.com/blog/43fm From neurogasm at gmail.com Mon Apr 17 20:38:02 2006 From: neurogasm at gmail.com (Kun) Date: Mon, 17 Apr 2006 20:38:02 -0400 Subject: scanning through page and replacing all instances of 00:00:00.00 In-Reply-To: References: Message-ID: Tim Chase wrote: >> for col in range(0, numcols): >> print "
" > > This is the point at which you want to intercept the column data and > make your change: > > print "" % foo > > or alternatively > > DATECOLUMNS = [3, 14] > for col in range(0, numcols): > foo = record[col] > if col in DATECOLUMNS: > foo = foo.replace("00:00:00.00", "") > print "" % foo > > I don't know off the top of my head if your MySQL cursor object supports > metadata...something like the following pseudocode: > > for col in range(0, numcols): > foo = record[col] > if cursor.fieldtypes[col] == MYSQL_DATE: > foo = foo.replace("00:00:00.00", "") > print "" % foo > > Adjust accordingly. > > -tkc > much thanks! > > > > mu From gene.tani at gmail.com Sun Apr 30 23:49:23 2006 From: gene.tani at gmail.com (gene tani) Date: 30 Apr 2006 20:49:23 -0700 Subject: Measure memory usage in Python In-Reply-To: <1146431890.904603.98620@i39g2000cwa.googlegroups.com> References: <1146431890.904603.98620@i39g2000cwa.googlegroups.com> Message-ID: <1146455362.984926.216240@g10g2000cwb.googlegroups.com> Rune Strand wrote: > Is there a way to measure how much memory a data structure use? For > instance, what is the footprint of a particular list object like > [0,1,2,3,4,5,6,7,8,9]? i have a note to try this, but haven't got around to it, if you want to blog/post http://pysizer.8325.org/ From rzantow at gmail.com Mon Apr 3 08:07:02 2006 From: rzantow at gmail.com (Rick Zantow) Date: Mon, 03 Apr 2006 08:07:02 -0400 Subject: how to comment lot of lines in python References: <1143760897.940841.285300@i39g2000cwa.googlegroups.com> <44310867$1_1@newspeer2.tds.net> Message-ID: Kent Johnson wrote in news:44310867$1_1 @newspeer2.tds.net: > Sion Arrowsmith wrote: >> Eric Deveaud wrote: >>> some moderns editors allow you to comment/uncomment a selected Bunch >>> of lines of code >> >> Out of curiousity, is there a modern editor which *doesn't* allow you >> to comment/uncomment a selected bunch of lines of code? >> > TextPad is my editor of choice but it doesn't have this feature. > I use TextPad all the time, and while it is true that the feature is not built in, it's misleading to say it doesn't have it. It is implemented by means of a macro definition. I assign a key to a 'comment' macro (basically replacing regex ^ with '# ' for the selected text) to do this. And of course I have a reciprocal 'uncomment' macro as well. -- rzed From antroy at gmail.com Wed Apr 19 10:13:12 2006 From: antroy at gmail.com (Ant) Date: 19 Apr 2006 07:13:12 -0700 Subject: items in an array In-Reply-To: <1145455441.531332.295700@e56g2000cwe.googlegroups.com> References: <1145455441.531332.295700@e56g2000cwe.googlegroups.com> Message-ID: <1145455992.020224.122930@u72g2000cwu.googlegroups.com> If you just want the items concatenated with a comma separator, the following is what you need: >>> list_arr = ["one", "two", "three"] >>> list = ",".join(list_arr) >>> print(list) one,two,three From fredrik at pythonware.com Thu Apr 13 03:08:08 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 13 Apr 2006 09:08:08 +0200 Subject: list.clear() missing?!? References: <1144767680.583085.310160@v46g2000cwv.googlegroups.com> <1144792144.168802.146310@i39g2000cwa.googlegroups.com> <1144870852.886477.238570@u72g2000cwu.googlegroups.com> Message-ID: Peter Hansen wrote: > > * learning slices is basic to the language (this lesson shouldn't be > > skipped) > > And yet it doesn't appear to be in the tutorial. oh, please. slices are explained in the section on strings, and in the section on lists, and used to define the behaviour of the list methods in the second section on lists, ... > I could have missed it, but I've looked in a number of the obvious places http://docs.python.org/tut/node5.html#SECTION005140000000000000000 section 3.1.2 contains an example that shows to remove stuff from a list, in place. if you want a clearer example, please consider donating some of your time to the pytut wiki: http://pytut.infogami.com/ From johnjsal at NOSPAMgmail.com Wed Apr 19 11:50:50 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 19 Apr 2006 15:50:50 GMT Subject: Ironpython book? In-Reply-To: References: <1145329406.419299.12780@i40g2000cwc.googlegroups.com> <1he15xj.1dy2h0vzbebqmN%aleaxit@yahoo.com> <1he18dm.e64uky1urr3n0N%aleaxit@yahoo.com> Message-ID: John Salerno wrote: > But it sounds like, from Fred's post "Fredrik". Have no idea why Fred slipped out. :) From aleaxit at yahoo.com Mon Apr 17 22:14:20 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 17 Apr 2006 19:14:20 -0700 Subject: How protect proprietary Python code? (bytecode obfuscation?, what better?) References: <1145293384.791678.14450@v46g2000cwv.googlegroups.com> <1145300492.623527.300740@e56g2000cwe.googlegroups.com> Message-ID: <1hdyc4i.jlfzl691w2ehN%aleaxit@yahoo.com> gangesmaster wrote: ... > but anyway, it's stupid. why be a dick? those who *really* want to get > to the source will be able to, no matter what you use. after all, the > code is executing on their CPU, and if the CPU can execute it, so > can really enthused men. and those who don't want to use your product, > don't care anyway if you provide the source or not. so share. Alternatively, if you have secrets that are REALLY worth protecting, keep a tiny part of your app, embedding all worthwhile secrets, on YOUR well-secured server -- expose it as a webservice, or whatever, so the "fat client" (most of the app) can get at it. This truly gives you complete control: you don't care any more if anybody decompiles the part you distribute (which may be 90% or 99% of the app), indeed you can publish the webservice's specs or some API to encourage more and more people to write to it, and make your money by whatever business model you prefer (subscription, one-off sale, pay-per-use, your choice!). If you keep your client thin rather than fat, the advantages increase (your app can be used much more widely, etc), but you may need substantial amounts of servers and other resources to support widespread use. When I started proposing this approach, years and years ago, the fact that your app can work only when connected to the net might be considered a real problem for many cases: but today, connectivity is SO pervasive, that all sort of apps require such connectivity anyway -- e.g, look at Google Earth for a "fat client", Google Maps for a "thin" one accessing a subset of roughly the same data but running (the client side) inside a browser (with more limited functionality, to be sure). Alex From pink at odahoda.de Mon Apr 10 06:12:58 2006 From: pink at odahoda.de (Benjamin Niemann) Date: Mon, 10 Apr 2006 12:12:58 +0200 Subject: Python 3.0 or Python 3000? References: <4439aba9$0$18019$c3e8da3@news.astraweb.com> Message-ID: Dennis Lee Bieber wrote: > On Sun, 9 Apr 2006 22:15:15 -0400, "Tim Peters" > declaimed the following in comp.lang.python: > >> [John Salerno] >> > Is 'Python 3000' just a code name for version 3.0, or will it really be >> > called that when it's released? >> >> The smart money is on changing the name to Ecstasy, to leverage >> marketing publicity from the hallucinogenic club drug of the same >> name. "class" will be renamed to "rave", and the license will be >> changed to prohibit use by people with bipolar disorder. Either that, >> or the name will be Python 3.0. > > Or... just to save "3000" as a "time way down the road"... The next > major version of Python will be: Python PI (and each build will add > another digit... "3.1, 3.14, 3.141, ...") That's actually the versioning scheme of TeX, currently being at 3.141592 -- Benjamin Niemann Email: pink at odahoda dot de WWW: http://pink.odahoda.de/ From __peter__ at web.de Fri Apr 28 11:39:57 2006 From: __peter__ at web.de (Peter Otten) Date: Fri, 28 Apr 2006 17:39:57 +0200 Subject: Converstion References: <1146181848.615239.281200@j33g2000cwa.googlegroups.com> <1146206766.870443.297810@e56g2000cwe.googlegroups.com> <4451BDDE.6030208@lexicon.net> <1146237857.377980.15620@v46g2000cwv.googlegroups.com> Message-ID: Paddy wrote: > the del version - is that an optimisation? > Is it actually faster? del x[-1:] # or del x[-1] if you are sure that len(x) > 0 just deletes the last item (if any) from x whereas x = x[:-1] copies all but the last item of the original list into a new one. This can take much longer: [copy 10000 lists with 5000 items on average] $ python -m timeit -n10000 -s'data = range(10000)' 'data = data[:-1]' 10000 loops, best of 3: 38.9 usec per loop [remove the last item from a list 10000 times] $ python -m timeit -n10000 -s'data = range(10000)' 'del data[-1:]' 10000 loops, best of 3: 0.272 usec per loop $ python -m timeit -n10000 -s'data = range(10000)' 'del data[-1]' 10000 loops, best of 3: 0.246 usec per loop Peter From nephish at xit.net Sat Apr 22 11:10:38 2006 From: nephish at xit.net (nephish at xit.net) Date: 22 Apr 2006 08:10:38 -0700 Subject: need a thread to keep a socket connection alive? Message-ID: <1145718638.526525.235090@i39g2000cwa.googlegroups.com> hey there, i have a script that waits for message packets from a data server over a socket. it goes a little like this: while 1: x+=1 databack = sockobj.recv(158) if databack: print 'caught a message %s bytes ' % len(databack) if len(databack) > 120: message = databack[3:-3] #strip stx and enx print '\n\n%s' % message else: break print 'end data ack' it works fine for a while, but the server requires that i send a heartbeat ping every 600 seconds or it will terminate the connection. so i also need something like while 1: sockobj.send(ping) ping_acknowlage = sockobj.recv(48) time.sleep(550) should i do this with threads? i dont want to interrupt the listening cycle to send a ping. appreciate any tips on how would be the best way to pull this off. From johnjsal at NOSPAMgmail.com Fri Apr 7 23:56:51 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 07 Apr 2006 23:56:51 -0400 Subject: how you know you're a programming nerd In-Reply-To: <88FZf.44$B42.34@dukeread05> References: <3GuZf.1940$No6.41580@news.tufts.edu> <88FZf.44$B42.34@dukeread05> Message-ID: <443734db$0$782$c3e8da3@news.astraweb.com> Ron Adam wrote: > When you are working on your programming project on Friday night instead > of going out. Ok, you win. :) Oh wait, it's Friday night and I'm typing this message...dang it! From nobody at 127.0.0.1 Tue Apr 25 14:44:36 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Tue, 25 Apr 2006 18:44:36 GMT Subject: python application ideas. References: Message-ID: Thomas Bartkus wrote: > Tis the conundrum of programming in general. If all you know how to do is > write code - then you truly have nothing to do. What *other* interests do > you have? Hobbies? Job Skills? > What *does* "blow your hair back" ;-) > > That's where your programming ideas need to come from. yeah, learning experiences only come from enjoyable tasks. lord knows the countless boring, uninspired assignments handed down in a cs degree program teach absolutely nothing. oh wait... From kent at kentsjohnson.com Mon Apr 17 05:55:56 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Mon, 17 Apr 2006 05:55:56 -0400 Subject: Python certification/training In-Reply-To: References: <1145193231.657614.275950@v46g2000cwv.googlegroups.com> <1145205741.731529.84530@u72g2000cwu.googlegroups.com> Message-ID: <4443661f$1_2@newspeer2.tds.net> Richard Marsden wrote: > Aahz wrote: >> Then may I suggest that you subscribe to the tutor list? That will give >> you a good place to ask questions; as you learn Python, answering other >> people's questions will give you a good way to hone your own knowledge. > > > Which is? :-) http://mail.python.org/mailman/listinfo/tutor Kent From nicola.musatti at gmail.com Wed Apr 5 08:50:22 2006 From: nicola.musatti at gmail.com (Nicola Musatti) Date: 5 Apr 2006 05:50:22 -0700 Subject: Standalone Python functions in UML? In-Reply-To: <44338953$0$20293$626a54ce@news.free.fr> References: <4432a339$0$13233$626a54ce@news.free.fr> <44338953$0$20293$626a54ce@news.free.fr> Message-ID: <1144241422.785391.167170@i40g2000cwc.googlegroups.com> bruno at modulix wrote: [...] > Yes, there's in UML a fundamental distinction between classes and > objects - distinction that does not exist in a lot of OO languages. This > greatly limits UML's usability for some common idioms in dynamic OOPL's. > Seems like UML has been designed to express only the restricted subset > of OO supported by rigid static languages like C++, Java and ADA. Moreover, it also seems like UML has been designed to express the restricted OO subset of the paradigms supported by languages like C++ and ADA. And I suspect UML design tools are not that popular within the C and Lisp programming communities... Cheers, Nicola Musatti From tzot at sil-tec.gr Tue Apr 11 04:58:22 2006 From: tzot at sil-tec.gr (Christos Georgiou) Date: Tue, 11 Apr 2006 11:58:22 +0300 Subject: Decorators, Identity functions and execution... References: <1144597938.664642.133100@v46g2000cwv.googlegroups.com> Message-ID: On Tue, 11 Apr 2006 15:05:22 +1200, rumours say that Lawrence D'Oliveiro might have written: >In article , > Roy Smith wrote: > >>One of the most basic >>maxims on the Internet has always been, "Be liberal in what you accept, be >>conservative in what you produce". >How do you explain top-posting, then? ?Be lazy and let your news/mail client choose for you.? Unless you meant ?how do you explain top-posting *acceptance* by non top-posters.?? That is another branch of psychology. -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From sjmachin at lexicon.net Wed Apr 5 17:56:30 2006 From: sjmachin at lexicon.net (John Machin) Date: 5 Apr 2006 14:56:30 -0700 Subject: Filters like old skool Jive, Fudd, Valspeak... Text transformation in Python References: <1144237161.700762.75630@e56g2000cwe.googlegroups.com> Message-ID: <1144274190.122083.111080@z34g2000cwc.googlegroups.com> > Any good "generators" written in Python? I'd like to roll me one of > these as well; e.g. execute the program and it will create a few > paragraphs of text in the jargon of a discipline, subdiscipline, > subculture, etc. Anyone know what I'm talking about? Perhaps you might be interested in this (contains a link to a Python script): http://en.wikipedia.org/wiki/Mark_V_Shaney From felipe.lessa at gmail.com Mon Apr 10 11:59:57 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Mon, 10 Apr 2006 12:59:57 -0300 Subject: About classes and OOP in Python In-Reply-To: <1144678797.749000.155010@t31g2000cwb.googlegroups.com> References: <1144678797.749000.155010@t31g2000cwb.googlegroups.com> Message-ID: <1144684797.6280.15.camel@kenshin.CASA> Em Seg, 2006-04-10 ?s 07:19 -0700, fyhuang escreveu: > class PythonClass: > private foo = "bar" > private var = 42 > allow_readwrite( [ foo, var ] ) You are aware that foo and var would become class-variables, not instance-variables, right? But you can always do: class PythonClass(object): def __init__(self): self.__foo = "bar" foo = property(lambda self: self.__foo) And then: >>> a = PythonClass() >>> a.foo 'bar' >>> a.foo = 'baz' Traceback (most recent call last): File "", line 1, in ? AttributeError: can't set attribute But you can also bypass this "security": >>> a._PythonClass__foo = 'baz' >>> a.foo 'baz' But this was not a mistake, nobody mistakenly writes "_PythonClass__". > Or allow_read to only allow read-only access. Also there might be a > way to implement custom getters and setters for those times you want > to modify input or something: > > class PythonClass: > def get foo(): > return "bar" > > def set var( value ): > var = value There's a PEP somewhere that proposes things like (same example I gave earlier): class PythonClass(object): def __init__(self): self.__foo = "bar" create property foo: def get(self): return self.__foo -- Felipe. From pythor at gmail.com Tue Apr 4 12:15:50 2006 From: pythor at gmail.com (Pythor) Date: 4 Apr 2006 09:15:50 -0700 Subject: how do you use pickle? In-Reply-To: References: Message-ID: <1144167350.837406.172430@i39g2000cwa.googlegroups.com> John Salerno wrote: > I'm sorry, but I'm terribly confused. Nothing seems to be working for > me. I *think* what I need to pickle is an image file, SNIP Hint: Read the source for that page more carefully. From neurogasm at gmail.com Sun Apr 16 21:14:42 2006 From: neurogasm at gmail.com (Kun) Date: Sun, 16 Apr 2006 21:14:42 -0400 Subject: filling today's date in a form In-Reply-To: References: Message-ID: Felipe Almeida Lessa wrote: > Em Dom, 2006-04-16 ?s 19:22 -0400, Kun escreveu: >> i have a form > > Which kind of form? Which toolkit? > >> which takes in inputs for a mysql query. one of the inputs >> is 'date'. normally, a user has to manually enter a date, > > Enter the date in which kind of control? > >> but i am >> wondering if there is a way to create a button which would automatically >> insert today's date in the date form field if the user chooses to use >> today's date. > > Almost 100% sure that there is, but I can't tell you if or how if you > don't tell us how you are doing what you are doing. > Form is an html form called by a python cgi file using fieldstorage. Date as in '2006-04-16'... is that what you meant by control? From felipe.lessa at gmail.com Tue Apr 11 13:07:39 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Tue, 11 Apr 2006 14:07:39 -0300 Subject: Manipulating sets from the 2.4 C API? In-Reply-To: <443BDF95.4000009@v.loewis.de> References: <443BDF95.4000009@v.loewis.de> Message-ID: <1144775259.11151.8.camel@kenshin.CASA> Em Ter, 2006-04-11 ?s 18:55 +0200, "Martin v. L?wis" escreveu: > Dave Opstad wrote: > > If I want to handle sets should I just use a dictionary's keys and > > ignore the values, or is there some more explicit set support somewhere > > I'm not seeing? > > Indeed, there is. To create a new set, do > > PyObject_Call(PySet_Type, ""); > > To, say, invoke the add method, do > > PyObject_CallMethod(s, "add", "O", o); I don't know much about the C API, but I'll ask anyway: the methods, say, PySet, would be included for clarity/brevity or for performance reasons? -- Felipe. From nancyhowes at gmail.com Wed Apr 5 11:25:43 2006 From: nancyhowes at gmail.com (Nancy) Date: 5 Apr 2006 08:25:43 -0700 Subject: ceval.c no such file or dir and SIGSEGV Message-ID: <1144250742.956668.310320@i39g2000cwa.googlegroups.com> Hi, I'm running 2.4 Python. I have an extension program that calls C funcs. Actually I have a C prog that calls python that calls C. In a python to C function call I get a SIGSEGV and this stack trace. I have print statements that show it made it into the C extension function, and within there its crashing with this trace. gdb also puts up a popup that says Python/ceval.c No such file or directory. Thanks. Program received signal SIGSEGV, Segmentation fault. [Switching to Thread 1024 (LWP 7873)] PyEval_EvalFrame (f=0x8472c8c) at ../Python-2.4/Python/ceval.c:899 in ../Python-2.4/Python/ceval.c (gdb) where #0 PyEval_EvalFrame (f=0x8472c8c) at ../Python-2.4/Python/ceval.c:899 #1 0x081f4611 in fast_function (func=0x0, pp_stack=0xbfffe304, n=4, na=1, nk=0) at ../Python-2.4/Python/ceval.c:3629 #2 0x081f4174 in call_function (pp_stack=0xbfffe304, oparg=1) at ../Python-2.4/Python/ceval.c:3568 #3 0x081f26ba in PyEval_EvalFrame (f=0x847741c) at ../Python-2.4/Python/ceval.c:2163 #4 0x081f4611 in fast_function (func=0x0, pp_stack=0xbfffe434, n=4, na=1, nk=0) at ../Python-2.4/Python/ceval.c:3629 #5 0x081f4174 in call_function (pp_stack=0xbfffe434, oparg=1) at ../Python-2.4/Python/ceval.c:3568 #6 0x081f26ba in PyEval_EvalFrame (f=0x8476b6c) at ../Python-2.4/Python/ceval.c:2163 #7 0x081f4611 in fast_function (func=0x0, pp_stack=0xbfffe564, n=4, na=1, nk=0) at ../Python-2.4/Python/ceval.c:3629 #8 0x081f4174 in call_function (pp_stack=0xbfffe564, oparg=1) at ../Python-2.4/Python/ceval.c:3568 #9 0x081f26ba in PyEval_EvalFrame (f=0x84724bc) at ../Python-2.4/Python/ceval.c:2163 #10 0x081f4611 in fast_function (func=0x0, pp_stack=0xbfffe694, n=4, na=1, nk=0) at ../Python-2.4/Python/ceval.c:3629 #11 0x081f4174 in call_function (pp_stack=0xbfffe694, oparg=1) at ../Python-2.4/Python/ceval.c:3568 #12 0x081f26ba in PyEval_EvalFrame (f=0x848f65c) at ../Python-2.4/Python/ceval.c:2163 #13 0x081f4611 in fast_function (func=0x0, pp_stack=0xbfffe7c4, n=4, na=1, nk=0) at ../Python-2.4/Python/ceval.c:3629 #14 0x081f4174 in call_function (pp_stack=0xbfffe7c4, oparg=1) at ../Python-2.4/Python/ceval.c:3568 #15 0x081f26ba in PyEval_EvalFrame (f=0x846b5fc) at ../Python-2.4/Python/ceval.c:2163 #16 0x081f4611 in fast_function (func=0x0, pp_stack=0xbfffe8f4, n=4, na=1, nk=0) at ../Python-2.4/Python/ceval.c:3629 #17 0x081f4174 in call_function (pp_stack=0xbfffe8f4, oparg=1) at ../Python-2.4/Python/ceval.c:3568 #18 0x081f26ba in PyEval_EvalFrame (f=0x848ea1c) at ../Python-2.4/Python/ceval.c:2163 #19 0x081f4611 in fast_function (func=0x0, pp_stack=0xbfffea24, n=4, na=1, nk=0) at ../Python-2.4/Python/ceval.c:3629 #20 0x081f4174 in call_function (pp_stack=0xbfffea24, oparg=1) at ../Python-2.4/Python/ceval.c:3568 #21 0x081f26ba in PyEval_EvalFrame (f=0x848dddc) at ../Python-2.4/Python/ceval.c:2163 #22 0x081f4611 in fast_function (func=0x0, pp_stack=0xbfffeb54, n=4, na=1, nk=0) at ../Python-2.4/Python/ceval.c:3629 #23 0x081f4174 in call_function (pp_stack=0xbfffeb54, oparg=1) at ../Python-2.4/Python/ceval.c:3568 #24 0x081f26ba in PyEval_EvalFrame (f=0x847959c) at ../Python-2.4/Python/ceval.c:2163 #25 0x081f30fe in PyEval_EvalCodeEx (co=0x402dcca0, globals=0x1, locals=0x0, args=0x4032e970, argcount=3, kws=0x0, kwcount=0, defs=0x0, defcount=0, closure=0x0) at ../Python-2.4/Python/ceval.c:2730 #26 0x0824c8e9 in function_call (func=0x4031ee2c, arg=0x4032e964, kw=0x0) at ../Python-2.4/Objects/funcobject.c:550 #27 0x081a86c9 in PyObject_Call (func=0x8472c8c, arg=0x1, kw=0x1) at ../Python-2.4/Objects/abstract.c:1746 #28 0x081f4005 in PyEval_CallObjectWithKeywords (func=0x1, arg=0x4032e964, kw=0x0) at ../Python-2.4/Python/ceval.c:3419 #29 0x081a8690 in PyObject_CallObject (o=0x1, a=0x1) at ../Python-2.4/Objects/abstract.c:1737 #30 0x080ce555 in pyGraphResolvePoint (funcIndex=1, sim=0, field_name=0x825c17c "signal", x=2.2000000000000002, y=7.2000000000000002, point=0xbfffed38) at pygraph.c:94 #31 0x080c1058 in graphNodeResolvePoint (sim=0, fieldName=0x825c17c "signal", x=2.2000000000000002, y=7.2000000000000002) at graph.c:57 #32 0x0807a7a6 in fibs_pointEval (sim=0, pointname=0x825c17c "signal", pos={x = 2.2000000000000002, y = 7.2000000000000002}) at libfibs.c:386 #33 0x0807b03f in libfibsTest (xmdlpath=0x825bd58 "xmdl.test", x=2.2000000000000002, y=7.2000000000000002) at libfibs.c:716 #34 0x08079c01 in main () at libfibsTest.c:8 #35 0x40186507 in __libc_start_main (main=0x8079bc8
, argc=1, ubp_av=0xbfffeeb4, init=0x80789cc <_init>, fini=0x825bd20 <_fini>, rtld_fini=0x4000dc14 <_dl_fini>, stack_end=0xbfffeeac) at ../sysdeps/generic/libc-start.c:129 (gdb) Quit (gdb) From tim.peters at gmail.com Sat Apr 22 16:46:38 2006 From: tim.peters at gmail.com (Tim Peters) Date: Sat, 22 Apr 2006 16:46:38 -0400 Subject: Problem calling math.cos() In-Reply-To: References: <3ev2g.9680$%97.5795@newsfe15.lga> Message-ID: <1f7befae0604221346y4fe68b1cycb8a4c551743ac65@mail.gmail.com> [Roy Smith] > I certainly agree about using atan2() instead of atan(), but I'm surprised > there's not an easier way to get the phase of a complex, just like abs() > gives you the modulus. I can see why you wouldn't want to pollute the > global namespace with another built-in just for this purpose, but surely a > complex.phase property wouldn't hurt? Or method. "Does anyone care enough to do the work?" is the real question. I don't :-) From aleaxit at yahoo.com Fri Apr 28 11:11:11 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 28 Apr 2006 08:11:11 -0700 Subject: Non-web-based templating system References: <1146221757.653214.115090@g10g2000cwb.googlegroups.com> Message-ID: <1hehtoq.9zic4f19ddp82N%aleaxit@yahoo.com> wrote: > Hi, > > I'm creating a small application in Python that uses lists and > dictionaries to create a rudimentary database. I'd like to create some > "fill-in-the-blanks" reports from this data, ideally by taking an RTF > or plaintext file as a template and replacing placeholder tags with my > data. > Are there any good pre-written systems that would allow me to do this? I have a certain fondness for the first over-100-lines module I wrote for Python, which eventually resulted in: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52305 and while I haven't checked its descendant: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/465508 it may have important enhancements. There are also a couple of variations on the web that are specialized for XML and HTML (search for yaptu), but the generic one should work better for RTF and TXT. Alex From thn at mail.utexas.edu Thu Apr 6 19:00:12 2006 From: thn at mail.utexas.edu (Thomas Nelson) Date: 6 Apr 2006 16:00:12 -0700 Subject: python on Mac In-Reply-To: References: <1144284073.446005.53950@t31g2000cwb.googlegroups.com> <1144330655.771606.275130@v46g2000cwv.googlegroups.com> <1144337441.565462.202030@v46g2000cwv.googlegroups.com> Message-ID: <1144364412.424015.167100@t31g2000cwb.googlegroups.com> Ok, I fixed my /usr/bin/python and added /usr/public/bin/ to my PATH in .profile. Everything seems ok now. Thanks again to everyone for their help. THN From tim.golden at viacom-outdoor.co.uk Mon Apr 10 08:48:30 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: 10 Apr 2006 05:48:30 -0700 Subject: can't pass command-line arguments In-Reply-To: <1144636890.976327.253000@i39g2000cwa.googlegroups.com> References: <1144636890.976327.253000@i39g2000cwa.googlegroups.com> Message-ID: <1144673310.017604.11630@t31g2000cwb.googlegroups.com> BartlebyScrivener wrote: > I'm still new at this. I can't get this to work as a script. If I just > manually insert the values for sys.argv[1] and sys.argv[2] it works > fine, but I can't pass the variables from the command line. What am I > doing wrong? On windows xp, python 2.4.3 > [... snip code ...]> Did you see this thread a little while ago? http://groups.google.com/group/comp.lang.python/browse_thread/thread/8ed6d03307df1a6a/60d017deadbac420#60d017deadbac420 In summary, it suggests looking at FTYPE and ASSOC, and in particular at the %* param to FTYPE The business of typing the .py or not is as secondary issue, I suspect, and as someone else pointed out is governed by the PATHEXT env var. TJG From rrr at ronadam.com Mon Apr 24 15:21:47 2006 From: rrr at ronadam.com (Ron Adam) Date: Mon, 24 Apr 2006 14:21:47 -0500 Subject: MS VC++ Toolkit 2003, where? In-Reply-To: <1heagzk.1pzfash1awhj3eN%aleaxit@yahoo.com> References: <1he8pss.1yk7ug81rv7pw2N%aleaxit@yahoo.com> <1145811839.042394.73260@t31g2000cwb.googlegroups.com> <1he8sbx.dqqp3q10n5thaN%aleaxit@yahoo.com> <1145849491.347970.112150@e56g2000cwe.googlegroups.com> <1he9m4m.9d8okx1x7mxeaN%aleaxit@yahoo.com> <444C7896.9040104@v.loewis.de> <1heagzk.1pzfash1awhj3eN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > "Martin v. L?wis" wrote: > >> Alex Martelli wrote: >>> As suggested to me by David Rushby 10 hours ago, >>> >>> http://www.microsoft.com/downloads/details.aspx?FamilyId=272BE09D-40BB-4 >>> 9FD-9CB0-4BFA122FA91B&displaylang=en >>> >>> does work. >> Can you please try this again: I'm also getting the error message >> that AIM is getting. > > Try tinyurl http://tinyurl.com/gv8wr please. I still get the following with the tinyurl link: ~~~ The download you requested is unavailable. If you continue to see this message when trying to access this download, go to the "Search for a Download" area on the Download Center home page. ~~~ Pasting the above tinyurl into firefox results in the following link. http://www.microsoft.com/downloads/details.aspx?familyid=272BE09D-40BB-4&displaylang=en Which appears to still be truncated. :-/ > I've also tinyurl'd your URL for the 1.1 SDK, to > http://tinyurl.com/5flob . This one works. > ((I suspect the problem has to do with a limitation of 80 > characters/line in NNTP messages, which my favorite newsreader enforces > unconditionally)). > > Alex From tksri2000 at yahoo.com Thu Apr 13 17:18:29 2006 From: tksri2000 at yahoo.com (tksri2000 at yahoo.com) Date: 13 Apr 2006 14:18:29 -0700 Subject: Buffer.so,oci.so compilation for DCoracle Message-ID: <1144963109.637606.161650@i39g2000cwa.googlegroups.com> I am trying to compile Buffer.so for oracle 10g. This is as part of DCoracle installation. I am following the instructions under src/README.txt. ORACLE_PATH=.:/opt/oracle/product/10.2.0/bin Python 2.4.3 (#2, Apr 10 2006, 13:02:28) [GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-53)] on linux2 I get the follwing error: make gcc -pthread -fPIC -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I/users/sk616655/usr/local/include/python2.4 -I/users/sk616655/usr/local/include/python2.4 @DEFS@ -I/opt/oracle/product/10.2.0/rdbms/demo -I/opt/oracle/product/10.2.0/network/public -I/opt/oracle/product/10.2.0/plsql/public -DDCORACLE8 -c ././oci_.c -o ./oci_.o gcc: cannot specify -o with -c or -S and multiple compilations *** Error code 1 clearmake: Error: Build script failed for "oci_.o" zsh: exit 1 clearmake Help please. sri From johnjsal at NOSPAMgmail.com Wed Apr 19 09:46:10 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 19 Apr 2006 13:46:10 GMT Subject: Ironpython book? In-Reply-To: <1145329406.419299.12780@i40g2000cwc.googlegroups.com> References: <1145329406.419299.12780@i40g2000cwc.googlegroups.com> Message-ID: alacrite at gmail.com wrote: > Anyone know if there is a book for Ironpython in the works? A good > knowledge of .NET and Python is enough to get started but just poking > around Ironpython homepage it seems like there are some new language > features added to handle some quirks with working within the CLR. > Although I could be wrong. > > Thanks > > -Jake > Just out of curiosity, is Python.NET a dead project? From fulvio at pc.jaring.my Thu Apr 6 07:29:32 2006 From: fulvio at pc.jaring.my (Fulvio) Date: Thu, 6 Apr 2006 19:29:32 +0800 Subject: how to create file with spaces In-Reply-To: <1144318680.674373.111220@j33g2000cwa.googlegroups.com> References: <1144318680.674373.111220@j33g2000cwa.googlegroups.com> Message-ID: <200604061929.33091.fulvio@pc.jaring.my> Alle 18:18, gioved? 06 aprile 2006, s99999999s2003 at yahoo.com ha scritto: > How can i deal with spaces in this case? I don't have an idea with python, but if can help I may say that bash you might use "\ " to escape a space or use a quoted full path. The shell program "basename" is failing, anyhow with file names containing spaces. F From none at no.chance Tue Apr 25 06:35:43 2006 From: none at no.chance (Peter Tillotson) Date: Tue, 25 Apr 2006 11:35:43 +0100 Subject: Probability Problem In-Reply-To: References: Message-ID: I had a possibly similar problem calculating probs related to premium bond permutation. With 10^12 memory ran out v quickly. In the end I got round it by writing a recursive function and quantising the probability density function. Elliot Temple wrote: > Problem: Randomly generate 10 integers from 0-100 inclusive, and sum > them. Do that twice. What is the probability the two sums are 390 apart? > > I have code to do part of it (below), and I know how to write code to do > the rest. The part I have calculates the number of ways the dice can > come out to a given number. The problem is the main loop has 9 > iterations and it takes about 2.5 minutes to begin the 4th one, and each > iteration is about 101 times longer than the previous one. So: > >>>> x = 2.5 * 101**6 >>>> x /= (60*24*365.25) >>>> x > 5045631.5622908585 > > It'd take 5,000 millennia. (If my computer didn't run out of memory > after about 4 minutes, that is.) > > Any suggestions? Either a way to do the same thing much more efficiently > (enough that I can run it) or a different way to solve the problem. > > Code: > > li = range(101) > li2 = [] > range101 = range(101) > for x in xrange(9): > print "x is %s" % x > li2 = [] > for y in li: > for z in range101: > li2 += [y+z] > li = li2 > print li.count(800) > # prints how many ways the dice can add to 800 > > > This link may help: > http://www.math.csusb.edu/faculty/stanton/m262/intro_prob_models/calcprob.html > > > -- Elliot Temple > http://www.curi.us/blog/ > From podi.ex at gmail.com Thu Apr 20 03:05:01 2006 From: podi.ex at gmail.com (Podi) Date: 20 Apr 2006 00:05:01 -0700 Subject: How to pass variable to test class In-Reply-To: References: <1145174626.993263.237420@v46g2000cwv.googlegroups.com> Message-ID: <1145516701.181921.261780@i40g2000cwc.googlegroups.com> Thanks for replying. I need to pass some external values to the test cases because I want to run the same tests in different environments such as lab/instrument setup. Regards, Podi From onurb at xiludom.gro Tue Apr 25 05:12:04 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 25 Apr 2006 11:12:04 +0200 Subject: Multiple hierarchie and method overloading In-Reply-To: References: Message-ID: <444de839$0$29622$636a55ce@news.free.fr> Philippe Martin wrote: > Hi, > > I have something like this: > > Class A: > def A_Func(self, p_param): > ..... > Class B: > def A_Func(self): > ..... > > Class C (A,B): > A.__init__(self) > B.__init__(self) > > ..... > > self.A_Func() #HERE I GET AN EXCEPTION "... takes at least 2 arguments (1 > given). Ho, yes, also: A.A_Func() really takes 2 arguments (self, and p_param). When called from an instance of A, the first argument (ie: self) will be automagically feed with the instance itself - but you still have to pass the second one. > > I renamed A_Func(self) to fix that ... but is there a cleaner way around ? Yes : passing the second argument. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From broz at broznews.org Fri Apr 14 09:12:37 2006 From: broz at broznews.org (broz) Date: Fri, 14 Apr 2006 09:12:37 -0400 Subject: Searching and MySQL module stuff In-Reply-To: Message-ID: Thx for the help in finding the search page for this mailing list!! BartlebyScrivener pointed me to the right place. >From there http://groups.google.com/group/comp.lang.python , I found what I needed I also discovered I can load mysql-python on my mac fairly easily, if I use Darwin Ports. http://darwinports.opendarwin.org/ Rock and roll! Thx all! From mike7411 at gmail.com Fri Apr 28 17:39:28 2006 From: mike7411 at gmail.com (mike7411 at gmail.com) Date: 28 Apr 2006 14:39:28 -0700 Subject: GUI slider control Message-ID: <1146260368.681045.55560@e56g2000cwe.googlegroups.com> Could someone tell me the easiest way to create a GUI slider control in Python? From wildemar at freakmail.de Fri Apr 21 08:57:46 2006 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Fri, 21 Apr 2006 14:57:46 +0200 Subject: what has python added to programming languages? (lets be esoteric, shall we ;) Message-ID: <4448D6CA.6080702@freakmail.de> Over the time I've seen lots of remarks about python that read like "a lot like lists in lisp" or "like the hashtable in java" or any other form of "like in ". Are there any concepts that python has not borrowed, concepts that were not even inspired by other languages? I'm just interested if it is "merely" a best-of collection of language features or if there are actually inventions that have not - or hardly - existed in programming before python? wildemar From josecarlos.balderas at gmail.com Mon Apr 17 03:46:48 2006 From: josecarlos.balderas at gmail.com (Jose Carlos Balderas Alberico) Date: Mon, 17 Apr 2006 09:46:48 +0200 Subject: Another SimpleXMLRPCServer question. Message-ID: Let's hope this is my last question on the matter. I'm implementing a SimpleXMLRPCServer, and last week I had a problem John helped me solve. The thing is that my server is to be called from a remote machine, so when declaring the instance, the line ("localhost", 8000) wouldn't work because it would only listen on 127.0.0.1. Next thing I tried was the line ('', 8000) (two simple quotes). That way it worked just fine, because now the server listens on all interfaces. My question now is: is this the way SimpleXMLRPCServers are implemented? All the examples I've found use the simple quotes, without providing any other aditional examples. I want to know if there are any security risks that raise from the fact that it listens on all interfaces. I haven't been able to find any information on this. If you need more info regarding my question, please ask. Thank you very much in advance. Jose Carlos. -------------- next part -------------- An HTML attachment was scrubbed... URL: From peter at engcorp.com Tue Apr 11 14:58:43 2006 From: peter at engcorp.com (Peter Hansen) Date: Tue, 11 Apr 2006 14:58:43 -0400 Subject: XPath/Screen Scraping Gurus.. In-Reply-To: <237101c65d84$c0c54da0$0301a8c0@Mesa.com> References: <237101c65d84$c0c54da0$0301a8c0@Mesa.com> Message-ID: bruce wrote: > I'm not that familiar with Pythin, but I wasn wondering if there are any > XPath/Python Gurus that I might be able to talk to regarding screen scraping > applications... Since you mention XPath, it seems likely you are really interested in *web-scraping*. Screen-scraping refers, I believe, to the process of identifying what is onscreen in GUI programs, possibly even at the pixel level, and trying to translate that back into a higher level model (e.g. text in fields) of what is going on. Web-scraping, on the other hand, generally doesn't need to involve the graphic representation of anything, and can work at the level of HTML, XML, and ... XPath. (Disclaimer: I know these terms are not really standardized, but I think the defacto standard definitions match what I've described fairly closely.) -Peter From hierarchicalpolymorphist at gmail.com Thu Apr 13 00:30:18 2006 From: hierarchicalpolymorphist at gmail.com (Kevin CH) Date: 12 Apr 2006 21:30:18 -0700 Subject: Regular Expression: Matching substring In-Reply-To: <1144898647.858122.98680@u72g2000cwu.googlegroups.com> References: <1144895624.539696.322960@e56g2000cwe.googlegroups.com> <1144898647.858122.98680@u72g2000cwu.googlegroups.com> Message-ID: <1144902618.744717.188740@z34g2000cwc.googlegroups.com> Leon wrote: > Hi Kevin, > > You may notice that, for matching the regex (0|(1(01*0)*1))*, the left > most > three characters of a string must not be ``101" while not followed by > an `0'. > After reading the first `1', automata expects `1' or ``00" or ``010" > or ``11", > right?:) Why it must expect "010"? Why not say "0110", since 1* can represent 0 or more repetitions. > > > Kevin CH ??? > > > Hi, > > > > I'm currently running into a confusion on regex and hopefully you guys > > can clear it up for me. > > > > Suppose I have a regular expression (0|(1(01*0)*1))* and two test > > strings: 110_1011101_ and _101101_1. (The underscores are not part of > > the string. They are added to show that both string has a substring > > that matches the pattern.) Applying a match() function on the first > > string returns true while false for the second. The difference is the > > first one has unmatched chunk in the beginning while the second at the > > end. How's the regex rule work here? > > > > Thanks. From tim.golden at viacom-outdoor.co.uk Wed Apr 12 03:41:44 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 12 Apr 2006 08:41:44 +0100 Subject: Help needed on COM issue Message-ID: [Mike Howard] | Should read ... | I'm doing some conversion of vb code to python code and I have a | problem with a COM object | | Specifically in VB I can do | Set oR = oA.Action | debug.print oR.Item(1,2) | [returns say "1"] | oR.Item(1,2)="4" | debug.print oR | [returns "4"] | oR.Update | [saves the record with the new item] | | In Python I need to do .. | | oR=oA.Action() | print oR.Item(1,2)[0] | [returns say "1"] | | But when I ty to update the value | | oR.Item(1,2)[0]="4" | | I get a TypeError : object doesn't support item assignment. You sometimes find that altho' VB lets you shortcut attribute value and assignment, it's actually doing a .Value= behind-the-scenes. (At least, I seem to remember coming across that). So try something like: oR.Item(1, 2)[0].Value = "4" TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From Serge.Orlov at gmail.com Wed Apr 12 04:47:21 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 12 Apr 2006 01:47:21 -0700 Subject: A question about the urllib2 ? In-Reply-To: References: Message-ID: <1144831641.616081.72350@i40g2000cwc.googlegroups.com> Bo Yang wrote: > Hi , > Recently I use python's urllib2 write a small script to login our > university gateway . > Usually , I must login into the gateway in order to surf the web . So , > every time I > start my computer , it is my first thing to do that open a browser to > login the gateway ! > > So , I decide to write such a script , sending some post information to > the webserver > directly to login automatic once the computer is on . And I write the > code below : > > urllib2.urlopen(urllib2.Request(url="https://202.113.16.223/php/user_login.php", > data="loginuser=0312889&password=o127me&domainid=1&refer=1& logintype= > ?????")) > > In the five '#' above , I must submit some Chinese character , but the > urllib2 complain > for the non-ascii characters . I guess the server expect that a browser is coming from page https://202.113.16.223/, so the url should be submitted in the encoding of page https://202.113.16.223/ which is gb2312. urllib2.urlopen(urllib2.Request(url="https://202.113.16.223/php/user_login.php", data=u"loginuser=0312889&password=o127me&domainid=1&refer=1& logintype= ??".encode('gb2312'))) should work From diffuser78 at gmail.com Thu Apr 6 10:56:41 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 6 Apr 2006 07:56:41 -0700 Subject: GUI issues in Python In-Reply-To: References: <1144328552.221998.230480@g10g2000cwb.googlegroups.com> Message-ID: <1144335401.607337.172140@j33g2000cwa.googlegroups.com> Thanks Daniel, I really think that this should be the solution to my problem. A quick Question...is wxPython Operating System dependent or it can be used with anu OS like Linux, Windows and Mac ? From caleb.hattingh at gmail.com Sat Apr 1 03:54:59 2006 From: caleb.hattingh at gmail.com (Caleb Hattingh) Date: 1 Apr 2006 00:54:59 -0800 Subject: Python 2.5 licensing: stop this change In-Reply-To: References: Message-ID: <1143881699.232542.224960@j33g2000cwa.googlegroups.com> WAIT- Did I just get caught by an April Fools Joke? I have a nasty feeling about this :)) C From a.schmolck at gmail.com Tue Apr 4 06:39:47 2006 From: a.schmolck at gmail.com (Alexander Schmolck) Date: 04 Apr 2006 11:39:47 +0100 Subject: Dice probability problem References: Message-ID: Alexander Schmolck writes: > addDice(resultFor1, pool[1]) > addDice(pool[0], pool[1]) sorry should have spelled out that successive lines are meant to be equivalent, i.e. addDice(resultFor1, pool[1]) == addDice(pool[0], pool[1]) 'as From fabianosidler at gmail.com Thu Apr 27 17:07:34 2006 From: fabianosidler at gmail.com (Fabiano Sidler) Date: Thu, 27 Apr 2006 23:07:34 +0200 Subject: inheriting type or object? Message-ID: <200604272307.34836.fabianosidler@gmail.com> Hi folks! As stated in subject, how do I decide wether to inherit or ? Whenever I want to intantiate my derived type, I taked here, but inheriting from consequently would be reasonable in cases of pure static objects (i.e. objects/types using staticmethods exclusively), for whose I would prefer toplevel code outside a class definition in python, since python does not oblige programmers to use classes (like JAVA et. al.). So, finally, my question is: Is there a design pattern, that makes a reasonable (direct) base type for new objects/types? Right now, I can't see any. Thank you for answering! Greetings, F. Sidler From jweida at gmail.com Fri Apr 14 09:19:39 2006 From: jweida at gmail.com (Jerry) Date: 14 Apr 2006 06:19:39 -0700 Subject: Kross - Start of a Unified Scripting Approach In-Reply-To: <1145016269.843447.143680@e56g2000cwe.googlegroups.com> References: <1144866431.999725.293670@v46g2000cwv.googlegroups.com> <1hdqj4h.1ixp24v1dqm4wrN%aleaxit@yahoo.com> <1144988779.784290.53620@g10g2000cwb.googlegroups.com> <1145016269.843447.143680@e56g2000cwe.googlegroups.com> Message-ID: <1145020778.953720.86750@u72g2000cwu.googlegroups.com> Awesome, thanks for the explaination. It was very informative. From against at spam.pl Thu Apr 13 07:10:08 2006 From: against at spam.pl (=?ISO-8859-2?Q?Grzegorz_=A6lusarek?=) Date: Thu, 13 Apr 2006 13:10:08 +0200 Subject: how to match n- lists for a common elements. Message-ID: Hi all. I my application i have situation when i have some lists and i must get from lists common elements. Exacly i don't know how many list I have so at the moment of creation each of one I append them to one list. So I get list wchich consist of lists of objects. And now i want to get common objects of this list. How to do it? Grzegorz From cvanarsdall at mvista.com Wed Apr 19 18:57:01 2006 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Wed, 19 Apr 2006 15:57:01 -0700 Subject: Conditions vs Events Message-ID: <4446C03D.7020303@mvista.com> Le Monde De Python, I've been working a lot with python threads from the threading module. Specifically, when is it better to use a condition object vs an event object? It seems to me that, at least superficially, I can just about use these two mechanisms interchangeably. The only real difference I can see is that I can call isSet() on an event in the case that an event is triggered before wait() is called. Are there any differences? Also, does calling wait reset some type of "notify" in a condition object like it does in an event object? Anyhow, thanks for your help! -carl -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From buchstaebchen at googlemail.com Thu Apr 13 11:31:38 2006 From: buchstaebchen at googlemail.com (buchstaebchen at googlemail.com) Date: 13 Apr 2006 08:31:38 -0700 Subject: quick surface plots Message-ID: <1144942298.800990.139160@g10g2000cwb.googlegroups.com> Hi folks, I need advice in finding an appropriate python module for 3D surface plots, such as for the visualization of wave-dynamics...I'd prefer something capable of being embedded in wxpython frames, as matplotlib is doing pretty well for 2D, however, I couldn't get a hold of functions like there. vpython hasn't any likewise, while mayavi is way to complex (and doesn't allow quick animation?) Any recommendation (or some old threads I failed to look for) ? thanks for any reply and cheers! From nszabolcs at gmail.com Mon Apr 3 12:54:34 2006 From: nszabolcs at gmail.com (Szabolcs Nagy) Date: 3 Apr 2006 09:54:34 -0700 Subject: Best IDE for Python? In-Reply-To: References: <1143783179.361616.76750@i39g2000cwa.googlegroups.com> Message-ID: <1144083274.892079.52540@u72g2000cwu.googlegroups.com> ide unification effort: http://pyxides.stani.be/ (there are some useful links and it's more recent than the python.org wiki) From reply.in.the.newsgroup at my.address.is.invalid Thu Apr 27 02:54:59 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Thu, 27 Apr 2006 08:54:59 +0200 Subject: begging for a tree implementation References: <1146091386.013265.153660@v46g2000cwv.googlegroups.com> <1146107842.659346.178910@t31g2000cwb.googlegroups.com> Message-ID: <2lq0521052qd9a5tb3k3na8imm3ulrbebb@4ax.com> Micah: >I'd like a full-featured tree What features? -- Ren? Pijlman From onurb at xiludom.gro Wed Apr 19 13:04:09 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 19 Apr 2006 19:04:09 +0200 Subject: How protect proprietary Python code? (bytecode obfuscation?, what better?) In-Reply-To: <1145450399.254863.234380@i40g2000cwc.googlegroups.com> References: <1145293384.791678.14450@v46g2000cwv.googlegroups.com> <4444c777$0$9453$626a54ce@news.free.fr> <1145450399.254863.234380@i40g2000cwc.googlegroups.com> Message-ID: <44466dd9$0$20865$636a55ce@news.free.fr> Ben Sizer wrote: > bruno at modulix wrote: > >>seberino at spawar.navy.mil wrote: >> >>>I suppose another idea is to rewrite entire Python app in C if compiled >>>C code >>>is harder to decompile. >> >>Do you really think "native" code is harder to reverse-engineer than >>Python's byte-code ? > > > Yes, until there's a native code equivalent of "import dis" that > telepathically contacts the original programmer to obtain variable > names that aren't in the executable. Lol !-) Ok, granted. Let's rephrase it: "do you really think that native code is harder *enough* to reverse-engineer ?" -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From nico at netsys.co.za Wed Apr 12 08:18:49 2006 From: nico at netsys.co.za (Nico Kruger) Date: Wed, 12 Apr 2006 14:18:49 +0200 Subject: Problem with spawning an external process In-Reply-To: <1144839351.3376.51.camel@notamc2.snetsys.co.za> References: <1144834050.3376.35.camel@notamc2.snetsys.co.za> <1144834879.3376.39.camel@notamc2.snetsys.co.za> <5f56302b0604120253u2705a0fdo837a981d9930a635@mail.gmail.com> <1144836062.3376.42.camel@notamc2.snetsys.co.za> <5f56302b0604120341m1795e472l6bda5f2be91780bc@mail.gmail.com> <1144839351.3376.51.camel@notamc2.snetsys.co.za> Message-ID: <1144844328.3376.62.camel@notamc2.snetsys.co.za> Not working with Python 2.3.5 here on Fedora Core 2 :(. Oh well, at least it's working on 2.4. Must be specific to something in the combination of Fedora Core 2 and Python 2.3.x, that is all I can think of. On Wed, 2006-04-12 at 12:55, Nico Kruger wrote: > Daniel, you are correct, it is not that good news for me :) > > But anyway, thanks to your responses, I installed Python 2.4.3 and it is > working on my machine now as well. We were overdue for an upgrade to our > Python environment anyways, so I think this is the final incentive to > upgrade. > > Although, I will download 2.3.5 now and get back to you with the status. > Would be interesting to know when exactly this problem was fixed, maybe > it would help to know what is causing the problem? It really is a > strange one. > > Again, thanks for your effort! > > -- NetSys International (Pty) Ltd. Tel : +27 12 349 2056 Fax : +27 12 349 2757 Web : http://www.netsys.co.za P.O. Box 35798, Menlo Park, 0102, South Africa ---- The information contained in this communication is confidential and may be legally privileged. It is solely for use of the individual or entity to whom is addressed and others authorised to receive it. If you are not the intended recipient you are hereby notified that any disclosure, copying, distribution or taking of any action in reliance on the contents of this information is strictly prohibited and may be unlawful. This Message has been scanned for viruses and dangerous content by the NetSys International Mail Scanner and is believed to be clean. From rridge at csclub.uwaterloo.ca Tue Apr 25 17:07:36 2006 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: 25 Apr 2006 14:07:36 -0700 Subject: MinGW and Python References: <1145861223.509630.247350@y43g2000cwc.googlegroups.com> <444C79D7.4060007@v.loewis.de> <444DC62B.7000702@v.loewis.de> <1145985979.369429.114040@i39g2000cwa.googlegroups.com> <444e7d85$0$12131$9b622d9e@news.freenet.de> Message-ID: <1145999256.027851.132780@y43g2000cwc.googlegroups.com> Martin v. L?wis wrote: > Well, there is no native C library on Microsoft Windows: the system > simply doesn't include an official C library (I know there is crtdll.dll > and msvcrt.dll, but these aren't "endorsed" system C libraries). MSVCRT.DLL has been a standard system compent of Windows since at least Windows 98. Many other system components depend on it. Essentially, MSVCRT.DLL is an "undocumented" part of the Windows API. It's not exactly "endorsed", Microsoft would rather you use it's current compiler and runtime, but it is the standard "official" Windows system C library. Ross Ridge From mlacunza at gmail.com Thu Apr 20 00:30:19 2006 From: mlacunza at gmail.com (Mario Lacunza) Date: Wed, 19 Apr 2006 23:30:19 -0500 Subject: Error with OpenOffice Message-ID: <1145507419.10167.6.camel@localhost.localdomain> Hello, I try to make the exercises found in Ooo website but I receipt this error: mario at laptop:~$ python Python 2.4.2 (#2, Sep 30 2005, 21:19:01) [GCC 4.0.2 20050808 (prerelease) (Ubuntu 4.0.1-4ubuntu8)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import uno Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.4/site-packages/uno.py", line 37, in ? import pyuno SystemError: dynamic module not initialized properly >>> Any idea?? Mi configuracion/My config: Ubuntu Breezy 5.10 Linux Kernel 2.6.12-10-386 Python 2.4.2 wxPython 2.6.1.1Pre OpenOffice 2.0.1 -- Saludos / Best regards Mario Lacunza V?squez Desarrollador de Software - Webmaster Desarrollador 2 Estrellas VS2005 Website : http://mlacunzav.cogia.net Email : mlacunza[AT]gmail[DOT]com Email : mario_lacunza[AT]yahoo[DOT]es Blog : http://mlacunza.blogspot.com Lima - Peru From deets at nospam.web.de Fri Apr 14 16:57:36 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 14 Apr 2006 22:57:36 +0200 Subject: skip item in list "for loop" In-Reply-To: References: <1145038171.945758.256600@j33g2000cwa.googlegroups.com> <4aa88dFs6u2cU1@uni-berlin.de> Message-ID: <4aagm1Fs467vU1@uni-berlin.de> Felipe Almeida Lessa schrieb: > Em Sex, 2006-04-14 ?s 20:33 +0200, Diez B. Roggisch escreveu: >> def read_lines(inFile): >> fg = iter(inFile) >> for line in fg: >> if "pmos4_highv" in line: >> fg.next() >> else: >> yield line > > Just be aware that the "fb.next()" line can raise an StopIteration > exception that would otherwise be caught by the for loop. If you have > any resources that need to be cleaned up, try...finally is you friend. Actually I did that on purpose - as the StopIteration would simply end the generator. Any clean-up - well, if that was the scope of the generator on could add it of course, but I'd do that on the same level the file has been opened. Regards, Diez From onurb at xiludom.gro Fri Apr 28 06:32:26 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 28 Apr 2006 12:32:26 +0200 Subject: Get all attributes of a com object In-Reply-To: References: <1146151043.933987.145080@t31g2000cwb.googlegroups.com> <4450e4b7$0$21092$626a54ce@news.free.fr> <1146209689.917251.224530@g10g2000cwb.googlegroups.com> <4451e0bd$0$7724$636a55ce@news.free.fr> Message-ID: <4451ef90$0$2631$636a55ce@news.free.fr> Duncan Booth wrote: > bruno at modulix wrote: > > >>eicwo01 wrote: >> >>>Thanks for your tips. >>>But dir() and inspect did not really help. >> >>Really ? >> >>def dump(obj): >> for name in dir(obj): >> print getattr(obj, name) >> > > > That will show him the attributes of the Python wrapper around the COM > object, it won't show him the attributes of the underlying COM object > itself. I stand corrected - and shouldn't answer questions about MS technos :( (snip) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From marcelo_urbano at hotmail.com Wed Apr 12 21:49:32 2006 From: marcelo_urbano at hotmail.com (Marcelo Urbano Lima) Date: Wed, 12 Apr 2006 22:49:32 -0300 Subject: object instance after if isalpha() In-Reply-To: Message-ID: ops, I forgot to use the self. so in this example what i was trying to do worked. I'll look further in my original program. sorry to bother you. >From: "Marcelo Urbano Lima" >To: python-list at python.org >Subject: object instance after if isalpha() >Date: Wed, 12 Apr 2006 20:44:11 -0300 > >Hi >I'm still learning python and I've been loving it, but, that's not the >reason I'm writing. > >I'm trying to create an object only if a variable is alpha and see what I >get. > >$ cat 1.py >class abc: > def __init__(self): > name='marcelo' > >a='STRING' >print a.isalpha() > >if a.isalpha(): > x=abc() > >print 'was x created?:', x,'\n' >print x.name > > >$ python 1.py >True >was x created?: <__main__.abc instance at 0x186b9e6c> > >Traceback (most recent call last): > File "1.py", line 12, in ? > print x.name >AttributeError: abc instance has no attribute 'name' > >Why? (I really think I'm doing something stupid but could not see) >btw, it's python 2.4.1 for cygwin. > >I'd really appreciate your help. > >Thanks > >_________________________________________________________________ >Seja um dos primeiros a testar o Windows Live Messenger Beta a gera??o do >seu MSN Messenger. >http://imagine-msn.com/minisites/messenger/default.aspx?locale=pt-br > >-- >http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ COPA 2006: O hor?rio dos jogos do Brasil na Copa Clique aqui! http://copa.br.msn.com/tabelas/tabela/ From tjreedy at udel.edu Thu Apr 27 01:41:17 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 27 Apr 2006 01:41:17 -0400 Subject: Editing a function in-memory and in-place References: <1146115733.082702.106380@t31g2000cwb.googlegroups.com> Message-ID: "Ian Bicking" wrote in message news:1146115733.082702.106380 at t31g2000cwb.googlegroups.com... > > The func_code attributes of functions is writable, but I don't know how > to create the proper code object. Just compiling a new body isn't good > enough. Did you directly compile the body or compile a function and then extract the code object? In any case, if you need to patch the code object and cannot do so directly due to read-only fields, this may help: >>> import new >>> dir(new) ['__builtins__', '__doc__', '__file__', '__name__', 'classobj', 'code', 'function', 'instance', 'instancemethod', 'module'] >>> help(new.code) Help on class code in module __builtin__: class code(object) | code(argcount, nlocals, stacksize, flags, codestring, constants, names, | varnames, filename, name, firstlineno, lnotab[, freevars[, cellvars]]) | | Create a code object. Not for the faint of heart. | | Methods defined here: ... Terry Jan Reedy From bytecolor at yahoo.com Wed Apr 26 15:56:01 2006 From: bytecolor at yahoo.com (bytecolor) Date: 26 Apr 2006 12:56:01 -0700 Subject: win32com short path name on 2k In-Reply-To: <1146078739.470371.282350@j33g2000cwa.googlegroups.com> References: <1146054018.702204.222710@e56g2000cwe.googlegroups.com> <1146077363.184978.231500@u72g2000cwu.googlegroups.com> <1146078739.470371.282350@j33g2000cwa.googlegroups.com> Message-ID: <1146081361.264670.21510@y43g2000cwc.googlegroups.com> Thanks Russell, those funcs sound familiar. I've probably used them or, more than likely, read about them in the past. -- bytecolor From phpbird at gmail.com Mon Apr 3 11:32:52 2006 From: phpbird at gmail.com (JuHui) Date: 3 Apr 2006 08:32:52 -0700 Subject: can I get the index number in for x in y loop? Message-ID: <1144078372.411795.21570@i39g2000cwa.googlegroups.com> >>> a='String' >>> for x in a: ... print x ... S t r i n g >>> can I get the index number of a in the upon loop within for x in a loop? From aahz at pythoncraft.com Fri Apr 21 16:59:08 2006 From: aahz at pythoncraft.com (Aahz) Date: Fri, 21 Apr 2006 13:59:08 -0700 Subject: www.python.org problems Message-ID: <20060421205908.GA11853@panix.com> Before people start sending a flood of e-mail to webmaster, we already know that www.python.org is having problems. Please be patient. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Argue for your limitations, and sure enough they're yours." --Richard Bach From walterbyrd at iname.com Mon Apr 10 19:14:19 2006 From: walterbyrd at iname.com (walterbyrd) Date: 10 Apr 2006 16:14:19 -0700 Subject: Best Python web-hosting? In-Reply-To: <4439870a$0$4206$c3e8da3@news.astraweb.com> References: <1144605832.364688.305300@j33g2000cwa.googlegroups.com> <4439870a$0$4206$c3e8da3@news.astraweb.com> Message-ID: <1144710859.872630.297820@u72g2000cwu.googlegroups.com> John Salerno wrote: > I was testing out http://www.devisland.net/ and it's pretty nice. They > installed the latest versions of Python, mod_python and mysqldb at my > request, and support was good. Only real problem is it's too expensive > for the space you get (about $5/month for 100MB), but you said space > wasn't much of an issue. I have just discovered http://www.dollar-hosting.org/ 400mb hdd, and 5gm bandwith for $10/year. And they have mod_python. From darkbard at gmail.com Mon Apr 24 11:25:56 2006 From: darkbard at gmail.com (Gabriele *darkbard* Farina) Date: 24 Apr 2006 08:25:56 -0700 Subject: Python C API question Message-ID: <1145892356.049190.246910@j33g2000cwa.googlegroups.com> Hi, I'm a newbie in python extension development, and I'd like to ask you a simple question. I have to implement a simple estension that parses a source file and returns an xml.dom.minidom.Document instance. I'd like to know how can I import and then manage xml.dom.minidom.* objects using Python C API. thanks, Gabriele From has.temp2 at virgin.net Sat Apr 8 09:06:52 2006 From: has.temp2 at virgin.net (has) Date: 8 Apr 2006 06:06:52 -0700 Subject: download for official Python logo artwork? Message-ID: <1144501612.822176.57820@g10g2000cwb.googlegroups.com> Anyone know where I can find source artwork, preferably vector-based, for python.org's new 'ying-yang' snake icon? I think it's hiding. Thanks. From ziga.seilnacht at gmail.com Thu Apr 6 19:13:58 2006 From: ziga.seilnacht at gmail.com (Ziga Seilnacht) Date: 6 Apr 2006 16:13:58 -0700 Subject: good style guides for python-style documentation ? References: Message-ID: <1144365238.137763.228360@t31g2000cwb.googlegroups.com> Fredrik Lundh wrote: > (reposted from doc-sig, which seems to be mostly dead > these days). > > over at the pytut wiki, "carndt" asked: > > Are there any guidelines about conventions concerning > punctuation, text styles and language style (e.g. how > to address the reader)? > > any suggestions from this list ? > > Documenting Python http://docs.python.org/dev/doc/style-guide.html recommends Apple Publications Style Guide: http://developer.apple.com/referencelibrary/API_Fundamentals/UserExperience-fund-date.html GNOME Documentation Style Guide is also quite useful: http://developer.gnome.org/documents/style-guide/ . Ziga From cygnus at cprogrammer.org Mon Apr 17 17:23:36 2006 From: cygnus at cprogrammer.org (Jonathan Daugherty) Date: Mon, 17 Apr 2006 14:23:36 -0700 Subject: Missing interfaces in Python... In-Reply-To: References: <20060417210541.GV7561@vulcan.cprogrammer.org> Message-ID: <20060417212336.GW7561@vulcan.cprogrammer.org> # so with interfaces, missing methods will suddenly appear out of thin # air ? With interfaces, the idea is that they're enforced; so, they'll appear because someone implements them. -- Jonathan Daugherty http://www.parsed.org From fredrik at pythonware.com Sun Apr 9 10:50:56 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 9 Apr 2006 16:50:56 +0200 Subject: Decorators, Identity functions and execution... References: Message-ID: Chance Ginger wrote: > It isn't a syntax error...I tried it before I posted. In fact > def t(x) : > def I(x) : return x > return I > > is correct. tabs don't make it through all channels. don't use tabs for indentation when you post to newsgroups or mailing lists. and @(Y) is not valid Python syntax. no amount of indentation will change that. > Decorators are a way to add "syntactic" sugar to Python, > extending it in ways that make it useful for tools. that's a rather narrow view of what a decorator does, and doesn't help much in understanding how they work. which is unfortunate, because it's very simple: decorators are simply ordinary callables, and the result of the decoration is whatever the callable returns. in fact, any callable can be used to decorate a function: >>> @str ... def foo(bar): ... pass ... >>> foo '' >>> foo("bar") Traceback (most recent call last): File "", line 1, in ? TypeError: 'str' object is not callable and it's all done at runtime; there is no magic involved whatsoever. >>> @open ... @str ... def bar(foo): ... pass ... Traceback (most recent call last): File "", line 1, in ? IOError: [Errno 2] No such file or directory: '' > I am trying to do is lessen the impact on the time used in > executing Python code when I use some forms of decorators. if you don't want Python to execute some code, all you have to do is to make sure that it isn't called. From szabolcs.berecz at gmail.com Wed Apr 12 08:24:28 2006 From: szabolcs.berecz at gmail.com (Szabolcs Berecz) Date: Wed, 12 Apr 2006 14:24:28 +0200 Subject: Python2CPP ? In-Reply-To: References: Message-ID: On 4/12/06, Michael Yanowitz wrote: > 2) Efficiency. It is alot quicker to code something in Python. If I can > write it in Python and auto-convert it to C++. I would save time coding. I don't think you will get a more efficient code. The reason is the extremely dynamic nature of python. Almost everything is done at runtime. I think one goal of PyPy is to automatically infer the types of variable, but I don't think they have reached that point, yet. One project you can consider is the psycho python package which generates specialized native code at the price of high memory consumption. > 3) Education. I would learn more about Python, C++, their similarities and > differences. I don't think so. Higher level languages translated to C are not very readable (or at least that's what I have seen) > 4) Other. Just want to know how well Language translators work these days. I > have seen > Fortran2C and Pascal2C translators in the past. Would like to see how > well these > work with Python. Than I think PyPy is the way to go. I have heard about another project with the goal of translating python to high efficiency C++ code but forgot the url. Anybody? Szabi From mfmorss at aep.com Tue Apr 25 16:45:47 2006 From: mfmorss at aep.com (mfmorss at aep.com) Date: Tue, 25 Apr 2006 16:45:47 -0400 Subject: Xah's Edu Corner: Criticism vs Constructive Criticism In-Reply-To: Message-ID: Would these contestants please GET OFF THE LIST with their non-Python-related contentiousness? Mark F. Morss Principal Analyst, Market Risk American Electric Power Ari Johnson To Sent by: python-list at python.org python-list-bounc cc es+mfmorss=aep.co m at python.org Subject Re: Xah's Edu Corner: Criticism vs Constructive Criticism 04/25/2006 03:39 PM "Xah Lee" writes: A large amount of free, constructive criticism follows. 1. Learn where to post things. > Criticism versus Constructive Criticism 2. Learn when to capitalize words in a title. > Xah Lee, 2003-01 3. Learn when to post things. > A lot intelligent people are rather confused about criticism, > especially in our $B!H(Bfree-speech$B!I(B free-for-all internet age. When > they say $B!H(Bconstructive criticisms are welcome$B!I(B they mostly mean > $B!H(Bbitching and complaints not welcome$B!I(B. Rarely do people actually > mean that $B!H(Bcriticism without suggestion of possible solutions are not > welcome$B!I(B or $B!H(Bimpolite criticism not welcome$B!I(B. 4. Try "many." 5. Learn how to use commas. 6. Nobody says "constructive criticisms are welcome." They use the singular, as should you. 7. Learn how to use commas. 8. Learn how to use parallel structure. > Such discernment is important. Wanton bitching as internet-using geeks > are used to is not criticism is any form. 9. Generally, the use of sentence forms like "such is " is even frowned upon in legal writing anymore; but it is almost never appropriate to use the word "bitching" in the next sentence. > People can be respected and make a living out of criticisms, called > critics, but not bitching. And when one really value opinions, you > often want criticism without qualifications. Just be happy that > valuable criticisms may come to you free from the experts in the > public. The instant you qualify what kind of feedback are welcome, your > feedback is compromised. (this is particularly so for political or > controversial subjects) 10. You're still insisting that criticism in the general sense is a plural thing. It is not. Also, these "criticisms" are not what we call "critics." We call the people making them critics. I'd let this one slide but you bounce back and forth too many times in one sentence to get away with it. 11. Learn how to match a verb to its noun. 12. You still haven't figured out when to use "criticisms." I'll give you another hint: nowhere within your writing. 13. Learn when your "expert" criticism is apropos and when it is not. 14. If you can't figure out when not to pluralize the word criticism, I don't know why I expect you to know when to use "is" instead of "are." However, I still recommend you learn this not-so-subtle point of English grammar. 15. Sentences in parentheses are still sentences - capitalize and punctuate appropriately. 16. When you make a sweeping, general statement, it helps to support it with some kind of logically-related evidence. > One easy way for many of the unix geeks to understand this is the > cryptology industry. 17. Learn when to capitalize proper nouns. 18. The cryptology industry is not a "way." It is an industry. Learn how to write clear sentences that use words in meaningful ways. One way to do this is to utilize verbs. > If one really desires valuable criticisms that is polite or with > solutions or $B!H(Bconstructive$B!I(B (whatever that means), one usually have > to pay. 19. The rule is that third-person singular subjects take "is" and third-person plural subjects take "are." You seem to have this backwards. 20. If you are offering a dissertation on constructive criticism, you ought to define the term rather than using a parenthetical shoulder-shrug like this. 21. Third-person singular subjects take "has," not "have." 22. When you write something, even when it is not welcome or not relevant to the place you post it, it is helpful to actually make a point rather than just making several statements of things which alternate between obvious and nonsensical. > This post is archived at: > http://xahlee.org/UnixResource_dir/writ/criticism.html 23. If something from three years ago is on the web, it is indexed by Google. If someone wants to read it, they will find it via Google. There is no need to post it on inappropriate newsgroups. > > Xah > xah at xahlee.org > $B-t(B http://xahlee.org/ (This isn't constructive criticism, but just a question:) Are you the sum of your web page? -- http://mail.python.org/mailman/listinfo/python-list From tim.golden at viacom-outdoor.co.uk Fri Apr 28 09:38:56 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Fri, 28 Apr 2006 14:38:56 +0100 Subject: Get all attributes of a com object Message-ID: [Stefan Schukat] | You can only build a proxy module if you have the typelibrary | information which not all programs provide, since it prohibits | changes in the interface the easy way. E.g., MFC application | will normally not provide a typelibrary but support dynamic | dispatch. Oh. Thanks. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From jnair at ensim.com Mon Apr 10 08:00:51 2006 From: jnair at ensim.com (jnair at ensim.com) Date: 10 Apr 2006 05:00:51 -0700 Subject: Is this object counter code pythonic References: <1144666496.940311.148120@j33g2000cwa.googlegroups.com> <1144668918.777564.310590@t31g2000cwb.googlegroups.com> Message-ID: <1144670451.089729.205450@v46g2000cwv.googlegroups.com> Fredrik is then this a valid "property" use case and pythonic to get/set a common varibale across objects class E(object): _i = 0 def geti(self) : return E._i def seti(self,val) : E._i = val i = property(geti,seti) if __name__ == "__main__": e1 = E() e1.i = 100 e2 = E() print e2.i From fuzzyman at gmail.com Thu Apr 6 14:07:26 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 6 Apr 2006 11:07:26 -0700 Subject: help with designing an app. based on ConfigParser In-Reply-To: References: Message-ID: <1144346846.538792.200060@u72g2000cwu.googlegroups.com> Alexandre CONRAD wrote: [snip..] > > So I told my self, the best way would be able to have a "sub-section". I > could then look for all servers (aka sub-sections) inside [UPDATE > SERVERS] and retrieve the needed info. But AFAIK, it's not possible > having sub-sections with ConfigParser. So I'm here to ask if anyone has > an efficient trick for that ? Maybe an other module based on > ConfigParser exists that would allow sub-sections ? > ConfigObj allows sub-sections and is also easier to use than ConfigParser. That says nothing about whether sub-sections are the right answer to your problem, but at least it is possible. :-) http://www.voidspace.org.uk/python/configobj.html Fuzzyman http://www.voidspace.org.uk/python/index.shtml > I might be looking for something too complicated and maybe some simplier > alternative exists which doesn't cross my mind right now. (no, don't > tell me to use XML for my config file, it has to be easely modifiable by > the user using the most basic bloc-note). > > Regards, > -- > Alexandre CONRAD - TLV > Research & Development > tel : +33 1 30 80 55 05 > fax : +33 1 30 80 55 06 > 6, rue de la plaine > 78860 - SAINT NOM LA BRETECHE > FRANCE From bearophileHUGS at lycos.com Fri Apr 21 17:59:54 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 21 Apr 2006 14:59:54 -0700 Subject: Pythonesque interface. In-Reply-To: <1145640417.247970.116480@v46g2000cwv.googlegroups.com> References: <1145639147.524042.260220@z34g2000cwc.googlegroups.com> <4asil8FuicdvU1@uni-berlin.de> <1145640417.247970.116480@v46g2000cwv.googlegroups.com> Message-ID: <1145656794.388937.60580@e56g2000cwe.googlegroups.com> Michael Tobis>Yes but he obviously wants this to be delivered to the browser.< I think Jython can be used to create applets that run with the JavaVM. Can't it be used to solve the OP problem (even without PIL)? Bye, bearophile From hitesh287 at gmail.com Mon Apr 24 18:38:46 2006 From: hitesh287 at gmail.com (Hitesh Joshi) Date: 24 Apr 2006 15:38:46 -0700 Subject: What am I doing wrong here In-Reply-To: References: <1145916134.764210.235250@t31g2000cwb.googlegroups.com> <1145917676.746433.167870@u72g2000cwu.googlegroups.com> Message-ID: <1145918326.766920.238720@e56g2000cwe.googlegroups.com> Thank you Robert, It worked!!! Thank you so much.... From nogradi at gmail.com Tue Apr 11 03:58:02 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Tue, 11 Apr 2006 09:58:02 +0200 Subject: using vim as a python class/module/function etc.. browser In-Reply-To: References: <443B1B24.3070401@optonline.net> <443B3427.1090902@optonline.net> Message-ID: <5f56302b0604110058t13b4a704w8b7329ce128e5ac9@mail.gmail.com> > >>Of course, modern versions of Exuberant Ctags also support Python, too. > > > > I apt-installed this package but the man page is rather intimidating so > > I thought I might as well make sure I was going in the right direction. > > You will probably want to read the vim documentation on how to use ctags > from > vim. That will tell you all you need to know without extraneous cruft. > > > Just need to verify that the stable version (sarge) is modern enough.. > > It ought to be. It has supported Python for years and years. For browsing source code I found the folding feature of vim very useful. It collapses the body of function and class definitions into one line so you can have a general overview of definitions in the code. It is available from version 6 up and I recently wrote a vim plugin specifically for folding python source code. You can find it here: http://www.vim.org/scripts/script.php?script_id=1494 There is also an excellent vim plugin by Yegappan Lakshmanan for working with 'tags' files using ctags. It displays all your function and class definitions (from multiple files if you wish) in a narrow vertical window where you can easily jump to the file containing a chosen definition. This script is here: http://www.vim.org/scripts/script.php?script_id=273 HTH, Daniel From af.dingo at gmail.com Wed Apr 12 08:17:03 2006 From: af.dingo at gmail.com (af.dingo at gmail.com) Date: 12 Apr 2006 05:17:03 -0700 Subject: symbolic links, aliases, cls clear In-Reply-To: <1143672131.167324.36920@i39g2000cwa.googlegroups.com> References: <1143672131.167324.36920@i39g2000cwa.googlegroups.com> Message-ID: <1144844223.094969.82870@t31g2000cwb.googlegroups.com> If I may recommend an alternative, print "\033[H\033[J" the ansi sequence to clear the screen. From usenet at mulch.ca Sat Apr 1 11:14:27 2006 From: usenet at mulch.ca (usenet at mulch.ca) Date: 1 Apr 2006 08:14:27 -0800 Subject: Logging and threading In-Reply-To: <6f7s22tj3umbggra8f50cur4uqjl64jc3a@4ax.com> References: <1143863831.438403.91610@i40g2000cwc.googlegroups.com> <6f7s22tj3umbggra8f50cur4uqjl64jc3a@4ax.com> Message-ID: <1143908067.374638.13210@u72g2000cwu.googlegroups.com> As simple and as obvious as I expected, thanks Dennis. -Alex From bgporter at acm.org Fri Apr 28 09:09:31 2006 From: bgporter at acm.org (Brett g Porter) Date: Fri, 28 Apr 2006 09:09:31 -0400 Subject: Non-web-based templating system In-Reply-To: <4bec7mF10pfe5U1@uni-berlin.de> References: <1146221757.653214.115090@g10g2000cwb.googlegroups.com> <4bec7mF10pfe5U1@uni-berlin.de> Message-ID: <4452140B.1070503@acm.org> Diez B. Roggisch wrote: > qscomputing at gmail.com wrote: > > Maybe the built-in string interpolation is sufficient? > > print "Hello %(name)s" % dict(name="Peter Pan") Or in recent pythons, the built-in string templating system (see http://docs.python.org/lib/node109.html) >>> from string import Template >>> d = dict(name="Barney") >>> s = Template("Hello $name") >>> s.substitute(d) 'Hello Barney' From godoy at ieee.org Fri Apr 7 16:48:17 2006 From: godoy at ieee.org (Jorge Godoy) Date: Fri, 07 Apr 2006 17:48:17 -0300 Subject: wxPython and SuSE 10.0 References: Message-ID: <8764llf6y6.fsf@ieee.org> Steve writes: > I was wondering if there is a wxPython RPM for SuSE 10.0 available. I > Googled for it with no luck, but I'm hopeful that there is one out > there. There are RPMs within SuSE's DVD / CDs, IIRC. Anyway, you can get it with Apt, smart and even YaST. -- Jorge Godoy "Quidquid latine dictum sit, altum sonatur." - Qualquer coisa dita em latim soa profundo. - Anything said in Latin sounds smart. From fredrik at pythonware.com Tue Apr 11 08:35:31 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 11 Apr 2006 14:35:31 +0200 Subject: Help - strange behaviour from python list References: Message-ID: Sean Hammond wrote: > I've managed to create a scenario in which editing an object in a list of > objects seems to edit every object in the list, rather than just the one. > I'm totally stumped and wondered if anyone would be kind enough to read my > explanation and see if they have any suggestions. I have probably stumbled > into some typical newbie problem, but anyway: some useful resources: http://docs.python.org/tut/node6.html#SECTION006710000000000000000 (see the paragraph that starts with "important warning") http://www.python.org/doc/faq/general/#why-are-default-values-shared-between-objects http://docs.python.org/ref/function.html (see the paragraph that starts with "Default parameters are evaluated when the function definition is executed") (you cannot say we didn't warn you ;-) From jstroud at ucla.edu Mon Apr 3 20:08:33 2006 From: jstroud at ucla.edu (James Stroud) Date: Mon, 03 Apr 2006 17:08:33 -0700 Subject: Is pwm Python MegaWidgets viable? In-Reply-To: <44306C31.1020007@redlinepy.com> References: <499rh1Fnh7voU1@individual.net> <1143983854.954254.221080@i40g2000cwc.googlegroups.com> <44306C31.1020007@redlinepy.com> Message-ID: Paul Watson wrote: > gregarican wrote: > >> Paul Watson wrote: >> >> >>> Does pwm run well on Python 2.4? The last release appears to be in >>> 2003. The Manning discussion forum is dead. >>> >>> Is there a better path to learning and producing tkInter apps? >>> >>> >>> Has there been any discussion of wxPython becoming part of the base >>> Python distro? A requirement here is to not require download/install of >>> anything other than the Python release. >> >> >> >> I can't vouch for Python 2.4, but I used the PMW library pretty >> extensively for an app that is based on Python 2.3. Tkinker itself >> offers most of the basic widgets that any Tk implementation does, and >> there's an online guide (can't recall the URL right now) to Tkinter >> that is great for an introduction tutorial. PMW is an add-on to Tkinter >> that is useful if there are specific widgets that you need that basic >> Tkinter doesn't provide and you don't feel like creating them from >> scratch. Just because it doesn't have a new release in the past couple >> of years doesn't mean that it's truly a dead project. Perhaps it's >> stabilized and there haven't been overwhelming requests for adding any >> new items to it. Using PMW won't help you learn Tkinter any quicker in >> any event. Just icing on the cake :-) > > > Many thanks for your reply. I was setting out to make use of the > Manning book by Grayson. Perhaps I should just use online tutorial and > such for learning plain-old tk first. However, I have heard good things > about the book. Just trying to use what was already at hand. If you want to write full-featured GUI apps with Tkinter, Grayson is your best bet. Lundh's tutorial is excellent as a reference, but, last I checked, was not as extensive as Grayson in terms of teaching new users. Also, PMW is relatively heavy-weight, so make sure the Python standard library doesn't already do what you want before including PMW (e.g. ScrolledText, etc.). James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From aleaxit at yahoo.com Fri Apr 21 11:14:46 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 21 Apr 2006 08:14:46 -0700 Subject: how to append to a list twice? References: Message-ID: <1he4xao.1d6me4454w0xpN%aleaxit@yahoo.com> John Salerno wrote: > If I want to create a list of the form [100, 99, 99, 98, 98, 97, 97...] > (where each item is repeated twice after the first one), how might I do > that most efficiently? > > Right now I have this: > > series = [100] > for x in range(10): # just for testing > series.append(series[-1] - 1) > > But of course that only does it once, and I don't want to have to copy > and paste the append line. Perhaps there's a better way than this. def makeseries(N): series = [N] append = series.append for tailer in xrange(N-1, -1, -1): append(tailer) append(tailer) return series series = makeseries(100) assuming that by "most efficiently" you mean "fastest", this might come close; you'll want to also time an alternative where makeseries is a generator which just yields the values, and the last assignment becomes series=list(makeseries(100)). Alex From rbutler at mtsu.edu Thu Apr 13 00:10:24 2006 From: rbutler at mtsu.edu (Ralph Butler) Date: Wed, 12 Apr 2006 23:10:24 -0500 Subject: pyzeroconf unicast question Message-ID: <0aWdnbauh8uvUqDZRVn-rg@comcast.com> Hi: I have been using pyzeroconf to register and discover services on a local network using the default multicast support. Now, I would like to register a service on a remote node and discover that service from my local machine. Neither machine is behind a firewall. This sort of thing is supported by zeroconf in general (as described in chapter 5 of the Zero Configuration Networking book). However, I am not sure that it is supported by the pyzeroconf implementation. It looks to me as if I might make some small changes to the code in Zeroconf.py and get it to go, but I have been unsuccessful thus far and am not totally sure that changes are even necessary. I googled for examples of this, but only found examples using the 'local' designation for services. If you can provide any pointers to specific examples, I would very much appreciate seeing them. Thanks. --ralph Ralph M. Butler, PhD rbutler at mtsu.edu From danmcleran at yahoo.com Tue Apr 25 16:06:01 2006 From: danmcleran at yahoo.com (danmcleran at yahoo.com) Date: 25 Apr 2006 13:06:01 -0700 Subject: Plotting package? In-Reply-To: References: Message-ID: <1145995560.961583.280650@j33g2000cwa.googlegroups.com> Try matplotlib, it's pretty nice and easy to use. From peter at engcorp.com Tue Apr 11 11:54:51 2006 From: peter at engcorp.com (Peter Hansen) Date: Tue, 11 Apr 2006 11:54:51 -0400 Subject: Override on terminal In-Reply-To: <1144766236.330882.142520@j33g2000cwa.googlegroups.com> References: <1144766236.330882.142520@j33g2000cwa.googlegroups.com> Message-ID: fivestars wrote: > Do you know how to write, from python code, on a unix(linux) terminal > on specified coordinates? Search for the "curses" module. > And also: is it possible to override, from python code, something on a > unix(linux) terminal? The word "override" is ambiguous here (actually it's just about entirely meaningless). Can you describe what you want in more detail? Maybe with an example? > I would have a suggestion that won't use files. That also doesn't make sense, though perhaps it would if we understood the question. > I hope that i've been clear. Not very, but please try again. :-) -Peter From mandelin at cs.berkeley.edu Mon Apr 10 16:52:38 2006 From: mandelin at cs.berkeley.edu (Dave Mandelin) Date: 10 Apr 2006 13:52:38 -0700 Subject: wxStyledTextCtrl - Dead? References: <4438efbb$0$60784$157c6196@dreader1.cybercity.dk> Message-ID: <1144702358.186240.161950@e56g2000cwe.googlegroups.com> I don't know the answers to 1 and 2, but from the demo I know that the answer to 3 is wx.stc.StyledTextControl. As for 4, I guess it depends on what you want to do. StyledTextControl looked pretty scary to me, and for my application I mainly needed to display styled text, not edit it, so I embedded a web browser window and used HTML+CSS (and even a little JavaScript now). That worked quite nicely. If you need to edit the text as well, then I don't know. The rich edit control (TextCtrl with style wx.TE_RICH2) is one option, but it is not particularly nice to use. -- Want to play tabletop RPGs over the internet? Check out RPZen: http://koboldsoft.com
So for some reason BS thinks that everything from to the end is a single string. Kent From wahab at chemie.uni-halle.de Sun Apr 9 14:56:24 2006 From: wahab at chemie.uni-halle.de (Mirco Wahab) Date: Sun, 09 Apr 2006 20:56:24 +0200 Subject: how relevant is C today? In-Reply-To: <44393167$1@nntp0.pdx.net> References: <44381ee4$0$4209$c3e8da3@news.astraweb.com> <871ww7elvu.fsf@ieee.org> <1144541959.611623.25540@i39g2000cwa.googlegroups.com> <44393167$1@nntp0.pdx.net> Message-ID: Hi Scott your summary looks very concise and good to read. I'd like to make some minor additions, > C can express neither exceptions nor coroutines (nor their fancy cousin, > continuations), which could be and were expressed in assembly. Nor does > C provide memory management. A few library functions give you some > primitives to roll your own, but garbage collection is out of the > question (despite Hans Boehm), because the language does not carry > enough infrastructure to find type information through introspection. So, al-imho, C 'abstracts out' some consistent 'von-Neumann' or 'Harvard-' machine from any architecture where its ported to. And that is - imho - the main strength of C. It covers well most machine code vs. C instruction mapping (~1:1), and RAM storage vs. coressponding data representation (1:1), as you said partially. It can't handle any aspect beyond these simple mappings in its language core, this is where more complex bulding blocks (libraries) will come into play. > In exchange for these losses, the C programmer can write code that > executes in response to an external signal and yet does not create a > total hash of the internal memory structures. That kind of thing is > important in an OS, and something few languages (including C++) can do. > If you intend to study C++, study C first (it is easier to grasp), as > almost everything you learn in C can be used in C++. C++ is a "big" > language, while C is a "small" one; it will take much longer to "know" > C++ even though C++ started with the goal of being "C with objects." > If you are interested in languages, reading "the Design and Evolution > of C++" is a great base; it explains how C++ got the way it is from its > initial design goals. I would say, from my own experience, that you wouldn't use all C++ features in all C++ projects. Most people I know would write C programs 'camouflaged' as C++, that is: write clean & simple C - and use some C++ features e.g, class bound methods for interfaces - but no inheritance at all (use compound objects) and no exceptions (handle errors 'the olden way'). Regards M. From arkanes at gmail.com Fri Apr 28 11:42:33 2006 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 28 Apr 2006 10:42:33 -0500 Subject: MS VC++ Toolkit 2003, where? In-Reply-To: <1146164804.118046.249250@e56g2000cwe.googlegroups.com> References: <1he8pss.1yk7ug81rv7pw2N%aleaxit@yahoo.com> <1145811839.042394.73260@t31g2000cwb.googlegroups.com> <1he8sbx.dqqp3q10n5thaN%aleaxit@yahoo.com> <1145849491.347970.112150@e56g2000cwe.googlegroups.com> <1he9m4m.9d8okx1x7mxeaN%aleaxit@yahoo.com> <1146164804.118046.249250@e56g2000cwe.googlegroups.com> Message-ID: <4866bea60604280842x6c915802xcae2d6fbb8192b5d@mail.gmail.com> On 27 Apr 2006 12:06:44 -0700, sturlamolden wrote: > > Alex Martelli wrote: > > > Provides the core msvcrt.lib for msvcr71.dll against which to link > > your extensions. This is critically important, as without it you are > > going to wind up linking against the wrong run-time and will see crashes > > whenever a core object such as a file is shared across run-time > > barriers. > > You can find msvcr71.dll in the same directory as Python. > > The problem is that you cannot redistribute msvcr71.dll unless you by a > copy of Visual Studio 2003 or install VC++ Toolkit 2003. As far as I > can tell, the .NET SDK license does not give you permission to > redistribute msvcr71.dll. So if you are going to use Py2Exe, this is a > dead end. But if you are just going to build a Python extension, you > don't need to redistribute the DLL (it's already in Python). In that > case you can use MinGW insted. Just make sure MinGW links with the > correct CRT. That is, open > > c:\mingw\lib\gcc\mingw32\3.4.2\specs > > in an editor and change "-lmsvcrt" to "-lmsvcr71" > > There is a second advantage with this. MinGW is an optimizing compiler. > The C/C++ compiler you get from the .NET SDK is not. This is untrue - the MSVC compiler in the VS 2003 Toolkit is exactly the same compiler that ships with real visual studio, and does excellent optimization. Modulo all the extremely correct comments in this thread about how useless it is to make comments about the optimization capabilities of a compiler, I find that the VS 2003 compiler generally generates faster and (often much) smaller code than GCC/mingw >There is a "Visual > C++ 2005 Express" edition which has an optimizing compiler. But it > links yet another version of the CRT, msvcr80.dll, and does not give > you permission to redistribute msvcr71.dll. > There are numerous distribution issues with the VS 2005 runtimes (I don't want to get into them now) besides the legal ones, but it's useless for building extension modules unless you also re-build Python (and then your Python can't use any other extension modules). It's workable for people embedding Python and probably not anyone else. > -- > http://mail.python.org/mailman/listinfo/python-list > From ejohnso9at at earthlink.dot.net Fri Apr 14 18:50:00 2006 From: ejohnso9at at earthlink.dot.net (ej) Date: Fri, 14 Apr 2006 16:50:00 -0600 Subject: Should I learn Python instead? References: <1145048531.915798.97060@v46g2000cwv.googlegroups.com> Message-ID: <4440280e$1@nntp.zianet.com> "fyleow" wrote : > I realize that learning the library is part of the process, but as a > beginner I appreciate simplicity. > Is Python easier than C#? Absolutely. > Can someone show how to access an XML document on the web and have it ready > to be manipulated for comparison? Yes. (see below) > Any other advice for a newbie? Learn Python. It's good to know other languages too, but when it comes to getting stuff done fast & cleanly, you will find Python an invaluable tool. # here's a simple use of the urllib module to fetch a document from the web (output from an interactive python interpreter session): > python Python 2.3.4 (#1, Feb 7 2005, 15:50:45) [GCC 3.3.4 (pre 3.3.5 20040809)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import urllib >>> url = 'http://www.google.com' >>> fd = urllib.urlopen(url) >>> html = fd.read() >>> print html Google

Error in /Users/tjg/code/textmate/test_pytestmate.py at line 17

    [/Users/tjg/code/textmate/test_pytestmate.py:17]
    
''' assert pytestmate.create_output( ['[/Users/tjg/code/textmate/test_pytestmate.py:17]'] E ) == text > assert '\n\n\nPyTestMate\n\n***<...mate/test_pytestmate.py*** at line 17
[/Users/tjg/code/textmate/test_pytestmate.py:17]
\n' == '\n\n\nPyTestMate\n\n***<...st_pytestmate.py*** at line 17

\n
\n[/Users/tjg/code/textmate/test_pytestmate.py:17]\n
\n\n' + where '\n\n\nPyTestMate\n\n<...mate/test_pytestmate.py at line 17
[/Users/tjg/code/textmate/test_pytestmate.py:17]
\n' = (['[/Users/tjg/code/textmate/test_pytestmate.py:17]']) + where = pytestmate.create_output [/Users/tjg/code/textmate/test_pytestmate.py:55] =============================================== granted the left side of that equality could be messed up due to create_output() NOT doing the right thing. But the right side is simply the contents of the variable "text" so WHY is the first part of the path being substituted with "..."? Any insight greatly appreciated. -- Stand Fast, tjg. From no-spam at no-spam-no-spam.com Sun Apr 23 07:20:04 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Sun, 23 Apr 2006 13:20:04 +0200 Subject: Finding Module Dependancies In-Reply-To: References: <1145657885.389499.232600@t31g2000cwb.googlegroups.com> Message-ID: Larry Bates wrote: > > Remember that Python is so dynamic that you can build dependencies > during program execution and import them on-the-fly. So a dependency > checker would always be incomplete. You always need to write unit > tests. The Pychecker will usually see also missing on-the-fly imports and most of that like. You'd need to do tricky exec stuff to trick him - and even then he can warn for smelling style of code. You'd have to add upon warnings a #$pycheck_no to all such smelling lines in order to confirm, that you really know what you are doing. To my experience you'd usually not get the written tests dense enough (at reasonable costs) to look into all branches of execution flow. All 5 things are needed for efficiency : (frequency of application decreasing the list down) * auto-postmortem debugging (dev) ( auto-postmortem report (dist)) * running written tests * code checks * walking major execution branches by manual tests * beta cycling -robert From duncan.booth at invalid.invalid Tue Apr 25 05:51:54 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 25 Apr 2006 09:51:54 GMT Subject: test assignmet problem References: <444decd9$0$27062$626a54ce@news.free.fr> Message-ID: bruno at modulix wrote: > Almost : > > a = b() > if a: > do_stuff_with_b(a) > else: > a = c() > if a: > do_stuff_with_c(a) > else: > do_other_stuff() > > > Now there are probably better ways to write this, but this would require > more knowledge about your real code. if there are more than a couple of options you can generalise code such as this to use a for loop: for guard, action in [ (b, do_stuff_with_b), (c, do_stuff_with_c), ]: if guard(): action(a) break else: do_other_stuff() From mikelemmer6 at yahoo.com Wed Apr 19 13:49:11 2006 From: mikelemmer6 at yahoo.com (Jeff Groves) Date: 19 Apr 2006 10:49:11 -0700 Subject: Activating Batch Files from Python In-Reply-To: References: <1145417944.549477.198510@g10g2000cwb.googlegroups.com> Message-ID: <1145468951.826803.120860@i39g2000cwa.googlegroups.com> >How about sourcing it from a shell, then using that same shell instance >to run the programs? How would I do that? As I've said, I haven't found a Python command that lets you send multiple commands to the same shell yet. If I could, my problem would be solved. From jack at performancedrivers.com Mon Apr 17 12:58:51 2006 From: jack at performancedrivers.com (Jack Diederich) Date: Mon, 17 Apr 2006 12:58:51 -0400 Subject: Queue can result in nested monitor deadlock In-Reply-To: <1145292096.906390.254280@e56g2000cwe.googlegroups.com> References: <1145284326.177062.230120@v46g2000cwv.googlegroups.com> <1145292096.906390.254280@e56g2000cwe.googlegroups.com> Message-ID: <20060417165851.GC5762@performancedrivers.com> On Mon, Apr 17, 2006 at 09:41:37AM -0700, Jonathan Amsterdam wrote: > If you don't want to call it deadlock, fine, but the program execution > I describe will make no progress to the end of time. Thread 2 can never > put anything in the queue, because Thread 1 holds M, and Thread 1 will > never release M because that can only happen if someone puts something > on the queue. > Right, the problem isn't with Queue it is with your global lock M. Here is the pseudo code for your program: acquire_lock("No_one_else_can_do_anything") wait_for_someone_else_to_do_something() # waits forever -Jack From onurb at xiludom.gro Fri Apr 7 08:45:44 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 07 Apr 2006 14:45:44 +0200 Subject: Best way to process table rows from an RDBMS In-Reply-To: <1144403472.453332.213960@i39g2000cwa.googlegroups.com> References: <1144403472.453332.213960@i39g2000cwa.googlegroups.com> Message-ID: <44365f41$0$12864$626a54ce@news.free.fr> dananrg at yahoo.com wrote: > I can handle making the connections and running queries, but what's the > best way to process table rows returned in Python? depends on what you want to do with them. > What about turning a > table definition into an object? Just looking for ways to be efficient, > since I know I will be hitting the same external RDBMS from Python and > regularly processing a fixed set of tables with a certain fixed set of > attribute columns. Before ReinventingTheSquareWheel(tm), you may want to have a look at existing Python ORMs like SQLObjects or SQLAlchemy... -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From doug.shawhan at gmail.com Tue Apr 11 10:42:04 2006 From: doug.shawhan at gmail.com (lysdexia) Date: 11 Apr 2006 07:42:04 -0700 Subject: Terminal Emulation Modules? Message-ID: <1144766524.548625.144180@g10g2000cwb.googlegroups.com> I am attempting to screen scrape SuperDOS, an extremely closed system that uses wyse 60 terminals to communicate with a dos machine. I have not been able to communicate properly with superdos until trying the handy miniterm.py example from the pyserial package in conjunction with Markus Gutschke's wy60 emulator which translates input through an xterm into wyse 60 commands. These programs together allow me to interact with superdos pretty well ... with the exception of the arrow keys: for those I must fall back to the old cntl-letter combos to get the cursor to behave (actually cntl-letter x 2.. for some reason it likes an extra prod). This is fine, as now I have a way to debug my eventual script. My big problem is, I am completely unable to get SuperDos to respond to my carriage returns from within the script! I can watch the script work through miniterm.py. I have sent the return and newline characters in various combinations starting with "\n,\r", "\x0a\x0d", but they respond weirdly, putting the cursor *above* the existing command line, changing the cursor to an outline and generally letting me know that I am on the wrong track. Has some clever human already created a handy module to handle wyse60 and other terminal emulation from within a python program? I have looked over the curses module, but it seems to be aimed at drawing proper screens for the user, not translation. PySerial's ability to suck up the output via readlines() is awesome, and I can see how I *think* it should all be done, but the charset weirdness has got me stymied! I am going to look at Mr. Gutscheke's source to see how he does it, but I am barely conversant in python and fear that exposure to that much C code may cause dizziness! Thanks! From walterbyrd at iname.com Mon Apr 10 12:43:47 2006 From: walterbyrd at iname.com (walterbyrd) Date: 10 Apr 2006 09:43:47 -0700 Subject: Is there a Python MVC that works just as well with just CGI, or FCGI? Message-ID: <1144687427.086586.16400@i40g2000cwc.googlegroups.com> As I understand it, django works with fcgi, but it's a pain to setup. Are there any python MVCs that are optimized to work without mod_python. Or any other module that isn't likely to be loaded by standard python hosters? From onurb at xiludom.gro Tue Apr 4 12:44:16 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 04 Apr 2006 18:44:16 +0200 Subject: Standalone Python functions in UML? In-Reply-To: <1144145349.186395.44890@z34g2000cwc.googlegroups.com> References: <1144145349.186395.44890@z34g2000cwc.googlegroups.com> Message-ID: <4432a2a6$0$13233$626a54ce@news.free.fr> Ravi Teja wrote: (snip) >>>More theoretical question is if I create classes on the fly, how UML can > > reflect that? > > "On the fly" usually means "at runtime". I guess you mean if you > "change code" will my diagram stay in sync?. Nope, the OP really meant "on the fly", as in "at runtime". In python, it is possible to create new classes at runtime. Remember, everything-is-an-object implies that classes are objects too. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From ygao2004 at gmail.com Sat Apr 8 04:27:07 2006 From: ygao2004 at gmail.com (ygao) Date: 8 Apr 2006 01:27:07 -0700 Subject: unicode wrap unicode object? In-Reply-To: References: <1144452777.460885.131450@t31g2000cwb.googlegroups.com> Message-ID: <1144484827.891444.246920@z34g2000cwc.googlegroups.com> sorry,my poor english. I got a solution from others. I must use utf-8 for chinese. >>> import sys >>> reload(sys) >>> sys.setdefaultencoding("utf-8") >>> s='\xe9\xab\x98' #this uff-8 string >>> ss=U'\xe9\xab\x98' >>> ss1=ss.encode('unicode_escape').decode('string_escape') >>> s1=s.decode('unicode_escape') >>> s1==ss True >>> ss1==s True From utabintarbo at gmail.com Fri Apr 21 11:46:24 2006 From: utabintarbo at gmail.com (utabintarbo) Date: 21 Apr 2006 08:46:24 -0700 Subject: what has python added to programming languages? (lets be esoteric, shall we ; ) In-Reply-To: <1145632508.559750.109590@v46g2000cwv.googlegroups.com> References: <1145626586.497042.72080@i39g2000cwa.googlegroups.com> <1145632508.559750.109590@v46g2000cwv.googlegroups.com> Message-ID: <1145634384.131087.262500@e56g2000cwe.googlegroups.com> Why does Python have to "add" anything, if it makes "that which came before" more easily accessible/usable? Perhaps that is its innovation. Is that not sufficient? From zannablu at libero.it Fri Apr 28 10:51:19 2006 From: zannablu at libero.it (Faber) Date: Fri, 28 Apr 2006 14:51:19 GMT Subject: time conversions [hh:mm:ss.ms <-> sec(.ms) References: <1146213549.597990.115220@y43g2000cwc.googlegroups.com> Message-ID: kpp9c wrote: > I was looking at python & datetime and hoping that it would already > have a method/func to translate time formats. I need to translate seconds > to hh:mm:ss.ms and vice versa and would like the ability to do some basic > arithmetic in these formats. Have a look at datetime.timedelta: from datetime import timedelta seconds_value = 4237.63 td = timedelta(seconds=seconds_value) print td # Shows 1:10:37.630000 print td.seconds # Shows 4237 other_td = td + timedelta(seconds=13) print other_td # Shows 1:10:50.630000 print other_td.seconds # Shows 4250 > I think that there just has to be a package or module out there that > already does this with reasonable speed and accuracy. The accuracy seems perfect, don't know about speed - take some test :) Regards -- Faber http://faberbox.com/ http://smarking.com/ We live in a society exquisitely dependent on science and technology, in which hardly anyone knows anything about science and technology. -- Carl Sagan From ptmcg at austin.rr._bogus_.com Wed Apr 19 12:00:20 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 19 Apr 2006 16:00:20 GMT Subject: accessing a classes code References: Message-ID: "Ryan Krauss" wrote in message news:mailman.4754.1145458893.27775.python-list at python.org... ====================== I have a set of Python classes that represent elements in a structural model for vibration modeling (sort of like FEA). Some of the parameters of the model are initially unknown and I do some system identification to determine the parameters. After I determine these unknown parameters, I would like to substitute them back into the model and save the model as a new python class. To do this, I think each element needs to be able to read in the code for its __init__ method, make the substitutions and then write the new __init__ method to a file defining a new class with the now known parameters. Is there a way for a Python instance to access its own code (especially the __init__ method)? And if there is, is there a clean way to write the modified code back to a file? I assume that if I can get the code as a list of strings, I can output it to a file easily enough. ====================== Any chance you could come up with a less hacky design, such as creating a sub-class of one of your base classes? As in: class BaseClass(object): def __init__(self): # do common base class stuff here print "doing common base functionality" class SpecialCoolClass(BaseClass): def __init__(self,specialArg1, coolArg2): # invoke common initialization stuff # (much simpler than extracting lines of source code and # mucking with them) super(SpecialCoolClass,self).__init__() # now do special/cool stuff with additional init args print "but this is really special/cool!" print specialArg1 print coolArg2 bc = BaseClass() scc = SpecialCoolClass("Grabthar's Hammer", 6.02e23) Prints: ---------- doing common base functionality doing common base functionality but this is really special/cool! Grabthar's Hammer 6.02e+023 If you're still stuck on generating code, at least now you can just focus your attention on how to generate your special-cool classes, and not so much on extracting source code from running classes. -- Paul From malvert at telenet.be Wed Apr 12 07:26:47 2006 From: malvert at telenet.be (malv) Date: 12 Apr 2006 04:26:47 -0700 Subject: UDP max datagram size References: <1144830363.827740.198340@z34g2000cwc.googlegroups.com> Message-ID: <1144841207.694056.145050@i39g2000cwa.googlegroups.com> I seem to recall from UDP datagram tests between linux and XP I ran a few years ago that XP maximum datagram sizes are indeed smaller than linux. From python at rcn.com Tue Apr 11 13:59:31 2006 From: python at rcn.com (Raymond Hettinger) Date: 11 Apr 2006 10:59:31 -0700 Subject: Sorting a list of objects by multiple attributes In-Reply-To: <1144732269.462038.250550@i40g2000cwc.googlegroups.com> References: <1144718377.331845.56390@z34g2000cwc.googlegroups.com> <1144718963.906712.131510@t31g2000cwb.googlegroups.com> <1144732269.462038.250550@i40g2000cwc.googlegroups.com> Message-ID: <1144778370.969987.67080@i40g2000cwc.googlegroups.com> [George Young] >> For multiple keys the form is quite analogous: >> >> L.sort(key=lambda i: (i.whatever, i.someother, i.anotherkey)) [Noah] > If you are lambda-phobic (as I am) this should also work for an > arbitrary set of attributes: > > attrs = 'attr1 attr2 attr3'.split() > sortlist = [[getattr(o,a) for a in attrs] + [o] for o in objects] > sorted_objects = [x[-1] for x in sorted(sortlist)] The cult of lambda avoidance has lost contact with reality. Some Pythonistas now habitually twist their code into knots rather than use lambda. The above code fragment is a case in point -- it is shocking that the poster deems the three-line rewrite as an improvement on George's clear and succinct code fragment. Lambda avoidance is rooted in two things, an aversion to the keyword name and an observation that misuse can result in atrocious code. Also, some of the use cases have fallen by the wayside with the introduction of listcomps, genexps, and operator.attrgetter. Still, some use cases remain and there is no reason to mangle your code in the name of a foolish psuedo-principle. My advice: use lambda when appropriate and don't feel guilty about it From julien.arnoux at ext.cri74.org Fri Apr 21 08:18:56 2006 From: julien.arnoux at ext.cri74.org (Julien ARNOUX) Date: Fri, 21 Apr 2006 14:18:56 +0200 Subject: Read and extract text from pdf Message-ID: <1145621937.28404.12.camel@localhost.localdomain> Hi, I have a problem :), I just want to extract text from pdf file with python. There is differents libraries for that but it doesn't work... pyPdf and pdfTools, I don't know why but it doesn't works with some pdf... For example space chars are delete in the text.. Pdf playground : I don't understand how it work. If you have an idea, a tutorial, a library or anything who can help me to do that. From python.list at tim.thechases.com Fri Apr 28 19:27:55 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 28 Apr 2006 18:27:55 -0500 Subject: convert a int to a list In-Reply-To: <871wvhxvqi.fsf@localhost.localdomain> References: <871wvhxvqi.fsf@localhost.localdomain> Message-ID: <4452A4FB.3040901@tim.thechases.com> > **************************************************************** > a = ['spam!', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]] > > As an exercise, write a loop that traverses the previous list and > prints the length of each element. What happens if you send an > integer to len? > **************************************************************** > > for i in a: > print len(a[i]) > > will not do. > the list has str, int, list, list. > I am expecting the output to be 1, 1, 3, 3 which are the number of > elements of each element of a, someone might think the result should > be 4, 3, 3 which is len(a), len(a[2]), len(a[3]) but how can I do both > thoughts with a loop? Well, first off, you've got a strange indexing going on there: a[i] requires that the index be an integer. You likely *mean* for thing in a: print len(thing) If so, you can just wrap it in a check: for thing in a: if "__len__" in dir(thing): print len(thing) else: print len(str(thing)) #print 1 or whatever sort of result you expect here. Or you can give it a best-effort: for thing in a: try: print len(thing) except TypeError: print 1 and let exception-handling deal with it for you. Just a few ideas, -tkc From rpdooling at gmail.com Tue Apr 18 02:43:53 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 17 Apr 2006 23:43:53 -0700 Subject: Ironpython book? In-Reply-To: <1hdykd6.1ubb4c1jh6mfmN%aleaxit@yahoo.com> References: <1145329406.419299.12780@i40g2000cwc.googlegroups.com> <1hdyh5s.1ithyei4n7ucmN%aleaxit@yahoo.com> <1145334081.117264.75050@u72g2000cwu.googlegroups.com> <1hdykd6.1ubb4c1jh6mfmN%aleaxit@yahoo.com> Message-ID: <1145342633.307500.235390@v46g2000cwv.googlegroups.com> >> Who's "the ruling hierarchy"? I guess I just meant the congnoscenti. Them that knows what's what. >> I'm a Mac fan, with Linux a close second I suspected. I've played with Linux distros, but never a Mac. That takes more $$ than M$, and Apple is even more proprietary than MS, if you ask me. It interests me how many Open Source advocates and anti-Microsoft folks are willing to pay top dollar for Macs, which I guess means that, for them, it's less a Cathedral vs. Bazaar thing and more about It Works vs. It Doesn't? I'm no Microsoft lover, but XP doesn't crash on my machines. So I continue using it, along with Python, Firefox and whatever else I please. Anyway, thanks for the info. From johnmc at velseis.com.au Wed Apr 5 19:26:32 2006 From: johnmc at velseis.com.au (John McMonagle) Date: Thu, 06 Apr 2006 09:26:32 +1000 Subject: Mouse event - binding In-Reply-To: <1144278261.528825.201330@u72g2000cwu.googlegroups.com> References: <1144187162.980829.226020@j33g2000cwa.googlegroups.com> <1144254078.165317.264510@i39g2000cwa.googlegroups.com> <1144278261.528825.201330@u72g2000cwu.googlegroups.com> Message-ID: <1144279592.16780.8.camel@cornell> On Wed, 2006-04-05 at 16:04 -0700, beta wrote: > Hi John, > > It don't work! > I did what you told me, here is theBall function > > def theBall(self): > self.ball = self.draw.create_oval("0i", "0i", "0.20i", > "0.20i", > fill="red") > self.draw.tag_bind(self.ball, '', changeColour) > Sorry, that should read: self.draw.tag_bind(self.ball, '', self.changeColour) -- This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean. From fredrik at pythonware.com Sat Apr 22 07:04:12 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 22 Apr 2006 13:04:12 +0200 Subject: how to append to a list twice? References: <1he4xao.1d6me4454w0xpN%aleaxit@yahoo.com> <1he63p0.15i0slyckj3lzN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > > But Now You've Violated The DRY Principle!!! > > Just as with any other unrolled loop, yes -- loop unrolling is an > optimization which is based exactly on exchanging some textual > repetition for a tiny bit more speed. I had hoped that the Unusual Capitalization would have been enough to make up for the missing smiley... (but note that the OP explicitly didn't want to copy and paste; given that he wrote a newsgroup posting instead seems to indicate that his programming editor isn't quite as good as the editor in his newsreader) From mhellwig at xs4all.nl Sun Apr 16 16:13:19 2006 From: mhellwig at xs4all.nl (Martin P. Hellwig) Date: Sun, 16 Apr 2006 22:13:19 +0200 Subject: XML-RPC server via xinetd In-Reply-To: References: Message-ID: <4442a56a$0$31651$e4fe514c@news.xs4all.nl> Jos Vos wrote: > Hi, > > I'm trying to figure out how to implement a XML-RPC server that > is called by xinetd i.s.o. listening on a TCP socket itself. > > I already have implemented a stand-alone XML-RPC server using > SimpleXMLRPCServer, but I now want something similar, that is > started via xinetd (i.e. reading/writing via stdin/stdout). > > Any hints or code examples? > > Thanks, > Isn't this just a standard daemon functionality? So if you could wrap up your program in a daemon like fashion (e.g. http://homepage.hispeed.ch/py430/python/daemon.py) and then point the xinetd configuration to the right script, it should just work? Beware that I didn't try this myself yet ;-) though should do in the near future so if you could give a head ups on your progress I would appreciate it. -- mph From parker at hiredatum.demon.co.uk Mon Apr 24 01:49:50 2006 From: parker at hiredatum.demon.co.uk (Ian Parker) Date: Mon, 24 Apr 2006 06:49:50 +0100 Subject: How I learned Tkinter References: <1145810017.100862.215950@j33g2000cwa.googlegroups.com> Message-ID: In message <1145810017.100862.215950 at j33g2000cwa.googlegroups.com>, peter writes >I've been trying to teach myself Tkinter programming over the last few >months >(in a strictly amateur way), and have made a number of requests for >help in this >newsgroup and elsewhere. > >I've now (sort of) got there - in that I have used Tkinter for some >programs for >personal use - and I've written up my experiences at > >http://www.aqzj33.dsl.pipex.com/how_i_learned_tkinter/contents.htm > > >In general I found that while Frederik Lundh's tutorial is >comprehensive and >well written, there is little else around to help the newcomer working >without >the benefit of more experienced colleagues, and that in places the >documentation >is too sparse to be of much help. > >Any thoughts? Is my experience typical? > >Peter > Recently I decided to use tkinter because it was included with Python and like you I suffered through a few weeks of puzzling out tkinter. I wish I'd read your notes before I started! Regards Ian -- Ian Parker From timothy.soehnlin at gmail.com Mon Apr 10 09:42:10 2006 From: timothy.soehnlin at gmail.com (timothy.soehnlin at gmail.com) Date: 10 Apr 2006 06:42:10 -0700 Subject: StringIO.readline() returns '' In-Reply-To: References: Message-ID: <1144676530.547480.298480@j33g2000cwa.googlegroups.com> You can also just type buf.getvalue() which returns the current StringIO buffer as a python string, without the rewinding From alexci at web.de Sat Apr 15 20:18:40 2006 From: alexci at web.de (Aleksandar Cikota) Date: Sun, 16 Apr 2006 02:18:40 +0200 Subject: Async Sleep? Message-ID: Hi all, Does a async sleep exist? How to check this every 10 sec, but that the CPU is free? Code: import win32com.client import time import os Document = win32com.client.Dispatch('MaxIm.Document') Application = win32com.client.dynamic.Dispatch('MaxIm.Application') path_to_watch = "F:/Images/VRT/" before = dict ([(f, None) for f in os.listdir (path_to_watch)]) ##check this every 10 sec after = dict ([(f, None) for f in os.listdir (path_to_watch)]) added = [f for f in after if not f in before] if added: name= ' ,'.join (added) print name if str(name[-3:])=='fit': Document.OpenFile('F:/Images/VRT/'+name) Document.SaveFile('F:/Images/VRT/'+ str(name[0:-4])+'.jpeg', 6, False) Application.CloseAll() before = after Tkank You! Regards, Aleksandar From xi at gamma.dn.ua Tue Apr 18 16:27:22 2006 From: xi at gamma.dn.ua (Kirill Simonov) Date: Tue, 18 Apr 2006 23:27:22 +0300 Subject: __reduce__(1) vs __reduce__(2) Message-ID: <20060418202722.GA31530@58sirius016.dc.ukrtel.net> Could someone explain why __reduce__(2) works for files while __reduce__(1) doesn't? >>> f = file('/etc/passwd') >>> f.__reduce__(1) Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.4/copy_reg.py", line 69, in _reduce_ex raise TypeError, "can't pickle %s objects" % base.__name__ TypeError: can't pickle file objects >>> f.__reduce__(2) (, (,), None, None, None) What is a correct procedure of getting state and restoring Python objects? -- xi From __peter__ at web.de Mon Apr 24 10:03:16 2006 From: __peter__ at web.de (Peter Otten) Date: Mon, 24 Apr 2006 16:03:16 +0200 Subject: Subclass str: where is the problem? References: <1145882577.827728.54960@j33g2000cwa.googlegroups.com> <1145883907.466748.325610@t31g2000cwb.googlegroups.com> <1145886773.533093.65420@t31g2000cwb.googlegroups.com> Message-ID: pascal.parent at free.fr wrote: > This is good... try this: > > value = 'test' > value > 'test' > type(value) > > value = type(value) is type('') and Upper(value) or value > value > 'TEST' > type(value) > Try again with value = "" This makes Upper(value) a False value in a boolean context: >>> class Upper(str): ... pass ... >>> Upper("") '' >>> type(Upper("")) >>> type(Upper("") or "") versus >>> type(Upper("x") or "x") Peter From sybrenUSE at YOURthirdtower.com.imagination Mon Apr 3 13:56:34 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Mon, 3 Apr 2006 19:56:34 +0200 Subject: Registration Code References: Message-ID: Math enlightened us with: > But now I want the end-user to register this software with a > registration code or perhaps something like an evaluation demo > version which expires after some period of time... Fair enough. What do you want to know from us? > Is this the right place to ask or does anybody know where to look > for more on the subject? You never asked anything ;-) Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From stijndesaeger at gmail.com Mon Apr 3 02:28:31 2006 From: stijndesaeger at gmail.com (vdrab) Date: 2 Apr 2006 23:28:31 -0700 Subject: "definitive" source on advanced python? In-Reply-To: <1hd6vcf.upjvx07fad4bN%aleaxit@yahoo.com> References: <1144040231.239622.159630@j33g2000cwa.googlegroups.com> <1hd6vcf.upjvx07fad4bN%aleaxit@yahoo.com> Message-ID: <1144045711.723349.231460@t31g2000cwb.googlegroups.com> Thank you. The original question was not meant to sound particularly arrogant, and as you point out a book covering ONLY things like metaprogramming would probably be pretty useless in its own way. I have been using python on and off for about a year or so but still find myself staring at some of the funky recipes at the aspn cookbook site, not knowing which way is up. A good reference seems to be hard to come by, hence the question. Thanks for the link, I will have a look at some of the material. s. From theLunpa at gmail.com Thu Apr 13 13:06:58 2006 From: theLunpa at gmail.com (Lunpa) Date: 13 Apr 2006 10:06:58 -0700 Subject: Tkinter vs PyGTK In-Reply-To: <1144852602.826618.124620@i39g2000cwa.googlegroups.com> References: <1144825422.167548.153860@z34g2000cwc.googlegroups.com> <1144826842.238389.63170@t31g2000cwb.googlegroups.com> <7xfykjmd9c.fsf@ruckus.brouhaha.com> <1144829749.490901.16830@v46g2000cwv.googlegroups.com> <7xbqv7mas8.fsf@ruckus.brouhaha.com> <1144848267.412008.257230@z34g2000cwc.googlegroups.com> <1144852602.826618.124620@i39g2000cwa.googlegroups.com> Message-ID: <1144948018.313278.150210@z34g2000cwc.googlegroups.com> makes me wonder how useable pygui is now... I made the mistake of using wxpython a while back... having something that runs perfectly in windows, and *sorta* works in other platforms hardly counts as cross platform, imho. And they wonder why tkinter is shipped with python while wxpython is not... Personaly, I would just use Tkinter untill a new gui library comes along that actualy works in platforms people use, not just the one the dev prefers. Setting up gtk in windows can be a daunting task for some, though for projects that I know probably won't see the anyone else's machine, I just use pygtk, for consistency with the rest of my apps. I guess this was slightly off topic, but I think its also important to consider who might be using your apps when picking out a gui to use. From fredrik at pythonware.com Wed Apr 19 11:20:57 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 19 Apr 2006 17:20:57 +0200 Subject: Ironpython book? References: <1145329406.419299.12780@i40g2000cwc.googlegroups.com> <1he15xj.1dy2h0vzbebqmN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > > Just out of curiosity, is Python.NET a dead project? > > AFAIK, it's a long-completed research project. I do not know of anybody > planning to fork it to a new project, though that of course does not > rule out that somebody might be planning to do so. brian's latest development blog entry is from april 13th, this year. http://brianlloyd.blogspot.com/ "I'm happy to say its been a pretty busy month in Python for .NET-land" From invalidemail at aerojockey.com Thu Apr 13 01:40:47 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 12 Apr 2006 22:40:47 -0700 Subject: quiet conversion functions References: Message-ID: <1144906847.210465.120090@e56g2000cwe.googlegroups.com> Tim Chase wrote: > Is there some set of preexisting functions that do this sort > of "sensible" conversions without griping about crazy values > passed to them? No, because this isn't Perl. Seriously, it's a core principle of the Python language not to presume what a user considers to be "sensible", because, frankly, what's sensible isn't going to be the same for everyone. If you type "input this" at a Python prompt, you'll see a list of guidelines the language designers use. The one in effect here is: In the face of ambiguity, refuse the temptation to guess. Out of curiosity, what would Perl do? $ perl -e 'print int("3.14")'; echo 3 $ perl -e 'print int("33fwegfgqer")'; echo 33 $ perl -e 'print int("3OO3")'; echo 3 $ perl -e 'print int({"a","b","c","d"})'; echo 135601192 $ perl -e 'print int("hello, world")'; echo 0 Somebody (I'm guessing Larry Wall himself) thought it was "sensible" for int() to return the internal pointer of the hash. Carl Banks From aleaxit at yahoo.com Mon Apr 24 23:24:17 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 24 Apr 2006 20:24:17 -0700 Subject: Probability Problem References: Message-ID: <1hebf8p.1sb844li5y2g3N%aleaxit@yahoo.com> Lawrence D'Oliveiro wrote: > In article , > Elliot Temple wrote: > > >Problem: Randomly generate 10 integers from 0-100 inclusive, and sum > >them. Do that twice. What is the probability the two sums are 390 apart? > > I think the sum would come close to a normal distribution. Yes, very close indeed, by the law of large numbers. However, very close (in a math course at least) doesn't get the cigar. You can compute the requested answer exactly with no random number generation whatsoever: compute the probability of each result from 0 to 1000, then sum the probabilities of entries that are exactly 390 apart. Alex From pwatson at redlinepy.com Sun Apr 2 20:28:33 2006 From: pwatson at redlinepy.com (Paul Watson) Date: Sun, 02 Apr 2006 19:28:33 -0500 Subject: Is pwm Python MegaWidgets viable? In-Reply-To: <1143983854.954254.221080@i40g2000cwc.googlegroups.com> References: <499rh1Fnh7voU1@individual.net> <1143983854.954254.221080@i40g2000cwc.googlegroups.com> Message-ID: <44306C31.1020007@redlinepy.com> gregarican wrote: > Paul Watson wrote: > > >>Does pwm run well on Python 2.4? The last release appears to be in >>2003. The Manning discussion forum is dead. >> >>Is there a better path to learning and producing tkInter apps? >> >> >>Has there been any discussion of wxPython becoming part of the base >>Python distro? A requirement here is to not require download/install of >>anything other than the Python release. > > > I can't vouch for Python 2.4, but I used the PMW library pretty > extensively for an app that is based on Python 2.3. Tkinker itself > offers most of the basic widgets that any Tk implementation does, and > there's an online guide (can't recall the URL right now) to Tkinter > that is great for an introduction tutorial. PMW is an add-on to Tkinter > that is useful if there are specific widgets that you need that basic > Tkinter doesn't provide and you don't feel like creating them from > scratch. Just because it doesn't have a new release in the past couple > of years doesn't mean that it's truly a dead project. Perhaps it's > stabilized and there haven't been overwhelming requests for adding any > new items to it. Using PMW won't help you learn Tkinter any quicker in > any event. Just icing on the cake :-) Many thanks for your reply. I was setting out to make use of the Manning book by Grayson. Perhaps I should just use online tutorial and such for learning plain-old tk first. However, I have heard good things about the book. Just trying to use what was already at hand. From richard.m.tew at gmail.com Tue Apr 25 10:05:04 2006 From: richard.m.tew at gmail.com (Richard Tew) Date: 25 Apr 2006 07:05:04 -0700 Subject: Python on Nintendo DS Message-ID: <1145973904.773689.317470@v46g2000cwv.googlegroups.com> An update to my Python on Nintendo DS efforts. Summary: - Working bug free port of Python for the Nintendo DS. - Programmers wanted to help write extensions to expose the DS hardware to Python. - Stackless Python supported, but not bug free. When I last worked on it, it had several remaining bugs including a broken zipimport, unreliability due to limited stack space and more. I spent a statutory holiday on it and located and fixed all the bugs, including the allocation of stack space and the problems with zipimport (due to a misunderstanding about what seek function API I should respect). As it stands now, it seems pretty bug free. Python itself running on the Nintendo DS with no access to the hardware features (graphics, microphone, speakers, touchscreen) is not much use. As a text-based calculator it serves one purpose I guess. But to really serve as a useful tool on the DS, it needs to expose these pieces of hardware. SDL is one option, as there is a reportedly buggy port of SDL for the DS, and ideally as PyGame is based on SDL, a port of that would hopefully be straightforward. If anyone has an experience writing extension modules in C, and with programming the DS hardware in C, and wishes to help flesh out some form of library codebase to make this a useful port of Python, please let me know! :) Also, I switched to the Stackless Python code base. The tasklet scheduler locks up if invoked, but I haven't had the chance to look into this yet. But given that tasklets run and switch in the limited scenarios I have tried, fixing the scheduler should be a matter of time. Richard From durumdara at gmail.com Sat Apr 8 15:15:17 2006 From: durumdara at gmail.com (DurumDara) Date: Sat, 08 Apr 2006 21:15:17 +0200 Subject: Insertion (sql) bug in Py2.4 pySQLite 2.2 Message-ID: <44380BC5.7000805@gmail.com> Hi ! I have this code in my program. Before this I use APSW, but that project's connection object doesn't have close method... ... crs.execute(*'''create table files (*f_id integer not null primary key, f_name varchar(255), f_size long, f_attr integer, f_crtime varchar(20), f_mdtime varchar(20), f_hash long )*''') ... crs=connection.cursor() crs.execute('insert into files (f_crtime,f_mdtime,f_attr,f_id,f_hash,f_size,f_name) values(?,?,?,?,?,?,?)',('1','1',1,1,1,1,'a')) ... * So: I create a table in the first, and later I want to push some elements to it. Before this example code I use special method to create insert sql with tuple of values. But everytime it have been failed with this message: SQL error or inaccessible database. Then I simplified the code with hand maded SQL. And then I got same error message. The database file removed and rebuilded with every execution. When I tired by this error, I returned to APSW, and then I don't got error messages. What is the problem in this package ? http://initd.org/pub/software/pysqlite/releases/2.2/2.2.0/pysqlite-2.2.0.win32-py2.4.exe With Py2.3 I use pysqlite package in my CD organizer program, and then I does not exp. same problems. Please help me: dd From kharifcrop at gmail.com Sat Apr 1 09:17:41 2006 From: kharifcrop at gmail.com (Rohit) Date: 1 Apr 2006 06:17:41 -0800 Subject: newbie string conversion question Message-ID: <1143901061.088986.41120@v46g2000cwv.googlegroups.com> As part of a proprietary socket based protocol I have to convert a string of length 10, say, "1234567890" to send it as 5 characters such that their hex values are 0x21 0x43 0x65 0x87 0x09 (Hex value of each character is got by transposing two digits at a time) How can I do this in python? I would like the result to be available as a string since I am concatenating it to another string before sending it out. Thanks, Rohit From rpdooling at gmail.com Fri Apr 21 15:30:45 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 21 Apr 2006 12:30:45 -0700 Subject: python-mysql on Windows -- How to? In-Reply-To: <1145625374.537868.289600@i39g2000cwa.googlegroups.com> References: <1145602923.653628.222040@u72g2000cwu.googlegroups.com> <1145618125.010034.273380@e56g2000cwe.googlegroups.com> <1145625374.537868.289600@i39g2000cwa.googlegroups.com> Message-ID: <1145647844.936831.148170@i40g2000cwc.googlegroups.com> Oh, good. Do report back. It comes up often, and I've used only mxODBC. rd From johnjsal at NOSPAMgmail.com Wed Apr 12 15:40:36 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 12 Apr 2006 19:40:36 GMT Subject: Best Python web-hosting? In-Reply-To: <443b15dd$0$11701$c3e8da3@news.astraweb.com> References: <1144605832.364688.305300@j33g2000cwa.googlegroups.com> <4439870a$0$4206$c3e8da3@news.astraweb.com> <1144710859.872630.297820@u72g2000cwu.googlegroups.com> <443b15dd$0$11701$c3e8da3@news.astraweb.com> Message-ID: John Salerno wrote: > walterbyrd wrote: > >> And they have mod_python. > > > You sure about that? I've learned to be skeptical, because a lot of > hosts don't even seem to understand the difference between supporting > "Python" (which in reality is just CGI for them) and mod_python. In > fact, I've even been told that a host *does* have mod_python installed, > and it took several emails to find out that, no, they really don't, they > just support CGI. > > All I see on this site is "Python 2.3.4", no mention of mod_python. I > have an email in to them to inquire, but I'm not getting my hopes up. Yes, you are right. After doing a little work to their server, mod_python seems to be installed/working! Very nice. I signed up for the $.50 plan just so I can have a little site to do some mod_python testing. Thanks for the recommendation. From steve at REMOVETHIScyber.com.au Fri Apr 7 21:52:51 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 08 Apr 2006 11:52:51 +1000 Subject: very strange problem in 2.4 References: <1144454473.488240.271200@t31g2000cwb.googlegroups.com> <2tCdnYMo5LbIkqrZnZ2dnUVZ_u2dnZ2d@comcast.com> Message-ID: On Fri, 07 Apr 2006 21:18:12 -0400, John Zenger wrote: > Your list probably contains several references to the same object, > instead of several different objects. This happens often when you use a > technique like: > > list = [ object ] * 100 > > ..because although this does make copies when "object" is an integer, it > just makes references in other cases. Wrong. It always makes references. >>> L = [1]*3 >>> id(L[0]), id(L[1]), id(L[2]) (155972920, 155972920, 155972920) This isn't a caching issue either, it also happens for objects which aren't cached: >>> x = 4591034.56472 >>> y = 4591034.56472 >>> x == y True >>> x is y False >>> L = [x]*3 >>> x is L[0] is L[1] is L[2] True >>> y is L[0] False -- Steven. From marcs2006 at gmail.com Tue Apr 11 10:42:04 2006 From: marcs2006 at gmail.com (marcello) Date: Tue, 11 Apr 2006 16:42:04 +0200 Subject: [fcntl]how to lock a file References: Message-ID: Carl J. Van Arsdall wrote: > [...] > > If you end up having problems working with the python fcntl module let > me know your configuration I'd be interested to see if anyone else had > similar problems to me. Python 2.2.3 (#1, Aug 8 2003, 08:44:02) [GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-13)] on linux2 kernel 2.4.21-4.0.1.ELsmp glibc-2.3.2-95.6 What else can i add? best regards Marcello From pmartin at snakecard.com Wed Apr 26 09:52:56 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Wed, 26 Apr 2006 08:52:56 -0500 Subject: Inherit from array References: <1146057315.721573.196140@u72g2000cwu.googlegroups.com> <444f79a8$0$5191$626a54ce@news.free.fr> Message-ID: I think he did from array import * Philippe bruno at modulix wrote: > TG wrote: >> Hi there. >> >> I'm trying to create a simple class called Vector which inherit from >> array. > > Which array ? > > bruno at bousin ~ $ python > Python 2.4.2 (#1, Feb 9 2006, 02:40:32) > [GCC 3.4.5 (Gentoo 3.4.5, ssp-3.4.5-1.0, pie-8.7.9)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> array > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'array' is not defined > > > -- > bruno desthuilliers > python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for > p in 'onurb at xiludom.gro'.split('@')])" From pythor at gmail.com Sun Apr 9 20:16:41 2006 From: pythor at gmail.com (Pythor) Date: 9 Apr 2006 17:16:41 -0700 Subject: More pythonic circle? References: <1144544696.577777.239130@e56g2000cwe.googlegroups.com> <1144560529.697224.151660@e56g2000cwe.googlegroups.com> <1144598199.816461.143540@i39g2000cwa.googlegroups.com> <1144625349.438773.152640@z34g2000cwc.googlegroups.com> Message-ID: <1144628201.383509.249490@i39g2000cwa.googlegroups.com> John Machin wrote: > [Michael Tobis] > Also, with this code, you are using radius for the dimensions of the > enclosing box, as well as the radius of the circle, so it's guaranteed > to not to actually produce a whole circle. Recall what python does with > negative indices! > > [Pythor] > I'm not sure what you mean here. It produces an eighth-circle, and > then plots each point in the 8 symmetrical positions on the circle. > Except for the (dx+1) point made above, what piece of the circle is > missing? > ====== > What Michael means is that for example a circle of radius 5 is 11 > pixels wide and 11 pixels high. You are trying to cram it into a box of > 5 x 5 pixels [or maybe 6x6 (I'm numpy-challenged)]. The result will > resemble a train smash. Have you considered *TESTING* your code? It's > not very difficult at all to draw the expected results for radii of > about 4 or 5 pixels on the back of an envelope ... > Sure, I tested it. And it works, for the most part. I did miss those the dx+1 points, which John pointed out. On the other hand, I'm not having any trouble producing a whole circle, while you seem to think I'm only producing half a circle. The code that limits itself to a 5x5 box is only expected to produce an eighth of the circle. The actual assignment portion uses reflection to plot points in the whole area. If there's some other problem with it, I haven't noticed. > By the way, there are signs of a benchmark war breaking out. What are > typical sizes you would be using in practice for the radius and the > enclosing box? > Well, I'm not really asking someone else to write my code for me, but here goes. The desire is to have an array of about 1000 X 1000, bigger would be better. I want to fill this array with regions of values, with each region being between .5% and 5% of the total area. I'm using random circular regions placed around the array, allowing new regions to overlap old ones. So, I'm using circles of roughly 5 to 50 radius, and throwing a few thousand into the array. Actually, this is a prelude to trying the same thing with spheres in a 3-dimensional array, but a 1000X1000x1000 array is larger than my memory can handle. From bencvt at gmail.com Sun Apr 23 19:41:26 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 23 Apr 2006 16:41:26 -0700 Subject: Passing data attributes as method parameters In-Reply-To: <1145834871.667658.201550@u72g2000cwu.googlegroups.com> References: <1145834871.667658.201550@u72g2000cwu.googlegroups.com> Message-ID: <1145835686.151946.324150@e56g2000cwe.googlegroups.com> Panos Laganakos wrote: > I'd like to know how its possible to pass a data attribute as a method > parameter. > > Something in the form of: > > class MyClass: > def __init__(self): > self.a = 10 > self.b = '20' > > def my_method(self, param1=self.a, param2=self.b): > pass > > Seems to produce a NameError of 'self' not being defined. Default arguments are statically bound, so you'll need to do something like this: class MyClass: def __init__(self): self.a = 10 self.b = '20' def my_method(self, param1=None, param2=None): if param1 is None: param1 = self.a if param2 is None: param2 = self.b --Ben From johnjsal at NOSPAMgmail.com Sun Apr 9 18:05:59 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sun, 09 Apr 2006 18:05:59 -0400 Subject: how relevant is C today? In-Reply-To: References: <44381ee4$0$4209$c3e8da3@news.astraweb.com> <44382711.10403@v.loewis.de> <44393fbe$0$19226$c3e8da3@news.astraweb.com> Message-ID: <44398651$0$4206$c3e8da3@news.astraweb.com> Mirco Wahab wrote: > At which level in the 'python challenge' did > you get stuck - and why? Ugh, don't remind me! :) I'm stuck on level 12, which is yet another image processing puzzle. I'm getting tired of those, and I think it's really a shame that there is a reliance on image puzzles rather than simply doing some coding to figure out an algorithm, for example. (I really enjoyed writing my own function to figure out the Morris sequence.) Level 11 was an image puzzle that I flat-out cheated on to move forward, and now here I am again at 12, another complex image puzzle, and I can't find the answer for it. If anyone feels like emailing me with the solution, I certainly won't be offended. :) I just hope that later puzzles stop relying on PIL and start requiring that you do some real coding with other modules, or even with just the core language itself. From fredrik at pythonware.com Mon Apr 17 18:05:42 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 18 Apr 2006 00:05:42 +0200 Subject: scanning through page and replacing all instances of 00:00:00.00 References: Message-ID: "Kun" wrote: > because in my sql database, the date is only 'date' (as in yyyy-mm-dd), > only when i extract it with my python-cgi does the date turn into > (yyyy-mm-dd 00:00:00.00), thus i figured the best way to fix this > problem is to parse it after the matter. you still make no sense. why not fix this in your python cgi script ? From rpaulj at us.ibm.com Fri Apr 21 10:54:04 2006 From: rpaulj at us.ibm.com (R Paul Johnson) Date: Fri, 21 Apr 2006 10:54:04 -0400 Subject: R Paul Johnson is out of the office. Message-ID: I will be out of the office starting 04/21/2006 and will not return until 04/24/2006. I will respond to your message when I return. From sjmachin at lexicon.net Tue Apr 18 21:20:04 2006 From: sjmachin at lexicon.net (John Machin) Date: Wed, 19 Apr 2006 11:20:04 +1000 Subject: Uniquifying a list? In-Reply-To: References: Message-ID: <44459044.20908@lexicon.net> On 19/04/2006 1:31 AM, Tim Chase wrote: > Is there an obvious/pythonic way to remove duplicates from a list > (resulting order doesn't matter, or can be sorted postfacto)? Google is your friend: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560 From dave at waveform.plus.com Fri Apr 28 05:14:59 2006 From: dave at waveform.plus.com (Dave Hughes) Date: 28 Apr 2006 09:14:59 GMT Subject: Strange constructor behaviour (or not?) References: <4451d948$1@news.fhg.de> Message-ID: <4451dd13$0$2563$ed2619ec@ptn-nntp-reader02.plus.net> Rolf Wester wrote: > Hi, > > when defining: > > class A: > def __init__(self, l=[]): > self.l = l > a = A() > a.l.append(1111) > b = A() > print a.l > > I get the output > > [1111] > > instead of an empty list. I guess it's because the default value in > the constructor is constructed once and whenever the constructor is > called without l being specified. Exactly right. See Python FAQ item 1.4.22 (http://www.python.org/doc/faq/general/#why-are-default-values-shared-be tween-objects) > My work around is: > > class A: > def __init__(self, l=None): > if l == None: > self.l = [] > else: > self.l = l > > Is there a way to take the first definition but force the constructor > to create a new empty list every time it is called? Not as far as I know. Worth reading the above FAQ as it also contains an interesting use of this side-effect. Dave. -- From geoffrey.clementsNO at SPAMbaesystems.com Tue Apr 25 10:28:22 2006 From: geoffrey.clementsNO at SPAMbaesystems.com (Geoffrey Clements) Date: Tue, 25 Apr 2006 15:28:22 +0100 Subject: MySQLdb "begin()" - References: <1145973021.073264.262180@i39g2000cwa.googlegroups.com> Message-ID: <444e2f74$1_1@glkas0286.greenlnk.net> wrote in message news:1145973021.073264.262180 at i39g2000cwa.googlegroups.com... > Hi - Feeling a bit weird about this but I cannot find the 'begin' > method on a connection object of MySQLdb. Can anyone explain why ? > > I'm using version 1.2.0 which is pretty recent and I've read that > 'begin' should be a method of connection but it's not there ! Feeling > pretty puzzled ! > What exactly do you expect a begin method to do? Have you read this: http://www.python.org/dev/peps/pep-0249/ -- Geoff From michele.simionato at gmail.com Sat Apr 15 03:46:19 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 15 Apr 2006 00:46:19 -0700 Subject: PEP 359: The "make" Statement In-Reply-To: References: Message-ID: <1145087179.137588.202200@g10g2000cwb.googlegroups.com> Tim Hochberg ha scritto: > I think this PEP is going off the rails. It's primary virtue was that it > was a simpler, clearer way to write: > > class Foo(args): > __metaclass__ = some_metaclass > #... > > Once it starts calling secret magic methods behind the scenes it's > losing that virture. And for what? Supporting some use cases that have > reasonable solutions already? FWIW, this is my feeling too. Let's keep it simple, please! Michele Simionato From fulvio at pc.jaring.my Thu Apr 6 07:19:45 2006 From: fulvio at pc.jaring.my (Fulvio) Date: Thu, 6 Apr 2006 19:19:45 +0800 Subject: how to convert string In-Reply-To: References: <1144261976.640631.9280@e56g2000cwe.googlegroups.com> <200604061813.58405.fulvio@pc.jaring.my> Message-ID: <200604061919.45878.fulvio@pc.jaring.my> Alle 18:21, gioved? 06 aprile 2006, Fredrik Lundh ha scritto: > will work, as long as the message isn't too long I was trying some print" \b\b\b\b", i, For a number of 4 digit, but I think I miscalculated some lenght variation. The reason of this is because it won't leave previous printing. But I also got some wrong positioning :-) F From kay.schluehr at gmx.net Mon Apr 24 17:12:52 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 24 Apr 2006 14:12:52 -0700 Subject: Classic class conversion Message-ID: <1145913172.093019.182190@e56g2000cwe.googlegroups.com> Just reasoning about conversion of classic to new style classes ( keeping deprecation of ClCl in Py3K in mind ) I wonder if there is a metaclass that can be used to express the semantics of ClCl in terms of new style classes? Intuitively I would expect that there is quite a lot of Python semantics that could be expressed in pure Python - of course without circular definitions. From kelvie at ieee.org Fri Apr 21 20:10:55 2006 From: kelvie at ieee.org (Kelvie Wong) Date: Fri, 21 Apr 2006 17:10:55 -0700 Subject: Raising a specific OSError In-Reply-To: <44496345.3090407@ilm.com> References: <1145659457.805754.129340@u72g2000cwu.googlegroups.com> <44496345.3090407@ilm.com> Message-ID: <94ccbe710604211710gcce5028t87e387e268ebb6e7@mail.gmail.com> I do not see the point in doing so (why not just copy+paste that string?), but the errno (specifically ENOENT) corresponds to the POSIX.1 error number, and the string "No such file or directory" is done in C via strerror(ENOENT); (check errno(3) and strerror(3)). I doubt there is something that does this in the standard library (just checked, there's an errno module, but it is quite sparse), but a simple C extension would be trivial to write. However, the best way is just to copy and paste that text into your program, I mean, why not? raise OSError("[Errno 2] No such file or directory") On 4/21/06, David Hirschfield wrote: > I wasn't clear enough in my original post. > > I know how to raise a basic OSError or IOError, but what if I want to raise > specifically an "OSError: [Errno 2] No such file or directory"? > Somehow it must be possible to raise the error with the correct information > to bring up the standard message, but where do I find the right values to > give? > > Thanks, > -Dave > > > > alisonken1 wrote: > To raise a specific error, just find the error that you want to raise, > then give the error a text string to print: ex. > > raise IOError("This raises an IO error") > > On the stderr output, when the routine hits this line, you will get: > > > > > > raise IOError("This raises an IOError") > > Traceback (most recent call last): > File "", line 1, in ? > IOError: This raises an IOError > > > Just be sure of the error that you want to raise, since some of them > will do stuff like closing open file descriptors as well. > > > > > -- > Presenting: > mediocre nebula. > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- Kelvie From cretin at des.alpes.ch Wed Apr 12 15:05:37 2006 From: cretin at des.alpes.ch (Azolex) Date: Wed, 12 Apr 2006 21:05:37 +0200 Subject: Sorting a list of objects by multiple attributes In-Reply-To: <1144868049.142764.44520@u72g2000cwu.googlegroups.com> References: <1144718377.331845.56390@z34g2000cwc.googlegroups.com> <1144718963.906712.131510@t31g2000cwb.googlegroups.com> <1144732269.462038.250550@i40g2000cwc.googlegroups.com> <1144778370.969987.67080@i40g2000cwc.googlegroups.com> <443d489f$1_1@news.bluewin.ch> <1144868049.142764.44520@u72g2000cwu.googlegroups.com> Message-ID: <443d4f89$1_2@news.bluewin.ch> Raymond Hettinger wrote: > Azolex: >> Let's push the diagnosis a bit further : the aversion to the keyword >> "lambda" has to do with the fact that it ignores the english word used >> by all non-geeks to convey the meaning, eg "given" > > Right. However, Guido has said that lambda is here to stay, > so it's time to get over it. You are saying lambda is a given ? ;) I've not observed the BDFL's pronouncement, so I have to ask : was it clear from his words that he meant the actual keyword, or could it be he just meant the construct while refering to it by the keyword ? From nobody at 127.0.0.1 Fri Apr 21 17:25:59 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Fri, 21 Apr 2006 21:25:59 GMT Subject: Recommended IDE for creating GUI? In-Reply-To: <124idf0362d75dd@corp.supernews.com> References: <124idf0362d75dd@corp.supernews.com> Message-ID: can anyone here comment on boa constructor? http://boa-constructor.sourceforge.net/ From http Wed Apr 12 04:57:11 2006 From: http (Paul Rubin) Date: 12 Apr 2006 01:57:11 -0700 Subject: Tkinter vs PyGTK References: <1144825422.167548.153860@z34g2000cwc.googlegroups.com> <1144826842.238389.63170@t31g2000cwb.googlegroups.com> <7xfykjmd9c.fsf@ruckus.brouhaha.com> <1144829749.490901.16830@v46g2000cwv.googlegroups.com> Message-ID: <7xbqv7mas8.fsf@ruckus.brouhaha.com> "Ravi Teja" writes: > A highly unscientific measurement, using execution time from SciTe on > my 3.5 yr old box. > > Python startup - 0.272 sec > With your snippet for Tk - 0.402 sec What OS? Try rebooting the box (to clear cache) and measuring again? From wgwigw at gmail.com Tue Apr 4 03:27:36 2006 From: wgwigw at gmail.com (momobear) Date: 4 Apr 2006 00:27:36 -0700 Subject: wxpython in action book In-Reply-To: References: Message-ID: <1144135656.688071.170640@i39g2000cwa.googlegroups.com> Butternut squash wrote: > any recommendations? any opinions? > > I want to learn to program in python and need a gui reference. I'll be > updating various mysql tables. I have most of the code ready to roll by > using a command line. I need put some lipstick on my project. > > pyQT seems viable but there is not really a good reference and tutorial > > so now I'm considering wxPython and saw this book and I'm wanting to know if > if's even worth spending my $40 on. > > Thanks. what about pygtk, do u have any idea ab it? From robert.kern at gmail.com Fri Apr 14 14:37:41 2006 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 14 Apr 2006 13:37:41 -0500 Subject: Writing backwards compatible code In-Reply-To: <1145039730.10779.19.camel@kenshin.CASA> References: <1145039730.10779.19.camel@kenshin.CASA> Message-ID: Felipe Almeida Lessa wrote: > Em Sex, 2006-04-14 ?s 13:28 -0500, Robert Kern escreveu: > >>Steven D'Aprano wrote: >> >>>I came across an interesting (as in the Chinese curse) problem today. I >>>had to modify a piece of code using generator expressions written with >>>Python 2.4 in mind to run under version 2.3, but I wanted the code to >>>continue to use the generator expression if possible. >> >>Why? AFAICT, it really is just syntactic sugar. Very nice syntactic sugar, but >>not necessary at all. If you are going to have the ugly, syntactically bitter >>version in your code anyways, why clutter up your code even more trying to do both? > > Right. You can always use classes. Well, I guess you could, but using actual generators would be much cleaner. -- Robert Kern robert.kern at gmail.com "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From ldo at geek-central.gen.new_zealand Tue Apr 25 05:01:37 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 25 Apr 2006 21:01:37 +1200 Subject: Can you create an instance of a subclass with an existing instance of the base class? References: <1145650105.664762.321560@j33g2000cwa.googlegroups.com> <444cb1e3$0$28592$626a54ce@news.free.fr> Message-ID: In article <444cb1e3$0$28592$626a54ce at news.free.fr>, bruno at modulix wrote: >Lawrence D'Oliveiro wrote: >(snip) >> I think you're taking Python's OO-ness too seriously. One of the >> strengths of Python is that it can _look_ like an OO language without >> actually being OO. > >According to which definition of OO ? Isn't there one? From eoinrogers at gmail.com Sun Apr 30 11:32:47 2006 From: eoinrogers at gmail.com (Byte) Date: 30 Apr 2006 08:32:47 -0700 Subject: Converting tuple to String Message-ID: <1146411167.835198.19230@e56g2000cwe.googlegroups.com> Is their a command to convert a tuple to string? e.g. xyz = "Hello", "There" print xyz Is their any way of getting print to see xyz as being one string i.e. "Hello There" rather than "Hello" and "There", despite "Hello" and "There" being, in reality, seperate? Thanks in advance, -- /usr/bin/byte From kruhftREMOVE at gmail.com Thu Apr 13 12:27:43 2006 From: kruhftREMOVE at gmail.com (Burton Samograd) Date: 13 Apr 2006 10:27:43 -0600 Subject: Initializing defaults to module variables References: <87psjm3ef4.fsf@gmail.com> <8764ld31ey.fsf@gmail.com> Message-ID: <87wtdt1lvk.fsf@gmail.com> "Fredrik Lundh" writes: > since you know the name of the config file you're looking for, you can > simplify (and unweirdify) your code a bit by changing your config file to > look like this: > > # File: config.py > > # > # configuration defaults > > some_param = "value" > some_other_param = 1 > > # > # get user overrides > > import os > try: > execfile(os.path.expanduser("~/.program/config.py")) > except IOError: > pass # ignore missing config file, but not syntax errors > > # end of file > > with this in place, you just have to do > > import config > > in any application module than needs to access the configuration > data. nice, that looks to be just what I was looking for. thanks. -- burton samograd kruhft .at. gmail kruhft.blogspot.com www.myspace.com/kruhft metashell.blogspot.com From fredrik at pythonware.com Sat Apr 1 02:58:02 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 1 Apr 2006 09:58:02 +0200 Subject: Doc suggestions (was: Why "class exceptions" are not deprecated?) References: <1142964085.356976.166620@t31g2000cwb.googlegroups.com><1143574346.354680.136060@i39g2000cwa.googlegroups.com><1143765024.109931.96090@j33g2000cwa.googlegroups.com> <1143842010.610324.16710@t31g2000cwb.googlegroups.com> Message-ID: rurpy at yahoo.com wrote: > > (and probably for no thanks), > > Do you think you know me well enough from a > handful of usenet postings to conclude that? yes. anyone who's been involved with open source project long enough has seen enough people like you to know you. you're not unique, in any way. From nobody at 127.0.0.1 Sun Apr 30 16:43:42 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Sun, 30 Apr 2006 20:43:42 GMT Subject: basic python programing References: <1146376141.767029.17850@j73g2000cwa.googlegroups.com> <1146383327.664894.279250@v46g2000cwv.googlegroups.com> <1146419329.959290.69870@j73g2000cwa.googlegroups.com> Message-ID: <2k95g.65986$F_3.22479@newssvr29.news.prodigy.net> gregarican wrote: >> How To Ask Questions The Smart Way >> http://www.catb.org/~esr/faqs/smart-questions.html > > Actual the parent post on the thread wasn't asking a question. They > were making a somewhat puzzling dangling statement. Maybe it's time for the sequel, How To Make Smart Statements :) From fredrik at pythonware.com Sat Apr 8 02:18:20 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 8 Apr 2006 08:18:20 +0200 Subject: Screen placement based on screen resolution References: <1144437293.086701.49990@v46g2000cwv.googlegroups.com> Message-ID: Lonnie Princehouse wrote: > Tkinter takes strings as its arguments; it's TCL's legacy. geometry strings are an X windows thing... > You can use string formatting for this: > > x = width/2-40 > y = height/2-30 > > root.geometry('%ldx%ld+%ld+%ld' % (width, height, x, y)) note that "+%ld" (why bother with the l, btw? Python's not C) will misbehave if you pass in a negative offset. better use "%+d". From fredrik at pythonware.com Thu Apr 13 08:16:11 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 13 Apr 2006 14:16:11 +0200 Subject: Figure out month number from month abbrievation References: <1144873227.982973.18720@i40g2000cwc.googlegroups.com> <200604131911.40313.fulvio@pc.jaring.my> Message-ID: "Fulvio" wrote: > > but it also looks as if the meaning of the word "localized" isn't clear to > > you; if you changed the locale, those names will be translated > > Mine behave strangely. Linux localized for Italian, but Python (or its > calander is in english) Python defaults to the C locale, which is a minimal english locale. To change this, you have to tell the locale module >>> import locale >>> locale.setlocale(locale.LC_ALL) 'C' >>> import calendar >>> list(calendar.month_abbr) ['', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] >>> locale.setlocale(locale.LC_ALL, "") # get locale from environment 'sv_SE' >>> list(calendar.month_abbr) ['', 'jan', 'feb', 'mar', 'apr', 'maj', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'dec'] >>> locale.setlocale(locale.LC_ALL, "it_IT") # use explicit locale 'it_IT' >>> list(calendar.month_abbr) ['', 'gen', 'feb', 'mar', 'apr', 'mag', 'giu', 'lug', 'ago', 'set', 'ott', 'nov', 'dic'] The point here is that this is a global setting; once you (or someone using your code) change the locale, all locale dependent code changes behaviour. >>> import locale, string >>> print string.uppercase ABCDEFGHIJKLMNOPQRSTUVWXYZ >>> locale.setlocale(locale.LC_ALL, "it_IT") 'it_IT' >>> print string.uppercase ABCDEFGHIJKLMNOPQRSTUVWXYZ ?????????????????????????????? From michael at elehack.net Wed Apr 5 09:34:28 2006 From: michael at elehack.net (Michael Ekstrand) Date: Wed, 05 Apr 2006 08:34:28 -0500 Subject: RELEASED Python 2.5 (alpha 1) In-Reply-To: <200604052248.19094.anthony@python.org> References: <200604052248.19094.anthony@python.org> Message-ID: <4433C764.3060503@elehack.net> After reading AMK's survey of what's new in Python 2.5, I am suitably impressed. As usual, I can't wait to start using the cool new features... extended generators? (mind is currently swimming with the question of "can I implement Scheme's call-with-current-continuation using extended generators".) Anyway, the more important question that came to mind: I see that 2.5 will include the excellent ElementTree. Will cElementTree be included where available? or is it only the pure-Python version that will be in the standard library? - Michael -- mouse, n: a device for pointing at the xterm in which you want to type. -- Fortune Visit me on the Web: http://www.elehack.net From sjuranic at gmail.com Wed Apr 5 10:46:28 2006 From: sjuranic at gmail.com (Steve Juranich) Date: Wed, 05 Apr 2006 07:46:28 -0700 Subject: Strange problem when running python code References: <1144175959.412184.187110@g10g2000cwb.googlegroups.com> <7sj63215re1f6mq02tiuqidv9h4pv970qs@4ax.com> Message-ID: Dennis Lee Bieber wrote: > As an occassional dabbler in the Tarot, I can assure you that cards > are NOT used for "mind-reading"; they merely offer up a possible future > which must be interpreted in light of the querant's situation... (or, > since I typically read for myself -- the allow my subconscious to reveal > my inclinations based upon the cards' meanings) Who said anything about tarot? I'm talking about the old "Pick a card, any card..." bit. Cheers. -- Steve Juranich Tucson, AZ USA From jstroud at ucla.edu Sun Apr 9 23:44:45 2006 From: jstroud at ucla.edu (James Stroud) Date: Sun, 09 Apr 2006 20:44:45 -0700 Subject: Tkinter problem on Mac OS X In-Reply-To: References: Message-ID: Andrew Trevorrow wrote: > Our app uses embedded Python to allow users to run arbitrary scripts. > Scripts that import Tkinter run fine on Windows, but on Mac OS X there > is a serious problem. After a script does "root = Tk()" our app's menus > are permanently changed in the following way: > > - The top item in the application menu changes to "About Tcl & Tk...". > - The Quit item is disabled. > - The File and Edit menus are completely replaced. > - All further menus (except Help) are removed. > > Is there a way to prevent Tkinter clobbering our app's menus? > Or perhaps a way to restore them after the root.mainloop() call? > > I've read Fredrik Lundh's excellent tutorial on Tkinter and done a lot > of googling but haven't been able to find a solution. > > I can probably add some Mac-specific code to detect a menu change after > a script ends and then rebuild our menus, but I'm hoping there's a > simpler Tkinter (or Tcl?) solution. > > Andrew This menu mashing is a problem. This really has nothing to do with programing in Tcl, Tk, Python, or Tkinter. First of all, the "About Tcl & Tk" is hard-wired during the build of Aqua Tk. To fix this will require downloading the sources and building your own Aqua Tk from scratch: http://tcltkaqua.sourceforge.net/8.4.10/ Alternatively, you can res-edit the appropriate files. The "About Tcl & Tk" menu item is held in an rsrc file. I forget exactly where, but I can take a look on my ibook if you are interested in this route. To do this, you will want a working copy of resknife. I had some trouble with it, so I had to build it for my ibook with xcode--IIRC, the build I downloaded had problems saving. Getting the source and building on my computer fixed it. Its a great program. I'm guessing the best way to get around destroying your menus is to intercept calls to Tk(). I've had bad luck with multiple Tk() instances running in the same session (this is the case with EVERY implementation of Tkinter I've seen, Linux, Mac, etc.). StringVar and IntVar instances get very screwy with multiple Tk()s. You might want to re-define Tk() to return the root instance created by your program. Also, knew Toplevel()s will have their own menus, resulting in your application's menus becoming replaced while the Toplevel() is in the foreground, that's just how Aqua Tk works. This may be something you have to live with if you want your students (I'm guessing) to learn about python in your environment. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From aum at spam.me.please Mon Apr 17 08:28:56 2006 From: aum at spam.me.please (aum) Date: Tue, 18 Apr 2006 00:28:56 +1200 Subject: Python certification/training References: <1145193231.657614.275950@v46g2000cwv.googlegroups.com> Message-ID: On Sun, 16 Apr 2006 06:13:51 -0700, chrisBrat wrote: > Are there any certifications that are available for developers learning > Python? Where? > I'm specifically looking for distance/on-line courses or certifications > but welcome any information available. Makes me wonder, just out of curiosity - are there any universities actually teaching python (in anything bigger than a small elective module), or are they all still owned by Java, C++, C# and Visual Basic? -- Cheers aum From apardon at forel.vub.ac.be Thu Apr 6 04:17:30 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 6 Apr 2006 08:17:30 GMT Subject: Dice probability problem References: Message-ID: On 2006-04-05, Tomi Lindberg wrote: > Antoon Pardon wrote: > >> def __rmul__(self, num): >> tp = num * [self] >> return reduce(operator.add, tp) >> >> sum3d6 = 3 * D(6) > > One basic question: is there any particular reason not to > use __mul__ instead (that would allow me to use both 3 * > D(6) and D(6) * 3, while __rmul__ raises an AttributeError > with the latter)? Well 3 * D(6) is similar to the notation used in roleplaying, while D(6) * 3 would make me think of the distribution {3:1, 6:1, 9:1, 12:1, 15:1, 18:} > Difference between the two methods is > slightly unclear to me. I have to look it up myself regularly. But in this case it was more a matter of some intuition that 3 * D(6) was not the same as D(6) * 3. You may have a different intuition. -- Antoon Pardon From my_email_is_posted_on_my_website at munged.invalid Wed Apr 26 01:00:47 2006 From: my_email_is_posted_on_my_website at munged.invalid (Roedy Green) Date: Wed, 26 Apr 2006 05:00:47 GMT Subject: Xah's Edu Corner: Criticism vs Constructive Criticism References: <1145992903.834316.198370@u72g2000cwu.googlegroups.com> Message-ID: On 25 Apr 2006 12:21:43 -0700, "Xah Lee" wrote, quoted or indirectly quoted someone who said : >Criticism versus Constructive Criticism I think you would do better to put this sort of thing on a website rather than post it in a newsgroup. It is too pretentious for a newsgroup. Newsgroups are about question and answer. -- Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching. From cretin at des.alpes.ch Mon Apr 10 13:56:38 2006 From: cretin at des.alpes.ch (Azolex) Date: Mon, 10 Apr 2006 19:56:38 +0200 Subject: updated pre-PEP: The create statement In-Reply-To: References: Message-ID: <443a9c60$1_1@news.bluewin.ch> Steven Bethard wrote: > I've updated the PEP based on a number of comments on comp.lang.python. > The most updated versions are still at: > > http://ucsu.colorado.edu/~bethard/py/pep_create_statement.txt > http://ucsu.colorado.edu/~bethard/py/pep_create_statement.html > > In this post, I'm especially soliciting review of Carl Banks's point > (now discussed under Open Issues) which asks if it would be better to > have the create statement translated into: > > = ("", *, **) > > instead of the current: > > = ("", , ) > > The former allows the create statement to be applied to a wider variety > of callables; the latter keeps a better parallel with the class statement. ... > and named, nested hierarchies like XML documents could be created > like:: > > create ETobject html: > "This statement would generate an ElementTree object" > > create ETobject head: > "generate the head" > ... > > create ETobject body: > "generate the body" > ... I think this is is a most important eventual use-case, and would like to see it better worked out - or else declared outside the scope of the proposed statement. As far as I can see, this does not cut it, since xml and html allow /sequencial repetition/ of tags and the results of the statement suites are passed as unordered namespaces/dicts. Cheers, az. From steven.bethard at gmail.com Mon Apr 10 01:34:04 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 09 Apr 2006 23:34:04 -0600 Subject: Python 3.0 or Python 3000? In-Reply-To: <4439aba9$0$18019$c3e8da3@news.astraweb.com> References: <4439aba9$0$18019$c3e8da3@news.astraweb.com> Message-ID: <2NednVmCM_vVc6TZRVn-sw@comcast.com> John Salerno wrote: > Is 'Python 3000' just a code name for version 3.0, or will it really be > called that when it's released? Actually, there's an official response these days in `PEP 3000`_: """ Naming Python 3000, Python 3.0 and Py3K are all names for the same thing. The project is called Python 3000, or abbreviated to Py3k. The actual Python release will be referred to as Python 3.0, and that's what "python3.0 -V" will print; the actual file names will use the same naming convention we use for Python 2.x. I don't want to pick a new name for the executable or change the suffix for Python source files. """ .. _PEP 3000: http://www.python.org/dev/peps/pep-3000/ STeVe From gaz082 at gmail.com Thu Apr 20 22:16:43 2006 From: gaz082 at gmail.com (Gaz) Date: 20 Apr 2006 19:16:43 -0700 Subject: Looking for a programming resource for newbees In-Reply-To: <1145581209.588428.249770@v46g2000cwv.googlegroups.com> References: <1145581209.588428.249770@v46g2000cwv.googlegroups.com> Message-ID: <1145585802.943378.281590@v46g2000cwv.googlegroups.com> bambooforest ha escrito: > Hi all, > > I'm from a Linguistics background and am new(er) to programming. Could > someone recommend a book or resource that teaches programming aspects > with Python? Python I hear is a very appropriate language for handling > text and language processing. > > I'm searching for a resource that examines programming from a case > study like perspective. Such as, you're faced with problem of type X - > and here's how you should look at it to break it down to form an > optimal solution (e.g. because this type or problem is handled well > with this type of data structure, etc.). > > I've looked at the online Python tutorial at python.org and resources > like O'Reilly's Python in a Nutshell, but they seem to teach you > language syntax and concepts like data types, or assume you already > know how to program. I'm searching for something that teaches > programming. > > Thanks everyone, > > -Steve Hi Steve, If you know little about programming, you should get any book or google for "programming tutorials" or something like that, no matter which language uses that book/website as example. Programing is just learning simple basic operation and tools to help you develop algorithms to reach your goals. Once you have mastered those simple operation and basic programming skills, read again the Pytutorial and find out how to translate your little programs programmed with the language you used to learn. From fanmail at micah-wedemeyer.net Wed Apr 26 23:17:22 2006 From: fanmail at micah-wedemeyer.net (Micah) Date: 26 Apr 2006 20:17:22 -0700 Subject: begging for a tree implementation In-Reply-To: References: <1146091386.013265.153660@v46g2000cwv.googlegroups.com> Message-ID: <1146107842.659346.178910@t31g2000cwb.googlegroups.com> Sybren Stuvel wrote: > Micah enlightened us with: > > I'm looking for a simple tree implementation: 0-n children, 1 root. > > All the nice methods would be appreciated (getLeaves, isLeaf, > > isRoot, depthfirst, breadthfirst,...) That's really all I need. I > > could code one up, but it would take time to debug, and i'm really > > short on time right now. > > What kind of tree do you want? B+-tree? Black/Red tree? Binary search > tree? > > Sybren > -- > The problem with the world is stupidity. Not saying there should be a > capital punishment for stupidity, but why don't we just take the > safety labels off of everything and let the problem solve itself? > Frank Zappa I'm looking for a simple abstract-data-type tree. I would have thought there would be a built-in type, but I can't find one. I just need to be able to start from a root node and attach children from there. I could jury-rig one using a dict or some tuples, but I'd like a full-featured tree if someone has one implemented. Thanks for the reply! Micah From whatever at wherever.com Sat Apr 8 16:37:06 2006 From: whatever at wherever.com (ArKane) Date: Sat, 08 Apr 2006 20:37:06 GMT Subject: How's python's web scraping capabilities (vs LWP) ... Message-ID: <0d7g32tgus9nv8ilbkr10fc7n1pnte3m5f@4ax.com> Hello all, I've been hacking away at perl for a few months now, mainly using the LWP module, used for web scraping. Amoung its capabilities include support for HTTPS and proxies, authentication, cookies (including the ability to automatically import Internet Explorer cookies), etc. It seems to me, however, that trying to write more sophisticated apps using GUIs with perl is somewhat akin to pulling teeth, so I've been looking at python, but was wondering if there was an LWP equivalent for python? From fredrik at pythonware.com Tue Apr 25 03:21:45 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 25 Apr 2006 09:21:45 +0200 Subject: MinGW and Python References: <1145861223.509630.247350@y43g2000cwc.googlegroups.com><444C79D7.4060007@v.loewis.de> Message-ID: Brian Elmegaard wrote > > the gcc project is to provide a portable compiler, not one that > > generates the best code for any given platform. And in that goal, it > > succeeds remarkably well. > > Will a python program be slower on the same machine running windows > compared to linux? a better optimizer usually results in programs that run faster, not slower. From fuzzyman at gmail.com Sat Apr 1 03:41:02 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 1 Apr 2006 00:41:02 -0800 Subject: Python 2.5 licensing: stop this change In-Reply-To: <1143880645.973457.105300@t31g2000cwb.googlegroups.com> References: <1143880645.973457.105300@t31g2000cwb.googlegroups.com> Message-ID: <1143880862.164360.131780@e56g2000cwe.googlegroups.com> Fuzzyman wrote: > Steve Holden wrote: > > As the only director of the Python Software Foundation to vote against a > > recent Board motion to implement the change in licensing terms described in > > > > http://pyfound.blogspot.com/2006/04/python-25-licensing-change.html > > > > I would like to place on record my protest against this change. I think > > it will harm the Python language and ultimately be counter-productive, > > reducing the user base and discouraging open source programmers from > > contributing to the code base. > > > > If you disagree with this proposed change it's not too late to do > > something about it. If this change goes ahead it will be the end of > > Python as we know it. > > > > Can I ask for clarification. The charge applies to any commercial use > of a derivative work based on the Python source code ? > > Normal applications that use Python, including bunding the standard > CPython as an executable, using tools like py2exe, won't be covered. > Right ? > > Does this cover commercial applications that embed the Python > interpreter ? (Looks like it will) > Hmmm... after due consideration (and reading the announcmement properly), I support this license change in full. Nice one Steve. Fuzzy > All the best, > > Fuzzyman > http://www.voidspace.org.uk/python/index.shtml > > > regards > > Steve > > -- > > Steve Holden +44 150 684 7255 +1 800 494 3119 > > Holden Web LLC/Ltd www.holdenweb.com > > Love me, love my blog holdenweb.blogspot.com From duncan.booth at invalid.invalid Sat Apr 1 10:17:26 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 1 Apr 2006 15:17:26 GMT Subject: newbie string conversion question References: <1143901061.088986.41120@v46g2000cwv.googlegroups.com> Message-ID: Felipe Almeida Lessa wrote: >>>> a = "1234567890" >>>> b = [] >>>> for i in range(len(a)/2): > ... b.append(chr(int(a[i*2:i*2+2][::-1], 16))) > ... >>>> b = ''.join(b) >>>> print b > !Ce??? >>>> print repr(b) > '!Ce\x87\t' Alternatively: >>> s = "1234567890" >>> ''.join(chr(int(b+a,16)) for a,b in zip(s[::2],s[1::2])) '!Ce\x87\t' From dubrovsky at physics.uq.edu.au Sun Apr 2 21:40:26 2006 From: dubrovsky at physics.uq.edu.au (Alejandro Dubrovsky) Date: Mon, 03 Apr 2006 11:40:26 +1000 Subject: urllib2 through basic auth'ed proxy References: <87u09fxzxs.fsf@pobox.com> Message-ID: John J. Lee wrote: > jjl at pobox.com (John J. Lee) writes: > >> Alejandro Dubrovsky writes: > [...Alejandro complains about non-working HTTP proxy auth in urllib2...] > > [...John notes urllib2 bug...] >> A workaround is to supply a stupid HTTPPasswordMgr that always returns >> the proxy credentials regardless of what the handler asks it for (only >> tested with a perhaps-broken 2.5 install, since I've broken my 2.4 >> install): > [...snip ugly code] >> Yuck, yuck, yuck! I had realised the auth/proxies code in urllib2 was >> buggy, but... And all those hoops to jump through. >> >> Also, if you're using 2.5 SVN HEAD, it seems revision 42133 broke >> ProxyHandler in an attempt to fix the URL host:post syntax! > [...] > > In fact the following also works with Python 2.3.4: > > import urllib2 > proxy_handler = urllib2.ProxyHandler({"http": > "http://john:blah at localhost:3128"}) print > urllib2.build_opener(proxy_handler).open('http://python.org/').read() > It does too. Thanks again. (I think this version is uglier, but easier to insert into third party code) From zpincus at stanford.edu Fri Apr 21 13:51:44 2006 From: zpincus at stanford.edu (Zachary Pincus) Date: Fri, 21 Apr 2006 10:51:44 -0700 Subject: Define type of 'module' object that is imported Message-ID: Hi folks, I'm sure this has come up before, but the search terms I've been using are so non-specific that I can't get any traction on Google. Here's my question: I have written a subclass of ModuleType that handles lazy loading of some slow resources. I would like a given module to be created as an instance of that particular subclass on import, so that if I do: import foo type(foo) I get instead of . Is there any way to effect this? Something like __metaclass__ = ... but at the beginning of a module instead of at the beginning of a class? Thanks, Zach Pincus Program in Biomedical Informatics and Department of Biochemistry Stanford University School of Medicine From patrohlf at adelphia.net Fri Apr 7 15:28:04 2006 From: patrohlf at adelphia.net (Pat) Date: Fri, 7 Apr 2006 12:28:04 -0700 Subject: Screen placement based on screen resolution References: <1144437293.086701.49990@v46g2000cwv.googlegroups.com> Message-ID: <1oqdncF9As1MIavZnZ2dnUVZ_vadnZ2d@adelphia.com> Thanks. S "Lonnie Princehouse" wrote in message news:1144437293.086701.49990 at v46g2000cwv.googlegroups.com... > Tkinter takes strings as its arguments; it's TCL's legacy. You can use > string formatting for this: > > x = width/2-40 > y = height/2-30 > > root.geometry('%ldx%ld+%ld+%ld' % (width, height, x, y)) > From spe.stani.be at gmail.com Sat Apr 22 09:03:25 2006 From: spe.stani.be at gmail.com (SPE - Stani's Python Editor) Date: 22 Apr 2006 06:03:25 -0700 Subject: howto py2exe/py2app for self updating application Message-ID: <1145711005.836692.10220@v46g2000cwv.googlegroups.com> Hi, I'm creating a GUI program with wxPython which will be distributed for Mac and Windows. The audience of the program is not technical at all (eg they've never heard about Python yet ;-), so everything should go automatically. The program should be able to update itself and to update its database (collection of .txt files). These are two separated things and don't happen simultaneously. I thought of the following: - seperate the code which will be updated and zip it to use a zipimport - zip the .txt files These files can then be downloaded (urllib or so) and if the download has completed succesfully, replace their old files. For the updated python code it is necessary to restart the program for the database not. These questions arise: ++ How can I bundle a zipimport file with py2exe/py2app? Let say this is the folder layout of the program: application.py code.zip (contains main.py, ui.py, etc..) * data.zip (contains .txt files) * other files (preferably bundled but not necessary) such as the wxPython libraries and whatever py2app will want to include (* means should be remote updatable/synchronizable) application.py is just a dummy file which calls code.main.main() Should I declare code.zip as a data file or as a python package? Of course it would be nice if someone be so kind to suggest a simple setup.py recipee for this... ++ I have Python2.4, wxPython2.6.3, OS X 10.4 Will it run on other versions of OS X? If not will a version compiled with py2app on OS X 10.3 run on OS X 10.4 or do I need to provide a file for every OS X version? ++ Do I have to declare something special for py2app and wxPython? Thanks in advance, Stani PS Please cc your answer to spe.stani.be IatI gmail.com From scott.daniels at acm.org Sun Apr 9 19:45:08 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Sun, 09 Apr 2006 16:45:08 -0700 Subject: More pythonic circle? In-Reply-To: <1144544696.577777.239130@e56g2000cwe.googlegroups.com> References: <1144544696.577777.239130@e56g2000cwe.googlegroups.com> Message-ID: <4439999f@nntp0.pdx.net> Pythor wrote: > I wrote the following code for a personal project. I need a function > that will plot a filled circle in a two dimensional array. I found > Bresenham's algorithm, and produced this code. Please tell me there's > a better way to do this. > > import numpy > > def circle(field=None,radius,center=(0,0),value=255,): ... Break this code into two functions. Roughly: def wedge_nz(radius): '''points in octant 2 of 0-origin radius-sized circle, no zeroes''' x, y = int(radius), 1 dr2 = x ** 2 + y ** 2 r2 = radius ** 2 dy_limit = int(radius * .71) # sin of 45 degrees + a smidge while y <= dy_limit: if r2 >= dr2: # dx**2 + dy**2 for tx in range(1, x + 1): yield tx, y dr2 += y * 2 + 1 # dr2 = x ** 2 + (y + 1) ** 2 y += 1 else: dr2 -= x * 2 - 1 # dr2 = (x - 1) ** 2 + y ** 2 x -= 1 if x < y: break and: def circle2(field=None, radius=3.2, center=(0, 0), entry=255): '''Fill field at all points within 'radius' of center with entry. center is assumed integral. ''' x, y = center if field is None: field = numpy.zeros((int(x + radius), int(y + radius)), 'u') for px, py in wedge_nz(radius): for dx in (px, -px): for dy in (py, -py): # Done once per quadrant. Do both octants. field[max(0, y + dy)][max(0, x + dx)] = entry field[max(0, y + dx)][max(0, x + dy)] = entry # do the diameters for dx in range(-radius, radius + 1): field[y][max(0, x + dx)] = entry field[max(0, y + dx)][x] = entry return field There is still overlap done at x = y and x = -y; you could squeeze that out as well by changing wedge_nz not to put it out, and making circle2 do diagonal diameters as well (leaving the center the sole overwrite). --Scott David Daniels scott.daniels at acm.org From cesugden at gmail.com Thu Apr 27 11:32:38 2006 From: cesugden at gmail.com (Chris) Date: 27 Apr 2006 08:32:38 -0700 Subject: Twisted and Tkinter In-Reply-To: References: <1146104350.843046.186230@v46g2000cwv.googlegroups.com> <1146147995.608638.245540@u72g2000cwu.googlegroups.com> Message-ID: <1146151958.731021.177480@e56g2000cwe.googlegroups.com> Exception in Tkinter callback Traceback (most recent call last): File "C:\Python24\lib\lib-tk\Tkinter.py", line 1345, in __call__ return self.func(*args) TypeError: unbound method sendMessage() must be called with ChatFactory instance as first argument (got nothing instead) I have simplified the code as well, now attached below: from twisted.internet import reactor from twisted.internet.protocol import Protocol, ClientFactory from twisted.protocols.basic import LineReceiver from Tkinter import * from twisted.internet import tksupport class ChatClient(LineReceiver): def connectionMade(self): self.sendLine("Hello server") def lineReceived(self, line): print line def connectionLost(self, reason): pass class ChatFactory(ClientFactory): protocol = ChatClient def clientConnectionFailed(self, connector, reason): reactor.stop() def clientConnectionLost(self, connector, reason): reactor.stop() def sendMessage(self): self.sendLine("Test") root = Tk() b1 = Button(root,text="Send") b1.configure(command=ChatFactory.sendMessage) b1.pack() tksupport.install(root) reactor.connectTCP('localhost',8886,ChatFactory()) reactor.run() From daniel.dittmar at sap.corp Thu Apr 6 10:38:35 2006 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Thu, 06 Apr 2006 16:38:35 +0200 Subject: GUI issues in Python In-Reply-To: <1144328552.221998.230480@g10g2000cwb.googlegroups.com> References: <1144328552.221998.230480@g10g2000cwb.googlegroups.com> Message-ID: diffuser78 at gmail.com wrote: > I want to create a GUI where a user can select drag and drop kind of > boxes, circles and make connections between them. > > This is basically for depicting states and dependencies. I am writing a > program where I let the user input states and dependencies in a certain > domain. Based on input given by user in the GUI, I grab it and run my > algorithm to generate the output. > > I am wondering if there is any library like that in Python, or if > anybody of you has done something similar in past, could you post some > pointers. wxPython has an interface to the OGL library (screenshot: http://www.wxpython.org/ss/wxPythonOSX.png, features: http://www.wxwindows.org/contrib/ogl/ogl.htm) Daniel From sturlamolden at yahoo.no Fri Apr 28 17:25:58 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 28 Apr 2006 14:25:58 -0700 Subject: MinGW and Python In-Reply-To: <1146257693.464534.130710@j73g2000cwa.googlegroups.com> References: <1146248734.511062.115290@j73g2000cwa.googlegroups.com> <1146253355.564139.147500@j73g2000cwa.googlegroups.com> <1146257693.464534.130710@j73g2000cwa.googlegroups.com> Message-ID: <1146259558.395156.79330@g10g2000cwb.googlegroups.com> Ross Ridge wrote: > Links where you can download them were posted in the thread you started > on the MinGW C/C++ forum. AFAIK the links were for various versions of the "VS 2005 redistributable". It does not contain msvcr71.dll, instead it has msvcr80.dll. I don't think there is a download for msvcr71.dll. From nobody at 127.0.0.1 Wed Apr 19 13:51:32 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 19 Apr 2006 17:51:32 GMT Subject: multiline comments In-Reply-To: References: Message-ID: Sion Arrowsmith wrote: > Really? Under what circumstances is it easier to see what's going on > with start/end comments than with comment-to-end-of-line? Off the top of my head: 1. The code is usually easier to read as # can obscure the first token on the line. This can be alleviated by leaving a space after the # or coloring the # differently. 2. It's easier to see where a nested comment begins and ends. Instead of counting #s at the beginning of lines, just find the matching closer. This is fairly simple to automate in a good editor. Counting #s can be automated as well, but fails if the programmer gets lazy and doesn't add extra #s when nesting, i.e. turns this: line 1 #line 2 line 3 into this #line 1 #line 2 #line 3 instead of this #line 1 ##line 2 #line 3 3. Preserves history better. Say I have consecutive lines commented out. With #s, all you see is this: #line 1 #line 2 #line 3 #line 4 If they were commented out in two chunks at different times, multiline comments can preserve that information: (* line 1 line 2 *) (* line 3 line 4 *) This isn't meant to be an exhaustive list. There are ways to address all these things with single-line comments, but it takes more work. Economy of expression favors nested comments in my book. Gregor has a good point about grep, but C-based languages with /**/ suffer the same problem. I think the answer is smarter searches, not dumber comments. From michael.mcgarry at gmail.com Tue Apr 11 15:16:41 2006 From: michael.mcgarry at gmail.com (Michael McGarry) Date: 11 Apr 2006 12:16:41 -0700 Subject: RegExp question In-Reply-To: References: <1144781090.622493.252460@t31g2000cwb.googlegroups.com> Message-ID: <1144783001.905105.305220@z34g2000cwc.googlegroups.com> Tim, for some reason that does not seem to do the trick. I am testing it with grep. (i.e., grep -e '(and|or|xor)\s*#' myfile) Michael From Serge.Orlov at gmail.com Mon Apr 3 11:12:40 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 3 Apr 2006 08:12:40 -0700 Subject: Can't detect EOF from stdin on windows console References: <4430ec0e$0$20103$834e42db@reader.greatnowhere.com> Message-ID: <1144077159.968781.32640@e56g2000cwe.googlegroups.com> Dmitry Anikin wrote: > I want to read stdin in chunks of fixed size until EOF > I want to be able (also) to supply data interactively in console > window and then to hit Ctrl+Z when finished [snip fighting with windows] > Read at most size bytes from the file (less if the read hits EOF before obtaining size bytes). > According to that, stdin.read(3), when supplied with "12^Z" should return immediately > with two-character string instead of waiting for third character after EOF. On windows EOF is recognized only in the beginning of a line. That is how almost all console applications work on windows. So you have to use either .readline() method or .read(1) From __peter__ at web.de Fri Apr 7 09:57:42 2006 From: __peter__ at web.de (Peter Otten) Date: Fri, 07 Apr 2006 15:57:42 +0200 Subject: Simple string formatting question References: <4434DCEC.4080308@REMOVEMEcyber.com.au> Message-ID: Steven D'Aprano wrote: > I have a sinking feeling I'm missing something really, > really simple. > > I'm looking for a format string similar to '%.3f' > except that trailing zeroes are not included. > > To give some examples: > > Float String > 1.0 1 > 1.1 1.1 > 12.1234 12.123 > 12.0001 12 > > and similar. > > Here is a (quick and dirty) reference implementation: > > def format(f, width=3): > fs = '%%.%df' % width > s = fs % f > return s.rstrip('0').rstrip('.') > > > Is there a way of getting the same result with just a > single string format expression? Does it have to be a string or can you cheat? If so: >>> class Format(str): ... def __new__(cls, width): ... return str.__new__(cls, "%%.%df" % width) ... def __mod__(self, other): ... return str.__mod__(self, other).rstrip("0").rstrip(".") ... >>> format = Format(3) >>> for f in [1.0, 1.1, 12.1234, 12.0001]: ... print f, "-->", format % f ... 1.0 --> 1 1.1 --> 1.1 12.1234 --> 12.123 12.0001 --> 12 For passing around in your app that should be as convenient as a string -- of course it will break if you store the "format" in a file, say. Peter From cretin at des.alpes.ch Mon Apr 10 07:26:23 2006 From: cretin at des.alpes.ch (Azolex) Date: Mon, 10 Apr 2006 13:26:23 +0200 Subject: how to make a generator use the last yielded value when it regains control In-Reply-To: <1144390994.551650.31490@v46g2000cwv.googlegroups.com> References: <4435cde3$0$11677$c3e8da3@news.astraweb.com> <1144390994.551650.31490@v46g2000cwv.googlegroups.com> Message-ID: <443a40e0$1_1@news.bluewin.ch> Lonnie Princehouse wrote: > Here's my take on the thing. It only prints one term, though. > > http://www.magicpeacefarm.com/lonnie/code/morris.py.html > > (a bit too long to post) > excerpt : def morris(seed, n): """...""" if n == 1: return seed else: return length_encode(morris(seed,n-1)) What's wrong with the following ? def morris(seed,n) : """...""" for k in xrange(n-1) : seed=length_encode(seed) return seed or even def morris(seed,n) : return reduce(lambda x,y:y(x),n*[length_encode],seed) I'd defend using recursion when it allows a more concise expression of an algorithm, but not in other cases. Mmmhhh, btw, strangely, it looks like a hole in the library that you can't write eg morris= lambda seed,n: reduce(operator.__rcall__,n*[length_encode],seed) From brandon.mcginty at gmail.com Fri Apr 14 16:16:30 2006 From: brandon.mcginty at gmail.com (brandon.mcginty at gmail.com) Date: Fri, 14 Apr 2006 13:16:30 -0700 Subject: News-retrieval client-news.google Message-ID: <027c01c66000$5262c8f0$6400a8c0@D1FWTS61> Hi All, I'm trying to write a news retrieval client in python. I'm going to get the news from google's news service. However, when I run the following code, google gives me a 403 error. Is it google, or urllib2? Or is it the code? I can parse the 'contents' variable, I just need to know what is going wrong. THX, Brandon #startofcode import urllib2,htmldata url='http://news.google.com/news'#?ned=tus&rec=0' contents = urllib2.urlopen(url).read() Print contents #endofcode ---------- Feel free to contact me for technical support, or just to chat; I always have time to talk and help, and an open ear. Email:Brandon.mcginty at gmail.com Skype:brandon.mcginty Msn:brandon_mcginty at hotmail.com Aim:brandonmcginty (Not currently available.) Cell:4802025790 (Weekends and nights only, please.) "Kindness is a language that the deaf can hear and the blind can see." Mark Twain -- No virus found in this outgoing message. Checked by AVG Free Edition. Version: 7.1.385 / Virus Database: 268.4.1/312 - Release Date: 4/14/2006 From pitarda at gmail.com Sat Apr 29 13:04:39 2006 From: pitarda at gmail.com (pitarda) Date: 29 Apr 2006 10:04:39 -0700 Subject: How to get computer name In-Reply-To: References: <1146328920.066207.236540@e56g2000cwe.googlegroups.com> Message-ID: <1146330279.267574.73240@i39g2000cwa.googlegroups.com> Thanks! :) Though,... I think once I saw something like: getComputerByName but can't find it anymore,... :) From rpdooling at gmail.com Thu Apr 20 14:09:45 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 20 Apr 2006 11:09:45 -0700 Subject: perspective on ruby In-Reply-To: <1145555339.316764.123210@i39g2000cwa.googlegroups.com> References: <1145555339.316764.123210@i39g2000cwa.googlegroups.com> Message-ID: <1145556585.403429.201730@z34g2000cwc.googlegroups.com> RK, I always liked this Martelli post, which I found by searching on Ruby early on when I was still trying to decide to learn Python or Ruby. For a mere hobbyist doing both is out of the question: http://groups.google.com/group/comp.lang.python/msg/28422d707512283 If you want more just search on "ruby" in comp.lang.python or "python" in comp.lang.ruby That should cover it. rick "A language is a dialect with an army and navy." --Max Weinrich From nobody at 127.0.0.1 Wed Apr 19 14:10:49 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 19 Apr 2006 18:10:49 GMT Subject: multiline comments In-Reply-To: References: <1145425311.771598.140970@i40g2000cwc.googlegroups.com> Message-ID: Peter Tillotson wrote: > discouraged except where vital. Perhaps we should make them really hard > and elegant - mandate latex/mathml markup so good editors can display > the equations we are implementing :-) I like this guy already! :) From my_email_is_posted_on_my_website at munged.invalid Wed Apr 26 17:49:19 2006 From: my_email_is_posted_on_my_website at munged.invalid (Roedy Green) Date: Wed, 26 Apr 2006 21:49:19 GMT Subject: (was Re: Xah's Edu Corner: Criticism vs Constructive Criticism) References: <1145992903.834316.198370@u72g2000cwu.googlegroups.com> <4GM3g.3084$TT.1768@twister.nyroc.rr.com> <1146079773.910552.217390@y43g2000cwc.googlegroups.com> Message-ID: On 26 Apr 2006 12:29:33 -0700, "Xah Lee" wrote, quoted or indirectly quoted someone who said : >This is a public notice that what you are trying to do is getting close >to harrassment from the law's perspective. and what you do Xah, is very close to spam, another form of harassment. -- Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching. From aleaxit at yahoo.com Mon Apr 3 11:53:06 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 3 Apr 2006 07:53:06 -0800 Subject: Get the input from user References: <1144045891.952385.176780@v46g2000cwv.googlegroups.com> Message-ID: <1hd7kg7.yit5fu2stwzN%aleaxit@yahoo.com> wrote: > hi, > I am doing example of address book.when user enter stop and presses > enter my loop should stop.But there is some prob in my loop.It is > accepting \r after pressing Enter key.How do i check end of input : > addressbook={} > name = raw_input("Enter Name (stop to Finish)") > > name = EnterAddress(addressbook) > > ShowAddress(name, addressbook) > > def ShowAddress(name, addressbook): > name = raw_input("Enter Name for Address ") > print "Address of %s is %s" %(name,addressbook[name]) > > def EnterAddress(addressbook): > while name != "stop": > entry = raw_input("Enter the address") > addressbook[name]=entry > name = raw_input("Enter Name (Leave blank to Finish)") > return name Add 'name' to the arguments of EnterAddress, just as you correctly have it in ShowAddress. Alex From arv.nntp at gmail.com Sun Apr 16 05:07:11 2006 From: arv.nntp at gmail.com (Alexis Roda) Date: Sun, 16 Apr 2006 11:07:11 +0200 Subject: Unified web API for CGI and mod_python? In-Reply-To: References: <1138116339.781705.67960@f14g2000cwb.googlegroups.com> Message-ID: Tim Chase escribi?: > > root at rubbish# cd ~tim/WebStack-1.1.2 > root at rubbish# python2.3 setup.py install > running install > error: invalid Python installation: unable to open > /usr/lib/python2.3/config/Makefile (No such file or directory) > apt-get install python2.3-dev HTH From michael at elehack.net Thu Apr 6 10:29:41 2006 From: michael at elehack.net (Michael Ekstrand) Date: Thu, 06 Apr 2006 09:29:41 -0500 Subject: pre-PEP: The create statement In-Reply-To: References: <59Wdnbd8EazRCqnZnZ2dnUVZ_vudnZ2d@comcast.com> Message-ID: <443525D5.1020008@elehack.net> Steven Bethard wrote: > Michael Ekstrand wrote: >> Something it could be useful to try to add, if possible: So far, it >> seems that this create block can only create class-like things (objects >> with a name, potentially bases, and a namespace). Is there a natural way >> to extend this to other things, so that function creation can be >> modified? For example: >> >> create tracer fib(x): >> # Return appropriate data here >> pass >> >> tracer could create a function that logs its entry and exit; behavior >> could be modifiable at run time so that tracer can go away into oblivion. >> >> Given the current semantics of create, this wouldn't work. What would be >> reasonable syntax and semantics to make something like this possible? >> >> Maybe this would need to be a separate PEP. But it seems at least >> somewhat related. > > I think this probably needs a separate PEP. Function definitions are > really very different from class definitions. But feel free to write > that PEP. ;) If I have extra time this summer, maybe. It'd be fun to write a PEP and figure out how to add it in to Python. But that will definitely have to wait until *after* semester tests, if I can even get to it at all... - Michael -- mouse, n: a device for pointing at the xterm in which you want to type. -- Fortune Visit me on the Web: http://www.elehack.net From mensanator at aol.com Fri Apr 28 20:33:51 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 28 Apr 2006 17:33:51 -0700 Subject: convert a int to a list References: <871wvhxvqi.fsf@localhost.localdomain> Message-ID: <1146270830.929803.143230@e56g2000cwe.googlegroups.com> Tim Chase wrote: > > **************************************************************** > > a = ['spam!', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]] > > > > As an exercise, write a loop that traverses the previous list and > > prints the length of each element. What happens if you send an > > integer to len? > > **************************************************************** > > > > for i in a: > > print len(a[i]) > > > > will not do. > > the list has str, int, list, list. > > I am expecting the output to be 1, 1, 3, 3 which are the number of > > elements of each element of a, someone might think the result should > > be 4, 3, 3 which is len(a), len(a[2]), len(a[3]) but how can I do both > > thoughts with a loop? > > Well, first off, you've got a strange indexing going on > there: a[i] requires that the index be an integer. You > likely *mean* > > for thing in a: > print len(thing) > > If so, you can just wrap it in a check: > > for thing in a: > if "__len__" in dir(thing): > print len(thing) > else: > print len(str(thing)) > #print 1 > > or whatever sort of result you expect here. > > Or you can give it a best-effort: > > for thing in a: > try: > print len(thing) > except TypeError: > print 1 > > and let exception-handling deal with it for you. > > Just a few ideas, And probably what the writer of the exercise had in mind. But I would say it's wrong. To my way of thinking, "each element" implies recursive: import operator def typelen(t,offset=0): if operator.isSequenceType(t): print '\t'*offset,'Sequence length:',len(t) if len(t)>1: for i in t: if (operator.isSequenceType(i)): typelen(i,offset+1) if (operator.isMappingType(i)): typelen(i,offset+1) if operator.isNumberType(i): print '\t'*(offset+1),'Number length: n/a' else: if (operator.isMappingType(t)): print '\t'*offset,'Mapping length:',len(t) if operator.isNumberType(t): print '\t'*(offset+1),'Number length: n/a' if operator.isMappingType(t): print '\t'*offset,'Mapping length:',len(t) for i in t: if (operator.isSequenceType(i)): if len(i)>1: typelen(i,offset+1) if operator.isNumberType(t): print '\t'*offset,'Number length: n/a' a=['spam!',1,['Brie','Roquefort','Pol le Veq'],[1,2,3],{'ab':1,'abc':2}] typelen(a) I added a dictionary to the example since dictionaries have length even though they are not sequences. Running it, I get: Sequence length: 5 Sequence length: 5 Sequence length: 1 Sequence length: 1 Sequence length: 1 Sequence length: 1 Sequence length: 1 Number length: n/a Sequence length: 3 Sequence length: 4 Sequence length: 1 Sequence length: 1 Sequence length: 1 Sequence length: 1 Sequence length: 9 Sequence length: 1 Sequence length: 1 Sequence length: 1 Sequence length: 1 Sequence length: 1 Sequence length: 1 Sequence length: 1 Sequence length: 1 Sequence length: 1 Sequence length: 10 Sequence length: 1 Sequence length: 1 Sequence length: 1 Sequence length: 1 Sequence length: 1 Sequence length: 1 Sequence length: 1 Sequence length: 1 Sequence length: 1 Sequence length: 1 Sequence length: 3 Number length: n/a Number length: n/a Number length: n/a Mapping length: 2 Sequence length: 2 Sequence length: 1 Sequence length: 1 Sequence length: 3 Sequence length: 1 Sequence length: 1 Sequence length: 1 From luis at geodynamics.org Fri Apr 14 20:21:57 2006 From: luis at geodynamics.org (Luis Armendariz) Date: Fri, 14 Apr 2006 17:21:57 -0700 Subject: ping In-Reply-To: <9583ed900604141704x39542865ie71665c071aaf571@mail.gmail.com> References: <9583ed900604141704x39542865ie71665c071aaf571@mail.gmail.com> Message-ID: <44403CA5.3000605@geodynamics.org> david brochu jr wrote: > Thanks, > > Unfortunately substituting os.system with os.popen results in the output > being: > > > ', mode 'r' at 0x009C4650> > > ', mode 'r' at 0x009C4650> > > ', mode 'r' at 0x009C4650> > > ', mode 'r' at 0x009C4650> > > instead of giving me the ping stats "pinging etc etc, packets sent 4 > recienved 4 etc) > > Any idea around this? > > You're getting files back...so read them! :-) The output is there. -Luis From sjmachin at lexicon.net Fri Apr 21 19:59:15 2006 From: sjmachin at lexicon.net (John Machin) Date: Sat, 22 Apr 2006 09:59:15 +1000 Subject: Finding Module Dependancies In-Reply-To: <1145657885.389499.232600@t31g2000cwb.googlegroups.com> References: <1145657885.389499.232600@t31g2000cwb.googlegroups.com> Message-ID: <444971D3.6010104@lexicon.net> On 22/04/2006 8:18 AM, mwt wrote: > When I'm rewriting code (cutting and pasting pieces from earlier > modules) Instead of propagating multiple copies of source code, consider refactoring those modules so that top-level functions and classes can be used in other modules. > is there a quick way to determine if I have imported all the > necessary modules? I am used to working in Java, where the compiler > will tell you if you haven't imported everything, That's a clever design. It would be even better if it just shut up and did the imports for you :-) > and also Eclipse, > which has the handy "organize imports" feature. This is not the case in > Python, since it's not compiled, of course, and also running it might > not insure you've got all the imports, unless you go through every > possible usage scenario -- which in some cases is quite a few, and > could take a long time. This is called "testing". Yes, it could take a long time. > > So what I'm looking for is a command, like "check dependencies" or > something, which will list all the modules needed for a source module > to run. > Consider pychecker and pylint. I haven't tried pylint, but pychecker does what you want and a whole lot more: C:\junk>type miss_import.py # need to import re, but forgot def my_isdigit(s): return bool(re.match(r"\d+", s)) C:\junk>pychecker miss_import C:\junk>c:\python24\python.exe c:\python24\Lib\site-packages\pychecker\checker.py miss_import Processing miss_import... Warnings... miss_import.py:3: No global (re) found C:\junk> From frank at chagford.com Sat Apr 8 09:46:32 2006 From: frank at chagford.com (Frank Millman) Date: 8 Apr 2006 06:46:32 -0700 Subject: minidom + wxPython woes In-Reply-To: References: <1144448449.586601.293480@v46g2000cwv.googlegroups.com> <1144477016.011818.70290@e56g2000cwe.googlegroups.com> Message-ID: <1144503992.283231.305290@i40g2000cwc.googlegroups.com> Fredrik Lundh wrote: > Frank Millman wrote: > > > This sounds similar to a problem I reported a few months ago. This is > > the link. > > > http://groups.google.com/group/comp.lang.python/browse_frm/thread/6fc1097d26083e43/5fbdf493f3c38942?q=&rnum=1&hl=en#5fbdf493f3c38942 > > > > In my case, it turned out to be a bug in the pyexpat module - it is > > known about, but for some reason difficult to fix, so it is still > > there. > > no, it's not a bug in the pyexpat module -- the problem is that > wxPython uses it's own incompatible version of the expat library, > and loads it in a way that causes problems for any library that's > tries to use its own statically linked version. > > see MvL's comments in the sourceforge tracker for more info. > > I had a look at the sourceforge tracker. I did not understand much of it - rather too technical for me. There are two points worth noting. Firstly, it seems from various posts to the tracker item that the same problem has been reported with pygtk, Qt, and VTK. Secondly, in tracker item 1295808 (which, according to the notes, is actually the same bug), there is talk of submitting a patch in 2.5 to address the issue. It seems to me (FWIW - as I said, I do not really understand much of what I read) that it may not technically be a bug in pyexpat, but there is a real issue there, and the decision has been taken to make a change to pyexpat so that the problem will not arise in the future. Frank From duncan.booth at invalid.invalid Thu Apr 13 03:49:11 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 13 Apr 2006 07:49:11 GMT Subject: list.clear() missing?!? References: <1144767680.583085.310160@v46g2000cwv.googlegroups.com> <1144792144.168802.146310@i39g2000cwa.googlegroups.com> <1144870852.886477.238570@u72g2000cwu.googlegroups.com> Message-ID: Raymond Hettinger wrote: > Cons: > ----- > > * learning slices is basic to the language (this lesson shouldn't be > skipped) > also, a clear method would simply clear the entire list. You still need to learn the assigning to/deleting slices technique any time you want to clear out part of a list. Every so often I still get an "oh, I didn't know Python could do *that* moment", just had one now: >>> s = range(10) >>> s[::2] = reversed(s[::2]) >>> s [8, 1, 6, 3, 4, 5, 2, 7, 0, 9] I've no idea when I might need it, but it just never occurred to me before that you can also assign/del non-contiguous slices. The symmetry does breaks down a bit here as assigning to an extended slice only lets you assign a sequence of the same length as the slice, so you can't delete an extended slice by assignment, only by using del. >>> s = range(10) >>> del s[::2] >>> s [1, 3, 5, 7, 9] >>> s = range(10) >>> s[::2] = [] Traceback (most recent call last): File "", line 1, in -toplevel- s[::2] = [] ValueError: attempt to assign sequence of size 0 to extended slice of size 5 >>> From aleaxit at yahoo.com Mon Apr 17 22:14:18 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 17 Apr 2006 19:14:18 -0700 Subject: Why new Python 2.5 feature "class C()" return old-style class ? References: <1144752553.305591.88050@j33g2000cwa.googlegroups.com> <1144756774.177225.311120@z34g2000cwc.googlegroups.com> <443ba5a9$0$14281$626a54ce@news.free.fr> <1144763398.243329.231380@g10g2000cwb.googlegroups.com> <443bbdbe$0$15517$626a54ce@news.free.fr> <443c22d1$0$11341$636a55ce@news.free.fr> <1hdwol0.luxoeathwi1cN%aleaxit@yahoo.com> Message-ID: <1hdyazp.1afc5rlwzjyolN%aleaxit@yahoo.com> Aahz wrote: > In article <1hdwol0.luxoeathwi1cN%aleaxit at yahoo.com>, > Alex Martelli wrote: > >Aahz wrote: > >> > >> Method resolution order is the primary up-front difference, but > >> introspective code can also have problems. > > > >The crucial difference between the old-style classes and the new ones > >is about how Python lookups special methods. > > Right. Thanks! I don't actually use new-style classes much myself, so > I forgot about that one. (And I needed it for the draft that's due > today...) Glad to have been of help, then! BTW, I use new-style classes almost exclusively (except when maintaining legacy code, or, up to 2.4, for exceptions)... Alex From cyberco at gmail.com Sun Apr 9 08:06:01 2006 From: cyberco at gmail.com (cyberco) Date: 9 Apr 2006 05:06:01 -0700 Subject: mod_python + apache + winxp => nogo In-Reply-To: <4436E2BE.8060802@sympatico.ca> References: <1144445910.877992.80210@v46g2000cwv.googlegroups.com> <4436E2BE.8060802@sympatico.ca> Message-ID: <1144584361.462089.63170@v46g2000cwv.googlegroups.com> Thanks Jim, I indeed did not look in the mailinglist archive (you have to subscribe for that and Google didn't cache it yet). The problem was indeed the missing .DLL's. After adding them to my 'PATH' variable apache was at least able to start. Unfortunately things still don't work. When I try to load a .py file I get the error: ============== [Sun Apr 09 14:03:46 2006] [error] make_obcallback: could not import mod_python.apache.\n [Sun Apr 09 14:03:46 2006] [error] python_handler: no interpreter callback found. [Sun Apr 09 14:03:46 2006] [error] [client 192.168.2.100] python_handler: Can't get/create interpreter., referer: http://myserver/test/ ============== This seems more like a bug in mod_python. Any suggestions? From aleaxit at yahoo.com Tue Apr 25 23:46:49 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 25 Apr 2006 20:46:49 -0700 Subject: MinGW and Python References: <1145861223.509630.247350@y43g2000cwc.googlegroups.com> <444C79D7.4060007@v.loewis.de> <1145968025.903148.140700@i39g2000cwa.googlegroups.com> <1heca3f.14i9v2akwb61sN%aleaxit@yahoo.com> <1fs3g.75522$dW3.69605@newssvr21.news.prodigy.com> Message-ID: <1hed99c.v7rg17w0nvzrN%aleaxit@yahoo.com> Edward Elliott wrote: > Alex Martelli wrote: > > At the same time, if the 14% slowdown is representative, then it's not > > true that the compiler responsible for it "optimizes as well" as the > > other; indeed, "does not optimize particularly well", under such a > > hypothesis, would be far from a "beyond BS" assertion. > > Maybe someone with access to Windows and some free time could compare > pybench compiled under msvc and mingw. The best way to test the compiler > is to eliminate all other variables. I assume you mean "compare pybench on Python 2.4.3 compiled under" etc. Unfortunately, I suspect the ex-officio gcc defenders will only react by finding yet another quibble (anything to avoid admitting that gcc may not be as good at optimizing as a _Microsoft_ product -- perish the thought!), therefore I'm disinclined to invest my scarce free time in that particular endeavour. Alex From gry at ll.mit.edu Fri Apr 7 10:25:01 2006 From: gry at ll.mit.edu (gry at ll.mit.edu) Date: 7 Apr 2006 07:25:01 -0700 Subject: Characters contain themselves? In-Reply-To: References: Message-ID: <1144419901.071235.158590@g10g2000cwb.googlegroups.com> In fact, not just characters, but strings contain themselves: >>> 'abc' in 'abc' True This is a very nice(i.e. clear and concise) shortcut for: >>> 'the rain in spain stays mainly'.find('rain') != -1 True Which I always found contorted and awkward. Could you be a bit more concrete about your complaint? -- George [Thanks, I did enjoy looking up the Axiom of Foundation!] From kruhftREMOVE at gmail.com Mon Apr 17 14:16:55 2006 From: kruhftREMOVE at gmail.com (Burton Samograd) Date: 17 Apr 2006 12:16:55 -0600 Subject: C FFI: easy conversion from list to argv? Message-ID: <87vet8awyw.fsf@gmail.com> Hi, I'm trying to update the fuse python bindings to my app and I was curious if there were any C utility functions that would turn a sys.argv into a C style argv array, or am I going to have to write those myself? Thanks. -- burton samograd kruhft .at. gmail kruhft.blogspot.com www.myspace.com/kruhft metashell.blogspot.com From rpdooling at gmail.com Thu Apr 27 11:16:23 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 27 Apr 2006 08:16:23 -0700 Subject: finding IP address of computer In-Reply-To: <1146150198.737288.37640@i40g2000cwc.googlegroups.com> References: <1146150198.737288.37640@i40g2000cwc.googlegroups.com> Message-ID: <1146150983.359961.7160@i39g2000cwa.googlegroups.com> One way: >>> import socket >>> socket.getaddrinfo(socket.gethostname(), None)[0][4][0] It was the first google hit From fname.sname.lname at gmailCUTMECUT.com Tue Apr 25 17:16:28 2006 From: fname.sname.lname at gmailCUTMECUT.com (Jakub Piotr Nowak) Date: Tue, 25 Apr 2006 21:16:28 +0000 (UTC) Subject: cgi subprocess, cannot get output Message-ID: Hello, In the following cgi program, I cannot get subprocess output. I print the header, flush stdout to prepare it to new content, but variable 'o' is always empty. Could somebody help me with that? def main(): print "Content-type: text/html\n\n" sys.stdout.flush() if form.has_key('sentence'): input = form['sentence'].value o = Popen(['./tinki', input], stdout=PIPE).communicate()[0] result = cgi.escape(o) results['xmlfile'] = result results['sentence'] = input content['output'] = (output % results) print template % content Best regards, -- Jakub P. Nowak From evenprimes at gmail.com Fri Apr 28 09:06:24 2006 From: evenprimes at gmail.com (Chris Cioffi) Date: Fri, 28 Apr 2006 09:06:24 -0400 Subject: Pyrex installation on windows XP: step-by-step guide In-Reply-To: <1146211615.763049.320230@e56g2000cwe.googlegroups.com> References: <1145449777.731155.181600@i40g2000cwc.googlegroups.com> <1146076193.605314.70200@g10g2000cwb.googlegroups.com> <1146164100.552822.280630@j33g2000cwa.googlegroups.com> <1146206258.782000.295980@g10g2000cwb.googlegroups.com> <1146211615.763049.320230@e56g2000cwe.googlegroups.com> Message-ID: On 28 Apr 2006 01:06:55 -0700, Julien Fiore wrote: > > I added "step A.5" to the guide and published it on the Python wiki, so > that anyone can update it easily: > http://wiki.python.org/moin/PyrexOnWindows > > -- > http://mail.python.org/mailman/listinfo/python-list > Thanks to Julien and everyone who's helping on this! I've tried to play around with Pyrex several months ago and didn't have the time/knowledge to figure out why things weren't working. Chris -- "A little government and a little luck are necessary in life, but only a fool trusts either of them." -- P. J. O'Rourke -------------- next part -------------- An HTML attachment was scrubbed... URL: From steven.bethard at gmail.com Sat Apr 29 20:09:24 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 29 Apr 2006 18:09:24 -0600 Subject: best way to determine sequence ordering? In-Reply-To: References: <70q4g.2006$No6.43783@news.tufts.edu> <1146259620.636600.119710@u72g2000cwu.googlegroups.com> <1146315935.017018.65580@u72g2000cwu.googlegroups.com> <2_idnXXyMIjKbc7ZnZ2dneKdnZydnZ2d@comcast.com> Message-ID: Edward Elliott wrote: > Remember kids: > 1. Numbers can show anything > 2. Know your data set > 3. Premature optimizations are evil Amen. =) STeVe From first180 at gmail.com Thu Apr 13 03:16:23 2006 From: first180 at gmail.com (Jay) Date: 13 Apr 2006 00:16:23 -0700 Subject: base64 References: <1144865224.094993.149200@u72g2000cwu.googlegroups.com> <443d6a0d@news.eftel.com> <443d740c$1@news.eftel.com> Message-ID: <1144912583.203735.124660@i39g2000cwa.googlegroups.com> I don't know whether it is right yet but it dues what I wanted it to do now so thank you all, Oh and sorry for my bad grammar. One last thing though is that I would like to be able to split the string up into lines of 89 carictors, I have lookd through the split methods and all I can find is splitting up words and splitting at a pacific caricature, I can not see how you split after a number of caricatures .......................START...................... from Tkinter import * from base64 import * ##################################################################### ##################################################################### # Module: Base64 Encoder / Decoder.py # Author: Jay Dee # Date: 08/04/2006 # Version: Draft 0.1 # Coments: A Base64 Encoder / Decoder for converting files into Base64 strings ##################################################################### ##################################################################### class App: def __init__(self, root): root.title("Base64 Encoder / Decoder") ##################################################################### # Menu Bar ##################################################################### self.menubar = Menu(root) # create a pulldown menu, and add it to the menu bar self.filemenu = Menu(self.menubar, tearoff=0) self.filemenu.add_command(label="Display!", command=self.Display) self.filemenu.add_separator() self.filemenu.add_command(label="Quit!", command=root.quit) self.menubar.add_cascade(label="File", menu=self.filemenu) # display the menu root.config(menu=self.menubar) ##################################################################### # Display B64 Text ##################################################################### # File Input self.FileInputFrame = Frame(root) self.FileInputFrame.pack(side=TOP, fill=X) self.FileInputLine = Entry(self.FileInputFrame, bg="white", width=70) self.FileInputLine.pack(side=LEFT, fill=X, expand=1) # Display Area self.DisplayFrame = Frame(root) self.DisplayFrame.pack(side=TOP, fill=BOTH, expand=1) self.DisplayText = Text(self.DisplayFrame, bg="lightblue", width=95, height=40) self.DisplayText.pack(side=LEFT, fill=BOTH, expand=1) root.bind("",self.Encode) def Encode(self,event): ''' Take's the file name from (self.FileInputLine), opens file, converts it to base64 then desplays it in (self.DisplayText) ''' self.DisplayText.delete(1.0,END) info = self.FileInputLine.get() if info == "": self.DisplayText.insert(END, "...Please enter file...") else: try: file = open(info,"rb") try: Data = file.read() Encode = b64encode(Data) Encode = Encode.split() self.DisplayText.insert(END, Encode) except: self.DisplayText.insert(END, "...Data Erra...") except: self.DisplayText.insert(END, "...No Sutch File...") def Display(self): ''' Take's the string from (self.DisplayText), Creats a topleval frame and displays the Data as an image,if that fales it displays it as text. ''' info = self.DisplayText.get(1.0,END) # Display as Image try: self.DisplayImage = Toplevel() self.InfoDisplay = PhotoImage(data=info) PhotoSize = [self.InfoDisplay.width(),self.InfoDisplay.height()] self.DisplayImageCanvas = Canvas( self.DisplayImage, width=150, height=PhotoSize[1] + 15) self.DisplayImageCanvas.pack(fill=BOTH, expand=1) self.InfoDisplay2 = self.DisplayImageCanvas.create_image( PhotoSize[0] / 2 + 10, PhotoSize[1] / 2 + 10, image=self.InfoDisplay) self.InfoDisplay2 = self.DisplayImageCanvas # Display as Text except: self.DisplayBase64Text = Text( self.DisplayImage, width=70, height=30) self.DisplayBase64Text.pack(fill=BOTH, expand=1) Decode = b64decode(info) self.DisplayImageText.insert(END, Decode) root = Tk() app = App(root) root.mainloop() From pmartin at snakecard.com Tue Apr 4 21:40:44 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Tue, 04 Apr 2006 20:40:44 -0500 Subject: Python Decompilers? References: <1144194130.731253.170930@t31g2000cwb.googlegroups.com> Message-ID: I needed a laugh: funny but why ? Felipe Almeida Lessa wrote: > Em Ter, 2006-04-04 ?s 16:42 -0700, flamesrock escreveu: >> Hi, > > Hi > >> Are there any good decompilers for python? > > Yes > >> -Thanks > > You're welcome =) > From rpdooling at gmail.com Mon Apr 10 02:50:00 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 9 Apr 2006 23:50:00 -0700 Subject: "Locate" command in Python In-Reply-To: <5Fj_f.2567$Es3.1608@newsread3.news.atl.earthlink.net> References: <1144633799.467327.15450@i39g2000cwa.googlegroups.com> <5Fj_f.2567$Es3.1608@newsread3.news.atl.earthlink.net> Message-ID: <1144651800.278586.124560@e56g2000cwe.googlegroups.com> How about one of these that works on Windows XP? I know there's no files.cache, but I wonder if your script could be combined with another function that would generate a list of paths on a Windows XP machine. Anyway, thanks for the script. From sjuranic at gmail.com Tue Apr 4 17:03:40 2006 From: sjuranic at gmail.com (Steve Juranich) Date: Tue, 04 Apr 2006 14:03:40 -0700 Subject: Strange problem when running python code References: <1144175959.412184.187110@g10g2000cwb.googlegroups.com> Message-ID: Roy Smith wrote: > ishtar2020 wrote: >>I've been writing my very first application in Python and everything is >>running smoothly, except for a strange problem that pops up every once >>in a while. I'm sure is the kind >>of newbie thing every seasoned programmer knows. > > Nobody here has a crystal ball. Please post your code, tell us what > changes you made, and cut-and-paste the entire error message and the > associated stack trace. Speak for yourself, Mr. I-Have-No-Crystal-Ball. Besides, any lummox knows that crystal balls are for seeing the future, not for mind-reading. No, to do proper mind reading you need youself a pointy hat and (preferably) a deck of cards. Sorry, weird day at work. Had to vent. -- Steve Juranich Tucson, AZ USA From fredrik at pythonware.com Sun Apr 2 01:00:20 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 2 Apr 2006 08:00:20 +0200 Subject: Site err? - modpython - django? References: <442ED1E7.6010003@zomething.com> Message-ID: "EP" wrote: > i am gettng slow response from thssite en wonder if problem with gil? or > django bug. is this coded in modpython and to many instances? i need > to select web teknology en maybe python en zope is too old to handle > high volume of download objs. what cas problem? thks for your help. not sure what you're really saying here, but feeding downloads through mod_python is not a very efficient thing to do (no matter what frame- work you're using). the following page contains some more info: http://www.jacobian.org/2005/dec/12/django-performance-tips/ (alse see the comments) From neurogasm at gmail.com Mon Apr 17 19:25:41 2006 From: neurogasm at gmail.com (Kun) Date: Mon, 17 Apr 2006 19:25:41 -0400 Subject: scanning through page and replacing all instances of 00:00:00.00 In-Reply-To: References: Message-ID: skip at pobox.com wrote: > Kun> i have the following python-cgi which extracts data from a mysql > Kun> table, how do i parse the date so that it doesn't display the time > Kun> '00:00:00.00'? > > I have no idea which column in your table is a datetime object, but just > convert it to a date. For example: > > >>> import datetime > >>> dt = datetime.datetime.now() > >>> print dt > 2006-04-17 18:19:38.698925 > >>> print dt.date() > 2006-04-17 > > Skip assuming that my date column is 2, how would i parse out the date? the example you gave is of you parsing out the current time, but how do you parse out a pre-specified time that is extracted via sql? i don't think something like dt.date() works because it doesn't work with a string? correct me if i'm wrong. From ldo at geek-central.gen.new_zealand Mon Apr 10 20:29:54 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 11 Apr 2006 12:29:54 +1200 Subject: python on Mac References: <1144284073.446005.53950@t31g2000cwb.googlegroups.com> <1hdc51n.1qgtjne1mduk7gN%aleaxit@yahoo.com> <1144291572.151260.56700@j33g2000cwa.googlegroups.com> <1144293362.889863.146200@i39g2000cwa.googlegroups.com> <1hdl37l.1mvgfva12tsntwN%aleaxit@yahoo.com> Message-ID: In article <1hdl37l.1mvgfva12tsntwN%aleaxit at yahoo.com>, aleaxit at yahoo.com (Alex Martelli) wrote: >Lawrence D'Oliveiro wrote: > >> In article <1144293362.889863.146200 at i39g2000cwa.googlegroups.com>, >> "pierreth" wrote: >> >> >You removed /usr/bin/python! This is a really bad idea >> >> Is there any way to put it back, short of a full system reinstall? > >There's a free 3rd party tool known as Pacifist to extract part-installs >from Apple's system DVDs... So there's no simple equivalent of "rpm --replace-pkgs"? From sushant.sirsikar at gmail.com Wed Apr 5 01:08:35 2006 From: sushant.sirsikar at gmail.com (sushant.sirsikar at gmail.com) Date: 4 Apr 2006 22:08:35 -0700 Subject: Extending Python Message-ID: <1144213715.479622.51740@j33g2000cwa.googlegroups.com> Hi All. We can extend the functionality of python using C,C++.I want to know what are the other lang that we can use to extend the functionality of Python? Bye From iainking at gmail.com Wed Apr 12 04:26:03 2006 From: iainking at gmail.com (Iain King) Date: 12 Apr 2006 01:26:03 -0700 Subject: UDP max datagram size Message-ID: <1144830363.827740.198340@z34g2000cwc.googlegroups.com> Hi. I've been looking everywhere for this and can't find it, apologies if I'm being obtuse: How do I set the max datagram packet size? I'm using the socket module. It seem like it's hardcoded at 255, but I need it to be larger. Iain From bretthall at gmail.com Thu Apr 27 12:57:01 2006 From: bretthall at gmail.com (bretthall at gmail.com) Date: 27 Apr 2006 09:57:01 -0700 Subject: PyEval_EvalFrame Message-ID: <1146157021.547361.185710@y43g2000cwc.googlegroups.com> I see a C/python program that we're using spending a lot of time in this function, far more than we think it should. What is it? Thanks in advance! There seems to be nothing (but a bunch of stack traces) when I google this. Brett From martin at v.loewis.de Thu Apr 27 01:37:01 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 27 Apr 2006 07:37:01 +0200 Subject: not quite 1252 In-Reply-To: <444fe3e2$1@usenet.zapto.org> References: <444f5e6b$1@usenet.zapto.org> <444FAA49.1000909@v.loewis.de> <444fe3e2$1@usenet.zapto.org> Message-ID: <4450587D.6060103@v.loewis.de> Anton Vredegoor wrote: >> Not sure I understand the question. If you process data in cp1252, >> then \x94 and \x94 are legal characters, and the Python codec should >> support them just fine. > > Tell that to the guys from open-office. Ok, I'll rephrase: Can you please explain your problem again, in different words? I thought you are trying to export data *from* open-office, and your message seems to suggest (without actually saying so) that the document contains \x93 and \x94 (you said "there are still characters in it like \93 or \94"). So if that is the case: What is the problem then? If you interpret the document as cp1252, and it contains \x93 and \x94, what is it that you don't like about that? In yet other words: what actions are you performing, what are the results you expect to get, and what are the results that you actually get? Regards, Martin From cygnus at cprogrammer.org Tue Apr 18 00:22:20 2006 From: cygnus at cprogrammer.org (Jonathan Daugherty) Date: Mon, 17 Apr 2006 21:22:20 -0700 Subject: Missing interfaces in Python... In-Reply-To: <1hdygys.mtpncg10evnveN%aleaxit@yahoo.com> References: <1145306373.781129.305840@z34g2000cwc.googlegroups.com> <20060417210541.GV7561@vulcan.cprogrammer.org> <20060417212336.GW7561@vulcan.cprogrammer.org> <1hdybsi.1g0xk7pmm2m2tN%aleaxit@yahoo.com> <1hdygys.mtpncg10evnveN%aleaxit@yahoo.com> Message-ID: <20060418042220.GD7561@vulcan.cprogrammer.org> # My real-world experience with Java is very dated -- nowadays, I'm # told, the NEED to cast is vastly reduced by Java 1.5's "generics" (I # haven't yet written one line of Java 1.5, not even for "play" # purposes, much less "real world" ones;-). Interesting; thanks. # So much for "compiler enforcement", hm?-) Yes, indeed. :) -- Jonathan Daugherty http://www.parsed.org From Serge.Orlov at gmail.com Fri Apr 28 08:48:18 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 28 Apr 2006 05:48:18 -0700 Subject: not quite 1252 In-Reply-To: <4450e193$1@usenet.zapto.org> References: <444f5e6b$1@usenet.zapto.org> <444f8781@usenet.zapto.org> <44507F68.7080804@lexicon.net> <4450e193$1@usenet.zapto.org> Message-ID: <1146228498.056632.168360@j73g2000cwa.googlegroups.com> Anton Vredegoor wrote: > In fact there are a lot of printable things that haven't got a text > attribute, for example some items with tag (xxxx)s. In my sample file I see , is that you're talking about? Since my file is small I can say for sure this tag represents two space characters. From bdesth.quelquechose at free.quelquepart.fr Tue Apr 25 21:04:52 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 26 Apr 2006 03:04:52 +0200 Subject: Looking for resources for making the jump from Java to Python easier and more productive In-Reply-To: <444def12$0$14288$626a54ce@news.free.fr> References: <1145691651.385835.298600@u72g2000cwu.googlegroups.com> <444cb3e1$0$21091$626a54ce@news.free.fr> <444def12$0$14288$626a54ce@news.free.fr> Message-ID: <444e98b9$0$27280$626a54ce@news.free.fr> bruno at modulix a ?crit : > Lawrence D'Oliveiro wrote: > >>In article <444cb3e1$0$21091$626a54ce at news.free.fr>, >> bruno at modulix wrote: >> >> >> >>>Lawrence D'Oliveiro wrote: >>> > > (snip) > >>>>I suppose this is an instance of the more general rule: "using OO when >>>>you don't have to". >>> >>>Lawrence, I'm afraid you're confusing OO with "statically-typed >>>class-based". FWIW, dynamic typing is part of OO since Smalltalk. >> >> >>I wasn't talking about dynamic typing, I was talking about subclassing, >>which is very much a part of OO. > > > What you wrote implies (well, at least I understand it that way) ... but I may just have it totally wrong !-) From dave at waveform.plus.com Mon Apr 24 21:52:13 2006 From: dave at waveform.plus.com (Dave Hughes) Date: 25 Apr 2006 01:52:13 GMT Subject: Coming from delphi - looking for an IDE - willing to spend money References: <1145925252.766752.86640@e56g2000cwe.googlegroups.com> Message-ID: <444d80cd$0$2546$ed2619ec@ptn-nntp-reader02.plus.net> Just call me James wrote: > Hi, > > Coming away from the luxury of the delphi IDE has been something of a > shock. > > As a consequence I've become aware that maybe I need to spend some > money on a python IDE. > > As a beginner I reckon integrated debugging would be helpful. > > Does anyone have any advice or suggestions? So far I've glanced at > Komodo, but as a beginner I'm not in a positon to evaluate it. > > thanks for exprienced advice, > > Greg I sympathize entirely (I've been a Delphi user since v2 and have yet to find an equally competent IDE for just about any language). Here's the list of IDEs I went through in my transition from Delphi to Python (I started off hacking around with Python on my Linux box with vim, but quickly went searching for something a bit more comprehensive and specific to the language): Boa Constructor http://boa-constructor.sourceforge.net/ Heavy-weight IDE designed to be a sort of Delphi-for-Python. Includes integrated debugging, visual form designer and property inspector (uses wxWindows as its GUI framework) and a pretty cool editor (based on the Scintilla component). It's still a bit flaky in some places, but it's certainly usable. That said, my machine isn't exactly fast: I eventually got fed up with the slow speed and went hunting for something a bit quicker... Stani's Python Editor (SPE) http://pythonide.stani.be/ Heavy-weight editor (based on Scintilla IIRC) with Blender integration. Uses wxGlade or XRCed as visual form designers. Didn't try this one for long; for some reason the interface just didn't "feel" right. Then again, it's open-source and many swear by it so you may as well give it a shot. TruStudio http://www.xored.com/trustudio Heavy-weight IDE (based on Eclipse). Gave it a whirl but as you can imagine, if my machine was slow with Boa Constructor, the Java-based Eclipse was just glacial... Urgh. PyScripter http://mmm-experts.com/Products.aspx?ProductId=4 Light-weight IDE with integrated debugging (no visual form designer). I was interested in this as it's written in Delphi. Hence, it's pretty damned fast, small, and serves as an interesting example of integrating the Python interpreter in Delphi applications (something I was interested in doing, though I haven't had an actual need to do so yet). Unfortunately, the editor component used is SynEdit (which, being a Delphi user I'm guessing you've probably heard of and/or used). SynEdit's a great component for small scale editing, but it's just got too many bugs when dealing with large files or long editing sessions, and lacks some of Scintilla's neat features like code-folding (given that the source for PyScripter is available it might be interesting to try replacing the SynEdit editor with Scintilla since there's a Delphi interface for Scintilla available ... although I suspect it'd be a pretty big job). Notepad2 http://www.flos-freeware.ch/notepad2.html Light-weight editor (based on Scintilla). Little more than a notepad replacement (no integrated debugger or visual stuff) with those features you always wanted in notepad (support for UNIX line breaks, syntax highlighting, etc). At this point I realized I'd gone from heavy-weight full-blown IDEs with integrated debugging, to heavy-weight editors, to light-weight editors, and back to using stack traces and the odd print statement for debugging. However, I also found (to my surprise) that I'd got comfortable enough with Python that not having integrated debugging no longer bothered me. I realized what I was really searching for was a small, fast, powerful editor... And so it was that after 2 or 3 weeks of hunting for the best IDE for me, I wound up right back where I started: vim :-) Still, I consider the journey to have been worth it (e.g. the integrated debugger in Boa helped me learn Python that much quicker by making it easy to spot my beginners mistakes). You might want to check out eric3 as well. I haven't tried it but it's another one some people swear by: http://www.die-offenbachs.de/detlev/eric3.html Good luck! Dave. -- From deets at nospam.web.de Wed Apr 12 12:53:17 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 12 Apr 2006 18:53:17 +0200 Subject: drag and drop to icon References: Message-ID: <4a4plvFreg7fU1@uni-berlin.de> Eric S. Johansson wrote: > I have a small problem that may be best solved by dragging and dropping > a mail message to an icon. But I'm honestly not sure what the data will > look like from different e-mail clients. Since most of my programming > experience is something a user rarely sees, I'm not even sure where to > start creating a test case. > > I would appreciate pointers to documentation (and yes I did Google > before asking) how to create an icon on a desktop (Macintosh and > Windows) and have that icon act on something which has been dropped on it. Drag'n'Drop is highly OS-dependand and clearly out of scope for standard-out-of-the-box python. If you are on macintosh, pyobjc and http://www.cocoadev.com/index.pl?DragAndDrop will certainly help. HTH, Diez From michele.simionato at gmail.com Tue Apr 11 05:53:29 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 11 Apr 2006 02:53:29 -0700 Subject: updated pre-PEP: The create statement In-Reply-To: References: <443a9c60$1_1@news.bluewin.ch> Message-ID: <1144741273.559724.216790@t31g2000cwb.googlegroups.com> Steven Bethard wrote: > Azolex wrote: > > Steven Bethard wrote: > >> and named, nested hierarchies like XML documents could be created > >> like:: > >> > >> create ETobject html: > >> "This statement would generate an ElementTree object" > >> > >> create ETobject head: > >> "generate the head" > >> ... > >> > >> create ETobject body: > >> "generate the body" > >> ... > > > > I think this is is a most important eventual use-case, and would like to > > see it better worked out - or else declared outside the scope of the > > proposed statement. As far as I can see, this does not cut it, since xml > > and html allow /sequencial repetition/ of tags and the results of the > > statement suites are passed as unordered namespaces/dicts. > > Good point. The code above would only work if you didn't care about the > order of elements. I'm half inclined to pull the example, but the > original was due to Michele Simionato, and I haven't quite convinced > myself yet that you couldn't hack it to have ETObject append to an > internal list somehow to keep order. Michele? Did you have a plan for > how this would work? > > STeVe Honestly, I don't want the 'create' statement to be used to write XML in Python. I think this would be a misuse of the functionality. OTOH I believe that the main selling point for the 'create' statements is that it make it easy to implement declarative minilanguages, so I have given an XML example. To solve the ordering issue one should change the internals of Python, in such a way to pass an ordered dict to the 'create' statement instead of an usual dictionary. I think the main use case for 'create' would be in things like object-relational-mappers, not in XML generation. You can pull out the example in the official PEP, if you like. It was just matter for thought. Michele Simionato From johnjsal at NOSPAMgmail.com Wed Apr 12 11:23:16 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 12 Apr 2006 15:23:16 GMT Subject: just one more question about the python challenge Message-ID: Sorry to post here about this again, but the hint forums are dead, and the hints that are already there are absolutely no help (mostly it's just people saying they are stuck, then responding to themselves saying the figured it out! not to mention that most of the hints require getting past a certain point in the puzzle before they make sense, and i'm just clueless). Anyway, I'm on level 12 and I not only don't know what to do, but I just don't care at this point to work with images anymore. I'd still like to read a description of what to do, if one exists somewhere (can't find one at all, though), but at this point I'd be happy with the next URL so I can just move on. I've been stagnating for a few days and I need to use Python again! :) From felipe.lessa at gmail.com Fri Apr 14 11:40:23 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Fri, 14 Apr 2006 12:40:23 -0300 Subject: PEP 359: The "make" Statement In-Reply-To: References: Message-ID: <1145029223.7921.9.camel@kenshin.CASA> Em Sex, 2006-04-14 ?s 09:31 -0600, Steven Bethard escreveu: > [1] Here's the code I used to test it. > > >>> def make(callable, name, args, block_string): > ... try: > ... make_dict = callable.__make_dict__ > ... except AttributeError: > ... make_dict = dict > ... block_dict = make_dict() > ... exec block_string in block_dict > ... return callable(name, args, block_dict) > ... > >>> (snip) I think it would be nice not to put those ">>>" and "..." to make copy and paste easier. Okay, I know we can do "".join(line[4:] for line in text), but that's just my humble opinion. -- Felipe. From fredrik at pythonware.com Wed Apr 26 07:08:32 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 26 Apr 2006 13:08:32 +0200 Subject: Nested Lists Assignment Problem References: <1146039200.264901.317920@j33g2000cwa.googlegroups.com> <1146041466.290523.15010@v46g2000cwv.googlegroups.com> Message-ID: "Licheng Fang" wrote: > But I still wonder why a nested assignment "a = [[0]*3]*3" generates 3 > references to the same list, while the commands below apparently do > not. that's because they're replacing a list item, rather than modifying it. >>>> a = [0] * 2 >>>> a > [0, 0] <- now you have two references to the same integer. >>>> a[0] = 1 <- now you've *replaced* the first integer with another integer. >>>> a > [1, 0] if you do the same thing with lists, it behaves in exactly the same way: >>> a = [[0]*3]*3 >>> a [[0, 0, 0], [0, 0, 0], [0, 0, 0]] <-- three references to the same list >>> a[0] = [1, 2, 3] <-- replace the first list >>> a [[1, 2, 3], [0, 0, 0], [0, 0, 0]] however, if you modify the *shared* object, the modification will of course be visible everywhere that object is used: >>> a[1][0] = "hello" <-- modified the first item in the shared list >>> a [[1, 2, 3], ['hello', 0, 0], ['hello', 0, 0]] From nnorwitz at gmail.com Wed Apr 5 02:44:16 2006 From: nnorwitz at gmail.com (nnorwitz at gmail.com) Date: 4 Apr 2006 23:44:16 -0700 Subject: IMPORTANT 2.5 API changes for C Extension Modules Message-ID: <1144219456.668201.201620@g10g2000cwb.googlegroups.com> If you don't write or otherwise maintain Python Extension Modules written in C (or C++), you can stop reading. Python 2.5 alpha 1 is in the process of being released later today. There are important changes that are in 2.5 to support 64-bit systems. These changes can cause Python to crash if your module is not upgraded to support the changes. Python was changed internally to use 64-bit values on 64-bit machines for indices. If you've got a machine with more than 16 GB of RAM, it would be great if you can test Python with large (> 2GB) strings and other sequences. For more details about the Python 2.5 schedule: http://www.python.org/dev/peps/pep-0356/ For more details about the 64-bit change: http://www.python.org/dev/peps/pep-0353/ How to fix your module: http://www.python.org/dev/peps/pep-0353/#conversion-guidelines The effbot wrote a program to check your code and find potential problems. http://svn.effbot.python-hosting.com/stuff/sandbox/python/ssizecheck.py Please test and upgrade your extension modules! Cheers, n From marcelo_urbano at hotmail.com Wed Apr 12 19:44:11 2006 From: marcelo_urbano at hotmail.com (Marcelo Urbano Lima) Date: Wed, 12 Apr 2006 20:44:11 -0300 Subject: object instance after if isalpha() Message-ID: Hi I'm still learning python and I've been loving it, but, that's not the reason I'm writing. I'm trying to create an object only if a variable is alpha and see what I get. $ cat 1.py class abc: def __init__(self): name='marcelo' a='STRING' print a.isalpha() if a.isalpha(): x=abc() print 'was x created?:', x,'\n' print x.name $ python 1.py True was x created?: <__main__.abc instance at 0x186b9e6c> Traceback (most recent call last): File "1.py", line 12, in ? print x.name AttributeError: abc instance has no attribute 'name' Why? (I really think I'm doing something stupid but could not see) btw, it's python 2.4.1 for cygwin. I'd really appreciate your help. Thanks _________________________________________________________________ Seja um dos primeiros a testar o Windows Live Messenger Beta a gera??o do seu MSN Messenger. http://imagine-msn.com/minisites/messenger/default.aspx?locale=pt-br From micklee74 at hotmail.com Thu Apr 27 06:35:45 2006 From: micklee74 at hotmail.com (micklee74 at hotmail.com) Date: 27 Apr 2006 03:35:45 -0700 Subject: can anyone advise me In-Reply-To: References: <1146131326.328919.285430@t31g2000cwb.googlegroups.com> Message-ID: <1146134145.220414.111140@e56g2000cwe.googlegroups.com> Dan Sommers wrote: > On 27 Apr 2006 02:48:46 -0700, > micklee74 at hotmail.com wrote: > > > why the output of this code : > > x = 0 > > while x < 10: > > z = 0 > > print x > > x = x + 1 > > while z < x: > > print z, > > z = z + 1 > > > is > > > 0 > > Okay, that was x, from the print statement inside the x-loop. > > > 0 1 > > And that's z, from the print statement inside the z-loop. z is 0, and > then when z is 1, it's not less than x, so we're done printing z's. > > And then we get the next x. > > > 0 1 2 > > And two more z's, 0 and 1, since x is now 2. > > And another x. > > Since this might be homework, I'll stop at a hint: you need to think > about when you want each printed line to end, and make sure that you > tell python to end it there. > > Regards, > Dan > > -- > Dan Sommers > > "I wish people would die in alphabetical order." -- My wife, the genealogist thanks..solved...just removed the print x.. From tl_news at nexgo.de Sat Apr 1 13:13:10 2006 From: tl_news at nexgo.de (Tino Lange) Date: Sat, 01 Apr 2006 20:13:10 +0200 Subject: datetime, tzinfo ... strange conversion? Message-ID: Hi! I'm surprised about the following code, maybe you can give me a hint whether that's bug or feature? I'm just trying to convert local time to GMT and one method gives a strange result: ###################### > #! /usr/bin/env python > > import datetime, pytz > > _tz_utc = pytz.timezone("UTC") > _tz_germany = pytz.timezone("Europe/Berlin") > > local = datetime.datetime.now(_tz_germany) > print "Local: ", local > > gmt = local.astimezone(_tz_utc) > print "GMT (1)", gmt > > gmt = datetime.datetime.combine(local.date(), local.timetz()).astimezone(_tz_utc) > print "GMT (2)", gmt > > gmt = datetime.datetime.combine(datetime.date.today(), datetime.time(local.hour, local.minute, local.second, local.microsecond, _tz_germany)).astimezone(_tz_utc) > print "GMT (3)", gmt > > gmt = datetime.datetime.combine(datetime.date.today(), datetime.time(local.hour, local.minute, local.second, local.microsecond, local.tzinfo)).astimezone(_tz_utc) > print "GMT (4)", gmt > > print "_tz_germany:", _tz_germany, "(id: %s)" % id(_tz_germany), ", local.tzinfo:", local.tzinfo, "(id: %s)" % id(local.tzinfo) ###################### Result: > tlange at tinux:~/is.work/Scripts$ ./timeconv.py > Local: 2006-04-01 20:09:26.469445+02:00 > GMT (1) 2006-04-01 18:09:26.469445+00:00 > GMT (2) 2006-04-01 18:09:26.469445+00:00 > GMT (3) 2006-04-01 19:09:26.469445+00:00 > GMT (4) 2006-04-01 18:09:26.469445+00:00 > _tz_germany: Europe/Berlin (id: -1212869684) , local.tzinfo: Europe/Berlin (id: -1212868756) --> Why is GMT (3) wrong? Cheers, Tino From alexci at web.de Mon Apr 17 14:57:35 2006 From: alexci at web.de (Aleksandar Cikota) Date: Mon, 17 Apr 2006 20:57:35 +0200 Subject: Threating problem Message-ID: Hi all, I have a problem with threading. The following part should be running in a main programm all the time, but so that the main programm also works (like 2 seperate programms, but in one) How to integrate the part in the main programm? Code: import win32com.client import time import os import threading Document = win32com.client.Dispatch('MaxIm.Document') Application = win32com.client.Dispatch('MaxIm.Application') p = win32com.client.dynamic.Dispatch('PinPoint.Plate') class TestThread ( threading.Thread ): path_to_watch = "F:/Images/VRT/" before = dict ([(f, None) for f in os.listdir (path_to_watch)]) while 1: time.sleep(2) after2 = dict ([(f, None) for f in os.listdir (path_to_watch)]) added = [f for f in after2 if not f in before] if added: name= ' ,'.join (added) if str(name[-3:])=='fit': Document.OpenFile('F:/Images/VRT/'+name) Document.SaveFile('F:/Images/VRT/'+ str(name[0:-4])+'.jpg', 6, 1024,2) Application.CloseAll() try: p.AttachFITS('F:/Images/VRT/'+name) p.ArcsecPerPixelHoriz = -1.7 p.ArcsecPerPixelVert = -1.7 p.MaxMatchResidual = 1.0 p.FitOrder = 3 p.CentroidAlgorithm = 0 p.RightAscension = p.TargetRightAscension p.Declination = p.TargetDeclination p.Catalog = 0 # GSC p.CatalogPath = 'F:/' p.ProjectionType = 1 # p.Solve() p.DetachFITS() pRA = p.RightAscension pDec = p.Declination print pRA print pDec except: p.DetachFITS() print 'Error' before = after2 TestThread().start() For your prompt reply, I say thank you in advance. Best regards, Aleksandar From n.estner at gmx.de Sat Apr 29 19:52:50 2006 From: n.estner at gmx.de (nikie) Date: 29 Apr 2006 16:52:50 -0700 Subject: best way to determine sequence ordering? References: <70q4g.2006$No6.43783@news.tufts.edu> <1146259620.636600.119710@u72g2000cwu.googlegroups.com> <1146315935.017018.65580@u72g2000cwu.googlegroups.com> <2_idnXXyMIjKbc7ZnZ2dneKdnZydnZ2d@comcast.com> Message-ID: <1146354770.313981.324600@u72g2000cwu.googlegroups.com> Steven Bethard wrote: > nikie wrote: > > Steven Bethard wrote: > > > >> nikie wrote: > >>> Steven Bethard wrote: > >>> > >>>> John Salerno wrote: > >>>>> If I want to make a list of four items, e.g. L = ['C', 'A', 'D', 'B'], > >>>>> and then figure out if a certain element precedes another element, what > >>>>> would be the best way to do that? > >>>>> > >>>>> Looking at the built-in list functions, I thought I could do something > >>>>> like: > >>>>> > >>>>> if L.index('A') < L.index('D'): > >>>>> # do some stuff > >>>> This is probably a pretty reasonable approach as long as you're not too > >>>> worried about efficiency. It scans the list twice though, so if you > >>>> start doing this with really big lists, it might be better to do > >>>> something like: > >>> On average, it'll only have go through half the list twice, as it can > >>> break as soon as it finds the item it searches for. Don't think you can > >>> get any more efficient than that. > >> Sure you can: > >> > >> a_index = None > >> d_index = None > >> for i, item in enumerate(L): > >> if item == 'A': > >> a_index = i > >> elif item == 'D': > >> d_index = i > >> if a_index is not None and d_index is not None: > >> break > >> > >> if a_index < d_index: > >> # do some stuff > >> > >> That goes through exactly the minimum number of elements. But it's > >> probably slower than two .index() calls since .index() is coded in C. > >> But timeit and see if you're interested. > > > > On my PC, calling index twice is 5 times faster. > > > > But let's just pretend for a moment Python code was compiled and > > optimized as well as C code. > > Ok, lets get comparable functions by writing them both in Python: That's changing the subject, and you know that. The OP asked whether using "L.index('A') < L.index('D')" was a good (pythonic, efficient) idea. It is. Maybe it wouldn't be efficient if "List.index" was implemented in python (because, as I have already said in my previous post, looping through an enumerate-object in python is more complex than a simple C-loop), but it is actually implemented in C. Even if you wrote a C function that tried to do all the comparisons in one sweep through the list, I'm willing to bet it won't be faster than the OP's suggestion on the average (at least for moderate-sized lists, otherwise, processing the list in blocks, using the cache more efficiently might be a good idea). That's what this thread was all about. Now, I don't really see what you are trying to say: Are you still trying to convince the OP that he should write a Python function like one of those you suggested, for performance reasons? If not, I must have misunderstood your last posts, and apologize for repeating the obvious ;-) From tjreedy at udel.edu Sat Apr 29 15:38:59 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 29 Apr 2006 15:38:59 -0400 Subject: (was Re: Xah's Edu Corner: Criticism vs Constructive Criticism) References: <1145992903.834316.198370@u72g2000cwu.googlegroups.com><4GM3g.3084$TT.1768@twister.nyroc.rr.com><1146231280.733609.143230@e56g2000cwe.googlegroups.com> <1146276319.504694.218970@v46g2000cwv.googlegroups.com> Message-ID: "Tagore Smith" wrote in message news:1146276319.504694.218970 at v46g2000cwv.googlegroups.com... > The only thing really wrong with Xah's post is that it was crossposted > to several groups. I think the content of repeatedly slandering people as criminals, because of technical disagreements, is even more abusive. tjr From diesch at spamfence.net Fri Apr 28 18:18:30 2006 From: diesch at spamfence.net (Florian Diesch) Date: Sat, 29 Apr 2006 00:18:30 +0200 Subject: Hooking things up in GUI application References: Message-ID: <20060428221833.17E4.1.NOFFLE@dieschf.news.arcor.de> "Ryan Ginstrom" wrote: >> Behalf Of sturlamolden >> If you use PyGTK (it also runs on Windows), you can design >> the GUI with >> GLADE and then use libglade to import the gui as an xml-resource. > > Yes, I've tried something similar with wxGlade. Nice, but it doesn't seem to > remove the most tedious work -- hooking up handlers (although it does help > here, at the cost of some behind-the-scenes magic), and getting data into and > out of GUI widgets. Kiwi looks promising, but it is under heavy development and you have to learn it by examples. Florian -- Emacs hat den weiten Weg von "krank, nur krank" bis "komisch" hinter sich. [David Kastrup in <853bgop2tc.fsf at lola.goethe.zz>] From nobody at 127.0.0.1 Wed Apr 26 00:57:22 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 26 Apr 2006 04:57:22 GMT Subject: MinGW and Python References: <1145861223.509630.247350@y43g2000cwc.googlegroups.com> <444C79D7.4060007@v.loewis.de> <1145968496.649214.100040@i40g2000cwc.googlegroups.com> <1hec9xh.m7rzefh64am3N%aleaxit@yahoo.com> <1hed8xt.158fdh212095ftN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > I believe the single figure is a useful summary. Even the most > sophisticated benchmarks are eventually boiled down to single figures, > as in "so many SPECmarks" etc, because in everyday discourse a scalar is > what you can reasonably discuss. Sure, philosophically speaking it > makes no sense to say that a compiler is better or worse than another at > optimization, without adding a lawyer's brief worth of qualifications ^^^^^^^^^^^^^^ hey is that a shot at me? ;) > each and every time. In real life, it's a useful and practical > temporary simplification, and engineers (as opposed to mathematicians > and philosophers) have a bias towards practical usefulness. I agree for benchmarks in general. It's more this particular benchmark I object to as not being representative. It's like the difference between SPECmark testing various CPU functions and Winstone measuring real-world application performance. If you're a CPU designer counting coup, SPECmark matters. For just about everyone else, Winstone tells you more. And when you're talking about small (less than an order of magnitude) differences in SPECmark, platform/system/application issues becomes the dominant factor in performance. A CPU that's twice as fast won't help my i/o-bound server. >From an engineering standpoint, the pybench number isn't that useful to me. It tells me little about the practical speed of my application on two different python interpreters. That's all I'm saying. No need to sic the philosophers on me (a fate I would not wish on my worst enemy). :) From rtw at freenet.co.uk Fri Apr 14 12:52:53 2006 From: rtw at freenet.co.uk (Rob Williscroft) Date: Fri, 14 Apr 2006 11:52:53 -0500 Subject: PEP 359: The "make" Statement References: Message-ID: Steven Bethard wrote in news:Pfydnbapx4Bi7qPZnZ2dnUVZ_t-dnZ2d at comcast.com in comp.lang.python: > Open Issues > =========== > > Does the ``make`` keyword break too much code? Originally, the make > statement used the keyword ``create`` (a suggestion due to Nick > Coghlan). However, investigations into the standard library [4]_ and > Zope+Plone code [5]_ revealed that ``create`` would break a lot more > code, so ``make`` was adopted as the keyword instead. However, there > are still a few instances where ``make`` would break code. Is there a > better keyword for the statement? > I don't know wether this has been suggested or not, but what about def: def namespace ns: x = 1 def type blah(object): pass def property x: def get(): return ns.x Rob. -- http://www.victim-prime.dsl.pipex.com/ From michele.simionato at gmail.com Fri Apr 7 08:59:31 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 7 Apr 2006 05:59:31 -0700 Subject: OT: job offering in Milan In-Reply-To: References: <1144402806.087904.164860@i39g2000cwa.googlegroups.com> Message-ID: <1144414771.488059.106950@g10g2000cwb.googlegroups.com> Robin Becker wrote: > Michele Simionato wrote: > ...... > > The Company > > StatPro, a leader Company in the field of portfolio analytics for the > > global asset management market, is looking for a Senior Systems/Network > > Engineering Specialist, who is ready for a new challenge. > > > .... > > > real pity, I used to do portfolio analytics for Bita Plus and SBC; minimax risk > curves were just my bag etc etc :). > > My math skills are now so degraded I have difficulty reading about conic > programming using Nesterov's barrier functions etc etc. > > Oh well back to web scraping :( > -- > Robin Becker This position is for a system administrator (we are going to setup a cluster Linux for risk computations) but very likely we will have opening for other positions, for experts in financial computations/risk analysis. So if there is somebody interested, he can write to luca.fittabile at statpro.com. Pretending I am on topic, I will add that most of our sofware is in Python, whereas all the numerical intensive routines are in C++. Michele Simionato From felipe.lessa at gmail.com Mon Apr 3 12:08:42 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Mon, 03 Apr 2006 13:08:42 -0300 Subject: can I get the index number in for x in y loop? In-Reply-To: <1144079271.758144.92070@v46g2000cwv.googlegroups.com> References: <1144078372.411795.21570@i39g2000cwa.googlegroups.com> <1144078792.350510.57870@i39g2000cwa.googlegroups.com> <1144079271.758144.92070@v46g2000cwv.googlegroups.com> Message-ID: <1144080522.8993.3.camel@kenshin.CASA> Em Seg, 2006-04-03 ?s 08:47 -0700, JuHui escreveu: > which one has best performance? Let's see... > a:for i in range(0,len(a)) $ python2.4 -mtimeit -s 'a=[None]*100' 'for i in range(len(a)): j = a[i] ' 100000 loops, best of 3: 17.7 usec per loop $ python2.4 -mtimeit -s 'a=[None]*100' 'for i in xrange(len(a)): j = a[i] ' 100000 loops, best of 3: 16.8 usec per loop > b:for x in a $ python2.4 -mtimeit -s 'a=[None]*100' 'i = 0 for j in a: i += 1 ' 100000 loops, best of 3: 15.7 usec per loop > c:for x,y in enumerate(a) $ python2.4 -mtimeit -s 'a=[None]*100' 'for i, j in enumerate(a): pass ' 100000 loops, best of 3: 12.9 usec per loop Using enumerate is cleaner and faster. HTH, -- Felipe. From pmartin at snakecard.com Tue Apr 25 10:24:00 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Tue, 25 Apr 2006 09:24:00 -0500 Subject: Multiple hierarchie and method overloading References: <1145931851.526941.231680@v46g2000cwv.googlegroups.com> Message-ID: <4iq3g.4020$B42.1410@dukeread05> Thanks, I'll try that. Philippe Ben Cartwright wrote: > Philippe Martin wrote: >> I have something like this: >> >> Class A: >> def A_Func(self, p_param): >> ..... >> Class B: >> def A_Func(self): >> ..... >> >> Class C (A,B): >> A.__init__(self) >> B.__init__(self) >> >> ..... >> >> self.A_Func() #HERE I GET AN EXCEPTION "... takes at least 2 >> arguments (1 >> given). >> >> >> I renamed A_Func(self) to fix that ... but is there a cleaner way around >> ? > > When using multiple inheritence, the order of the base classes matters! > E.g.: > > class A(object): > def f(self): > print 'in A.f()' > class B(object): > def f(self): > print 'in B.f()' > class X(A, B): > pass > class Y(B, A): > pass > > >>> x = X() > >>> x.f() > in A.f() > >>> y = Y() > >>> y.f() > in B.f() > > If you want to call B.f() instead of A.f() for an X instance, you can > either rename B.f() like you've done, or do this: > > >>> B.f(x) > in B.f() > > --Ben From kent at kentsjohnson.com Wed Apr 12 07:35:54 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Wed, 12 Apr 2006 07:35:54 -0400 Subject: datetime: the date of the day one month ago...how? In-Reply-To: <3b246$443cddda$c32e4536$21664@news.flashnewsgroups.com> References: <3b246$443cddda$c32e4536$21664@news.flashnewsgroups.com> Message-ID: <443ce09a$1_3@newspeer2.tds.net> gabor wrote: > hi, > > i'm trying to get the date of the day one month ago. > > for example: > > today = 12.apr.2006 > one-month-ago = 12.mar.2006 dateutil has one implementation of this: http://labix.org/python-dateutil Kent From g.brandl-nospam at gmx.net Tue Apr 4 09:19:26 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Tue, 04 Apr 2006 15:19:26 +0200 Subject: tuple syntax ',' (ending in comma?) In-Reply-To: References: Message-ID: Michael Yanowitz wrote: > Hello: > > I am still relatively new to Python. I am confused by the syntax for > tuples. > I had: > thread.start_new_thread(read_data_thread, (strDataFilename)) > and got back the following error: > > File "scene.py", line 256, in readData > thread.start_new_thread(read_data_thread, (strDataFilename)) > TypeError: 2nd arg must be a tuple > > The way I fixed this error was I added an extra , (comma) to the tuple: > thread.start_new_thread(read_data_thread, (strDataFilename,)) > > I am just confused by the syntax. I am used to a comma meaning that there > should be another parameter after the comma and if no additional parameter > the comma would not be necessary. What would you expect >>> 3 * (5 + 2) to print? Certainly not "(7, 7, 7)", but it would if all expressions in parentheses were tuples. Thus, the comma is necessary to disambiguate and explicitly tell the parser that you mean to construct a tuple. Georg From sschwarzer at sschwarzer.net Fri Apr 14 14:18:18 2006 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Fri, 14 Apr 2006 20:18:18 +0200 Subject: ftp connection and commands (directroy size, etc) In-Reply-To: References: Message-ID: <443FE76A.7050208@sschwarzer.net> Hi Arne On 2006-04-12 18:05, Arne wrote: > I am working on Windows XP and I want to do the following: > > 1. Connecting to a server using ftp > 2. Getting the directory structure and the size of each directory in the > root > 3. Getting the owner of a file > > All these steps I want to do with python. What I already have is: > [...] > Please be so kind and post a little bit of a solution code You should be able to do this with the ftputil library, at http://ftputil.sschwarzer.net/ ;-) If you encounter any problems, send a mail to the ftputil mailing list (see http://ftputil.sschwarzer.net/trac/wiki/MailingList ) or to me. Stefan From jjl at pobox.com Sat Apr 1 16:51:33 2006 From: jjl at pobox.com (John J. Lee) Date: 01 Apr 2006 21:51:33 +0000 Subject: Identifying filled circles in a scanned image References: <20060330231044.66670.qmail@web34203.mail.mud.yahoo.com> Message-ID: <87fykxhsm2.fsf@pobox.com> Douglas Douglas writes: > Hi everybody. > > I have a paper form that I scan into an image. My user fills some circles in > this paper form using black ink. Every form has ten rows with five circles each > and the user fills only one circle for each row. > > I was wondering if I could use the Python Imaging Library to process these > forms. I know the Image class is really powerful, but I can't think of a way of > how to locate wich circle was filled. > > Could anybody please give me an advice on this? I think in astronomical / biological circles this kind or problem is known as "blob analysis", or something like that (certainly I remember the word "blob" correctly ;-). Try one of the numpy / numarray / Numerical Python / SciPy lists, bound to be people there who know a lot about this sort of problem, and your problem sounds quite a bit easier than the general one. John From brochu121 at gmail.com Fri Apr 14 18:30:03 2006 From: brochu121 at gmail.com (david brochu jr) Date: Fri, 14 Apr 2006 18:30:03 -0400 Subject: ping Message-ID: <9583ed900604141530w59c9aaftf808f4533d84a4ff@mail.gmail.com> I am trying to ping websites and output the results to a txt file: import os file = open("c:\python24\scripts\ip.txt") redirect = open("c:\python24\scripts\log.txt","a") for x in file: ping = "ping " + x print >> redirect, os.system(ping) but the results seen in the log.txt file are: 0 0 0 0 0 0 0 0 What am i doing wrong?? How do I fix this so I can see the ping statistics inside the log.txt file? -------------- next part -------------- An HTML attachment was scrubbed... URL: From rschroev_nospam_ml at fastmail.fm Wed Apr 19 05:16:37 2006 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Wed, 19 Apr 2006 09:16:37 GMT Subject: multiline comments In-Reply-To: References: Message-ID: Duncan Booth schreef: > Would you care to name a few languages which support nested block > comments? There really aren't many: ML as you mentioned; Standard Pascal > doesn't permit nesting of comments but *some* implementations do allow it. > > Want to comment out a block of code in C++? The only (nearly) reliable way > is to insert single-line comments down the block. You can't use a block > comment if there are any other block comments inside the code you want to > block out. Depends, some compilers support that. But the preferred way, which works very well, is to use preprocessor directives: #if 0 ... #endif Works in both C and C++. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From Jue_Shi at or.mxim.com Tue Apr 18 14:18:06 2006 From: Jue_Shi at or.mxim.com (Shi, Jue) Date: Tue, 18 Apr 2006 11:18:06 -0700 Subject: Slicing matrix Message-ID: <5C99C308457E6D4EA5448EA52A66004A0844692F@or.mxim.com> In Chinese, we say "cutting Tofu". Cheese is really much harder to cut than Tofu. :) -----Original Message----- From: python-list-bounces+jue_shi=or.mxim.com at python.org [mailto:python-list-bounces+jue_shi=or.mxim.com at python.org]On Behalf Of Anthony Liu Sent: Monday, April 17, 2006 8:44 PM To: python-list at python.org Subject: Re: Slicing matrix Hi, James, I just realized that my English is so good that I can joke with slangs. Hopefully it isn't that offensive. Otherwise, I am sorry. --- James Stroud wrote: > Anthony Liu wrote: > > I figure it out, too. NumArray is so flexible, > it's > > like cutting the cheese. > > Some idioms do not translate so well. > > > -- > James Stroud > UCLA-DOE Institute for Genomics and Proteomics > Box 951570 > Los Angeles, CA 90095 > > http://www.jamesstroud.com/ > -- > http://mail.python.org/mailman/listinfo/python-list > __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -- http://mail.python.org/mailman/listinfo/python-list From steve at holdenweb.com Sat Apr 29 11:50:24 2006 From: steve at holdenweb.com (Steve Holden) Date: Sat, 29 Apr 2006 16:50:24 +0100 Subject: Using Databases in Python In-Reply-To: <9n06525hobm0fgal7bgrvtrfuu3kvku7f9@4ax.com> References: <1146237635.087759.312210@y43g2000cwc.googlegroups.com> <9n06525hobm0fgal7bgrvtrfuu3kvku7f9@4ax.com> Message-ID: Dennis Lee Bieber wrote: > On Fri, 28 Apr 2006 21:29:32 +0100, Steve Holden > declaimed the following in comp.lang.python: > > >>Dennis Lee Bieber wrote: > > >>> Given that his web-site implies that he does these for a living, it >>>may not be a publicly available item. >> >>Nah, he's a bozo and his web site is completely wrong (as usual :-). >> > > I didn't mean to imply everything is done commercially, only that > what I saw seemed to lean that way (I also clicked on one of the books > that showed up and got something about "unavailable" from Amazon ) Hmm, time to crawl the site, methinks. Thank you! regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From michele.simionato at gmail.com Thu Apr 6 10:57:20 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 6 Apr 2006 07:57:20 -0700 Subject: pre-PEP: The create statement In-Reply-To: <13B*uLudr@news.chiark.greenend.org.uk> References: <59Wdnbd8EazRCqnZnZ2dnUVZ_vudnZ2d@comcast.com> <1144328362.729594.173160@z34g2000cwc.googlegroups.com> <13B*uLudr@news.chiark.greenend.org.uk> Message-ID: <1144335440.387962.250960@u72g2000cwu.googlegroups.com> Sion Arrowsmith wrote: > Kay Schluehr wrote: > >Steven Bethard wrote: > >> Python-Version: 2.6 > >Have you a rough estimation how many modules will be broken when > >"create" is introduced as a keyword? > > A quick scan of the standard library suggests that it will have > a grand total of 3 modules requiring a fix (it's a method name > in imaplib and a named argument in a couple of places in bsddb > and distutils). Your own code my fare worse (mine does, but not > by much). This agrees with my scan (except I also found an occurrence of 'create' in Tkinter). BTW, I would be curious to see the script you are using for the scanning. Are you using tokenize too? In am quite fond of the tokenize module ;) Michele Simionato From luigipaioro at libero.it Mon Apr 3 12:56:12 2006 From: luigipaioro at libero.it (Luigi) Date: 3 Apr 2006 09:56:12 -0700 Subject: Capturing stdout without waiting for the process end References: <1144078426.023838.25970@i39g2000cwa.googlegroups.com> <1144082065.389468.20800@j33g2000cwa.googlegroups.com> Message-ID: <1144083372.170752.275520@z34g2000cwc.googlegroups.com> I use Linux. So, if I modify my sdtout behaviour, when I execute: fin, fout = os.popen4(arg) this is executed asyncronously? And how can I intercept a fout.write() event? The question is that I have a C program (by third part) that streams the logs into the stderr and stdout devices. I need to create an envelopment that captures the outputs and puts them in a file generating log events (for a real-time view). Thanks Luigi From mtobis at gmail.com Sat Apr 8 23:18:09 2006 From: mtobis at gmail.com (Michael Tobis) Date: 8 Apr 2006 20:18:09 -0700 Subject: programming puzzles? In-Reply-To: <1144549647.938771.272110@g10g2000cwb.googlegroups.com> References: <44381f2f$0$4209$c3e8da3@news.astraweb.com> <1144532090.213069.191600@i39g2000cwa.googlegroups.com> <4438428e$0$11362$c3e8da3@news.astraweb.com> <1144543413.421821.132730@e56g2000cwe.googlegroups.com> <1144549647.938771.272110@g10g2000cwb.googlegroups.com> Message-ID: <1144552689.007362.170830@v46g2000cwv.googlegroups.com> Yeah, this was *much* easier than I expected. My candidate was in second place according to /usr/share/dict/words which has ixodid but not dioxid; I'm really not confident that dioxid is a word. I recall that I had also found the third place word now that I look at it. What I had to do was print out all combinations of letters that could make between 999,000 and 1,001,000 and then eyeball them. The factorization was a trick because I had only 16 bit ints if I recall right; I think hacked it in floats. I am amazed at how fast the Python ran and how easy it was to solve. I found "ixodid" in two reasonable lines of Python or one over-long ugly one, (in addition to what I already posted). It runs in about 15 seconds on a G4 powerbook. All in memory! I once spent three whole days on this. Hundreds of lines of Fortran, pages and pages of fanfold paper. Argh. mt From alisonken1 at gmail.com Tue Apr 18 16:51:16 2006 From: alisonken1 at gmail.com (alisonken1) Date: 18 Apr 2006 13:51:16 -0700 Subject: indirect import of standard module In-Reply-To: <1145386200.076643.253740@u72g2000cwu.googlegroups.com> References: <1145386200.076643.253740@u72g2000cwu.googlegroups.com> Message-ID: <1145393476.931506.9650@e56g2000cwe.googlegroups.com> Unless you override some of os.* functions in foo, you want to import os into foo and bar separately. Python does not reimport the module a second time (create a second instance of os), it only creates a pointer to the first instance that's loaded. From continium at gmail.com Tue Apr 18 22:05:06 2006 From: continium at gmail.com (continium at gmail.com) Date: 18 Apr 2006 19:05:06 -0700 Subject: Quick Problem Message-ID: <1145412306.686740.266110@j33g2000cwa.googlegroups.com> I am learning how to program and I only started about a month ago so the answer to this is probably quite obvious. I'm running accross a problem when writing a rock, paper, scissor program. Although I can write such program in 5 minutes I want to write a program into which I will implement many other features such as logging in, checking past games and such. I have an if, elif construction determening the outcome possible(not a tie though) in everyone of these either the user or the computer wins. Here are the errors I get: Traceback (most recent call last): File "C:\Documents and Settings\admin\Desktop\test\test.py", line 59, in -toplevel- win(2) File "C:\Documents and Settings\admin\Desktop\test\test.py", line 31, in win uw = uw + 1 # user win UnboundLocalError: local variable 'uw' referenced before assignment Here is my code: cw = 0 #Computer wins total uw = 0 # User wins total def win(who): if who == 1: cw = cw + 1 # computer win elif who == 2: uw = uw + 1 # user win l = ['r', 'p', 's'] def rand(): random.shuffle(l) while 1 == 1: rand() cc = l[0] # Computer Choice uc = raw_input('[r]ock, [p]aper, [s]cissor') # User Choice if cc == uc: print 'Tie, try again' continue else: break if cc == 'r' and uc == 's': win(1) print 'lose' elif cc == 'r' and uc == 'p': win(2) print 'win' elif cc == 'p' and uc == 'r': win(1) print 'lose' elif cc == 'p' and uc == 's': win(2) print 'win' elif cc == 's' and uc == 'r': win(2) print 'win' elif cc == 's'and uc == 'p': win(1) print 'lose' else: print 'ELSE ERROR' print 'uw = ', uw print 'cw = ', cw From mahs at telcopartners.com Thu Apr 27 12:26:46 2006 From: mahs at telcopartners.com (Michael Spencer) Date: Thu, 27 Apr 2006 09:26:46 -0700 Subject: Editing a function in-memory and in-place In-Reply-To: <1146115733.082702.106380@t31g2000cwb.googlegroups.com> References: <1146115733.082702.106380@t31g2000cwb.googlegroups.com> Message-ID: Ian Bicking wrote: > I got a puzzler for y'all. I want to allow the editing of functions > in-place. I won't go into the reason (it's for HTConsole -- > http://blog.ianbicking.org/introducing-htconsole.html), except that I > really want to edit it all in-process and in-memory. So I want the > identity of the function to remain the same, even as I edit the body > and hopefully the signature too. > > Well, the reason is that I want to edit any function object, without > having to know who has a reference to the function. This way editing a > function or a method or a property.fget can all be done in the same > way. > > The func_code attributes of functions is writable, but I don't know how > to create the proper code object. Just compiling a new body isn't good > enough. > The experimental module below updates many of the builtin types in-place, including functions. Functions in particular are handled by update_FunctionType. I use this in my own development environment to edit live code i.e., as a better reload. Michael """Update live code with new source. Example: >>> source1 = "def func1(a): return 2*a" >>> namespace = {} >>> exec source1 in namespace >>> func1 = namespace["func1"] >>> func1(2) 4 >>> source2 = "def func1(a, b): return 2*a+b" >>> exec_update(namespace, source2, verbosity=2) Updating: , .func1 Updated True >>> func1(2,2) 6 >>> """ import types import gc class UpdateException(Exception): pass def exec_update(namespace, source, name="", verbosity = 1): module_proxy.verbosity = verbosity if verbosity == 2: print "Updating: %s, %s" % (type(namespace), name) if isinstance(namespace, types.ModuleType): proxy = module_proxy(namespace) elif isinstance(namespace, (type, types.ClassType)): proxy = cls_proxy(namespace) elif isinstance(namespace, dict): proxy = dict_proxy(namespace, name) else: raise UpdateException, "Unrecognized namespace type: %s" % type(namespace) exec source in proxy.dict, proxy return True class module_proxy(object): DO_NOT_COPY = () verbosity = 1 def __init__(self, module, name = ""): self.dict = module.__dict__ self.namespace = module self.name = getattr(module,"__name__", name) def __contains__(self, key): return key in self.dict def _setitem(self,key,value): self.dict[key] = value def _delitem(self, key): del self.dict[key] def __getitem__(self, key): return self.dict[key] def __setitem__(self, key, value): try: obj = self.dict[key] except KeyError: if self.verbosity >= 1: print "** %s.%s=%s (Binding)" % (self.name, key, repr(value)) self._setitem(key, value) return True try: if update(obj, value): if self.verbosity >= 1: print "%s.%s Updated" % (self.name, key) return True else: if self.verbosity >= 2: print "%s.%s No change" % (self.name, key) return False except UpdateException: if self.verbosity >= 1: print "** %s.%s=>%s (Rebinding)" % (self.name, key, repr(value)) self._setitem(key, value) return True def __delitem__(self, key): if self.verbosity >= 1: print "** del %s.%s" % (self.name, key) self._delitem(key) def update_ns(self, other_dict, delete_missing=False, skip = ()): dirty = False if delete_missing: for attr in self.dict.keys(): if not((attr in other_dict) or (attr in skip)): dirty = True del self[attr] for to_attr, to_obj in other_dict.iteritems(): if to_attr in skip: continue dirty |= self.__setitem__(to_attr, to_obj) return dirty class dict_proxy(module_proxy): def __init__(self, my_dict, name = ""): self.dict = my_dict self.namespace = None self.name = name class cls_proxy(module_proxy): def _setitem(self,key,value): setattr(self.namespace,key,value) def _delitem(self, key): delattr(self.namespace, key) def update_cls(self, other): DONOTCOPY = set(["__name__","__bases__","__base__","__dict__", "__doc__","__weakref__","__module__"]) # This will often fail if they are not equal, so find out first! obj = self.namespace try: obj.__bases__ = other.__bases__ except TypeError, err: raise UpdateException, err fromdict = obj.__dict__ todict = other.__dict__ obj_slots = set(getattr(obj, "__slots__", ())) other_slots = set(getattr(other, "__slots__", ())) if other_slots > obj_slots: raise UpdateException, "Can't add slots %s" % \ list(other_slots - obj_slots) return self.update_ns(todict, delete_missing=True, skip = DONOTCOPY | obj_slots) ##TODO - Instances with __slots__ (see decimal.Decimal) class instance_proxy(dict_proxy): def __init__(self, my_obj, name = ""): self.dict = my_obj.__dict__ self.namespace = my_obj self.name = name # Specialized updaters by type # Each updater must return: True, False or raise UpdateException # False: no change required - new object is equal to the old # True: object was successfully updated # UpdateException - object could not be updated in place. Caller must # then decide whether to re-bind def update_classmethod(obj, other): # Massive hack. classmethod (and staticmethod) do not expose their # underlying callable to Python. But they *seem* always to have # one reference - which must be to the callable. obj_refs = gc.get_referents(obj) other_refs = gc.get_referents(other) if len(obj_refs) != len(other_refs) != 1: raise UpdateException, "Too many references from classmethod" return update(obj_refs[0], other_refs[0]) update_staticmethod = update_classmethod def update_classmethod_FunctionType(obj, other): obj_refs = gc.get_referents(obj) if len(obj_refs) != 1: raise UpdateException, "Too many references from classmethod" return update(obj_refs[0], other) def update_property(obj, other): # These are read-only attributes, so unless we can update them # in-place, update_property will fail dirty = False dirty |= update(obj.fget, other.fget) dirty |= update(obj.fset, other.fset) dirty |= update(obj.fdel, other.fdel) dirty |= update(obj.__doc__, other.__doc__) return dirty def update_FunctionType(obj, other): # Note this applies only to Python-defined functions dirty = False for attr in ("func_code", "func_defaults", "func_dict", "func_doc", "func_globals"): try: obj_attr, other_attr = getattr(obj, attr), getattr(other,attr) except AttributeError, err: # missing attribute means can't update the function raise UpdateException, err try: # If possible, update the function attributes in-place # this preserves, in particular, func_defaults dirty |= update(obj_attr, other_attr) except UpdateException: # If we can't update the function attribute in place # go ahead and overwrite it dirty = True setattr(obj, attr, other_attr) return dirty def update_MethodType(obj, other): # No need to update the class/object bindings return update_FunctionType(obj.im_func, other.im_func) def update_MethodType_FunctionType(obj, other): return update_FunctionType(obj.im_func, other) def update_list(obj, other): if obj == other: return False obj[:] = other return True def update_dict(obj, other): if obj == other: return False obj.clear() obj.update(other) return True def update_deque(obj, other): if obj == other: return False obj.clear() obj.extend(other) return True def update_array(obj, other): if obj == other: return False if obj.typecode != other.typecode: raise UpdateException, "Can't change typecode of array" obj[:] = other return True def update_tuple(obj, other): # We go to some additional lengths with tuples if obj == other: return False if len(obj) == len(other): dirty = False for ob1, ob2 in zip(obj, other): # This will raise UpdateException if any of the members # are not updatable dirty |= update(ob1, ob2) return dirty raise UpdateException, "Unequal tuples" update_set = update_dict def update_type(obj, other): proxy_cls = cls_proxy(obj) return proxy_cls.update_cls(other) update_ClassType = update_type def update(obj, other): if obj is other: return False type_pair = type(obj), type(other) #name = getattr(obj,"__name__", "") try: update_method = _method_cache[type_pair] except KeyError: pass else: #print "UpdateType %r" % obj return update_method(obj, other) if type_pair[0] == type_pair[1]: if isinstance(obj, (object, types.InstanceType)): try: obj_dict, other_dict = obj.__dict__, other.__dict__ except AttributeError: pass else: obj_dict_proxy = instance_proxy(obj) return obj_dict_proxy.update_ns(other_dict, True) if isinstance(obj, IMMUTABLE_TYPES): if obj == other: return False raise UpdateException, "Can't update %s to %s" % type_pair # Can't update these, but if they compare equal, there's no need to import datetime IMMUTABLE_TYPES = (bool, int, long, float, complex, buffer, basestring, slice, types.BuiltinFunctionType, types.BuiltinMethodType, types.CodeType, types.DictProxyType, datetime.date, datetime.time, datetime.timedelta, datetime.tzinfo) del datetime def _get_types(): from collections import deque from array import array d= locals() d.update(types.__dict__) return d def _get_method_cache(): cache = {} type_dict = _get_types() for name, obj in globals().items(): if name.startswith("update_"): fromtypename, totypename = name.rsplit("_", 2)[-2:] if fromtypename == "update": fromtypename = totypename fromtype = eval(fromtypename, type_dict) totype = eval(totypename, type_dict) cache[(fromtype,totype)] = obj return cache _method_cache = _get_method_cache() From josecarlos.balderas at gmail.com Wed Apr 12 07:46:55 2006 From: josecarlos.balderas at gmail.com (Jose Carlos Balderas Alberico) Date: Wed, 12 Apr 2006 13:46:55 +0200 Subject: Can't connect to SimpleXMLRPCServer. Help needed. In-Reply-To: References: <443CDFBE.1090200@plus.net> Message-ID: Okay, I changed this: server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 8000), ....) for this: server = SimpleXMLRPCServer.SimpleXMLRPCServer(('', 8000), ....) Replacing "localhost" with two simple quotes ' makes it work. Anyone knows the reason for this? Thank so much. Jose Carlos 2006/4/12, Jose Carlos Balderas Alberico : > > Thank you for the quick reply John... > Is there a way to sort this out? Should I specify another address here: > > server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 8000), ....) > > instead of "localhost" ? > > I'm kind of new to client/server programming, so I'm at a loss here. > Thank you very much for your attention. > > Jose Carlos. > > > > > > 2006/4/12, John Abel : > > > Your server is only listening on 127.0.0.1. > > > > Jose Carlos Balderas Alberico wrote: > > > Up till now I've been setting up my server and client in the same > > > machine, using the "localhost" address for everything. > > > Once I've made it work, I need to move my client application to the > > > computer where it'll be run from, and for some reason, I get a > > > socket.error: (111, 'connection refused'). > > > > > > The server is listening on port 8000. I've used the line > > > > > > server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 8000), > > ....) > > > ##register functions... > > > ... > > > ... > > > server.serve_forever() > > > > > > > > > And the client does the following: > > > > > > host = "XXXX:8000" (where XXXX is the server's IP address) > > > conn = xmlrpclib.connect(host) > > > data = conn.requestData() (requestData is a function previously > > > registered in the server) > > > > > > I've made sure the server is listening on port 8000, since the netstat > > > command says it's listening on port 8000. > > > I've also pinged the server from the client and viceversa and I get an > > > answer. So they can see each other. > > > > > > I've tried looking in google but couldn't find a solution to this > > > problem. Anyone can give me a hand on this? > > > Thank you very much. > > > > > > Jose Carlos. > > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From pmartin at snakecard.com Tue Apr 25 10:23:15 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Tue, 25 Apr 2006 09:23:15 -0500 Subject: Multiple hierarchies and method overloading References: <1145931851.526941.231680@v46g2000cwv.googlegroups.com> Message-ID: Well, the whole point was to clean up my code: Actually this is what I have: Class A: def A_Func(self, p_param): ..... Class B: def A_Func(self): ..... Class C (A,B): A.__init__(self) B.__init__(self) Class D (A,B): A.__init__(self) B.__init__(self) Where A is a wxWidget class and B a "Common/utility" class which I wanted to factorize (and yes, inheritance was not mandatory here, just simpler) My common class does have an A_Func(self) while wxWidget an A_Func(self, p_param) ==> I actually got the error calling A_Func(self) as it was checked against A_Func(self, p_param). Regards, Philippe Lawrence D'Oliveiro wrote: > In article <1145931851.526941.231680 at v46g2000cwv.googlegroups.com>, > "Ben Cartwright" wrote: > >>Philippe Martin wrote: >> >>> I renamed A_Func(self) to fix that ... but is there a cleaner way around >>> ? >> >>When using multiple inheritence, the order of the base classes matters! > > When you have to start worrying about complications like this, isn't > that a sign that you're taking the whole OO thing a little too seriously? > > After all, technology is supposed to _solve_ problems, not create them. > If the complications of OO are making you lose sight of your original > problem, then maybe you should put them aside. From keith.b.perry at gmail.com Fri Apr 21 16:22:39 2006 From: keith.b.perry at gmail.com (kbperry) Date: 21 Apr 2006 13:22:39 -0700 Subject: win32com.client.constants - AttributeError In-Reply-To: <1145650126_8975@sp6iad.superfeed.net> References: <1145565829.143096.75510@e56g2000cwe.googlegroups.com> <1145590250_3749@sp6iad.superfeed.net> <1145631219.159431.105040@g10g2000cwb.googlegroups.com> <1145650126_8975@sp6iad.superfeed.net> Message-ID: <1145650959.327966.265710@e56g2000cwe.googlegroups.com> Wow..I didn't even realize that this existed. Thanks for your help! From martin at v.loewis.de Sat Apr 8 05:58:13 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 08 Apr 2006 11:58:13 +0200 Subject: freeze.py builds, but binary doesn't even run locally (shared GTK problem?) In-Reply-To: <1144471326.104324.323480@t31g2000cwb.googlegroups.com> References: <1144471326.104324.323480@t31g2000cwb.googlegroups.com> Message-ID: <44378935$0$3055$9b622d9e@news.freenet.de> kristian.hermansen at gmail.com wrote: > from _gtk import * > > ImportError: No module named _gtk If you look at the freeze output, you'll notice that _gtk is not linked into your application: It is a shared library (.so), so it can't be frozen. Instead, the resulting binary will look for _gtk.so on sys.path. Try copying _gtk.so into the directory where the binary is, or set PYTHONPATH before running the binary. If you want to freeze _gtk into the application, you need it as a static library. Regards, Martin From pthibault33 at yahoo.ca Wed Apr 5 23:16:02 2006 From: pthibault33 at yahoo.ca (pierreth) Date: 5 Apr 2006 20:16:02 -0700 Subject: python on Mac References: <1144284073.446005.53950@t31g2000cwb.googlegroups.com> <1hdc51n.1qgtjne1mduk7gN%aleaxit@yahoo.com> <1144291572.151260.56700@j33g2000cwa.googlegroups.com> Message-ID: <1144293362.889863.146200@i39g2000cwa.googlegroups.com> You removed /usr/bin/python! This is a really bad idea. You should never modify /usr/bin because the system is expecting it. This is why the new installation is in /usr/local/bin. Modify your /usr/local instead are change your .login file instead. It is much safer. From robert.kern at gmail.com Sat Apr 8 20:00:58 2006 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 08 Apr 2006 19:00:58 -0500 Subject: Python 2.5 licensing: stop this change In-Reply-To: References: <442E2FC1.6090600@hathawaymix.org> Message-ID: Francisco Reyes wrote: > Shane Hathaway writes: > >>I must saay that i am fully in favor of this change. The ppython >>developerrs need to eat too. Iis no one ellse aware off the perils oof >>ooutright open source llicenssing? > > I disagree with the change. I think Steve Holden is right. > > 1- How do you enforce this? > 2- Those that do want to "do the right thing".. may opt for switching > language isntead of paying. > 3- Users who have risked their jobs by introducing Python to their work > place may not only be in a bad spot and likely switch away from Python, but > some may actually LOOSE their jobs if the company they work for is sued. It was an April Fool's joke. It's not actually true. -- Robert Kern robert.kern at gmail.com "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From steve at REMOVEMEcyber.com.au Thu Apr 6 05:44:19 2006 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Thu, 06 Apr 2006 19:44:19 +1000 Subject: How to catch python's STDOUT References: <1144314684.986767.131650@j33g2000cwa.googlegroups.com> Message-ID: <4434E2F3.8020007@REMOVEMEcyber.com.au> praveenkumar.117 at gmail.com wrote: > Hi, > Can someone help me by suggesting how to capture python's > STDOUT. I doesn't want the python's output to get displayed on the > screen. >>> import sys, StringIO >>> SAVEOUT = sys.stdout >>> capture = StringIO.StringIO() >>> sys.stdout = capture >>> print "hello" >>> But be warned, I've had difficulty restoring stdout afterwards, and needed to exit the interactive interpreter to get things back to normal. Because I'm paranoid, I might prefer to leave sys.stdout as it, and use a custom print function which I control: _CAPTURE = StringIO.StringIO() _FLAG = True # start capturing def print(obj): global _CAPTURE, _FLAG if _FLAG: where = _CAPTURE else: where = sys.stdout print >>where, obj Then I can start or stop capturing printing just by changing a flag. -- Steven. From nobody at 127.0.0.1 Sat Apr 22 16:35:24 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Sat, 22 Apr 2006 20:35:24 GMT Subject: list example In-Reply-To: <1145737240.221433.176160@i40g2000cwc.googlegroups.com> References: <1145737240.221433.176160@i40g2000cwc.googlegroups.com> Message-ID: No substantive problems. The str() calls are unnecessary, print calls list.__str__ already. You can replace the loop with list comprehensions or slices. Same result, a bit more succinct. See these pages for more: http://docs.python.org/lib/typesseq.html http://docs.python.org/tut/node7.html (section 5.1.4) PAolo wrote: > Hi, > I wrote this small example to illustrate the usage of lists: > > even=[] > odd=[] > > for i in range(1,10): > if i%2: > odd.append(i) > else: > even.append(i) > > print "odd: "+str(odd) > print "even: "+str(even) > > numbers=even > numbers.extend(odd) > print "numbers:"+str(numbers) > numbers.sort() > print "sorted numbers:"+str(numbers) > > > any comment, suggestion? Is there something not elegant? > > Thnx > PAolo > From ToddLMorgan at gmail.com Thu Apr 20 22:42:24 2006 From: ToddLMorgan at gmail.com (ToddLMorgan at gmail.com) Date: 20 Apr 2006 19:42:24 -0700 Subject: How should multiple (related) projects be arranged (structured) and configured so that they can share code, have a related package structure and enable proper unittesting, and ensuring no namespace collisions In-Reply-To: <1145581506.477674.54130@t31g2000cwb.googlegroups.com> References: <1145546785.268550.154240@e56g2000cwe.googlegroups.com> <1145563823.160038.257950@j33g2000cwa.googlegroups.com> <4447ee60$0$5199$626a54ce@news.free.fr> <1145565632.131816.146560@i40g2000cwc.googlegroups.com> <1145568816.554279.323420@e56g2000cwe.googlegroups.com> <444801d0$0$20922$636a55ce@news.free.fr> <1145581506.477674.54130@t31g2000cwb.googlegroups.com> Message-ID: <1145587344.845567.181960@j33g2000cwa.googlegroups.com> Thanks for all the prompt helpful responses :- ) I have read and reread section 6.4 -> of the python docs and it doesn't really help me. Just a couple of clarifications. I am already using a VCS (Version Control System) - subversion actually. When I mentioned a clear separation of production and test code I was more referring to this sort of arrangement: src a.b.c.common a.b.c.common.test which I believe is bad versus the clearer physical separation test a.b.c.commom.test The first option has the testing code within the same folder hierarchy which makes it harder to separate the two physically at "release" time without writing some complicated scripts to selectively exclude items. In the Java world the second option is the standard, and my preference if it's possible. I suspect that some of my import / from problems stem from the fact that I want to use a standard base package for all my projects to avoid namespace issues. ie all my projects use packages of the form a.b.c.projectName where a.b.c is my namespace (dns address actually) a.b.c.common a.b.c.project1 a.b.c.project2 Is this not the way python projects should be packaged? Is there a problem with having a common base package name like this? ie does the first instance of the package a.b.c effectively mask out the others so that if a.b.c.common occurs first in the PYTHONPATH then a.b.c.project1 will never be found as the "a.b.c" package is only loaded from the a.b.c.common folder? Does anyone else have any issues with running a master test suite and indvidual tests. It seems that if I set up the imports/froms for the master testsuite then I can't run the tests individuallly and vice versa ... unless I remove all packages and have a single flat directory. There has got to be big projects written in python that need to separate out their testing code according to some logical grouping. thanks Todd From Gonzillaaa at gmail.com Tue Apr 4 12:03:25 2006 From: Gonzillaaa at gmail.com (Gonzillaaa at gmail.com) Date: 4 Apr 2006 09:03:25 -0700 Subject: scraping nested tables with BeautifulSoup In-Reply-To: <44329229$1_3@newspeer2.tds.net> References: <1144142334.695498.293650@u72g2000cwu.googlegroups.com> <4432753a$1_2@newspeer2.tds.net> <1144165142.767043.70100@g10g2000cwb.googlegroups.com> <44329229$1_3@newspeer2.tds.net> Message-ID: <1144166605.030565.174520@g10g2000cwb.googlegroups.com> so it must be the malformed HTML comment that is confusing BS. I might try different methods to see if I get the same problem... thanks From python-url at phaseit.net Tue Apr 4 11:18:48 2006 From: python-url at phaseit.net (Peter Otten) Date: Tue, 04 Apr 2006 15:18:48 +0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Apr 4) Message-ID: QOTW: "Don't be too sure that it's compatible for the indefinite future. XML is just as future-proof as any other format." - Sybren Stuvel "Submitting a proposed change or fix [of the Python docs] is easier and quicker than arguing about it on c.l.py and it seems to get pretty quickly to the actual document maintainers." - Kent Johnson Still struggling with recursion? comp.lang.python is newbie-friendly: http://groups.google.com/group/comp.lang.python/browse_frm/thread/2ca81c529b485f89/cf531016b54d0ca1?tvc=1 An interview with Michael Foord, author of MovablePython, is the latest entry in the Python411 series intended to help you learn Python and learn about Python: http://www.awaretek.com/python/index.html PyInstaller advances Gordon McMillan's earlier and widely-used work on Python installation: http://pyinstaller.hpcf.upr.edu/cgi-bin/trac.cgi "If PL/SQL is your only programming language, your Oracle work may suffer." In her introductory article Catherine Devlin demonstrates the power of Python from the perspective of a database user: http://www.oracle.com/technology/pub/articles/devlin-python-oracle.html http://catherinedevlin.blogspot.com/2006/03/otn-article-addendum.html Getting hold of subclasses is easy with new-style classes: http://groups.google.com/group/comp.lang.python/msg/8fbe567f4ff121f9 Once you learn about the secret of iter()'s second parameter, many use cases of a while-loop in C can be better expressed with a for-loop in Python: http://groups.google.com/group/comp.lang.python/browse_frm/thread/b3ab8141c492bb21/df51ed3d13dd4975?tvc=1 The Python 2.4.3 bugfix release is available: http://groups.google.com/group/comp.lang.python/browse_frm/thread/93a2ad5d99db34ec ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. For far, FAR more Python reading than any one mind should absorb, much of it quite interesting, several pages index much of the universe of Pybloggers. http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog http://www.planetpython.org/ http://mechanicalcat.net/pyblagg.html comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Steve Bethard, Tim Lesher, and Tony Meyer continue the marvelous tradition early borne by Andrew Kuchling, Michael Hudson and Brett Cannon of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topic/python/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From amorgan at xenon.Stanford.EDU Wed Apr 5 18:39:31 2006 From: amorgan at xenon.Stanford.EDU (Alan Morgan) Date: Wed, 5 Apr 2006 15:39:31 -0700 (PDT) Subject: efficiency of range() and xrange() in for loops References: Message-ID: In article , Giovanni Bajo wrote: >Steve R. Hastings wrote: > >>> in Python 2.X, range is defined to return a list. if you start >>> returning something else, you'll break stuff. >> >> Perhaps I'm mistaken here, but I don't see how this optimization could >> possibly break anything. > >Because you assume that the only use-case of range() is within a for-loop. >range() is a builtin function that can be used in any Python expression. For >instance: > >RED, GREEN, BLUE, WHITE, BLACK = range(5) Hmmm, this worked fine when I used xrange as well. Am I missing something? Obviously there *are* differences, viz: a = range(5) b = range(5) a==b # True! c = xrange(5) d = xrange(5) c==d # False! and various other more arcane things, but do these actually happen in real life? Alan -- Defendit numerus From vigalchin at gmail.com Mon Apr 10 16:10:24 2006 From: vigalchin at gmail.com (Vasya) Date: 10 Apr 2006 13:10:24 -0700 Subject: newbie to SWIG/Python Message-ID: <1144699824.886691.282300@t31g2000cwb.googlegroups.com> Hello, I have an API represented in a C header file. I ran SWIG over this hedaer fiel and generated a .py (python file) and a .c. If I write a Python script against this API how do I "link" the Python script with the SWIG-generated files?? Thanks, Vasili From sturlamolden at yahoo.no Tue Apr 25 10:42:21 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 25 Apr 2006 07:42:21 -0700 Subject: Hooking things up in GUI application In-Reply-To: References: <1145965957.073830.320580@y43g2000cwc.googlegroups.com> Message-ID: <1145976141.109430.178190@v46g2000cwv.googlegroups.com> Ryan Ginstrom wrote: > Yes, I've tried something similar with wxGlade. But GLADE is not wxGlade :-) wxGlade is a GUI designer for wxWidgets and wxPython. It looks a bit like GLADE on the surface, but does not share any code with GLADE. GLADE is a GUI designer for GTK, gtkmm, Mono, GNOME and PyGTK. http://glade.gnome.org/ http://www.pygtk.org/ http://www.mapr.ucl.ac.be/~gustin/win32_ports/ From cjns3274 at optonline.net Mon Apr 10 22:57:40 2006 From: cjns3274 at optonline.net (Chris Jones) Date: Mon, 10 Apr 2006 22:57:40 -0400 Subject: using vim as a python class/module/function etc.. browser Message-ID: <443B1B24.3070401@optonline.net> I'm trying to make sense of a python program and was wondering if vim has any python-oriented functionalities (apart from syntax highlighting) that would make it somewhat easier to browse the source code. What I had in mind is something that would let me use CTRL+] to automatically display whatever object is under the cursor (a bit like ctags for code written in C..) I have read somewhere about something called 'ptags' but could not find it in debian - and I'm not 100% sure it's really a python equivalent of ctags. I'm not too keen on using a gui IDE and would much prefer to stick with vim if at all possible. Any pointers or tips from python/vim folks welcome. CJ From thn at mail.utexas.edu Wed Apr 26 17:32:20 2006 From: thn at mail.utexas.edu (Thomas Nelson) Date: 26 Apr 2006 14:32:20 -0700 Subject: print names of dictionaries In-Reply-To: <1146085818.242086.206290@e56g2000cwe.googlegroups.com> References: <1146085818.242086.206290@e56g2000cwe.googlegroups.com> Message-ID: <1146087140.319985.36690@u72g2000cwu.googlegroups.com> Here's an OO way that may do what you want: >>> class MyD(dict): ... def __init__(self,dic,rep): ... dict.__init__(self,dic) ... self.rep = rep ... def __repr__(self): ... return self.rep ... >>> apps = MyD({'alpha':1,'beta':2},'apps') >>> apps apps >>> apps.keys() ['alpha', 'beta'] Of course, the easiest way is just to use a tuple (dict,string). As a side note, since dict is a builtin type and function, it might not be good style to use it as a loop variable. THN From fredrik at pythonware.com Thu Apr 27 05:36:06 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 27 Apr 2006 11:36:06 +0200 Subject: begging for a tree implementation References: <1146091386.013265.153660@v46g2000cwv.googlegroups.com><1146127110.773347.222270@e56g2000cwe.googlegroups.com> <4bbh68F10a2lbU1@uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > This is not to discourage you - just don't expect people to greet you as the > next messiah who finally brought one of CS most fundamental data structures > to Python... :) xml.etree was added to Python 2.5 before christmas :-) From tdwdotnet at gmail.com Thu Apr 13 16:18:51 2006 From: tdwdotnet at gmail.com (Tim Williams (gmail)) Date: Thu, 13 Apr 2006 21:18:51 +0100 Subject: Forms with multiple submit buttons vs 'form' objects with single 'submit' methods In-Reply-To: References: Message-ID: <9afea2ac0604131318scf57795m4646474a475bda73@mail.gmail.com> On 13 Apr 2006 12:26:52 -0700, neil.fitzgerald at ic.ac.uk < neil.fitzgerald at ic.ac.uk> wrote: > > Hi all, > > I'm using pywin to write a script that will commandeer internet > explorer to go to a certain website, where it will navigate menus, post > forms, and eventually retrieve certain data. > > Here's my question: Suppose a form has more than one submit button. > Now the COM 'form' object has a 'submit' method that doesn't take any > arguments, so how do I tell it which button I want to press? > > I'll be *unbelievably* grateful, for the rest of my natural life, to > whomever has the answer to this. > > Have a look at ishy_browser, its in 2 parts at http://www.ishpeck.net/index.php?P=b1115239318ishpeck http://www.ishpeck.net/index.php?P=b1115225809ishpeck HTH :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Thu Apr 13 04:40:32 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 13 Apr 2006 10:40:32 +0200 Subject: New Karrigel page in Wikipedia References: <1144867025.095969.92870@e56g2000cwe.googlegroups.com> <1144915559.734587.131140@e56g2000cwe.googlegroups.com> Message-ID: Ben Sizer wrote: > > http://en.wikipedia.org/wiki/Karrigell > > Why is Wikipedia being abused for software promotion and documentation? > Articles on Wikipedia are supposed to be from a neutral point of view > and purely informative, not biased or instructive. check the page history. it's already been nominated for speedy removal, but the Karrigell folks deleted the "prod" template ("it's free software!"). From rogerb at rogerbinns.com Wed Apr 5 03:14:55 2006 From: rogerb at rogerbinns.com (Roger Binns) Date: Wed, 5 Apr 2006 00:14:55 -0700 Subject: Convertion of Unicode to ASCII NIGHTMARE References: <1144079830.734516.8390@z34g2000cwc.googlegroups.com><1144081137.137744.253790@i39g2000cwa.googlegroups.com><34b9g3-ku8.ln1@home.rogerbinns.com><1144150561.389856.302670@v46g2000cwv.googlegroups.com><2enbg3-kr8.ln1@home.rogerbinns.com> Message-ID: "Fredrik Lundh" wrote in message news:mailman.4102.1144215505.27775.python-list at python.org... > Roger Binns wrote: > >> SQLite only accepts Unicode so a Unicode string has to be supplied. > > fact or FUD? let's see: Note I said SQLite. For APIs that take/give strings, you can either supply/get a UTF-8 encoded sequence of bytes, or two bytes per character host byte order sequence. Any wrapper of SQLite that doesn't do Unicode in/out is seriously breaking things. I ended up using the UTF-8 versions of the API as Python can't quite make its mind up how to represent Unicode strings at the C api level. You can have two bytes per char or four, and the handling/production of byte order markers isn't that clear either. > import pysqlite2.dbapi2 as DB pysqlite had several unicode problems in the past. It has since been cleaned up as you saw. Roger From davidh at ilm.com Fri Apr 21 18:21:21 2006 From: davidh at ilm.com (David Hirschfield) Date: Fri, 21 Apr 2006 15:21:21 -0700 Subject: Raising a specific OSError Message-ID: <44495AE1.5040007@ilm.com> I know this should be obvious, but how does one raise a specific type of OSError? When I attempt to perform a file operation on a non-existent file, I get an OSError: [Errno 2], but what if I want to raise one of those myself? Thanks in advance, -Dave -- Presenting: mediocre nebula. From quentel.pierre at wanadoo.fr Thu Apr 13 07:30:45 2006 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: 13 Apr 2006 04:30:45 -0700 Subject: New Karrigel page in Wikipedia In-Reply-To: <7x1ww1lro6.fsf@ruckus.brouhaha.com> References: <1144867025.095969.92870@e56g2000cwe.googlegroups.com> <1144915559.734587.131140@e56g2000cwe.googlegroups.com> <1144918850.680444.198980@g10g2000cwb.googlegroups.com> <7x1ww1lro6.fsf@ruckus.brouhaha.com> Message-ID: <1144927845.046176.69420@t31g2000cwb.googlegroups.com> Ok, thanks for the information. I have rewritten the page in a more neutral way and removed the tutorial-like part, I'll put in in wikibooks From anton.vredegoor at gmail.com Thu Apr 27 11:27:24 2006 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Thu, 27 Apr 2006 17:27:24 +0200 Subject: not quite 1252 In-Reply-To: <44507F68.7080804@lexicon.net> References: <444f5e6b$1@usenet.zapto.org> <444f8781@usenet.zapto.org> <44507F68.7080804@lexicon.net> Message-ID: <4450e193$1@usenet.zapto.org> John Machin wrote: > Firstly, this should be 'content.xml', not 'contents.xml'. Right, the code doesn't do *anything* :-( Thanks for pointing that out. At least it doesn't do much harm either :-| > Secondly, as pointed out by Sergei, the data is encoded by OOo as UTF-8 > e.g. what is '\x94' in cp1252 is \u201d which is '\xe2\x80\x9d' in > UTF-8. The kill_gremlins function is intended to fix Unicode strings > that have been obtained by decoding 8-bit strings using 'latin1' instead > of 'cp1252'. When you pump '\xe2\x80\x9c' through the kill_gremlins > function, it changes the \x80 to a Euro symbol, and leaves the other two > alone. Because the \x9d is not defined in cp1252, it then causes your > code to die in a hole when you attempt to encode it as cp1252: > UnicodeEncodeError: 'charmap' codec can't encode character u'\x9d' in > position 1761: character maps to Yeah, converting to cp1252 was all that was necessary, like Sergei wrote. > I don't see how this code repairs anything (quite the contrary!), unless > there's some side effect of just read/writestr. Enlightenment, please. You're quite right. I'm extremely embarrassed now. What's left for me is just to explain how it got this bad. First I noticed that by extracting from content.xml using OOopy's getiterator function, some \x94 codes were left inside the document. But that was an *artifact*, because if one prints something using s.__repr__() as is used for example when printing a list of strings (duh) the output is not the same as when one prints with 'print s'. I guess what is called then is str(s). Ok, now we have that out of the way, I hope. So I immediately posted a message about conversion errors, assuming something in the open office xml file was not quite 1252. In fact it wasn't, it was UTF-8 like Sergei wrote, but it was easy to convert it to cp1252, no problem. Then I also noticed that not all xml-tags were printed if I just iterated the xml-tree and filtered out only those elements with a text attribute, like 'if x.text: print x' In fact there are a lot of printable things that haven't got a text attribute, for example some items with tag (xxxx)s. When F pointed me to gremlins there was on this page the following text: Some applications add CP1252 (Windows, Western Europe) characters to documents marked up as ISO 8859-1 (Latin 1) or other encodings. These characters are not valid ISO-8859-1 characters, and may cause all sorts of problems in processing and display applications. I concluded that these \x94 codes (which I didn't know about them being a figment of my representation yet) were responsible for my iterator skipping over some text elements, but in fact the iterator skipped them because they had no text attribute even though they were somehow containing text. Now add my natural tendency to see that what I think is the case rather than neutrally observing the world as it is into the mix and of course I saw the \x94 disappear (but that was because I now was printing them straight and not indirectly as elements of a list) and also I thought that now the xml-parsing 'errors' had disappeared but that was just because I saw some text element appear that I thought I hadn't seen before (but in fact it was there all the time). One man's enlightenment sometimes is another's embarrassment, or so it seems. Thanks to you all clearing up my perceptions, and sorry about all the confusion I created. What I want to know next is how to access and print the elements that contain text but have no text attribute, that is, if it's not to taxing on my badly damaged ego. Anton From aleaxit at yahoo.com Sat Apr 22 15:48:13 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 22 Apr 2006 12:48:13 -0700 Subject: Problem calling math.cos() References: <3ev2g.9680$%97.5795@newsfe15.lga> Message-ID: <1he74jb.126zvqm1jw41n5N%aleaxit@yahoo.com> Sambo wrote: > I have the following module: > ------------------------------- > import math > > def ac_add_a_ph( amp1, ph1, amp2, ph2 ): > > amp3 = 0.0 > ph3 = 0.0 > ac1 = ( 0, 0j ) > ac2 = ( 0, 0j ) > ac3 = ( 0, 0j ) You're defining ac1, ac2, ac3 as tuples, each with two items. That's silly: remove these three useless and confusing lines (the first two are prety silly too). No damage, but, avoidable extra confusion. > ac1 = complex( amp1 * math.cos( math.radians( ph1 ) ), amp1 * \ math.sin( math.radians( ph1 ) ) ) > ac2 = complex( amp2 * math.cos( math.radians( ph2 ) ), amp2 * \ math.sin( math.radians( ph2 ) ) ) > ac3 = ac1 + ac2 > amp3 = math.abs( ac3 ) > ph3 = math.atan( ac3.imag / ac3.real ) > return [amp3, ph3] > -------------------------------------- > when I import it (electronics) in python.exe in windows2000 and > try to use it, it croaks. ??? > > >>> import math > >>> import electronics > >>> print electronics.ac_add_a_ph( 10, 0 , 6 , 45 ) > Traceback (most recent call last): > File "", line 1, in ? > File "f:\devel\python\electronics.py", line 10, in ac_add_a_ph > ac1 = complex( amp1 * math.cos( math.radians( ph1 ) ), amp1 * \ math.sin( math > .radians( ph1 ) ) ) [[some lines split to respect NNTP's constraint on 80-char lines]] > NameError: global name 'cos' is not defined > >>> > > > global?? huh? Weird -- I can't reproduce this; it's the kind of symptom you get when mistakenly using a comma instead of a dot, for example, but I don't see that error in your code. What I _do_ see is an "AttributeError: 'module' object has no attribute 'abs'" on the amp3 assignment -- of course, because that's indeed the fact (abs is a builtin, not a member to module math). Most likely, you got a bit confused and didn't copy-and-paste exactly what was going on. > what does abs stand for? why is that not absolute value? hmmm. abs does stand for absolute-value. > Hmm, complex numbers, cool I don't even have any idea where C > stands on this. C has no stand on complex numbers. Alex From kruhftREMOVE at gmail.com Thu Apr 13 16:06:26 2006 From: kruhftREMOVE at gmail.com (Burton Samograd) Date: 13 Apr 2006 14:06:26 -0600 Subject: function prototyping? References: <87hd4x1hx4.fsf@gmail.com> <87bqv51h7i.fsf@gmail.com> <1144952839.369290.121470@e56g2000cwe.googlegroups.com> <873bgh1g33.fsf@gmail.com> <443e9c22$0$18281$636a55ce@news.free.fr> Message-ID: <87psjlz1dp.fsf@gmail.com> bruno at modulix writes: > Burton Samograd wrote: > > "infidel" writes: > > I'm a C programmer, so I'm doing it in a bit of a C like way; > > prototype the function, initalize the array using the prototypes, have > > the functions defined somewhere else and then let the linker work it > > all out for me. I was hoping that python had some sort of lazy > > evaluation scheme for this type of behaviour so that you could defer > > linkage (or variable evalutation) until runtime, or at least variable > > reference (through the use of thunks or some sort). Maybe I was > > hoping for too much :) > > It's not a problem of "hoping for too much", but a problem of paradigm > shift. You're actually *thinking* in C, and Python is a *completely > different* language. You just can't directly transpose C idioms in > Python - nor could you transpose much Python idioms in C. So you need to > 'go down a level' and consider the real problem and how to solve it the > Python way - not how to implement the C-ish solution in Python. To be honest, I'm trying to do it in a more 'lispish' way (as in emacs lisp) where the configuration file is written in the implementation langugage. Just an interesting experiement really to see if it would work. It's been a year and a half since I really used python last so I'm just getting back up to speed with the idioms so I expect to make a few mistakes along the way. Thanks for the help. -- burton samograd kruhft .at. gmail kruhft.blogspot.com www.myspace.com/kruhft metashell.blogspot.com From sushant.sirsikar at gmail.com Thu Apr 6 01:21:46 2006 From: sushant.sirsikar at gmail.com (sushant.sirsikar at gmail.com) Date: 5 Apr 2006 22:21:46 -0700 Subject: ``pickling'' and ``unpickling'' Message-ID: <1144300906.286664.75350@j33g2000cwa.googlegroups.com> Hi, I am new in Python World.I want to know what is mean by ``pickling'' and ``unpickling'' ? And how can we used it?Please Give Me some links of Picking Examples. Thanks Sushant From remi at cherrypy.org Tue Apr 4 09:50:12 2006 From: remi at cherrypy.org (remi at cherrypy.org) Date: 4 Apr 2006 06:50:12 -0700 Subject: ANN: CherryPy-2.2.0-rc1 released Message-ID: <1144158612.574915.111400@i40g2000cwc.googlegroups.com> Hello everyone, After six months of hard work and 300 changesets since the last stable release I'm happy to announce that CherryPy-2.2.0-final is out. The biggest changes are: - switch to a lowercase api (although the old camelCase API is still supported for backward compatibility) - support for multiple applications (new "cherrypy.tree" object) - better error handling - lots of bug fixes (especially in file-based sessions) - better test suite. Check out http://www.cherrypy.org/wiki/UpgradeTo2.2 for more details. *************** About CherryPy: CherryPy is a simple (no dependencies), pythonic (doesn't get in your way) web development framework. Here is a sample Hello, World in CherryPy: # import cherrypy # class HelloWorld: # @cherrypy.expose # def index(self): # yield "" # yield "Hello world!" # yield "" # cherrypy.root = HelloWorld() # cherrypy.server.start() The project has been growing strongly lately: cherrypy.org averaged 3000 visitors/day in March, up from 2000 visitors/day in January and February; and the cherrypy-users list just passed 700 users. Details and downloads are available from: http://www.cherrypy.org Remi. From fredrik at pythonware.com Fri Apr 21 09:58:23 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 21 Apr 2006 15:58:23 +0200 Subject: what has python added to programming languages? (lets beesoteric, shall we ; ) References: <1145626253.362736.266010@v46g2000cwv.googlegroups.com> Message-ID: dadapapa at googlemail.com wrote: > Examples for this are one-liners like > > x,y = y,x > a,b,c = f(x) > for key in my_dict : do_some_thing_with(my_dict[key]) > > It might be that Guido adapted such notations from ABC, a language I am > not familiar with something like: PUT (x, y) IN y, x PUT f x y IN y, x FOR key IN keys my_dict: DO_SOME_THING_WITH my_dict[key] From tuzib at 163.com Wed Apr 5 23:34:43 2006 From: tuzib at 163.com (tuzib at 163.com) Date: 5 Apr 2006 20:34:43 -0700 Subject: How Software Gets Done! Message-ID: <1144294483.478524.89680@v46g2000cwv.googlegroups.com> HI everyone , It is time to test your skills now. Earn cash with your high tech skills on 2,028 currently open bid requests. Then subscribe to our newsletter and receive daily bid requests from our 52,830 registered buyers. join us free now. http://www.huymay.com/join.php We Sincerely invite you and your teams join our service to find good Freelancers Or Buyers. ----------------------------------------------------------------------------------------------------------------------- [About US] GetAFreelancer is a swedish company growing rapidly owned by Innovate it. Our clients are from more than 200 countries. We can help you find freelance programmers, Web Designers and Copywriters. Outsource projects to India, Romania, Ukraine or any other country.Find out why we have thousands of successfully outsourced projects. Post your project today! We can offer freelance programmers, interpreters and graphic designers the ability to work independently. As a freelancer you can choose among hundreds of outsourced projects. Innovate it is a swedish company regulated by swedish authorities. Innovate it is limited by shares(aktiebolag) and must file annual reports to Bolagsverket. Innovate it was started in May 1999 and has since then developed into a stable online business. GetAFreelancer.com was started in February 2004 and is today one of the top players in the online freelance area. Our company auditor is KPMG. KPMG is one of the largest and most trusted companies in the world. They operate in 148 countries and have about 6,500 partners, 70,000 client service professionals, and 17,000 administration and support staff working in member firms around the world. From michele.simionato at gmail.com Fri Apr 7 05:40:06 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 7 Apr 2006 02:40:06 -0700 Subject: OT: job offering in Milan Message-ID: <1144402806.087904.164860@i39g2000cwa.googlegroups.com> My current employer is looking for a senior system administrator/programmer with good Python expertise. Notice that the job is in Milan, Italy and that we do not consider remote work. You can mail your CV and/or ask questions to luca.fittabile at statpro.com I can say this is a nice place to work ;) Here is the announcement. --------------------------------------------------------------------------------- Position Title Senior System Engineer The Company StatPro, a leader Company in the field of portfolio analytics for the global asset management market, is looking for a Senior Systems/Network Engineering Specialist, who is ready for a new challenge. Skills/Experience The ideal candidate should have Bachelor or Master Scientific degree and at least 5 years of experience in Linux and Microsoft Operating Systems as System Administrator. He/She will be able to manage the installation, configuration, tuning and troubleshooting servers (Microsoft, Linux and BSD), both for institutional services and for specific projects. He/She should also have skills in networking and previous experience with cluster environments on unix-like systems. The candidate will be asked to develop scripting procedures for automating common system tasks and for system and application monitoring purpose. Experience with the python programming language and relational databases is a plus. Attitude He/she should be a pro-active, quick-learner individual with strong initiative and good English communication skills. The offer The offered package is in line with the top market levels for the position. The working location is Milan. From mensanator at aol.com Mon Apr 17 13:34:22 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 17 Apr 2006 10:34:22 -0700 Subject: How do I use Code Context under Options in IDLE? References: <1145278818.250198.145660@i40g2000cwc.googlegroups.com> Message-ID: <1145295262.629303.171930@v46g2000cwv.googlegroups.com> Phoe6 wrote: > Hi all, > I have this Code Context feature under Options in the IDLE. > How should I use it? Are there folks here who use it regularly and find > it useful. > Please guide me. Well, you could start by looking at the Help: Options Menu: Configure IDLE -- Open a configuration dialog. Fonts, indentation, keybindings, and color themes may be altered. Startup Preferences may be set, and Additional Help Souces can be specified. --- Code Context -- Open a pane at the top of the edit window which shows the block context of the section of code which is scrolling off the top or the window. But what does that actually mean? Take this code fragment example (with line numbers added for reference) 1 import collatz_functions as cf 2 3 def makepath(dstart,cstart,pattern,reps): 4 print pattern 5 alphabet = ' 123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' 6 # fopen('pathmade.lst', WRITE,TEXT) 7 coeff = dstart 8 oldcoeff = coeff/3 9 const = cstart 10 print 'coeff %d const %d oldcoeff %d' % (coeff,const,oldcoeff) 11 for i in xrange(1,reps+1): 12 print 'i',i 13 for j in xrange(1,len(pattern)): 14 print 'j',j 15 currstep = alphabet.index(pattern[j]) 16 print 'currstep',currstep 17 while currstep>2: 18 coeff = 4 * coeff 19 const = 4 * const 20 currstep = currstep - 2 21 print 'coeff %d const %d currstep %d' % (coeff,const,currstep) 22 if currstep==1: The moment line 3 scrolls off the top of the edit window, it appears in the code context window. This tells you that the current line at the top of the screen is in line 3's scope. When line 11 scrolls off, it appears in the code context window showing you that the current lines are now in the scope of the for loop. By the time you reach line 18, your code context window looks like (line 3 has scrolled off the code context window): 11 for i in xrange(1,reps+1): 13 for j in xrange(1,len(pattern)): 17 while currstep>2: Allowing you to see where line 18 is in the big picture. The moment I scroll past line 21, line 17 drops off the code context window showing me that my scope is now back to that of line 13. And no, I don't use it regulary because I wasn't even aware of it until you asked. > > Thanks! > Senthil From Sebastien.Boisgerault at gmail.com Sun Apr 23 17:34:36 2006 From: Sebastien.Boisgerault at gmail.com (=?iso-8859-1?q?S=E9bastien_Boisg=E9rault?=) Date: 23 Apr 2006 14:34:36 -0700 Subject: Calling Python from Matlab In-Reply-To: <1145142008.801960.49110@t31g2000cwb.googlegroups.com> References: <1145142008.801960.49110@t31g2000cwb.googlegroups.com> Message-ID: <1145828076.512187.67290@j33g2000cwa.googlegroups.com> > Also, can you elaborate on what (if anything) it is about Matlab that > you feel you can't replicate in Python? Are you aware of matplotlib and > numpy? The features provided by some matlab 'toolboxes' (libraries in matlab-speak) are lacking, and are beyond what numpy + scipy may provide. Some projects done in Matlab could easily be translated to Python, but probably not the control engineering kind for example -- the algorithms provided by the control toolbox, the identification toolbox, etc. are standard tools in the field, and were implemented by domain experts. Don't get me wrong. There are A LOT of scientific projects that can be done with Python, and I'd rather cut my hand than do some Matlab programming when I can avoid it. I also believe that the work involved in the proper installation of numpy + scipy + matplotlib is far beyond the average Matlab user ability (check the amount of "installation problem" on the numpy mailing-list ...). But for sure, the work done in these libs is just great and their community is extremely reactive and helpful. Last thought: the "All Python behavior in the presence of infinities, NaNs, and signed zeroes is a platform-dependent accident" meme still worries me from time to time ... But, hey, that's probably just me :) Cheers, S.B. From johnjsal at NOSPAMgmail.com Sat Apr 1 19:22:33 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sat, 01 Apr 2006 19:22:33 -0500 Subject: running IDLE from another program? In-Reply-To: <442f10a0_1@newspeer2.tds.net> References: <442d7a45$1_2@newspeer2.tds.net> <442dba0f$0$11191$c3e8da3@news.astraweb.com> <442e0913$1_3@newspeer2.tds.net> <442e1333$0$2459$c3e8da3@news.astraweb.com> <442e6011_3@newspeer2.tds.net> <442ee151$0$9423$c3e8da3@news.astraweb.com> <442eef26_1@newspeer2.tds.net> <442ef875$0$9425$c3e8da3@news.astraweb.com> <442f10a0_1@newspeer2.tds.net> Message-ID: <442f1a30$0$4194$c3e8da3@news.astraweb.com> Kent Johnson wrote: > John Salerno wrote: >> Kent Johnson wrote: >> >>> The working directory must be wrong. Try calling Python directly with >>> full paths: >>> >>> C:\Python24\pythonw C:\Python24\Lib\idlelib\idle.pyw -r C:\path\to\myprog.py >> >> Perfect! Thank you so much! >> >> I put this line in the command line field, and I left "working >> directory" empty because I'm not sure what goes there. Should it be the >> main python directory, or the directory of the file being run? Either >> way, it seems to work without a working directory. > > Great! I would set the working directory to the dir containing your > program. That way if you have multiple modules in the program you will > be able to import them without any trouble. > > Kent Ok, thanks again! I love how this works now! :) From AGEDOR999 at yahoo.fr Thu Apr 6 08:51:55 2006 From: AGEDOR999 at yahoo.fr (okay) Date: 6 Apr 2006 05:51:55 -0700 Subject: BIOCHIP --->>> NO GOOD !! Message-ID: <1144327915.817708.140010@z34g2000cwc.googlegroups.com> Hello, http://www.av1611.org/666/biochip.html To Archbishop Christodoulos Paraskevaides of the Greek Orthodox Church in Athens and Greece Archbishop, I talked with a Greek Orthodox believer in Australia and he told me two things of interest in these last days, as we see it this day even. They had a large group of personnel from America come to Australia to set the same kind of situation there as in America, getting set to gather up all that will resist taking of this biochip implant which is the mark of their beast name and number in it, as well as all the information about you held in the computer beast Belgium center. They have also taken all the weapons of self defense away from all the people of Australia so that only these U.N. "peacekeepers" have weapons together with the new world order police. It is going on in America too. Little by little, they are going to take all the weapons of self defense away from Americans so there will be no one to resist the dictatorship takeover by adolf george bush as liken to a modern day adolf hitler. And just as adolf hitler was, so is george busha member of the satanic "skull and bones" society. His guide book is hitler's Mein Kampf. These new world order people are in every capital in high places as written, Ephesians 6:12, and are they that do II Corinthians 11:14 to 15. First, they started by putting a biochip in every stray dog. And now, every item you buy at the supermarket will have a biochip in it. And they are set to implant all the military in America with this biochip implant mark of their beast. Then Australia, New Zealand and then to all of Europe. It will come very quickly before the son of perdition is revealed soon to take charge of this new world order of antichrist people. There will be no neutral country to flee to, as all nations are being taken over. And their spy satellites can check all people, those that have this biochip implant and those that do not, so as to send their gestapo police to gather all who have not the biochip implant and take them to prisons to torture people so as to force them to accept this biochip implant mark of their beast with his name and number in it. Archbishop, Jesus warned us through His words given by His real prophet of this time, liken to Daniel 12:1 to 4 and Matthew 24:37 to 41, only that He will redeem you off this evil corrupt earth full of rebellious people. Soon will anyone really make it to where He is and all the real saints await you, Revelation 6:9 to 11. Brethren in Christ Jesus' Name, I do believe the Lord has to save Americans from the real trouble to come soon. Daniel 12:1-2. Bush has taken all the military out of America. Now all there is, hidden all over America, Chinese, Russian, German and other supposed to be U.N. "peacekeepers", which are not there for that purpose. Bush is gathering more German soldiers to protect the U.S. military bases. He says. Did you know they have big prisons made from used-to-be military bases, now to be used to gather all the persons on adolf bush's Blue list of people who will oppose his tyrannical takeover of America when he creates a situation to call upon Marshall law and simply takes over America soon. And all that will not accept his smallpox inoculation and biochip implant with the mark name and number of their beast as per Revelation 13:16-18, will be placed into one of these 107,000 big white boxcars with shackles to take them to a termination building where they end up as a pile of ash, to hide whatever happened to them. And it all is done through good old "christian" bush's direction. He is not a Christian, but a son of the devil, as most of the U.S. government who are also illuminati satanists. When bush places the mark into the people all over America, then the vision I saw in Athens, Greece, can come to pass. Down she goes. Only the very elect chosen few will the Lord gather out of it who are accounted worthy to be chosen of Him. His very elect chosen and faithful, Mark 13:20 + 22 + 27, to be quickened by the Holy Spirit alive in them as wise virgins written in Matthew 25:1 to 12. His true bride to be taken, Revelation 12:14. Revelation 22:11-12. His Servant, Elijah Elijah the Tishbite, PO Box 53702, Main Post Office - Gladstone Street, Limassol CYPRUS Messages of G-d servant prophet Elijah are on internet at: http://two-olive-trees.org/frames.html http://www.av1611.org/666/biochip.html http://www.stoppuce.be http://www.bigbrotherawards.eu.org/article.php3?id_article=593 http://anndann.musicker.net/rfid.htm http://www.rense.com/ http://www.dak-ministries.com/Marque_B%EAte.php http://www.chez.com/clanmdrcs/article/o6.html http://www.bugbrother.com/article237.html http://www.conspiration.cc http://www.onnouscachetout.com http://www.cheminementspirituel.net http://perso.wanadoo.fr/metasystems/Kiosque/Kiosque_MdM.html LOVE AND PEACE MCE From allan at webframeworks.com Tue Apr 11 14:34:49 2006 From: allan at webframeworks.com (Allan) Date: 11 Apr 2006 11:34:49 -0700 Subject: Python string.title Function Message-ID: <1144780489.627578.208160@t31g2000cwb.googlegroups.com> Hi All - We're developing in Python 2.4.3 and are noticing something strange. For example, when testing, here's what we're seeing: x = "here's my title!"; x = x.title(); print x; Here'S My Title! Notice the capitalization -- "Here'S". Any feedback on this issue is much appreciated. Thanks much, Allan From robin at reportlab.com Tue Apr 18 10:20:58 2006 From: robin at reportlab.com (Robin Becker) Date: Tue, 18 Apr 2006 15:20:58 +0100 Subject: [OT] Any Python lullabies? In-Reply-To: References: Message-ID: <4444F5CA.1020700@chamonix.reportlab.co.uk> Not a lullaby, but appropriate near easter(s) while 1: life.side.bright.look() -- Robin Becker From walterbyrd at iname.com Mon Apr 10 19:14:27 2006 From: walterbyrd at iname.com (walterbyrd) Date: 10 Apr 2006 16:14:27 -0700 Subject: Best Python web-hosting? In-Reply-To: <4439870a$0$4206$c3e8da3@news.astraweb.com> References: <1144605832.364688.305300@j33g2000cwa.googlegroups.com> <4439870a$0$4206$c3e8da3@news.astraweb.com> Message-ID: <1144710867.157793.264870@v46g2000cwv.googlegroups.com> John Salerno wrote: > I was testing out http://www.devisland.net/ and it's pretty nice. They > installed the latest versions of Python, mod_python and mysqldb at my > request, and support was good. Only real problem is it's too expensive > for the space you get (about $5/month for 100MB), but you said space > wasn't much of an issue. I have just discovered http://www.dollar-hosting.org/ 400mb hdd, and 5gm bandwith for $10/year. And they have mod_python. From pmartin at snakecard.com Thu Apr 20 18:33:18 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Thu, 20 Apr 2006 17:33:18 -0500 Subject: Thanks from the Java Developer References: <1145474995.143893.31760@z34g2000cwc.googlegroups.com> <1145568613.146056.135230@u72g2000cwu.googlegroups.com> Message-ID: Yes, and then you have to answer Java/C/C++ job/contracts opening knowing real well the mistake they're making ... as well as you are for answering ;-) Ant wrote: > Python ruined my life. > > I am a Java programmer by profession, and ever since learning Python, I > find it a real chore to open Eclipse and write Java code (or worse - > the XML config files that seem to glue J2EE together). And while I > spend some of my spare time liberated by Python, I spend 10 times as > much time coding in Java at work. > > While this is just a little tongue in cheek, I do very frequently find > myself thinking "Why is this so hard?" when doing something that would > be trivial in Python. One of my favorites: > > f = open("file.txt") > s = f.read() > f.close() > > StringBuffer b = new StringBuffer(); > try { > BufferedReader br = new BufferedReader(new FileReader("file.txt")); > String line = br.readLine(); > > while (line != null){ > b.append(line); > line = br.readLine(); > } > } catch (IOException ex){} > String s = b.toString(); > > > WTF!! From tomerfiliba at gmail.com Tue Apr 18 05:26:57 2006 From: tomerfiliba at gmail.com (gangesmaster) Date: 18 Apr 2006 02:26:57 -0700 Subject: How protect proprietary Python code? (bytecode obfuscation?, what better?) In-Reply-To: References: <1145293384.791678.14450@v46g2000cwv.googlegroups.com> <1145300492.623527.300740@e56g2000cwe.googlegroups.com> Message-ID: <1145352417.100210.266170@e56g2000cwe.googlegroups.com> okay, i got the name wrong. i wasn't trying to provide production-level code, just a snippet. the function you want is PyRun_SimpleString( const char *command) #include char secret_code[] = "print 'moshe'"; int main() { return PyRun_SimpleString(secret_code); } and you need to link with python24.lib or whatever the object file is for your platform. -tomer From julius.welby at gmail.com Sat Apr 29 10:16:47 2006 From: julius.welby at gmail.com (jwelby) Date: 29 Apr 2006 07:16:47 -0700 Subject: Need help removing list elements. In-Reply-To: <1146319913.033340.30800@u72g2000cwu.googlegroups.com> References: <1146316090.540227.278230@j73g2000cwa.googlegroups.com> <1146319913.033340.30800@u72g2000cwu.googlegroups.com> Message-ID: <1146320207.017097.254270@j73g2000cwa.googlegroups.com> Ooops! Looking at your example a bit closer, change the 'and' in the list comprehension I posted to 'or', and it should do what you want. From No.Spam at Spam.none Sun Apr 30 21:35:11 2006 From: No.Spam at Spam.none (I. Myself) Date: Mon, 01 May 2006 01:35:11 GMT Subject: How can I implement a timeout with subprocess.Popen()? Message-ID: I want my Python program to invoke a compiled C program, and capture the text output. Here's a fragment from a program that works, using subprocess.Popen: p = Popen(execName, stdout=PIPE) while(1): line = p.stdout.readline() # get next line outfile.write(line) (Then I test for a certain unique phrase in line, and then break if it occurs) The above works fine as long as the target program runs for a little while and then stops. But what if it does not stop? It might run forever, with or without outputting any lines. How can I make this robust? The keyword might not occur. The target might crash. It might run forever, with or without text output. Thanks, Mitchell Timin -- I'm proud of http://ANNEvolve.sourceforge.net. If you want to write software, or articles, or do testing or research for ANNEvolve, let me know. Humans may know that my email address is: (but remove the 3 digit number) zenguy at shaw666 dot ca From robert.kern at gmail.com Wed Apr 12 22:22:47 2006 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 12 Apr 2006 21:22:47 -0500 Subject: quiet conversion functions In-Reply-To: <443DB46F.4050804@tim.thechases.com> References: <443DB46F.4050804@tim.thechases.com> Message-ID: Tim Chase wrote: > Are there existing "quiet" conversion functions? Kin of > int() and float()? Not in the standard library. Nor will there be. It goes against the development philosophy of the core Python development team. > My aim would be to call a function that would guarntee that > the result was of the defined type, choosing sensible > defaults if needed. Only you know what "sensible" is in your context, so you get to write the function. -- Robert Kern robert.kern at gmail.com "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From uymqlp502 at sneakemail.com Thu Apr 6 20:14:22 2006 From: uymqlp502 at sneakemail.com (Russ) Date: 6 Apr 2006 17:14:22 -0700 Subject: output formatting for user-defined types In-Reply-To: References: <1144283268.217968.316100@i39g2000cwa.googlegroups.com> <1144287077.109309.16300@z34g2000cwc.googlegroups.com> <1144346706.300959.123610@i40g2000cwc.googlegroups.com> Message-ID: <1144368862.466490.58240@v46g2000cwv.googlegroups.com> >I'm sorry, your system of units doesn't allow trig functions to operate on >degrees? I presume you don't allow grads either. What about steradians or >other arbitrary measures of angle or solid angle? I should have stated that more clearly. You can enter the value in degrees, but it will automatically get converted to radians for internal use. When you pass it to a trig function, it will automatically be in radians. For example: >>> angle = 30 * deg >>> print sin(angle) 0.5 You could force it to maintain degrees internally if you wanted to, but then you couldn't pass it to a trig function. That little feature prevents perhaps the most common unit error, passing degrees when radians are expected. I once heard about a simulation that was run for six months before the researchers realized that their results were corrupted by such an error. Yes, that's an extreme case, and maybe they were nitwits (with Ph.Ds), but these errors are very commonplace and often costly in terms of corrupted results or debugging time. And who knows how many times such errors subtly corrupted results but were never even detected? If you want to print it out in degrees, you must explicitly specify degrees, then it will get converted to degrees for output. For example: >>> angle = 30 * deg >>> print >> format ( angle, "deg", "%4.2f" ) 30.00 deg That may seem inconvenient, but it actually helps when the units are turned off for efficiency, because then the units are still known and can be printed out explicity. >(3) You're not my mother. If I want to shoot myself in the foot by >extracting the scalar part of one of your precious units and then doing >inappropriate things to it, that's absolutely none of your business. I am developing a way to guard against common errors in scientific and engineering software. If you want to use it, then don't. I work in air traffic control, so I am very concerned about such errors. [No, we don't use Python for actual operational ATC, but I use it for prototyping and data analysis. Nevertheless, I believe in avoiding errors anyway.] >I suggest another approach: play nice with the rest of Python by allowing >people to convert your units into strings and floats. Once they have >explicitly done so, it isn't your problem if they want to add 35 metres to >18 kilograms and convert the answer into minutes. Converting to a float is a trivial matter of dividing by the units of the scalar. For example: >>> dist = 4 * ft >>> print >> out, dist/ft 4 Note, however, that this requires the user to explicity ask for the conversion. What is unwise is to allow the conversion to happen automatically without the user's awareness. That's where bugs creep in. From sjmachin at lexicon.net Wed Apr 12 22:09:55 2006 From: sjmachin at lexicon.net (John Machin) Date: Thu, 13 Apr 2006 12:09:55 +1000 Subject: Iterating command switches from a data file - have a working solution but it seems inefficient In-Reply-To: References: <123r6925duev9b2@corp.supernews.com> Message-ID: <443db30a$1@news.eftel.com> On 13/04/2006 11:23 AM, James Stroud wrote: > News wrote: >> Hi everyone, >> My goal is to pull command switches/options from a file and then assign >> the values to select variables which would eventually be included in a >> class object. >> The data file looks something like this but the switches could be in any >> order and not all may be used. >> -m quemanager -s server -p port -k key -o object -c 20 -t test at email.com >> Also, please keep in mind that the source code will have more than one >> line in it and each has to be treaded separately. >> In a first pass, I wrote the following code which works but there is >> probably a better way of doing it. >> Any ideas to make it more efficient/stream-lined would be greatly >> appreciated. >> >> #!/usr/bin/python >> >> import string Which version of Python is the OP using?? >> inp = open("const.txt","r") >> # >> # Read File >> # >> >> while True: >> >> # >> # Get line from file >> # >> line=inp.readline() >> >> # >> # Check for EOF or break line up to extract relevant pieces >> # >> if len(line) == 0: >> break >> else: >> split_line=line.split() >> length=len(split_line) >> count=0 >> >> # >> # Evaluate list item and assign variable based on its contents >> # Print statements are for debugging purposes only >> # >> for i in range(length): >> if split_line[count] == "-m": >> qmgr=split_line[count+1] >> print "Queue Manager",qmgr; [snip] >> elif split_line[count] == "-c": >> check=split_line[count+1] >> print "Check",check; >> elif split_line[count] == "-d": >> report="" Uh-oh ... the plot just changed. Looks like -d and -q are NOT meant to be followed by an operand. >> print "Report",report; >> elif split_line[count] == "-q": >> display=False >> print "Display",display; >> else: >> continue >> >> count=count+1 >> >> # Close input file >> # >> inp.close() >> > > Anyone who got the previous message, there was a typo. This looks better > > opt_map = {'m': 'Queue Manager', 's': 'Server', 'p': 'Port', > 'o': 'Object', 'k': 'Key', 't': 'To', > 'c': 'Check', 'd': 'Report', 'q': 'Display} > 'Queue Manager' is not suitable for later use as an attribute name. > afile = open("filename") > > settings = {} > for aline in afile: > splitline = aline.split() > flags, options = splitline[::2], splitline[1::2] > flags = [f[1] for f in flags] # get rid of pesky "-"s Actually that's getting rid of the first character irrespective of whether it's "-" or not -- except when there's only one character in which case it will die in a hole. > for flag, option in zip(flags, options): > settings[opt_map(flag)] = option > print "%s = %s" % (opt_map(flag), option) opt_map is a dict; should be opt_map[flag] in above two lines > > afile.close() > Like Peter said, use optparse -- it handles the no-argument flags, has error detection, defaults, can be told the type of the flag, already returns the goodies as attributes of an object, ... From alainpoint at yahoo.fr Mon Apr 10 04:06:24 2006 From: alainpoint at yahoo.fr (alainpoint at yahoo.fr) Date: 10 Apr 2006 01:06:24 -0700 Subject: challenging (?) metaclass problem Message-ID: <1144656384.077748.229010@u72g2000cwu.googlegroups.com> Hi, I have what in my eyes seems a challenging problem. Thanks to Peter Otten, i got the following code to work. It is a sort of named tuple. from operator import itemgetter def constgetter(value): def get(self): return value return get def createTuple(*names): class TupleType(type): pass class T(tuple): __metaclass__ = TupleType def __new__(cls, *args): if len(names) != len(args): raise TypeError return tuple.__new__(cls, args) for index, name in enumerate(names): setattr(T, name, property(itemgetter(index))) setattr(TupleType, name, property(constgetter(index))) return T if __name__ == '__main__': Point=makeTuple('x','y') p=Point(4,7) assert p.x==p[0] assert p.y==p[1] assert Point.x==0 assert Point.y==1 Now my problem is the following. I want to write a function called createDerivedTuple in order to create a class derived from the one created with the function createTuple, taking the parent class as first argument: def createDerivedTuple(parentclass,*names): ....... code yet to be figured out .... The usage should be as follows: DerivedPoint=makeDerivedTuple(Point,'z') p=DerivedPoint(4,7,9) assert p.x==p[0] assert p.y==p[1] assert p.z==p[2] assert DerivedPoint.x==0 assert DerivedPoint.y==1 assert DerivedPoint.z==2 I am still a newbie on metaclasses but i am convinced there are elegant solutions to this challenging problem. Best regards Alain From vanillayangyang at gmail.com Wed Apr 12 23:24:07 2006 From: vanillayangyang at gmail.com (Leon) Date: 12 Apr 2006 20:24:07 -0700 Subject: Regular Expression: Matching substring In-Reply-To: <1144895624.539696.322960@e56g2000cwe.googlegroups.com> References: <1144895624.539696.322960@e56g2000cwe.googlegroups.com> Message-ID: <1144898647.858122.98680@u72g2000cwu.googlegroups.com> Hi Kevin, You may notice that, for matching the regex (0|(1(01*0)*1))*, the left most three characters of a string must not be ``101" while not followed by an `0'. After reading the first `1', automata expects `1' or ``00" or ``010" or ``11", right?:) Kevin CH ??? > Hi, > > I'm currently running into a confusion on regex and hopefully you guys > can clear it up for me. > > Suppose I have a regular expression (0|(1(01*0)*1))* and two test > strings: 110_1011101_ and _101101_1. (The underscores are not part of > the string. They are added to show that both string has a substring > that matches the pattern.) Applying a match() function on the first > string returns true while false for the second. The difference is the > first one has unmatched chunk in the beginning while the second at the > end. How's the regex rule work here? > > Thanks. From bencvt at gmail.com Tue Apr 11 19:38:52 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 11 Apr 2006 16:38:52 -0700 Subject: Regular expression intricacies: why do REs skip some matches? In-Reply-To: References: <1144795311.560566.4190@j33g2000cwa.googlegroups.com> Message-ID: <1144798732.127411.244680@t31g2000cwb.googlegroups.com> Tim Chase wrote: > > In [1]: import re > > > > In [2]: aba_re = re.compile('aba') > > > > In [3]: aba_re.findall('abababa') > > Out[3]: ['aba', 'aba'] > > > > The return is two matches, whereas, I expected three. Why does this > > regular expression work this way? It's just the way regexes work. You may disagree, but it's more intuitive that iterated pattern searching be non-overlapping by default. See also: >>> 'abababa'.count('aba') 2 > Well, if you don't need the actual results, just their > count, you can use > > how_many = len(re.findall('(?=aba)', 'abababa') > > which will return 3. However, each result is empty: > > >>> print re.findall('(?=aba)', 'abababa') > ['','',''] > > You'd have to do some chicanary to get the actual pieces: (snip) Actually, you can just define a group inside the lookahead assertion: >>> re.findall('(?=(aba))', 'abababa') ['aba', 'aba', 'aba'] --Ben From onurb at xiludom.gro Wed Apr 19 13:49:46 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 19 Apr 2006 19:49:46 +0200 Subject: accessing a classes code In-Reply-To: References: <444666af$0$12280$626a54ce@news.free.fr> Message-ID: <4446788a$0$31457$626a54ce@news.free.fr> Ryan Krauss wrote: (top-post corrected) > > On 4/19/06, bruno at modulix wrote: > >>Ryan Krauss wrote: >> >>>I have a set of Python classes that represent elements in a structural >>>model for vibration modeling (sort of like FEA). Some of the >>>parameters of the model are initially unknown and I do some system >>>identification to determine the parameters. After I determine these >>>unknown parameters, I would like to substitute them back into the >>>model and save the model as a new python class. >> >>Why ? Python is dynamic enough to let you modify classes at runtime... > Because I want to store the results in one place so that in order to > use the code later, all I have to do is import the classes that > include the parameters that were previously unknown. I want to make > using the results as easy and clean as possible for other users. > I'm afraid you're still thinking in terms of the solution instead of thinking in terms of the problem to solve. The fact that classes can be modified at runtime doesn't means that client code needs to be aware of what happens. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From Bulkan at gmail.com Mon Apr 10 23:55:31 2006 From: Bulkan at gmail.com (placid) Date: 10 Apr 2006 20:55:31 -0700 Subject: import help In-Reply-To: <443b1789$1@nntp0.pdx.net> References: <1144716990.314306.79950@v46g2000cwv.googlegroups.com> <443b1789$1@nntp0.pdx.net> Message-ID: <1144727730.972948.162920@t31g2000cwb.googlegroups.com> Scott David Daniels wrote: > placid wrote: > > I have the following class code for a Node for a Linked List, (saved in > > node.py) > > > > class Node : > > def __init__(self,element): > > self.element = element > > self.next = None > > > > then i have another module called LinkedList.py, with following code > > > > import sys > > import node > > def main(): > > print "Does nothin ATM, as it doesnt work" > > main() > > > > the problem im having is that im getting NameError exception when i run > > LinkedList.py "global name 'Node' is not defined" > > > > Does anyone know what the problem is here? > > I have trouble believing you. I suspect you are telling us what you im not leaving anything out, im telling you what's happening > think is happening, and leaving something vital out. In particular, > cut and paste the traceback. here it is! Traceback (most recent call last): File "LinkedList.py", line 7, in ? main() File "LinkedList.py", line 4, in main n = Node("test") NameError: global name 'Node' is not defined > > Here's another experiment, interactively do: > > import node > print node.__file__ >>> import node >>> print node.__file__ node.py > > Perhaps that will tell you something. More information, im using Windows XP Pro, these two files are in same directory... > > --Scott David Daniels > scott.daniels at acm.org From alisonken1 at gmail.com Thu Apr 27 20:09:51 2006 From: alisonken1 at gmail.com (alisonken1) Date: 27 Apr 2006 17:09:51 -0700 Subject: Advanced Treeview Filtering Help In-Reply-To: References: Message-ID: <1146182991.005170.273620@g10g2000cwb.googlegroups.com> > Your question was answered on PyGTK mailing list. Please, don't crosspost. Where is the pygtk mailing list? From tkpmep at hotmail.com Thu Apr 6 15:45:10 2006 From: tkpmep at hotmail.com (tkpmep at hotmail.com) Date: 6 Apr 2006 12:45:10 -0700 Subject: Partially unpacking a sequence Message-ID: <1144352710.190839.165580@z34g2000cwc.googlegroups.com> I have a list y >>>y ['20001201', 'ARRO', '04276410', '18.500', '19.500', '18.500', '19.500', '224'] from which I want to extract only the 2nd and 4th item by partially unpacking the list. So I tried >>>a,b = y[2,4] Traceback (most recent call last): File "", line 1, in ? TypeError: list indices must be integers Out of curiosity, I tried >>>a,b = y[2:4] >>>a '04276410' >>> b '18.500' Why does this work (to a point - it gives me items 2 and 3, not 2 and 4 as I require) and not my first attempt? What is the right syntax to use when partially upacking a sequence? Thanks in advance Thomas Philips From johnjsal at NOSPAMgmail.com Tue Apr 4 12:44:38 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 04 Apr 2006 16:44:38 GMT Subject: how do you use pickle? In-Reply-To: References: Message-ID: Fredrik Lundh wrote: > define "image file". the data in the file, the file name, or some other > representation? I was being dense again. I was just opening the file, but not reading it! After reading it, it's easy to pickle it. > did you, by any chance, name your test script "pickle.py" ? That did the trick! Thanks! From benji at benjiyork.com Tue Apr 25 10:04:30 2006 From: benji at benjiyork.com (Benji York) Date: Tue, 25 Apr 2006 10:04:30 -0400 Subject: Zope 3 In-Reply-To: <444e1377$0$30724$636a55ce@news.free.fr> References: <1145965796.432891.274310@i39g2000cwa.googlegroups.com> <444e1377$0$30724$636a55ce@news.free.fr> Message-ID: <444E2C6E.6080602@benjiyork.com> bruno at modulix wrote: > Zope is a world in itself - and is certainly not the simplest tool to > learn (nor the most pythonic). Those statements apply more to Zope 2 than Zope 3 (and Zope 2 is moving more and more toward Zope 3 these days). One of Zope 3's main goals was to focus on the Python programmer as a primary target. That being said there /are/ some powerful and novel concepts used in Z3 (the component framework). > You may want to consider other options like Django, Pylon or Turbogears. It's true that Z3 is not currently focused very well on the "middle-class" developer. It's more of an industrial-strength kind of thing, but considerable thought has been given lately on how to build bridges so everyone can benefit without being full-time Zope masters. Toward that end, I wrote a little quick start guide that might help the OP: http://www.benjiyork.com/quick_start -- Benji York From fredrik at pythonware.com Sun Apr 9 03:51:18 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 9 Apr 2006 09:51:18 +0200 Subject: Decorators, Identity functions and execution... References: Message-ID: Chance Ginger" wrote: > If I define a decorator like: > > def t(x) : > def I(x) : return x > return I ... you get a syntax error. > and use it like: > > @t(X) > def foo(a) : > # definition of foo... > pass that's also a syntax error. > or maybe this: > > @t(X) > @(Y) > def bar(a) : > # The definition of bar... and that's not even fixable. > Will in encounter much of a penalty in executing > 'foo' or 'bar'? since foo is wrapped, calling foo will call your I function, which in turn calls the original foo. > If so, is there a way to define t such that Python knows it is > the identity function and short-circuit evaluation? if you don't want to wrap something, don't wrap it: def t(x) : def I(x) : return x if date == friday: return x # don't wrap it return I # wrap it From iddw at hotmail.com Mon Apr 3 10:48:09 2006 From: iddw at hotmail.com (Dave Hansen) Date: Mon, 03 Apr 2006 09:48:09 -0500 Subject: Difference between 'is' and '==' References: <1143459098.385264.139560@g10g2000cwb.googlegroups.com> Message-ID: On 3 Apr 2006 10:37:11 -0400 in comp.lang.python, roy at panix.com (Roy Smith) wrote: >Adam DePrince wrote: >> It just happens that the >>logical operation >> >> (a is b ) -> (a == b ) >> >>is always True. > >Only for small values of "always". You can always do pathological >things with operators: > >class Foo: > def __eq__ (self, other): > return False > >f = Foo() >print f is f >print f == f > >frame:play$ ./is.py >True >False > >This may even be useful. What if you were trying to emulate SQL's >NULL? NULL compares false to anything, even itself. To test for >NULLness, you have to use the special "is NULL" operator. Another instance where this may be useful is IEEE-754 NaN. I don't have fpconst to verify if that's the case, but I would expect NaN is NaN to be true, but NaN == NaN to be false. Regards, -=Dave -- Change is inevitable, progress is not. From news at grauer-online.de Tue Apr 18 12:44:42 2006 From: news at grauer-online.de (Uwe Grauer) Date: Tue, 18 Apr 2006 18:44:42 +0200 Subject: How to stop winpdb programatically Message-ID: How can i stop winpdb at a special point in a file? I know that there is set_trace() in pdb which stops execution in the debugger, but how to do this in winpdb? Thanks for hints, Uwe From ryang at gol.com Tue Apr 4 04:01:43 2006 From: ryang at gol.com (Ryan Ginstrom) Date: Tue, 4 Apr 2006 17:01:43 +0900 Subject: Framework/module for generating HTML documentation Message-ID: <007101c657be$0504ef10$030ba8c0@RYAN> I have been maintaining a body of documentation in plain HTML files. I would now like to automate the generation of the HTML files. Maintaining the HTML files now is tedious and error prone, because every time I move/remove/add a section, I have to renumber the following sections and update my internal links. I have looked at some of the HTML-generation frameworks, but the selection is somewhat bewildering, and most also seem geared to generating dynamic or static content for Websites. I guess what I am looking for is a Wiki-like documentation generation engine, but generating a bunch of statically linked files. E.g., I want to go from something like this:

Introduction

Some text

Getting Started

Some text

Installation

Some text. See

Getting Started
for details.

To this: [index.html]

Contents

1. Introduction 2. Getting Started
2.1. Installation
[1.html]

1. Introduction

Some text

Contents Next [2.html]

2. Getting Started

Some text

Prev Contents Next [2_1.html]

2.1. Installation

Some text. See Getting Started for details.

Prev Contents Next If someone can recommend a framework/module that will help me achieve this, I would greatly appreciate it. I could do it from scratch, but if this has been tackled before (as I suspect it has), I'd like to stand on those developers' shoulders . Regards, Ryan --- Ryan Ginstrom From aleaxit at yahoo.com Sun Apr 23 23:54:26 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 23 Apr 2006 20:54:26 -0700 Subject: Using distutils in Windows XP / "Python in a Nutshell" References: Message-ID: <1he9kgi.1621kyl1gixpf0N%aleaxit@yahoo.com> Blair LeGent wrote: > Following the directions in "Python in a Nutshell" (an excellent book), Thanks! > I entered the C code for "helloworld.c", saved it as a file, and entered > this script and saved it as setup.py: > > from distutils.core import setup, Extension > setup(name='helloworld', ext_modules= [ > Extension('helloworld',sources=['helloworld.c'])]) > > Then, following directions, I type "python setup.py install" from a C:\> > prompt. I get these messages: > > running install > running build > running build_ext > error: The .NET Framework SDK needs to be installed before building > extensions for Python. > > ...but the .NET Framework IS installed; the latest version, in fact, SDK > v2.0, part of the Visual Studio 2005 beta I've got. From poking around > the Internet it looks like I'm supposed to (a) monkey with my registry, > (b) install an OLD version of the SDK, (c) screw around with distutils > source code, or (d) switch to Linux. Nowhere do I find a clear solution > to my problem, though. Can anyone help? Should we submit an errata to > O'Reilly? No need: the second edition (forthcoming!) does explain that the compiler you need to build Python extensions (for 2.4 and 2.4) is VS 2003. I don't belabor on the hows and whys of VS2005 not being supported -- I'm not into Windows (over the last few years) to grok them fully. explains one way to avoid shelling out $$$ to MS while still being able to build Python extensions -- and just today I asked on this very group about where to find VS 20003 Toolkit (it's not at its original location indicated at the above URL, any more!) and was promptly answere with a URL that worked just fine. Alex From lashkariNO at SPAMworldviz.com Tue Apr 25 19:48:35 2006 From: lashkariNO at SPAMworldviz.com (Farshid Lashkari) Date: Tue, 25 Apr 2006 16:48:35 -0700 Subject: can someone explain why .. In-Reply-To: References: Message-ID: Sch?le Daniel wrote: > thx for quick reply :) > > image is local variable of imageLabel > I would expect that in case imageLabel lives, it should > hold alife objects bound to its local variables > > I am just curious *why* reference to image is not hold by imageLabel > which on his part is hold by frame1 .. which is hold by global root These are the only lines of code that reference "imageLabel": imageLabel = Label(master = frame1, image = image) imageLabel.pack() Unless the constructor of Label adds a reference of itself to frame1, imageLabel will also become garbage collected at the end of the constructor. Are you sure this is the case? -Farshid From python.list at tim.thechases.com Fri Apr 21 11:16:14 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 21 Apr 2006 10:16:14 -0500 Subject: how to append to a list twice? In-Reply-To: References: Message-ID: <4448F73E.90609@tim.thechases.com> > If I want to create a list of the form [100, 99, 99, 98, 98, 97, 97...] > (where each item is repeated twice after the first one), how might I do > that most efficiently? > > Right now I have this: > > series = [100] > for x in range(10): # just for testing > series.append(series[-1] - 1) Well, you can do something like def foo(start): count = 0 while 1: yield start - ((count + 1) / 2) count += 1 which is pretty efficient in the matter. If you just need the results, you can do something like series = [100] for _ in range(10): series.extend([x[-1]-1]*2) Both should get you what you want, and one or the other may be better depending on the scenario in which you want to use it. -tkc From kbk at shore.net Fri Apr 28 23:08:27 2006 From: kbk at shore.net (Kurt B. Kaiser) Date: Fri, 28 Apr 2006 23:08:27 -0400 (EDT) Subject: Weekly Python Patch/Bug Summary Message-ID: <200604290308.k3T38R9n004599@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 378 open ( +7) / 3199 closed ( +4) / 3577 total (+11) Bugs : 901 open ( -7) / 5792 closed (+25) / 6693 total (+18) RFE : 214 open ( +3) / 214 closed ( +2) / 428 total ( +5) New / Reopened Patches ______________________ Allow PyArg_ParseTupleAndKeywords to unpack tuples (2006-04-22) http://python.org/sf/1474454 reopened by loewis Allow PyArg_ParseTupleAndKeywords to unpack tuples (2006-04-21) http://python.org/sf/1474454 opened by Roger Upole detect %zd format for PY_FORMAT_SIZE_T (2006-04-22) http://python.org/sf/1474907 opened by Brett Cannon New doctest option: +SKIP (2006-04-23) CLOSED http://python.org/sf/1475231 opened by Edward Loper patch fixing #1448060 (gettext.py bug) (2006-04-24) http://python.org/sf/1475523 opened by Thenault Sylvain IndentationError for unexpected indent (2006-04-24) http://python.org/sf/1475845 opened by Roger Miller Add help reference on Mac (2006-04-25) http://python.org/sf/1476578 opened by Bruce Sherwood __init__.py'less package import warnings (2006-04-27) http://python.org/sf/1477281 opened by Thomas Wouters Allow os.listdir to accept file names longer than MAX_PATH (2006-04-26) http://python.org/sf/1477350 opened by Roger Upole Fix doctest nit. (2006-04-28) http://python.org/sf/1478292 opened by Thomas Heller Picky floats (2006-04-28) http://python.org/sf/1478364 opened by Skip Montanaro Patches Closed ______________ Allow PyArg_ParseTupleAndKeywords to unpack tuples (2006-04-22) http://python.org/sf/1474454 closed by loewis Weak linking support for OSX (2006-04-17) http://python.org/sf/1471925 closed by ronaldoussoren test for broken poll at runtime (2006-04-17) http://python.org/sf/1471761 closed by ronaldoussoren New doctest option: +SKIP (2006-04-23) http://python.org/sf/1475231 closed by tim_one start testing strings > 2GB (2006-04-17) http://python.org/sf/1471578 closed by twouters New / Reopened Bugs ___________________ non-keyword argument following keyword (2006-04-23) http://python.org/sf/1474677 opened by George Yoshida pickling files works with protocol=2. (2006-04-22) http://python.org/sf/1474680 opened by Kirill Simonov Document os.path.join oddity on Windows (2006-04-23) CLOSED http://python.org/sf/1475009 opened by Miki Tebeka example code in what's new/sqlite3 docs (2006-04-23) CLOSED http://python.org/sf/1475080 opened by James Pryor Tkinter hangs in test_tcl (2006-04-23) http://python.org/sf/1475162 opened by Thomas Wouters Poorly worded description for socket.makefile() (2006-04-24) http://python.org/sf/1475554 opened by Roy Smith replacing obj.__dict__ with a subclass of dict (2006-04-24) http://python.org/sf/1475692 opened by ganges master SystemError in socket sendto (2006-04-25) CLOSED http://python.org/sf/1476111 opened by CyDefect Documentation date stuck on "5th April 2006" (2006-04-25) CLOSED http://python.org/sf/1476216 opened by Mat Martineau StringIO should implement __str__() (2006-04-25) CLOSED http://python.org/sf/1476356 opened by Dom Lachowicz Finish PEP 343 terminology cleanup (2006-04-26) http://python.org/sf/1476845 opened by Nick Coghlan Missing import line in example (2006-04-26) CLOSED http://python.org/sf/1477102 opened by Bruce Eckel Incorrect code in example (2006-04-26) CLOSED http://python.org/sf/1477140 opened by Bruce Eckel test_bsddb skipped -- Failed to load /home/shashi/Python-2.4 (2006-04-27) http://python.org/sf/1477450 opened by shashi test_ctypes: undefined symbol: XGetExtensionVersion (2006-04-28) http://python.org/sf/1478253 opened by balducci Invalid value returned by util.get_platform() on HP (2006-04-28) CLOSED http://python.org/sf/1478326 opened by S?bastien Sabl? test_capi crashed -- thread.error: can't allocate lock (2006-04-28) CLOSED http://python.org/sf/1478400 opened by shashi datetime.datetime.fromtimestamp ValueError. Rounding error (2006-04-28) CLOSED http://python.org/sf/1478429 opened by Erwin Bonsma size limit exceeded for read() from network drive (2006-04-28) http://python.org/sf/1478529 opened by Mark Sheppard Bugs Closed ___________ IDLE does not start 2.4.3 (2006-04-17) http://python.org/sf/1471806 closed by egrimes TempFile can hang on Windows (2006-04-20) http://python.org/sf/1473760 closed by tim_one import module with .dll extension (2006-04-18) http://python.org/sf/1472566 closed by gbrandl Document os.path.join oddity on Windows (2006-04-23) http://python.org/sf/1475009 closed by gbrandl example code in what's new/sqlite3 docs (2006-04-23) http://python.org/sf/1475080 closed by akuchling interactive: no cursors ctrl-a/e... in 2.5a1/linux/debian (2006-04-18) http://python.org/sf/1472173 closed by twouters doctest mishandles exceptions raised within generators (2005-10-25) http://python.org/sf/1337990 closed by tim_one SystemError in socket sendto (2006-04-25) http://python.org/sf/1476111 closed by twouters string parameter to ioctl not null terminated, includes fix (2006-02-17) http://python.org/sf/1433877 closed by twouters Documentation date stuck on "5th April 2006" (2006-04-25) http://python.org/sf/1476216 closed by akuchling can't send files via ftp on my MacOS X 10.3.9 (2006-02-23) http://python.org/sf/1437614 closed by tjreedy StringIO should implement __str__() (2006-04-25) http://python.org/sf/1476356 closed by rhettinger Missing import line in example (2006-04-26) http://python.org/sf/1477102 closed by akuchling Incorrect code in example (2006-04-26) http://python.org/sf/1477140 closed by akuchling Math mode not well handled in \documentclass{howto} (2005-02-17) http://python.org/sf/1124692 closed by fdrake Windows non-MS compiler doc updates (2003-11-10) http://python.org/sf/839709 closed by fdrake "print statement" in libref index broken (2006-01-21) http://python.org/sf/1411674 closed by fdrake AF_UNIX sockets do not handle Linux-specific addressing (2003-07-02) http://python.org/sf/764437 closed by gbrandl The -m option to python does not search zip files (2005-08-02) http://python.org/sf/1250389 closed by pmoore Invalid value returned by util.get_platform() on HP (2006-04-28) http://python.org/sf/1478326 closed by gbrandl test_capi crashed -- thread.error: can't allocate lock (2006-04-28) http://python.org/sf/1478400 closed by gbrandl datetime.datetime.fromtimestamp ValueError. Rounding error (2006-04-28) http://python.org/sf/1478429 closed by gbrandl shutil.copytree debug message problem (2006-04-19) http://python.org/sf/1472949 closed by gbrandl urllib2.Request constructor to urllib.quote the url given (2006-04-20) http://python.org/sf/1473560 closed by gbrandl New / Reopened RFE __________________ feature requests for logging lib (2006-04-22) http://python.org/sf/1474577 opened by blaize rhodes feature requests for logging lib (2006-04-22) CLOSED http://python.org/sf/1474609 opened by blaize rhodes compute/doc %z os-indep., time.asctime_tz / _TZ (2006-04-24) http://python.org/sf/1475397 opened by kxroberto Add SeaMonkey to webbrowser.py (2006-04-25) CLOSED http://python.org/sf/1476166 opened by Oleg Broytmann Drop py.ico and pyc.ico (2006-04-27) http://python.org/sf/1477968 opened by Martin v. L??wis RFE Closed __________ feature requests for logging lib (2006-04-22) http://python.org/sf/1474609 closed by gbrandl Add SeaMonkey to webbrowser.py (2006-04-25) http://python.org/sf/1476166 closed by gbrandl From jena.forum at centrum.cz Fri Apr 14 10:20:00 2006 From: jena.forum at centrum.cz (Jan Prochazka) Date: Fri, 14 Apr 2006 16:20:00 +0200 Subject: zlib and zip files Message-ID: <443FAF90.8080008@centrum.cz> Hi, I need to decompress zip archive. I wrote a parser of zip file, i obtain the compressed data, but when i call zlib.decompress(data) on them, it throws this error: decbuf = decompressor.decompress(compressed_data) error: Error -3 while decompressing: unknown compression method I try to compress by zlib the same data which are in that file, the result was 6 bytes bigger, '\x78\xda' on begin and '\xc9\x1f\x87\x0b' on end when i tried to put this extending data to zlib decompressor, it decompress some files of zip archive, but it fails, when i try to decompress 100MB file from archive could you help, please? thanks Honza From aahz at pythoncraft.com Tue Apr 11 16:24:30 2006 From: aahz at pythoncraft.com (Aahz) Date: 11 Apr 2006 13:24:30 -0700 Subject: Why new Python 2.5 feature "class C()" return old-style class ? References: <1144752553.305591.88050@j33g2000cwa.googlegroups.com> <1144763219.936992.219110@g10g2000cwb.googlegroups.com> Message-ID: In article , Felipe Almeida Lessa wrote: >Em Ter, 2006-04-11 ??s 07:17 -0700, Aahz escreveu: >> >> Can, yes. But should it? The whole point of adding the () option to >> classes was to ease the learning process for newbies who don't >> understand why classes have a different syntax from functions. Having >> >> class C(): pass >> >> behave differently from >> >> class C: pass >> >> would be of no benefit for that purpose. > >Why should a newbie use an old-style class? Because that's the default. Because lots of existing code still uses classic classes, so you need to learn them anyway. Because you can't use new-style classes in code intended for 2.1 or earlier; because of the changes made in 2.3, I don't particularly recommend new-style classes for 2.2. Because even the second edition of _Learning Python_ (targeted at Python 2.3) doesn't cover new-style classes much, so I'm certainly not alone in believing that new-style classes are better avoided for newbies. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "LL YR VWL R BLNG T S" From roy at panix.com Mon Apr 17 22:21:28 2006 From: roy at panix.com (Roy Smith) Date: Mon, 17 Apr 2006 22:21:28 -0400 Subject: Java Developer Exploring Python References: <1145290449.735642.120860@i40g2000cwc.googlegroups.com> <1145292795.565277.288760@v46g2000cwv.googlegroups.com> <1hdyb46.1yllkst1o2asjlN%aleaxit@yahoo.com> Message-ID: In article <1hdyb46.1yllkst1o2asjlN%aleaxit at yahoo.com>, aleaxit at yahoo.com (Alex Martelli) wrote: > Consider for example that one of the additions to Python 2.5 (currently > in alpha stage) is the inclusion in the Python standard library of > ctypes Indeed, I think the inclusion of ctypes is far and away the most exciting thing in 2.5. From andre.roberge at gmail.com Tue Apr 25 21:42:25 2006 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 25 Apr 2006 18:42:25 -0700 Subject: How to avoid using files to store intermediate results Message-ID: <1146015744.958386.128250@v46g2000cwv.googlegroups.com> I wrote a small wxPython based app to test code snippets. (google for "python lightning compiler" if you want to see the full code). In the basic mode, I redirect the standard input and output and execute the code taken from the editor window so that the result appears in the output window. Here are the 4 main lines of code to accomplish this: sys.stdout = self.outputWindow sys.stderr = self.outputWindow user_code = self.PythonEditor.GetText() exec user_code in myGlobals For example, if I have the following situation: ====input window==== print "Hello world!" ==================== the result of running the program will be this: ====output window=== Hello world! ==================== Simple enough :-) [Actually, there's more to it, but this description should suffice for illustration purposes.] Now, I want to be able to test the code using the doctest module. I can't use exec as doctest.testmod() will be testing my entire application, not simply the code in the input window! The solution I chose was to 1. Create a new file which contains the code to be tested with the appropriate "doctest" call. 2. Run this file with Python, redirecting the result to a second file. 3. Read the result from the second file into a string. 4. Print the string (which, because of redirection) appears in the output window. Here are the main lines of code to do this: sys.stdout = self.outputWindow sys.stderr = self.outputWindow user_code = self.PythonEditor.GetText() user_code += "\nimport doctest\ndoctest.testmod()" f = open('_doctest_file.py', 'w') f.write(user_code) f.close() if verbose: os.popen("python _doctest_file.py -v> _doctest_file.output") else: os.popen("python _doctest_file.py> _doctest_file.output") result = open("_doctest_file.output", 'r').read() print result ###### While this works, I find it "messy", as it creates some intermediate files. I was wondering if there was a better way to do things all in memory, in an OS independent way. [Note that the complete application is approximately 665 lines long ... a bit too much to post all here :-)] Andr? From grante at visi.com Tue Apr 25 21:17:35 2006 From: grante at visi.com (Grant Edwards) Date: Wed, 26 Apr 2006 01:17:35 -0000 Subject: can someone explain why .. References: Message-ID: <124tihfb2o0lq59@corp.supernews.com> On 2006-04-25, Sch?le Daniel wrote: >> I'm not familiar with Tkinter, but it seems as thought with 2, >> the "image" variable is garbage collected after the >> constructor of Main is called. With 1, you save a reference to >> the image, so it does not get garbage collected. Correct. > image is local variable of imageLabel Actually it's a parameter to the constructor that was called to create the "imageLabel" object. > I would expect that in case imageLabel lives, it should hold > alife objects bound to its local variables It would. Therefore the "image" object apparently isn't bound to a local variable in the object imageLabel. > I am just curious *why* reference to image is not hold by > imageLabel which on his part is hold by frame1... Good question. Untold millions of programmers have tripped over that bug. Well, would you believe untold dozens? I know I did. It's a common enough problem that it's given special mention in a couple books on Tkinter. My _guess_ is that this is one of the misfeatures resulting from the way Tkinter is implimented: it's not a real binding of Python to the tk library. It's a Python wrapper around a TCL interpreter which is bound to the tk library (or something like that). This results in some counter-intuitive (non-pythonic) behaviors like the one you discovered with bitmap images and labels. -- Grant Edwards grante Yow! I feel like I'm at in a Toilet Bowl with a visi.com thumbtack in my forehead!! From UrsusMaximus at gmail.com Thu Apr 6 08:19:27 2006 From: UrsusMaximus at gmail.com (UrsusMaximus at gmail.com) Date: 6 Apr 2006 05:19:27 -0700 Subject: An interview with Michael Foord, aka "Fuzzyman" on Python411 Message-ID: <1144325967.884129.149330@i39g2000cwa.googlegroups.com> www.awaretek.com/python/index.html features a Python411 interview with Michael Foord, aka Fuzzyman, Python hacker who has contributed a disproportionate amount and quality of open source projects, applications, tools, tutorials, Pyzine articles, and more in his mere 3 years in the community. This is the first Python411 interview, look for more to come. Also, if you are Python hacker with a story to tell, why not share your experiences and tell the community more about your project(s). Just email me at rdsteph at mac.com to set up an interview. Ron Stephens www.awaretek.com/python/index.html From johnjsal at NOSPAMgmail.com Thu Apr 13 11:48:24 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 13 Apr 2006 15:48:24 GMT Subject: trying to grasp OO : newbie Q? In-Reply-To: <1144941250.517385.144590@u72g2000cwu.googlegroups.com> References: <1144937168.508799.67410@i40g2000cwc.googlegroups.com> <1144938934.900062.219600@i40g2000cwc.googlegroups.com> <1144941250.517385.144590@u72g2000cwu.googlegroups.com> Message-ID: mitsura at skynet.be wrote: > Thanks guys, > > It is starting to make much more sense. Most documentation I find about > OO is very academic Couldn't we also say that this issue of namespace scope is a little more specific to Python than OOP in general? I could very easily be wrong, but I wouldn't want the poster to think that this is how OOP works always. From carlosperezs at alumnos.uvigo.es Thu Apr 27 04:35:30 2006 From: carlosperezs at alumnos.uvigo.es (carlosperezs at alumnos.uvigo.es) Date: Thu, 27 Apr 2006 10:35:30 +0200 Subject: No subject Message-ID: <1146126930.44508252ee3d6@correoweb.uvigo.es> Hallo !!! I am new in Python and my doubts are basics.I would like to a window appears when press a button. This window would have only an advise. Therefore it would be a simple window. I don't know which window to choose. Thank you. --oOo-----------------------------------------------------------------oOo-- Servicio de acceso ? correo electr?nico v?a web da Universidade de Vigo Servicio de acceso al correo electr?nico v?a web de la Universidad de Vigo Servicios Inform?ticos [ http://si.uvigo.es ] Universidade de Vigo [ http://www.uvigo.es ] URL: https://correoweb.uvigo.es From kent at kentsjohnson.com Sat Apr 8 09:10:58 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Sat, 08 Apr 2006 09:10:58 -0400 Subject: Characters contain themselves? In-Reply-To: References: Message-ID: <4437b0f4$1_3@newspeer2.tds.net> WENDUM Denis 47.76.11 (agent) wrote: > While testing recursive algoritms dealing with generic lists I stumbled > on infinite loops which were triggered by the fact that (at least for my > version of Pyton) characters contain themselves.See session: Strings are sequences and this is a problem for recursive functions that process nested lists. You do need to test for stringiness somehow. IIRC the usual solutions are - explicit test for string: isinstance(xx, basestring) - explicit test for list: isinstance(xx, list) - this fails for user-defined sequences that don't subclass list - test for __iter__ attribute. IIUC this relies on an implementation detail that strings don't define __iter__: In [6]: hasattr('aa', '__iter__') Out[6]: False In [7]: hasattr([], '__iter__') Out[7]: True Kent From aleaxit at yahoo.com Wed Apr 19 11:22:31 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 19 Apr 2006 08:22:31 -0700 Subject: Ironpython book? References: <1145329406.419299.12780@i40g2000cwc.googlegroups.com> <1he15xj.1dy2h0vzbebqmN%aleaxit@yahoo.com> Message-ID: <1he18dm.e64uky1urr3n0N%aleaxit@yahoo.com> John Salerno wrote: > Alex Martelli wrote: > > John Salerno wrote: > > ... > >> Just out of curiosity, is Python.NET a dead project? > > > > AFAIK, it's a long-completed research project. I do not know of anybody > > planning to fork it to a new project, though that of course does not > > rule out that somebody might be planning to do so. > > But is IronPython sort of the 'official' .NET implementation of Python > though? I know there is a difference between the two, but I haven't > heard about Python.NET in so long that I thought maybe it wasn't being > developed/used anymore. IronPython seems to be the equivalent of Jython > for .NET. Sure, particularly since both Jython and IronPython are brainchildren of Jim Hugunin. But, apparently, we're having communication problems. Since I say that Python.NET is "a long-completed research project", what contradition do you find between that and your opinion that "it [isn't] being developed/used anymore"? Why should a research project, that was finished years ago and to which (to the best of my knowledge) no followup is planned, be "developed" any further? IOW, although I believe it's absurd to call a research project "dead" when it's completed, I know of no current nor planned development for Python.NET. Alex From usidoesit at yahoo.com Thu Apr 20 13:48:59 2006 From: usidoesit at yahoo.com (RK) Date: 20 Apr 2006 10:48:59 -0700 Subject: perspective on ruby Message-ID: <1145555339.316764.123210@i39g2000cwa.googlegroups.com> I apologize if this is a stupid question, I'm asking Python group for perspective on Ruby, but I don't see how the alternative of going to a ruby group for a perspective on Ruby is going to do me any good... I just unpacked and tried out InstantRails, after turning off the local Plone stack. Looking over the IR stack, making the required hacks to the examples, looking at all it's pieces(including some of the more powerful PHP support mixed in), looking at the shipped examples, I had to marvel again at how far behind these folks are compared to something like Zope. They are 10 years behind an integrated platform like that. I just don't get it. The scripted object-oriented clean programming language is done. I'm more than willing to supprt RoR if it's being sold as the popular alternative to .NET programming, which it is in some CS curriculum (where Java being thrown out). But, all those "END"s are getting on my nerves. Thx From rupole at hotmail.com Wed Apr 19 07:47:08 2006 From: rupole at hotmail.com (Roger Upole) Date: Wed, 19 Apr 2006 07:47:08 -0400 Subject: win32com Excel bug? References: <1145426529.989164.212450@g10g2000cwb.googlegroups.com> Message-ID: <1145447060_50165@sp6iad.superfeed.net> wrote in message news:1145426529.989164.212450 at g10g2000cwb.googlegroups.com... > I'm driving Excel from python, largely successfully. Now I'm trying to > add errorbars to XY scatter plots. Keep getting a com_error. Can't > track down the problem. > > I modified a simple example to duplicate the problem. Thanks to Mathieu > Fenniak http://www.stompstompstomp.com/weblog/entries/67/ for the code. > > The traceback is shown below. You can see that the Excel chart series > has a method called ErrorBar. But when I try to use it with any or all > of its allowed arguments, it fails. The traceback goes into the guts of > win32com but I don't really have a clue at that point. (Happy to learn > something new though). > > The relevant Excel VBA language doc is here. > http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbaxl11/html/xlmthErrorBar1_HV03076818.asp > > Hope someone can help. Losing hair .... fast! > > > > In [16]: %run test.py > --Return-- >> c:\python23\lib\pdb.py(992)set_trace()->None > -> Pdb().set_trace() > (Pdb) c > There's a method waiting > --------------------------------------------------------------------------- > pywintypes.com_error Traceback (most > recent call > last) > > c:\temp\mpival\test.py > 79 > 80 # A simple example: > ---> 81 plot( (1,2,3,4,5), (6,7,8,9,10) ) > 82 > 83 # Some more data: > > c:\temp\mpival\test.py in plot(x, y, xAxisLog, yAxisLog) > 35 if series.ErrorBar: > 36 print "There's a method waiting" > ---> 37 series.ErrorBar(Direction = constants.xlY) According to the docs, the Include and Type arguments are required, and they're not being passed to the method. hth Roger ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups ----= East and West-Coast Server Farms - Total Privacy via Encryption =---- From ldo at geek-central.gen.new_zealand Mon Apr 10 03:35:12 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 10 Apr 2006 19:35:12 +1200 Subject: how to pipe to variable of a "here document" References: <1144641459.230416.104590@v46g2000cwv.googlegroups.com> <87fykmm1bt.fsf@gmail.com> Message-ID: In article , Dennis Lee Bieber wrote: > Question: Is there a DB-API module that can directly connect to the >database server? There certainly is for MySQL, which is what I mostly use. From cvanarsdall at mvista.com Thu Apr 13 11:37:40 2006 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Thu, 13 Apr 2006 08:37:40 -0700 Subject: Looking for thoughts on PyMPI Message-ID: <443E7044.4040709@mvista.com> Hey, anyone use the PyMPI suite: http://sourceforge.net/projects/pympi/ ?? I am an engineer doing research with MPI and thought I'd do some digging to see if any scripting languages had adopted it yet. I was just looking for general comments and reviews from the community on this project, thanks! -carl -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From martin at v.loewis.de Wed Apr 26 13:13:45 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 26 Apr 2006 19:13:45 +0200 Subject: not quite 1252 In-Reply-To: <444f5e6b$1@usenet.zapto.org> References: <444f5e6b$1@usenet.zapto.org> Message-ID: <444FAA49.1000909@v.loewis.de> Anton Vredegoor wrote: > The encoding that gives me the least problems seems to be cp1252, > however it's not completely perfect because there are still characters > in it like \93 or \94. Has anyone handled this before? I'd rather not > reinvent the wheel and start translating strings 'by hand'. Not sure I understand the question. If you process data in cp1252, then \x94 and \x94 are legal characters, and the Python codec should support them just fine. Regards, Martin From aleaxit at yahoo.com Tue Apr 18 10:54:06 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 18 Apr 2006 07:54:06 -0700 Subject: Ironpython book? References: <1145329406.419299.12780@i40g2000cwc.googlegroups.com> <1hdyh5s.1ithyei4n7ucmN%aleaxit@yahoo.com> <1145334081.117264.75050@u72g2000cwu.googlegroups.com> <1hdykd6.1ubb4c1jh6mfmN%aleaxit@yahoo.com> <1145342633.307500.235390@v46g2000cwv.googlegroups.com> <4ak7gpFo52lsU1@uni-berlin.de> Message-ID: <1hdzasf.ffqrjcimf3jpN%aleaxit@yahoo.com> Diez B. Roggisch wrote: > > I suspected. I've played with Linux distros, but never a Mac. That > > takes more $$ than M$, Find me a 2-kg, 5+ battery hours, well-heeled laptop (with wifi, 801b, etc etc) below the $999 of the iBook G4... it's hard today, it was just imposible back when I bought mine in 2003. I intended to load Linux on it (i.e., I bought it strictly for the nonpareil HW price/performance), and I know a few people who do that, but that was before I found out how well MacOSX works. IOW, Apple is very price-competitive _in the niches it plays in_ -- it just doesn't play in many "cheap and nasty" niches (such as, 4-kg, hardly-any-battery-life laptops;-). > > and Apple is even more proprietary than MS, if > > you ask me. > > Depends. Sure, if you dive into Cocoa programming and stuff. But you have to ...which is hardly "more proprietary than MS", anyway, since OpenStep does live, btw;-). > keep in mind that under the hood it's BSD - and even runs a X-Server if you > want to. So I can use all my Linux staples + have a fancy OS for > multimedia-stuff. For me, just like for most people I've discussed it with, the reasoning is similar. For example, Chip Turner (once of RedHat, and a major contributor to RPM tools, now a colleague at Google) blogs at and has a few notes on the matter (e.g. "there's nothing like sitting in the middle of a meeting and having the ONLY WORKING LAPTOP in the room. Wireless AND suspend, both working..." -- that's about his Powerbook;-). I'd say Chip mostly switched from Linux to Mac for the same reason he mostly switched from Perl to Python though he was a CPAN contributor too. Others feel even more strongly: e.g., Rob Pike, another colleague, apparently just dislikes Linux technically (mostly, I think, X11, but not just that) and that's why he uses Macs (Windows isn't even in the picture, of course). > > It interests me how many Open Source advocates and > > anti-Microsoft folks are willing to pay top dollar for Macs, which I > > guess means that, for them, it's less a Cathedral vs. Bazaar thing and > > more about It Works vs. It Doesn't? > > I can't comment on this in general, but on the CCC (Chaos Communication > Congress, a Hacker-con) last year the notebook-distribution was like this: > > 30% Macs > 30% ThinkPads > 40% rest Not too different from what you see, e.g., at OSCON, though there may be more Macs there. At Google meetings the distribution is more like 45-45-10, since Macs and Thinkpads are the laptop brands Google gives its employees for work use (and few bother to apply for a third alternative when they can just pick up either at a "tech stop"). But, sure, here we're talking about people who are primarily engineers, so the main ethos is indeed "it works/it doesn't". Opensource tends to work better (and indeed many of Mac's advantages come from its BSD underpinnings)... > So - it seems that quality is important, and of course any decent Hacker > will run a *nixish OS. Not necessarily: Tim Peters, among my top choices for "top Hacker in the PSF" Lifetime Award, prefers Windows. So, s/any/most/...!-) Alex From aleaxit at yahoo.com Tue Apr 11 15:32:38 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 11 Apr 2006 12:32:38 -0700 Subject: python on Mac References: <1144284073.446005.53950@t31g2000cwb.googlegroups.com> <1hdc51n.1qgtjne1mduk7gN%aleaxit@yahoo.com> <1144291572.151260.56700@j33g2000cwa.googlegroups.com> <1144293362.889863.146200@i39g2000cwa.googlegroups.com> <1hdl37l.1mvgfva12tsntwN%aleaxit@yahoo.com> Message-ID: <1hdmqtc.hytbgzgidbadN%aleaxit@yahoo.com> Lawrence D'Oliveiro wrote: > In article <1hdl37l.1mvgfva12tsntwN%aleaxit at yahoo.com>, > aleaxit at yahoo.com (Alex Martelli) wrote: > > >Lawrence D'Oliveiro wrote: > > > >> In article <1144293362.889863.146200 at i39g2000cwa.googlegroups.com>, > >> "pierreth" wrote: > >> > >> >You removed /usr/bin/python! This is a really bad idea > >> > >> Is there any way to put it back, short of a full system reinstall? > > > >There's a free 3rd party tool known as Pacifist to extract part-installs > >from Apple's system DVDs... > > So there's no simple equivalent of "rpm --replace-pkgs"? Never heard of one, but you should double-check on Macintosh-related groups, where you're more likely to find relevant expertise. Alex From jUrner at arcor.de Fri Apr 7 19:39:40 2006 From: jUrner at arcor.de (jUrner at arcor.de) Date: 7 Apr 2006 16:39:40 -0700 Subject: calculating system clock resolution In-Reply-To: <1144444527.376016.73100@i40g2000cwc.googlegroups.com> References: <1144434899.840346.220780@z34g2000cwc.googlegroups.com> <1144444527.376016.73100@i40g2000cwc.googlegroups.com> Message-ID: <1144453180.713760.12870@v46g2000cwv.googlegroups.com> Maybe it was not too clear what I was trying to point out. I have to calculate the time time.time() requires to return the next tick of the clock. Should be about 0.01ms but this may differ from os to os. BTW (I'm new to linux) cat /proc/cpuinfo is nice but I have 2457.60 bogomips. Is this something i should be concerned about? I mean is this contageous or something ;-) From tjreedy at udel.edu Wed Apr 19 22:23:59 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 19 Apr 2006 22:23:59 -0400 Subject: Lamdba forms References: <1145492986.738200.229690@i39g2000cwa.googlegroups.com> Message-ID: wrote in message news:1145492986.738200.229690 at i39g2000cwa.googlegroups.com... > hi all, I am a python newbie. why functions created with lambda forms > cannot contain statements? Because statement do not fit in expressions. > how to get unnamed function with statements? Can't. Many discussions in archives (which Google has). tjr From has.temp2 at virgin.net Fri Apr 14 08:04:29 2006 From: has.temp2 at virgin.net (has) Date: 14 Apr 2006 05:04:29 -0700 Subject: Kross - Start of a Unified Scripting Approach In-Reply-To: <1144988779.784290.53620@g10g2000cwb.googlegroups.com> References: <1144866431.999725.293670@v46g2000cwv.googlegroups.com> <1hdqj4h.1ixp24v1dqm4wrN%aleaxit@yahoo.com> <1144988779.784290.53620@g10g2000cwb.googlegroups.com> Message-ID: <1145016269.843447.143680@e56g2000cwe.googlegroups.com> Jerry wrote: > Kind of like AppleScript then? Same fundamental goal, i.e. language-independent application scripting. They seem to have a similar sort of approach to decoupling a scripting language from its host application (Kross::API::ScriptManager vs. the Open Scripting Architecture API) but a very different approach to the intercommunication part. Kross appears to create native language wrappers for the application's public (C++) classes; nothing fancy, but pretty straightforward. Mac apps use serialised procedure calls containing first-class queries and other arguments to describe the action to perform and the application object(s) to use in that action. A query engine in the application framework (e.g. Cocoa Scripting) locates the actual object(s) and applies the appropriate action to them. Much higher level of abstraction and a lot more sophisticated, though it can be a bit tricky for application developers to implement (for the same reason). Plus I get the impression that Kross doesn't do interprocess yet although it's on the cards, presumably using something like proxy objects and dbus to provide the bridge. With Macs you only need OSA for intraprocess communication; the Apple Event Manager, which handles the messaging part, can pass messages between processes as well. > Sorry, just starting to learn about some of this stuff (CLI, CLR, CIL, > etc...) and am interested in understanding better. As far as how the Mac does it, here's an old but good paper on the basic principles involved if you want to know more: http://www.cs.utexas.edu/users/wcook/papers/AppleScript/AppleScript95.pdf I couldn't find a nice, simple overview of the Kross system. You should be able to form a rough impression from reading through the following links, although some better examples of calling Kexi from scripts would help: http://wiki.kde.org/tiki-index.php?page=kross http://www.kexi-project.org/wiki/wikiview/index.php?Scripting http://www.kexi-project.org/docs/cvs-api/html/namespaceKross.html HTH From per9000 at gmail.com Mon Apr 10 03:50:37 2006 From: per9000 at gmail.com (per9000) Date: 10 Apr 2006 00:50:37 -0700 Subject: Automated Graph Plotting in Python References: <1144552132.926125.222210@i39g2000cwa.googlegroups.com> Message-ID: <1144655437.331075.52590@e56g2000cwe.googlegroups.com> Dear shrub-makers, if you are want to plot networks (fx. genetic networks) I can recommend Cytoscape: http://cytoscape.org/ (some kind of openware). The in-syntax is clean: node1 linktype1 node2 node2 linktype1 node3 node3 linktype2 node1 etc. But in general you are going to want to change the layout of the network after it is plotted. If you are into genetic networks it has a number of built-in stuff. (For 2D-plots (demand vs time) cytoscape is not an option.) I also recommend gnuplot (like everyone else) for making the standard y-axis, x-axis 2D-plots. It takes some time to learn syntax, but if I remember correctly it is pretty simple. /Per Then when you have found the shrubbery, you must cut down the mightiest tree in the forest...wiiiith *pause* a herring! From fuzzyman at gmail.com Mon Apr 3 17:21:02 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 3 Apr 2006 14:21:02 -0700 Subject: Registration Code In-Reply-To: <1144096273.915268.90360@v46g2000cwv.googlegroups.com> References: <1144096273.915268.90360@v46g2000cwv.googlegroups.com> Message-ID: <1144099262.842241.28280@j33g2000cwa.googlegroups.com> Dave Mandelin wrote: > Ken Seehart wrote: > > Math wrote: > > > Hello, > > I encypted the bytecode of a few important functions with a key based on > > information required from the user. Without the key, these functions > > can't be decrypted. This is somewhat more secure than just testing the > > key with an "if" statement since the latter could easily be bypassed by > > a hacker. > > That's a really good idea. I have a couple more questions, if you don't > mind: I am going to distribute an app using py2exe. Is it reasonably > easy to apply this technique to bytecode stored inside the library.zip > file, or should I just include the encrypted Python files as separate > files? > > Second, I hear that in general it is very difficult to make a > time-limited demo, because the code has to be all there, so all a > cracker has to do is bypass the "if". It seems that even this method > won't work for that. Do you know of any way to make time limiting > secure? > If an attacker is determined to 'decompile' your application then it will be possible. Although decompiling python byte-code (even from py2exe wrapped programs) is easy, it's probably a less practised art than breaking C code. (Although I guess such dissasembly is usually done on an assembler level). The obvious way to make it more secure is to include several checks. Unless you are going to be writing a program used by tens of thousands of users, it is likely that it is not worth the effort of the hackers to bother. I'd release the early versions using simple protection mechanisms, and develop your protectionas your userbase grows. Again - there are commercial tools available that will handle this for you, if you want a higher degree of protectoin (although by no means infallible) immediately. Fuzzyman http://www.voidspace.org.uk/python/index.shtml > Thanks. > > -- > Want to play tabletop RPGs online? > Check out RPZen: http://koboldsoft.com From felipe.lessa at gmail.com Tue Apr 18 20:46:08 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Tue, 18 Apr 2006 21:46:08 -0300 Subject: extracting a substring In-Reply-To: <1145406353.280681.134630@t31g2000cwb.googlegroups.com> References: <1145406353.280681.134630@t31g2000cwb.googlegroups.com> Message-ID: <1145407568.12172.35.camel@kenshin.CASA> Em Ter, 2006-04-18 ?s 17:25 -0700, b83503104 at yahoo.com escreveu: > Hi, > I have a bunch of strings like > a53bc_531.txt > a53bc_2285.txt > ... > a53bc_359.txt > > and I want to extract the numbers 531, 2285, ...,359. Some ways: 1) Regular expressions, as you said: >>> from re import compile >>> find = compile("a53bc_([1-9]*)\\.txt").findall >>> find('a53bc_531.txt\na53bc_2285.txt\na53bc_359.txt') ['531', '2285', '359'] 2) Using ''.split: >>> [x.split('.')[0].split('_')[1] for x in 'a53bc_531.txt \na53bc_2285.txt\na53bc_359.txt'.splitlines()] ['531', '2285', '359'] 3) Using indexes (be careful!): >>> [x[6:-4] for x in 'a53bc_531.txt\na53bc_2285.txt \na53bc_359.txt'.splitlines()] ['531', '2285', '359'] Measuring speeds: $ python2.4 -m timeit -s 'from re import compile; find = compile("a53bc_([1-9]*)\\.txt").findall; s = "a53bc_531.txt \na53bc_2285.txt\na53bc_359.txt"' 'find(s)' 100000 loops, best of 3: 3.03 usec per loop $ python2.4 -m timeit -s 's = "a53bc_531.txt\na53bc_2285.txt \na53bc_359.txt\n"[:-1]' "[x.split('.')[0].split('_')[1] for x in s.splitlines()]" 100000 loops, best of 3: 7.64 usec per loop $ python2.4 -m timeit -s 's = "a53bc_531.txt\na53bc_2285.txt \na53bc_359.txt\n"[:-1]' "[x[6:-4] for x in s.splitlines()]" 100000 loops, best of 3: 2.47 usec per loop $ python2.4 -m timeit -s 'from re import compile; find = compile("a53bc_([1-9]*)\\.txt").findall; s = ("a53bc_531.txt \na53bc_2285.txt\na53bc_359.txt\n"*1000)[:-1]' 'find(s)' 1000 loops, best of 3: 1.95 msec per loop $ python2.4 -m timeit -s 's = ("a53bc_531.txt\na53bc_2285.txt \na53bc_359.txt\n" * 1000)[:-1]' "[x.split('.')[0].split('_')[1] for x in s.splitlines()]" 100 loops, best of 3: 6.51 msec per loop $ python2.4 -m timeit -s 's = ("a53bc_531.txt\na53bc_2285.txt \na53bc_359.txt\n" * 1000)[:-1]' "[x[6:-4] for x in s.splitlines()]" 1000 loops, best of 3: 1.53 msec per loop Summary: using indexes is less powerful than regexps, but faster. HTH, -- Felipe. From arkanes at gmail.com Mon Apr 3 10:31:07 2006 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 3 Apr 2006 09:31:07 -0500 Subject: string building In-Reply-To: References: Message-ID: <4866bea60604030731i1305dbccrf2186588968b8d85@mail.gmail.com> On 4/3/06, John Salerno wrote: > Out of curiosity, is there any kind of equivalent in Python to the > StringBuilder class in C#? Here's a quick description from the .NET > documentation: > > "This class represents a string-like object whose value is a mutable > sequence of characters. The value is said to be mutable because it can > be modified once it has been created by appending, removing, replacing, > or inserting characters." > > It's used for dealing with large strings that otherwise would cause > performance problems if used as regular string objects. I'm just > wondering if Python has something like this, or if it is even really > necessary. I know there is even some discussion on when exactly > StringBuilder becomes useful over regular strings, but I imagine at some > point it is good to use. The StringIO module (and it's better performing counterpart, cStringIO) present a string as a file-like object and are the appropriate way to incrementally build large strings. From kent at kentsjohnson.com Wed Apr 19 08:04:09 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Wed, 19 Apr 2006 08:04:09 -0400 Subject: Writing backwards compatible code - when? In-Reply-To: <44455670$1@nntp0.pdx.net> References: <44455670$1@nntp0.pdx.net> Message-ID: <44462720$1_1@newspeer2.tds.net> > Bob Greschke wrote: >> Is there a list of all of the Python commands and modules that tell when >> (what version) they were added to Python? I was hoping the new Essential >> Reference would have it, but it doesn't. The Library Reference page for a module or built-in often documents the version when any change was made. You can also read through the What's New documents for each release to see what changed in that release. Kent From theller at python.net Tue Apr 18 15:23:45 2006 From: theller at python.net (Thomas Heller) Date: Tue, 18 Apr 2006 21:23:45 +0200 Subject: 2.5a1 import of .dlls In-Reply-To: <1145387607.160964.28940@u72g2000cwu.googlegroups.com> References: <1145387607.160964.28940@u72g2000cwu.googlegroups.com> Message-ID: sven.nystrom at gmail.com wrote: > I've re-built an extension module (as a .dll) using the 2.5a1 release. > Unexpectedly, I'm not able to simply import it (not the way I can when > building it for 2.3). Using imp.load_dynamic() the import succeeds. > >>>> import minx # Implemented in a .dll - fails > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named minx >>>> import imp # Workaround >>>> import os >>>> minx = imp.load_dynamic('minx', os.getcwd() + '\\minx.dll') >>>> > > I couldn't find anything to indicate this is by design in 2.5a1 (I did > read the PEP 328: Absolute and Relative Imports) - am I doing something > wrong? > Extension modules for 2.5 can no longer have the '.dll' extension, they must have a '.pyd' extension. I don't know why this isn't documented somewhere (although I would expect it in Misc/NEWS instead of in PEP 328) - you should filke a bug report. Thomas From spamspam at spam.eggs Thu Apr 13 10:39:04 2006 From: spamspam at spam.eggs (Ben C) Date: 13 Apr 2006 14:39:04 GMT Subject: trying to grasp OO : newbie Q? References: <1144937168.508799.67410@i40g2000cwc.googlegroups.com> Message-ID: On 2006-04-13, mitsura at skynet.be wrote: > Hi, > > I just started with Python and I am new to OO programming. > Here is a simple code: > " > class Obj: > myVar = 1 > > def __init__(self): > myVar = 2 > > # > > > myObj = Obj() > > print myObj.myVar > " > > The output is of this script is '1'. I would except it to be '2'. > I not understanding something fundamentally here. Good example, it demonstrates these things quite well. My understanding of this is as follows: myVar is a class variable, because you define it in the body of the class statement (not in any method). In Python, classes and instances can both be thought of as dictionaries, i.e. sets of key-value pairs. In this example, Obj is a class and myObj is an instance. When you write print myObj.myVar, the interpreter looks first in myObj for a value matching the key "myVar". It doesn't find one there (I explain why not below). So it continues the search in myObj's class, which is the class Obj. It does find one there, with the value 1, so that's what you get. The myVar that you define in __init__ is not an instance variable, but a local variable (local to the function __init__). To make an instance variable you have to use "self" explicitly: def __init__(self): self.myVar = 2 If you write it like this, your program will print out 2. People coming from languages like C++ where this-> is implicit sometimes forget to write "self."; in Python you always need it to get at the instance. From sushant.sirsikar at gmail.com Thu Apr 20 08:22:01 2006 From: sushant.sirsikar at gmail.com (sushant.sirsikar at gmail.com) Date: 20 Apr 2006 05:22:01 -0700 Subject: PYTHONPATH Message-ID: <1145535721.138411.145790@z34g2000cwc.googlegroups.com> Hi, I am using Linux env.I set the PYTHONPATH using import sys sys.path.append(----) But we i close python and start again i is not showing my new entry in PYTHONPATH. Can anyone help me to make my path persistant? Thanks From sigzero at gmail.com Sat Apr 8 22:15:02 2006 From: sigzero at gmail.com (Robert Hicks) Date: 8 Apr 2006 19:15:02 -0700 Subject: Tkinter In-Reply-To: <44384715$0$22981$c83e3ef6@nn1-read.tele2.net> References: <1144538582.829134.82040@e56g2000cwe.googlegroups.com> <44384715$0$22981$c83e3ef6@nn1-read.tele2.net> Message-ID: <1144548902.412219.280620@i39g2000cwa.googlegroups.com> Maybe because Tkinter comes *with* Python? It is sometimes easier to understand the way things work in Tkinter vs wxPython as well. Though I will add that Manning has just published "wxPython in Action" so that should help newbies out as well. Robert From n.estner at gmx.de Wed Apr 5 17:10:04 2006 From: n.estner at gmx.de (nikie) Date: 5 Apr 2006 14:10:04 -0700 Subject: Best way to have a for-loop index? References: <1141950744.482666.4430@j33g2000cwa.googlegroups.com> Message-ID: <1144271404.022031.86570@e56g2000cwe.googlegroups.com> Roy Smith wrote: > In article <1141950744.482666.4430 at j33g2000cwa.googlegroups.com>, > andrewfelch at gmail.com wrote: > > > I write a lot of code that looks like this: > > > > for myElement, elementIndex in zip( elementList, > > range(len(elementList))): > > print "myElement ", myElement, " at index: ",elementIndex > > > > > > My question is, is there a better, cleaner, or easier way to get at the > > element in a list AND the index of a loop than this? > > > > TIA, > > Andrew > > The real question is *why* do you want the index? > > If you're trying to iterate through list indicies, you're probably trying > to write C, C++, Fortran, Java, etc in Python. Interesting. I just wrote some tools today that parse through a bunch of logfiles and print out something like: "unmatched memory allocation in line XXX", or something like that. All of them have a main loop like this: for lineNumber, line in enumerate(file("some.log")): ... I don't think there's anything wrong with that, is there a better way to do it? Personally, I don't think "enumerate" would be there if it always encouraged an "unpythonic" programming style. But then again, I'm not dutch, so I couldn't tell... ;-) From onurb at xiludom.gro Tue Apr 25 05:07:26 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 25 Apr 2006 11:07:26 +0200 Subject: Multiple hierarchie and method overloading In-Reply-To: References: Message-ID: <444de723$0$12861$626a54ce@news.free.fr> Philippe Martin wrote: > Hi, > > > > > I have something like this: > > Class A: > def A_Func(self, p_param): > ..... > Class B: > def A_Func(self): > ..... > > Class C (A,B): > A.__init__(self) If that's really your code, you should have an exception right here. Else, please post real code. > B.__init__(self) > ..... > > self.A_Func() #HERE I GET AN EXCEPTION "... takes at least 2 arguments (1 > given). > > I renamed A_Func(self) to fix that ... but is there a cleaner way around ? Perhaps should you read these texts: http://diveintopython.org/object_oriented_framework/defining_classes.html http://www.freenetpages.co.uk/hp/alan.gauld/tutclass.htm http://docs.python.org/tut/node11.html -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From bignose+hates-spam at benfinney.id.au Thu Apr 27 20:14:18 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 28 Apr 2006 10:14:18 +1000 Subject: String Exceptions (PEP 352) References: Message-ID: <874q0eftet.fsf@benfinney.id.au> Thomas Guettler writes: > I like python because it is compatible to old versions. I like it because it has a documented, manageable procedure for breaking compatibility with old versions. > if foo and bar and i>10: > raise "if foo and bar i must not be greater than 10" Others have pointed out that this is a job for 'assert'. > Is it too late to change this? Yes. PEP-0352 has a status of "Final". > Way not make this line > > raise "..." > > behave like this: > > raise Exception("...") > > in the future? Because explicit is better than implicit, and special magic behaviour is to be deprecated (or never implemented) when possible. > Please keep Python compatible to old versions. Have a read of PEP 0005: Also note that the transition plan (documented in the PEP that concerns you) shows the support for the old behaviour is not to be dropped until Python 3.0, a release explicitly targeted at breaking backward compatibility to clean out crufty behaviour. -- \ "I went to the hardware store and bought some used paint. It | `\ was in the shape of a house." -- Steven Wright | _o__) | Ben Finney From fredrik at pythonware.com Thu Apr 6 15:26:41 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 6 Apr 2006 21:26:41 +0200 Subject: good style guides for python-style documentation ? Message-ID: (reposted from doc-sig, which seems to be mostly dead these days). over at the pytut wiki, "carndt" asked: Are there any guidelines about conventions concerning punctuation, text styles and language style (e.g. how to address the reader)? any suggestions from this list ? From gaz082 at gmail.com Fri Apr 21 13:05:47 2006 From: gaz082 at gmail.com (Gaz) Date: 21 Apr 2006 10:05:47 -0700 Subject: Pythonesque interface. Message-ID: <1145639147.524042.260220@z34g2000cwc.googlegroups.com> Hi guys. I'm doing a simple strategy game in python, hex based, with the PIL library. I'd like to know if there is a way to check the pointer position within a frame, so i can figure out which hex is the pointer on, but in a pythonesque way, not using Java or Flash. Sajax is the way to go? I dont think this is the solution, coz the frame should be requiered to be refreshed like 30 times a second, but heck, you are the Python savvies. Thank you! From arkanes at gmail.com Wed Apr 26 21:53:13 2006 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 26 Apr 2006 20:53:13 -0500 Subject: can this be done without eval/exec? In-Reply-To: References: Message-ID: <4866bea60604261853rf388f13j8ed5688e7444a66d@mail.gmail.com> On 4/26/06, Sch?le Daniel wrote: > Hello group, > > >>> lst=[] > >>> for i in range(10): > ... lst.append(eval("lambda:%i" % i)) > ... > >>> lst[0]() > 0 > >>> lst[1]() > 1 > >>> lst[9]() > 9 > >>> > > >>> lst=[] > >>> for i in range(10): > ... exec "tmp = lambda:%i" % i # assignment is not expression > ... lst.append(tmp) > ... > >>> lst[0]() > 0 > >>> lst[1]() > 1 > >>> lst[9]() > 9 > >>> > > and now the obvious one (as I thought at first) > > >>> lst=[] > >>> for i in range(10): > ... lst.append(lambda:i) > ... > >>> lst[0]() > 9 > >>> i > 9 > >>> > > I think I understand where the problem comes from > lambda:i seems not to be fully evalutated > it just binds object with name i and not the value of i > thus lst[0]() is not 0 > > are there other solutions to this problem > without use of eval or exec? > Using a factory function & closures instead of lambda: >>> def maker(x): ... def inner_maker(): ... return x ... return inner_maker ... >>> lst = [] >>> for i in range(10): ... lst.append(maker(i)) ... >>> lst[0]() 0 >>> lst[5]() 5 >>> lst[9]() 9 >>> > Regards, Daniel > -- > http://mail.python.org/mailman/listinfo/python-list > From gherron at islandtraining.com Tue Apr 18 20:42:13 2006 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 18 Apr 2006 17:42:13 -0700 Subject: extracting a substring In-Reply-To: <1145406353.280681.134630@t31g2000cwb.googlegroups.com> References: <1145406353.280681.134630@t31g2000cwb.googlegroups.com> Message-ID: <44458765.80604@islandtraining.com> b83503104 at yahoo.com wrote: >Hi, >I have a bunch of strings like >a53bc_531.txt >a53bc_2285.txt >... >a53bc_359.txt > >and I want to extract the numbers 531, 2285, ...,359. > >One thing for sure is that these numbers are the ONLY part that is >changing; all the other characters are always fixed. > >I know I should use regular expressions, but I'm not familar with >python, so any quick help would help, such as which commands or idioms >to use. Thanks a lot! > > > Try this: >>> import re >>> pattern = re.compile("a53bc_([0-9]*).txt") >>> >>> s = "a53bc_531.txt" >>> match = pattern.match(s) >>> if match: ... print int(match.group(1)) ... else: ... print "No match" ... 531 >>> Hope that helps, Gary Herron From darkbard at gmail.com Mon Apr 24 12:01:05 2006 From: darkbard at gmail.com (Gabriele *darkbard* Farina) Date: 24 Apr 2006 09:01:05 -0700 Subject: Python C API question In-Reply-To: References: <1145892356.049190.246910@j33g2000cwa.googlegroups.com> Message-ID: <1145894465.173440.194220@i39g2000cwa.googlegroups.com> It seems to be what I need. Thank you! From martin.witte at gmail.com Wed Apr 26 03:42:20 2006 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 26 Apr 2006 00:42:20 -0700 Subject: Introspection Class/Instance Name In-Reply-To: References: Message-ID: <1146037339.946998.185700@j33g2000cwa.googlegroups.com> What about: py> class A: py. def __init__(self): py. print self.__class__.__name__ py. print str(self) py. def __str__(self): py. return 'instance of %s' % self.__class__.__name__ py. py> a = A() A instance of A py> From paddy3118 at netscape.net Thu Apr 6 03:20:21 2006 From: paddy3118 at netscape.net (Paddy) Date: 6 Apr 2006 00:20:21 -0700 Subject: efficiency of range() and xrange() in for loops In-Reply-To: References: Message-ID: <1144308021.225344.102810@v46g2000cwv.googlegroups.com> I wondered at the tone of some of the replies, re-read the repliess and your original message. On first readings ithought that your original message was OK and that the replies were a bit 'strong' . On second reading I thought that the original could be interpreted a little less nicely, but I had to go looking. Please don't be put off using this news group. I guesss we all have to be extra careful about tone when no one can see your facial expressions :-) - Pad. P.S. I was having problems with the Google server - sorry if this is replicated. From steven.bethard at gmail.com Thu Apr 13 11:53:35 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 13 Apr 2006 09:53:35 -0600 Subject: PEP 359: The "make" Statement Message-ID: Ok, I finally have a PEP number. Here's the most updated version of the "make" statement PEP. I'll be posting it shortly to python-dev. Thanks again for the previous discussion and suggestions! PEP: 359 Title: The "make" Statement Version: $Revision: 45366 $ Last-Modified: $Date: 2006-04-13 07:36:24 -0600 (Thu, 13 Apr 2006) $ Author: Steven Bethard Status: Draft Type: Standards Track Content-Type: text/x-rst Created: 05-Apr-2006 Python-Version: 2.6 Post-History: 05-Apr-2006, 06-Apr-2006 Abstract ======== This PEP proposes a generalization of the class-declaration syntax, the ``make`` statement. The proposed syntax and semantics parallel the syntax for class definition, and so:: make : is translated into the assignment:: = ("", , ) where ```` is the dict created by executing ````. The PEP is based on a suggestion [1]_ from Michele Simionato on the python-dev list. Motivation ========== Class statements provide two nice facilities to Python: (1) They are the standard Python means of creating a namespace. All statements within a class body are executed, and the resulting local name bindings are passed as a dict to the metaclass. (2) They encourage DRY (don't repeat yourself) by allowing the class being created to know the name it is being assigned. Thus in a simple class statement like:: class C(object): x = 1 def foo(self): return 'bar' the metaclass (``type``) gets called with something like:: C = type('C', (object,), {'x':1, 'foo':}) The class statement is just syntactic sugar for the above assignment statement, but clearly a very useful sort of syntactic sugar. It avoids not only the repetition of ``C``, but also simplifies the creation of the dict by allowing it to be expressed as a series of statements. Historically, type instances (a.k.a. class objects) have been the only objects blessed with this sort of syntactic support. But other sorts of objects could benefit from such support. For example, property objects take three function arguments, but because the property type cannot be passed a namespace, these functions, though relevant only to the property, must be declared before it and then passed as arguments to the property call, e.g.:: class C(object): ... def get_x(self): ... def set_x(self): ... x = property(get_x, set_x, ...) There have been a few recipes [2]_ trying to work around this behavior, but with the new make statement (and an appropriate definition of property), the getter and setter functions can be defined in the property's namespace like:: class C(object): ... make property x: def get(self): ... def set(self): ... The definition of such a property callable could be as simple as:: def property(name, args, namespace): fget = namespace.get('get') fset = namespace.get('set') fdel = namespace.get('delete') doc = namespace.get('__doc__') return __builtin__.property(fget, fset, fdel, doc) Of course, properties are only one of the many possible uses of the make statement. The make statement is useful in essentially any situation where a name is associated with a namespace. So, for example, namespaces could be created as simply as:: make namespace ns: """This creates a namespace named ns with a badger attribute and a spam function""" badger = 42 def spam(): ... And if Python acquires interfaces, given an appropriately defined ``interface`` callable, the make statement can support interface creation through the syntax:: make interface C(...): ... This would mean that interface systems like that of Zope would no longer have to abuse the class syntax to create proper interface instances. Specification ============= Python will translate a make statement:: make : into the assignment:: = ("", , ) where ```` is the dict created by executing ````. The ```` expression is optional; if not present, an empty tuple will be assumed. A patch is available implementing these semantics [3]_. The make statement introduces a new keyword, ``make``. Thus in Python 2.6, the make statement will have to be enabled using ``from __future__ import make_statement``. Open Issues =========== Does the ``make`` keyword break too much code? Originally, the make statement used the keyword ``create`` (a suggestion due to Nick Coghlan). However, investigations into the standard library [4]_ and Zope+Plone code [5]_ revealed that ``create`` would break a lot more code, so ``make`` was adopted as the keyword instead. However, there are still a few instances where ``make`` would break code. Is there a better keyword for the statement? ********** Currently, there are not many functions which have the signature ``(name, args, kwargs)``. That means that something like:: make dict params: x = 1 y = 2 is currently impossible because the dict constructor has a different signature. Does this sort of thing need to be supported? One suggestion, by Carl Banks, would be to add a ``__make__`` magic method that would be called before ``__call__``. For types, the ``__make__`` method would be identical to ``__call__`` (and thus unnecessary), but dicts could support the make statement by defining a ``__make__`` method on the dict type that looks something like:: def __make__(cls, name, args, kwargs): return cls(**kwargs) Of course, rather than adding another magic method, the dict type could just grow a classmethod something like ``dict.fromblock`` that could be used like:: make dict.fromblock params: x = 1 y = 2 Optional Extensions =================== Remove the make keyword ------------------------- It might be possible to remove the make keyword so that such statements would begin with the callable being called, e.g.:: namespace ns: badger = 42 def spam(): ... interface C(...): ... However, almost all other Python statements begin with a keyword, and removing the keyword would make it harder to look up this construct in the documentation. Additionally, this would add some complexity in the grammar and so far I (Steven Bethard) have not been able to implement the feature without the keyword. Removing __metaclass__ in Python 3000 ------------------------------------- As a side-effect of its generality, the make statement mostly eliminates the need for the ``__metaclass__`` attribute in class objects. Thus in Python 3000, instead of:: class : __metaclass__ = metaclasses could be supported by using the metaclass as the callable in a make statement:: make : Removing the ``__metaclass__`` hook would simplify the BUILD_CLASS opcode a bit. Removing class statements in Python 3000 ---------------------------------------- In the most extreme application of make statements, the class statement itself could be deprecated in favor of ``make type`` statements. References ========== .. [1] Michele Simionato's original suggestion (http://mail.python.org/pipermail/python-dev/2005-October/057435.html) .. [2] Namespace-based property recipe (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/442418) .. [3] Make Statement patch (http://ucsu.colorado.edu/~bethard/py/make_statement.patch) .. [4] Instances of create in the stdlib (http://mail.python.org/pipermail/python-list/2006-April/335159.html) .. [5] Instances of create in Zope+Plone (http://mail.python.org/pipermail/python-list/2006-April/335284.html) Copyright ========= This document has been placed in the public domain. .. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 coding: utf-8 End: From peter at engcorp.com Tue Apr 11 07:17:41 2006 From: peter at engcorp.com (Peter Hansen) Date: Tue, 11 Apr 2006 07:17:41 -0400 Subject: Why new Python 2.5 feature "class C()" return old-style class ? In-Reply-To: References: <1144752553.305591.88050@j33g2000cwa.googlegroups.com> Message-ID: Georg Brandl wrote: > class C(): > > is meant to be synonymous with > > class C: > > and therefore cannot create a new-style class. I think "looping" understands that, but is basically asking why anyone is bothering with a change that involves a part of the language that is effectively deprecated. In other words, class(): never used to be valid, so why make it valid now? -Peter From rridge at csclub.uwaterloo.ca Fri Apr 28 16:54:53 2006 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: 28 Apr 2006 13:54:53 -0700 Subject: MinGW and Python References: <1146248734.511062.115290@j73g2000cwa.googlegroups.com> <1146253355.564139.147500@j73g2000cwa.googlegroups.com> Message-ID: <1146257693.464534.130710@j73g2000cwa.googlegroups.com> Ross Ridge wrote: > You'd have to point people who don't already have it to Microsoft's > download site. sturlamolden wrote: > Is there a download site? I have not been able to localise one. Links where you can download them were posted in the thread you started on the MinGW C/C++ forum. > 2. you need an import library for msvcrt.dll, if your VS don't ship > with one you are lost. I already listed in this thread other alternatives for legitimately obtaining an MSVCRT.DLL import library. Ross Ridge From jos at xos.nl Mon Apr 17 08:17:51 2006 From: jos at xos.nl (Jos Vos) Date: Mon, 17 Apr 2006 14:17:51 +0200 Subject: XML-RPC server via xinetd In-Reply-To: ; from fredrik@pythonware.com on Mon, Apr 17, 2006 at 12:42:00PM +0200 References: Message-ID: <20060417141751.A22675@xos037.xos.nl> On Mon, Apr 17, 2006 at 12:42:00PM +0200, Fredrik Lundh wrote: > except that if the OP's expecting the other end to use an ordinary XML-RPC > library, he needs to implement some minimal HTTP handling as well. Which makes me wondering why the classes (this also applies to BaseHTTPServer / BaseHTTPRequestHandler) ae designed the way they are. The underlying stream medium (TCP sockets or plain file streams like stdin/stdout) should not be integrated with the protocol (HTTP) handling, IMHO... -- -- Jos Vos -- X/OS Experts in Open Systems BV | Phone: +31 20 6938364 -- Amsterdam, The Netherlands | Fax: +31 20 6948204 From jnair at ensim.com Mon Apr 10 06:52:14 2006 From: jnair at ensim.com (jnair at ensim.com) Date: 10 Apr 2006 03:52:14 -0700 Subject: Is this code snippet pythonic Message-ID: <1144666334.053780.164660@e56g2000cwe.googlegroups.com> My Tead Lead my object counter code seen below is not pythonic class E(object): _count = 0 def __init__(self): E._count += 1 count = property(lambda self: E._count ) def test(): if __name__ == "__main__": e1 = E() print e1.count e2 = E() print e2.count e3 = E() print e3.count test() if not waht woutld be the pythonic way From eric_brunel at despammed.com Fri Apr 28 03:30:14 2006 From: eric_brunel at despammed.com (Eric Brunel) Date: Fri, 28 Apr 2006 09:30:14 +0200 Subject: How to align the text of a Listbox to the right References: <1146130550.583881.149820@g10g2000cwb.googlegroups.com> <1146146436.246148.270140@v46g2000cwv.googlegroups.com> Message-ID: On 27 Apr 2006 07:00:36 -0700, Leonardo da Vinci wrote: > I have to use a Listbox that shows a list of entries. Every entry is a > char string quite long in size and I cannot set "width" to a large > value due to limitations of screen resolution. The rightmost part is > more important, so I thought that I could show only the end of the > string by aligning the field to the right. As I see it, there are two solutions to your problems: - Display your strings differently. It may seem stupid, but there are sometimes situations where it is the best solution. Think about Apple's way of displaying full file path names in menus: they put the file base name first, then the full directory after a separator. If you have a way to do that, your problem is solved. - Don't use a Listbox to display your list, but another widget. A simple Text with no wrap option may be a solution; setting a tag with the option justify=LEFT on your whole text would do the trick. But if your lines of text should be selectable, it may not be the right solution. In this case, another widget you can use is a Canvas. It's a little trickier but can be done. Here is an example: -------------------------------------- from Tkinter import * root = Tk() cnv = Canvas(root, width=150, height=250) cnv.grid(row=0, column=0, sticky='nswe') hscroll = Scrollbar(root, orient=HORIZONTAL, command=cnv.xview) hscroll.grid(row=1, column=0, sticky='we') vscroll = Scrollbar(root, orient=VERTICAL, command=cnv.yview) vscroll.grid(row=0, column=1, sticky='ns') cnv.configure(xscrollcommand=hscroll.set, yscrollcommand=vscroll.set) xMax = 0 y = 0 for i in range(20): lbl = Label(cnv, text='Very, very long item number %s' % i) cnv.create_window(150, y, window=lbl, anchor='ne') y += lbl.winfo_reqheight() xMax = max(xMax, lbl.winfo_reqwidth()) cnv.configure(scrollregion=(150 - xMax, 0, 150, y)) root.mainloop() -------------------------------------- Putting bindings on the Label widgets created in the loop can be used to simulate the behaviour of a Listbox. HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From aleaxit at yahoo.com Tue Apr 18 10:54:07 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 18 Apr 2006 07:54:07 -0700 Subject: Any Python lullabies? References: <1145364607.000467.204880@g10g2000cwb.googlegroups.com> Message-ID: <1hdzbsg.1e58zw80iae4N%aleaxit@yahoo.com> Dustan wrote: ... > Howsabout this? > > > >>> import this > The Zen of Python, by Tim Peters > > Beautiful is better than ugly. ... Anna and I used it as one of our wedding's readings back in 2004 (together with other texts from Dickinson, Petrarca, Lucretius...) and I gave a lightining talk about it at OSCON that year (titled "the first Pythonic marriage"). I don't consider it a lullaby!-) Alex From rnd at onego.ru Tue Apr 4 03:52:23 2006 From: rnd at onego.ru (Roman Susi) Date: Tue, 04 Apr 2006 10:52:23 +0300 Subject: Standalone Python functions in UML? Message-ID: <443225B7.9010202@onego.ru> Hi! Out of curiosity, how do I draw functions outside classes with UML? How module could be drawn in this case? More theoretical question is if I create classes on the fly, how UML can reflect that? (I know that Python code itself is best at communication design ideas, but there are some people which prefer to talk UML.) (Have not found anything relevant with google) Thanks! Regards, Roman Suzi From onurb at xiludom.gro Mon Apr 3 09:49:10 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Mon, 03 Apr 2006 15:49:10 +0200 Subject: "definitive" source on advanced python? In-Reply-To: <1144067373.667073.128060@i40g2000cwc.googlegroups.com> References: <1144040231.239622.159630@j33g2000cwa.googlegroups.com> <1144067373.667073.128060@i40g2000cwc.googlegroups.com> Message-ID: <4431281b$0$9956$636a55ce@news.free.fr> Gabriel de Dietrich wrote: > Maybe you're looking for something like this? > http://jamesthornton.com/eckel/TIPython/html/Index.htm > > Haven't read it yet, but seems to be about design patterns. Not the > "definitive" stuff, though... While TIP is an interesting book, it is more about implementation of standard design patterns in Python than about 'advanced' Python programming. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From a.schmolck at gmail.com Sun Apr 9 16:06:48 2006 From: a.schmolck at gmail.com (Alexander Schmolck) Date: 09 Apr 2006 21:06:48 +0100 Subject: Automated Graph Plotting in Python References: <1144552132.926125.222210@i39g2000cwa.googlegroups.com> Message-ID: diffuser78 at gmail.com writes: > 1. Which is the best graph plotting utility in python or linux. matplotlib (provided it does the type of graphs you need, which is likely) 'as From clodoaldo.pinto at gmail.com Sat Apr 8 11:54:26 2006 From: clodoaldo.pinto at gmail.com (Clodoaldo Pinto) Date: 8 Apr 2006 08:54:26 -0700 Subject: Programming Tutorial for absolute beginners References: <1144439148.751062.16590@t31g2000cwb.googlegroups.com> <1144444872.962395.3310@z34g2000cwc.googlegroups.com> <1144446605.916499.24470@i39g2000cwa.googlegroups.com> <4437c7cd$0$11330$636a55ce@news.free.fr> Message-ID: <1144511666.148953.212510@v46g2000cwv.googlegroups.com> Bruno Desthuilliers wrote: > Clodoaldo Pinto a ?crit : > > bill pursell wrote: > > > (snip) > >>2) In the section on installing, you begin with: > >>"Python is an interpreted, interactive, object-oriented programming > >>language.". The complete novice sees those words and expects > >>them to be explained, but there is no definition given. I would > >>recommend simplifying that sentence, or explaining the terms. > > > > Ok, i will think about something, or just delete it. > > FWIW, being "interpreted" is not a feature of a language but of a given > implementation of a language - and actually, the reference > implementation (CPython) is byte-compiled, not interpreted. As for > interactivity, it comes from a program (the Python shell) that ships > with the reference implementation - not from the laguage itself. > That Python definition was taken literally from the old site's "about" page. The new "about" page is better for the purposes of this course: "Python is a remarkably powerful dynamic programming language that is used in a wide variety of application domains. Python is often compared to Tcl, Perl, Ruby, Scheme or Java. Some of its key distinguishing features include:..." Or the first page definition: "Python? is a dynamic object-oriented programming language that can be used for many kinds of software development. It offers strong support for integration with other languages and tools, comes with extensive standard libraries, and can be learned in a few days. Many Python programmers report substantial productivity gains and feel the language encourages the development of higher quality, more maintainable code." I'm leaning towards the first page one from which i would take this part out: "is a dynamic object-oriented programming language" That would leave this simple text: "Python? can be used for many kinds of software development. It offers strong support for integration with other languages and tools, comes with extensive standard libraries, and can be learned in a few days. Many Python programmers report substantial productivity gains and feel the language encourages the development of higher quality, more maintainable code." Regards, Clodoaldo From johnjsal at NOSPAMgmail.com Sun Apr 30 01:21:29 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sun, 30 Apr 2006 01:21:29 -0400 Subject: setting file permissions on a web server Message-ID: <445449f6$0$9437$c3e8da3@news.astraweb.com> I always read about how you need to set certain file permissions (for cgi files, for example), but it's never been clear to me *how* you do this. I know you can run the line chmod 755 scriptname.py but *where* do you run this? Is this done on your personal system, or on the server? What if you are using Windows? If it's done on the server, how do you do it? The only way I've figured out so far how to do this is to upload my cgi files to my server, then within my FTP program I right-click the file and change its permission number that way, but that seems an inefficient way to do it, especially having to do it each time. Is there a way to put the above line within the script perhaps, so that the script sets its permission automatically? Or do certain editors allow you to save files with a predetermined permission? Aside from my right-clicking method, I don't know how else to do it. From steven.bethard at gmail.com Sun Apr 16 15:39:19 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 16 Apr 2006 13:39:19 -0600 Subject: PEP 359: The "make" Statement In-Reply-To: References: <44403893.3060909@ieee.org> Message-ID: Tim Hochberg wrote: > Tim Hochberg wrote: >> I don't think that's correct. I think that with a suitably designed >> HtmlDocument object, the following should be possible: >> >> with HtmlDocument("Title") as doc: >> with doc.element("body"): >> doc.text("before first h1") >> with doc.element("h1", style="first"): >> doc.text("first h1") >> # I don't understand the point of tail, but you could do that too >> doc.text("after first h1") >> with doc.element("h1", style="second"): >> doc.text("second h1") >> doc.text("after second h1") >> > Here's code to do this. It would be probably be better to use elment > tree or some such instead of pushing out the HTML directly, but this > should get the idea across (testing using 2.5a1): [snip] Thanks, that's great! If you don't mind, I'm going to steal your code for the PEP. I think it makes a pretty good case against expanding the statement semantics to include customizing the dict in which the code is executed. STeVe From uval at rz.uni-karlsruhe.de Tue Apr 25 18:58:40 2006 From: uval at rz.uni-karlsruhe.de (=?ISO-8859-1?Q?Sch=FCle_Daniel?=) Date: Wed, 26 Apr 2006 00:58:40 +0200 Subject: can someone explain why .. Message-ID: I don't understand what is the difference between commented lines 1 and 2 with 1 uncommented and 2 commented it works as expected with 1 commented and 2 uncommented the picture doesn't appear here is my code #!/usr/bin/env python from Tkinter import * from Tkconstants import * root = None class Main: def __init__(self): global root root = Tk(className = "Zeitrechner") root.config(borderwidth = 5, relief = GROOVE) root.geometry("0x0+100+50") #self.im = image = PhotoImage(file = "./flower1.gif") #1 image = PhotoImage(file = "./flower1.gif") #2 frame1 = Frame(master = root, borderwidth = 3, relief = SUNKEN) imageLabel = Label(master = frame1, image = image) root.minsize(width = image.width(), height = image.height()) root.maxsize(width = 2*image.width(), height = image.height()) imageLabel.pack() frame1.pack(side = LEFT) def mainloop(self): root.mainloop() main = Main() main.mainloop() From grflanagan at yahoo.co.uk Tue Apr 4 12:48:47 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 4 Apr 2006 09:48:47 -0700 Subject: Dice probability problem In-Reply-To: References: Message-ID: <1144169327.292669.325360@i39g2000cwa.googlegroups.com> Tomi Lindberg wrote: > > # A die with n faces > D = lambda n: [x+1 for x in range(n)] > That can be written: D = lambda n : range(1,n+1) Gerard From aleaxit at yahoo.com Mon Apr 3 11:32:06 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 3 Apr 2006 07:32:06 -0800 Subject: Getting a list of all classes derived from a base class References: <1144039905.692207.8790@g10g2000cwb.googlegroups.com> <1hd6v7k.15gbqp4b4sh9iN%aleaxit@yahoo.com> <1144048750.977970.221610@e56g2000cwe.googlegroups.com> Message-ID: <1hd7ipf.ew4e40qexkneN%aleaxit@yahoo.com> Vijairaj wrote: > Thanks Dylan and Alex, that was a new learning for me. > > but both the solutions don't work in jython 2.1 is there an alternative > that will work with jython2.1 Alas, no: your simple idea is essentially the best you can do in any implementation of Pyhon at 2.1 level. To put a positive spin on it: if there *WEREN'T* some things that are much easier and slicker in Python 2.4, with all the years and the work we've put into Python since 2.1's times, now THAT would be bad!-) I do hope that Jython does eventually "grow up" to a more modern version of Python -- unfortunately, I'm too rusty with Java, and not involved enough in JVM work day by day, to actually help out there, and apparently so are most potential contributors to Jython:-( Alex From noway at sorry.com Sat Apr 1 12:43:35 2006 From: noway at sorry.com (Giovanni Bajo) Date: Sat, 01 Apr 2006 17:43:35 GMT Subject: New Python Logo Revealed References: <9bct22dngv6lncqfjju5oqi4772or4pdle@4ax.com> Message-ID: robin wrote: > I have an entry on my blog discussing the new Python logo, which is > apparently due to replace the current one within the month. I'd be > interested in what people think of it. > > Surf: > http://diagrammes-modernes.blogspot.com Tell me tell me it's an april's joke, please? :) -- Giovanni Bajo From chris at kateandchris.net Fri Apr 28 10:33:54 2006 From: chris at kateandchris.net (Chris Lambacher) Date: Fri, 28 Apr 2006 10:33:54 -0400 Subject: Can one query full name (or version) of selected packages at pypi? In-Reply-To: <1145525161.975827.277860@u72g2000cwu.googlegroups.com> References: <1145525161.975827.277860@u72g2000cwu.googlegroups.com> Message-ID: <20060428143354.GA31350@kateandchris.net> On Thu, Apr 20, 2006 at 02:26:02AM -0700, Caleb Hattingh wrote: > I could do these steps myself with normal http access and > screen-scraping, but is there already such a system/script somewhere? > Alternatively, how do you all keep versions of python addons > up-to-date? Manually? I use easy_install. Unfortunately not all packages work. Most notably the following failed last time I tried: twisted pygtk PIL win32all ctypes Mostly this is because they do something a little bit non standard with distutils. Newer versions of easy_install may have sorted these problems, I have not tried in the last month or two. http://peak.telecommunity.com/DevCenter/EasyInstall I hope that helps you out, Chris From robert.kern at gmail.com Sun Apr 16 01:17:23 2006 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 16 Apr 2006 00:17:23 -0500 Subject: Numpy and cPickle In-Reply-To: References: Message-ID: Mr. M wrote: > Somehow, the bug does not show up any more. I believe it was due to the > numpy version that is fetched by cPickle. Is there any way to control > (or even determine), which library version cPickle grabs for unpickling > a numpy array (numpy, scipy, etc)? You can import the appropriate module first. Then it will be in sys.modules and be picked up during unpickling. You may have to do some sys.path manipulation if you have more than one version lieing about on your filesystem. -- Robert Kern robert.kern at gmail.com "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From nuffnough at gmail.com Fri Apr 7 13:38:08 2006 From: nuffnough at gmail.com (nuffnough at gmail.com) Date: 7 Apr 2006 10:38:08 -0700 Subject: Newbie wxPython questions. Message-ID: <1144431488.217852.132790@j33g2000cwa.googlegroups.com> I am running through the wxPython guide and docs and extrapolating enough to get confused. BAsed on the tute in the getting started wiki I created a panel that has most of the elements I want; some check boxes and a couple of buttons. The button I have is a simple thing that is supposed to just close (destroy) the app. Only thing is, it destroys the panel and leaves the app behind. I have attempted to place this on teh frame by defining a frame; the button works great and closes the app, but because it isn't part of the panel, the panel is all squished up into the very top left corner and all you can see is the first checkbox, which you can't even check. Can I make a button on the panel destroy the frame? The next question I have is about adding a second button to the panel (or frame, I guess) that will then execute a bunch of things depending on which checkboxes are ticked. My attempts to add the button have been wrong so far, as you'll see with my code. The first code block is my panel only app. The second is how it looks after I defined the Frame first and then moved the Cancel button. TIA Nuffnough -- import wx, sys, os class Form1(wx.Panel): def __init__(self, parent, id): wx.Panel.__init__(self, parent, id) self.quote = wx.StaticText(self, -1, "Launching :",wx.Point(20,30)) st = wx.StaticText(self, -1, "Select the applications you need to launch:")#, (10, 10) cb1 = wx.CheckBox(self, -1, "Read Calander, Check Email")#,(65,40), (150, 20), wx.NO_BORDER) cb2 = wx.CheckBox(self, -1, "Internet Browser") self.Bind(wx.EVT_CHECKBOX, self.EvtCheckBox, cb1) self.Bind(wx.EVT_CHECKBOX, self.EvtCheckBox, cb2) sizer = wx.BoxSizer(wx.VERTICAL) sizer.AddMany( [ cb1, cb2, ]) border = wx.BoxSizer(wx.VERTICAL) border.Add(st, 0, wx.ALL, 15) border.Add(sizer, 0, wx.LEFT, 50) self.SetSizer(border) pos = cb2.GetPosition().x + cb2.GetSize().width + 25 btn0 = wx.Button(self, -1, "Cancel", (pos, 150)) self.Bind(wx.EVT_BUTTON, self.OnCloseMe, btn0) self.Bind(wx.EVT_CLOSE, self.OnCloseWindow) ''' Commented out btn1 cause I couldn't make it work btn1 = wx.Button(self, -1, "Open Apps", (pos + 60, 150)) self.Bind(wx.EVT_BUTTON, self.OnTestButton, btn1) ''' def EvtCheckBox(self, event): self.log.write('EvtCheckBox: %d\n' % event.IsChecked()) cb = event.GetEventObject() if cb.Is3State(): self.log.write("\t3StateValue: %s\n" % cb.Get3StateValue()) def OnTestButton(self, evt): self.cb1.SetString(1, "FUBAR") def OnCloseMe(self, event): self.Close(True) def OnCloseWindow(self, event): self.Destroy() app = wx.PySimpleApp() frame = wx.Frame(None, -1, "An application launcher") Form1(frame, -1) frame.Show(1) app.MainLoop() -- import wx, sys, os ID_ABOUT = 101 ID_EXIT = 110 class Frame1(wx.Frame): def __init__(self,parent,id,title): wx.Frame.__init__(self,parent,wx.ID_ANY, title, size = (300, 400), style=wx.DEFAULT_FRAME_STYLE) #self.control = wx.TextCtrl(self, 1, style=wx.TE_MULTILINE) self.CreateStatusBar() # A Statusbar in the bottom of the window # Setting up the menu. filemenu= wx.Menu() filemenu.Append(ID_ABOUT, "&About"," Information about this program") filemenu.AppendSeparator() filemenu.Append(ID_EXIT,"E&xit"," Terminate the program") # Creating the menubar. menuBar = wx.MenuBar() menuBar.Append(filemenu,"&File") # Adding the "filemenu" to the MenuBar self.SetMenuBar(menuBar) # Adding the MenuBar to the Frame content. pos = 20 btn0 = wx.Button(self, -1, "Button Text", (pos, 220)) self.Bind(wx.EVT_BUTTON, self.OnCloseMe, btn0) self.Bind(wx.EVT_CLOSE, self.OnCloseWindow) # def OnTestButton(self, evt): #Run some code that checks which boxes are ticked #Then perform a function for each ticked box def OnCloseMe(self, event): self.Close(True) def OnCloseWindow(self, event): self.Destroy() self.Show(True) class Form1(wx.Panel): def __init__(self, parent, id): wx.Panel.__init__(self, parent, id) self.quote = wx.StaticText(self, -1, "Choose Applications :",wx.Point(20,30)) st = wx.StaticText(self, -1, "Select the application(s) you need to open:")#, (10, 10) cb1 = wx.CheckBox(self, -1, "Email, Calender")#,(65,40), (150, 20), wx.NO_BORDER) cb2 = wx.CheckBox(self, -1, "Browser") self.Bind(wx.EVT_CHECKBOX, self.EvtCheckBox, cb1) self.Bind(wx.EVT_CHECKBOX, self.EvtCheckBox, cb2) sizer = wx.BoxSizer(wx.VERTICAL) sizer.AddMany( [ cb1, cb2, ]) border = wx.BoxSizer(wx.VERTICAL) border.Add(st, 0, wx.ALL, 15) border.Add(sizer, 0, wx.LEFT, 50) self.SetSizer(border) def EvtCheckBox(self, event): self.log.write('EvtCheckBox: %d\n' % event.IsChecked()) cb = event.GetEventObject() if cb.Is3State(): self.log.write("\t3StateValue: %s\n" % cb.Get3StateValue()) app = wx.PySimpleApp() frame = Frame1(None, -1, "Nuffy's wxPython explorer") Form1(frame, -1) frame.Show(1) app.MainLoop() From robert.kern at gmail.com Tue Apr 11 02:07:16 2006 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 11 Apr 2006 01:07:16 -0500 Subject: Python 3.0 or Python 3000? In-Reply-To: References: <4439aba9$0$18019$c3e8da3@news.astraweb.com> Message-ID: Sergei Organov wrote: > Dennis Lee Bieber writes: > >>On Mon, 10 Apr 2006 12:12:58 +0200, Benjamin Niemann >>declaimed the following in comp.lang.python: >> >>>That's actually the versioning scheme of TeX, currently being at 3.141592 >> >> My last exposure to TeX was some 15 odd years ago; and even >>then it was just rudimentary stuff fed through LaTeX. > > It's total nonsense as LaTeX is a bunch of macros written in TeX the > language. If you meant TeX the interpreter of the TeX the language (a > program), then it's total nonsense again, as interpreter is not > (usually) fed through anything. I'm pretty sure he meant that his last exposure to TeX was writing rudimentary stuff that he was feeding through LaTeX. > Latex the program just loads LaTeX macros into the TeX interpreter > before the document to be processed, so one may say LaTeX is fed through > TeX, but not vise versa. > > Anyway, it's unfair to speak of one of the most wonderful pieces of > software ever written in such a tone. Judging tone through email is error prone. Please try not to imagine insults where there are none. -- Robert Kern robert.kern at gmail.com "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From roy at panix.com Sat Apr 22 16:37:53 2006 From: roy at panix.com (Roy Smith) Date: Sat, 22 Apr 2006 16:37:53 -0400 Subject: Problem calling math.cos() References: <3ev2g.9680$%97.5795@newsfe15.lga> Message-ID: In article , "Tim Peters" wrote: > [Robert Kern] > > ... > > ph3 = math.atan( ac3.imag / ac3.real ) > > ... > > Don't do that: atan2 is the correct way to compute the angle, because > the signs of both inputs are needed to determine the correct quadrant. > So do: > > ph3 = math.atan2(ac3.imag, ac3.real) > > instead. I certainly agree about using atan2() instead of atan(), but I'm surprised there's not an easier way to get the phase of a complex, just like abs() gives you the modulus. I can see why you wouldn't want to pollute the global namespace with another built-in just for this purpose, but surely a complex.phase property wouldn't hurt? From rnd at onego.ru Tue Apr 4 13:05:19 2006 From: rnd at onego.ru (Roman Susi) Date: Tue, 04 Apr 2006 20:05:19 +0300 Subject: Standalone Python functions in UML? In-Reply-To: <1144145349.186395.44890@z34g2000cwc.googlegroups.com> References: <1144145349.186395.44890@z34g2000cwc.googlegroups.com> Message-ID: <4432A74F.6050700@onego.ru> Ravi Teja wrote: >>>Out of curiosity, how do I draw functions outside classes with UML? How > > module could be drawn in this case? > > As a utility class. So, function could be a utility class method. If there are no better ways. >>>More theoretical question is if I create classes on the fly, how UML can > > reflect that? > > "On the fly" usually means "at runtime". I guess you mean if you > "change code" will my diagram stay in sync?. You will have to use round > trip tools. I don't know any tool supports round trip for Python code. > But if you just mean reverse engineering, lookup PyNSource, Boa > Constructor, PyReverse among others No. I do not need it. I just want to know if UML is capable of doing it. > >>>(I know that Python code itself is best at communication design ideas, > > but there are some people which prefer to talk UML.) > > Actually no. Python is a good tool for "prototyping" which is not the > same as "communicating design ideas". Diagrams are better for the later > and do not need to be executable. At least from what I know, except > Eiffel, no language makes that claim. UML is really the only contender > currently for design notation. Well, maybe SOL (Semantic Object Language) could also be quite beneficial in some cases. At least, it depends with whom to communicate design ideas and what level of formality to maintain. Also, my argument that Python is quite good at communicating design ideas is supported by the fact that Python developers do not use UML (or other modelling tools/languages) as often as say Java programmers, nor feel the need to. And probably Python is too dynamic for UML. That is another reason rountrip tools aren't there. -- Roman From da.martian at gmail.com Tue Apr 4 07:36:01 2006 From: da.martian at gmail.com (ChaosKCW) Date: 4 Apr 2006 04:36:01 -0700 Subject: Convertion of Unicode to ASCII NIGHTMARE In-Reply-To: <34b9g3-ku8.ln1@home.rogerbinns.com> References: <1144079830.734516.8390@z34g2000cwc.googlegroups.com> <1144081137.137744.253790@i39g2000cwa.googlegroups.com> <34b9g3-ku8.ln1@home.rogerbinns.com> Message-ID: <1144150561.389856.302670@v46g2000cwv.googlegroups.com> Hi Thanks for all the posts. I am still digesting it all but here are my initial comments. >Don't. You can't. Those characters don't exist in the ASCII character set. >SQLite 3.0 deals with UTF-8 encoded SQL statements, though. >http://www.sqlite.org/version3.html As mentioned by the next poster, there is, its supposed to be encode with the 'ignore' option. Thus you lose data, but thats just dandy with me. As for SQLite supporting unicode, it probably does, but something on the python side (probabyl in apsw) converts it to ascii at some point before its handed to SQLite. >The .encode() method returns a new value; it does not change an object inplace. > sql = sql.encode('utf-8') Ah yes, big bistake on my part :-/ >He is using apsw. apsw correctly handles unicode. In fact it won't >accept a str with bytes >127 as they will be an unknown encoding and >SQLite only uses Unicode internally. It does have a blob type >using buffer for situations where binary data needs to be stored. >pysqlite's mishandling of Unicode is one of the things that drove >me to writing apsw in the first place. Ok if SQLite uses unicode internally why do you need to ignore everything greater than 127, the ascii table (256 bit one) fits into unicode just fine as far as I recall? Or did I miss the boat here ? Thanks, From thn at mail.utexas.edu Wed Apr 26 17:46:34 2006 From: thn at mail.utexas.edu (Thomas Nelson) Date: 26 Apr 2006 14:46:34 -0700 Subject: do while loop In-Reply-To: References: <1146012542.166096.78690@g10g2000cwb.googlegroups.com> Message-ID: <1146087994.619439.51890@e56g2000cwe.googlegroups.com> My usual way of emulating do-while is: started = False while (someBoolean or not started): started = True #whatever else This simply assures "whatever else" happens at least once. Is this Pythonic? THN From nephish at xit.net Tue Apr 18 07:43:07 2006 From: nephish at xit.net (nephish at xit.net) Date: 18 Apr 2006 04:43:07 -0700 Subject: freakin out over C++ module in python In-Reply-To: <4ajjocFteq94U1@uni-berlin.de> References: <1145324978.877495.12580@i40g2000cwc.googlegroups.com> <4ajjocFteq94U1@uni-berlin.de> Message-ID: <1145360587.236993.241260@i40g2000cwc.googlegroups.com> ok, well enough, looked at struct and it does seem to be what i am after. for that anyway. thanks, guess i will just have to take the time and pull it apart. cheers sk From sturlamolden at yahoo.no Thu Apr 27 14:55:00 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 27 Apr 2006 11:55:00 -0700 Subject: Pyrex installation on windows XP: step-by-step guide In-Reply-To: <1146076193.605314.70200@g10g2000cwb.googlegroups.com> References: <1145449777.731155.181600@i40g2000cwc.googlegroups.com> <1146076193.605314.70200@g10g2000cwb.googlegroups.com> Message-ID: <1146164100.552822.280630@j33g2000cwa.googlegroups.com> sturlamolden wrote: > I don't think this is safe. MinGW links with msvcrt.dll whereas the > main Python distribution links with msvcr71.dll (due to Visual C++ > 2003). In order to make minGW link with msvcr71.dll, edit the text file c:\mingw\lib\gcc\mingw32\3.2.4\specs and change "-lmsvcrt" to "-lmsvcr71". Now MinGW will link with the same CRT as Python 2.4. From sijben at eemvalley.com Thu Apr 20 06:05:47 2006 From: sijben at eemvalley.com (Paul Sijben) Date: Thu, 20 Apr 2006 12:05:47 +0200 Subject: massive threading performance (was:Re: UDP performance) In-Reply-To: <44473787$0$31643$e4fe514c@news.xs4all.nl> References: <44473787$0$31643$e4fe514c@news.xs4all.nl> Message-ID: <44475cf9$0$31649$e4fe514c@news.xs4all.nl> OK the problem I posted about earlier is NOT a UDP/socket problem, it is a threading problem. Albeit one that only happens when you have many thrreads???? I have made two little scripts using the code I copied below, one client and one server (attached). If I run them concurrently on the same machine I see the following times: >>1145526192.825508 <<1145526192.825848 >>1145526193.829325 <<1145526193.834927 a transfer time in the milliseconds. Much less than the times I see in the full application. OK so I put them both in a multithreaded script (also attached) >>1145526971.619558 <<1145526971.619909 >>1145526972.619241 <<1145526972.619647 again transfer time in milliseconds. Not like this that I get from the profile of my code: << 1145517554.363850 send >> 1145517554.647485 recv which uses the same communication and threading but has 20+ threads? Now I am completely baffled! again I really appreciate if anyone can shed light on this! Paul Paul Sijben wrote: > I am stumped by the following problem. I have a large multi-threaded > server accepting communications on one UDP port (chosen for its supposed > speed). > > I have been profiling the code and found that the UDP communication is > my biggest drain on performance! Communication where the client and the > server are on the same machine still takes 300ms or sometimes much more > per packet on an Athlon64 3000+ running Linux (Fedora Core 5 x64). > > I must be doing something wrong and would really appreciate feedback on > my code below: > > I open the server port with > > self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) > self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) > self.s.bind((myaddress, myport)) > > I then open a client port with > > self.s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM) > self.s.connect((host, port)) > > the client sends data with > > self.s.sendall(data) > > and the server with > > self.s.sendto(data,link.remoteaddress) > > both receive with > > buf, address = socket.recvfrom(8192) > > The sender and receiver are in separate threads (threading.Thread). > > Does anyone know what is going wrong here, the socket communication, the > thread scheduling? > > Paul Sijben > -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: client.py URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: server.py URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: mthreadpy.py URL: From steve at REMOVETHIScyber.com.au Mon Apr 3 19:28:45 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Tue, 04 Apr 2006 09:28:45 +1000 Subject: Registration Code References: Message-ID: On Mon, 03 Apr 2006 19:29:14 +0200, Math wrote: > Hello, > > I wonder if I can ask this particular question here... > I'm writing this piece of Python Software and I'm almost done...:-) > But now I want the end-user to register this software with a registration > code or perhaps something like an evaluation demo version which expires > after some period of time... > Is this the right place to ask or does anybody know where to look for more > on the subject? Is your application really such a gee-whiz super-duper can't-live-without-it program that your users will put up with all the inconvenience and hassle, not to mention loss of privacy, of having to register? Or will they just dump your program when the demo stops working? It seems to me that the hardest problem for any new application is getting people to use it: most users won't ever find out about it; of those who do most won't care about it; of those who care, most can't be bothered downloading and installing it; and of those who might have, most will probably know of an alternative that does the job as well or better, or at least that they are more familiar with. So every little barrier you put up to make it more difficult for users to use your application, the greater the chances that your application disappears into obscurity. Look at Microsoft. Their first version of Word (for Macintosh, as it turned out) was copy-protected. Their second version of Word, and every version since, as well as Excel and Powerpoint, have not included copy protection, time-limitations, product activation, or any other barrier to keep users away. On the contrary -- Microsoft have turned a blind eye to piracy until fairly recently. Same with Windows -- although, a few years back when Microsoft felt secure in owning the desktop, they introduced product activation. What are the odds that Vista will have it? -- Steven. From pascal.parent at free.fr Mon Apr 24 09:52:53 2006 From: pascal.parent at free.fr (pascal.parent at free.fr) Date: 24 Apr 2006 06:52:53 -0700 Subject: Subclass str: where is the problem? References: <1145882577.827728.54960@j33g2000cwa.googlegroups.com> <1145883907.466748.325610@t31g2000cwb.googlegroups.com> Message-ID: <1145886773.533093.65420@t31g2000cwb.googlegroups.com> This is good... try this: value = 'test' value 'test' type(value) value = type(value) is type('') and Upper(value) or value value 'TEST' type(value) value = 1 value 1 type(value) value = type(value) is type('') and Upper(value) or value value 1 type(value) From bieliza at hotmail.com Wed Apr 12 06:34:29 2006 From: bieliza at hotmail.com (bieliza at hotmail.com) Date: 12 Apr 2006 03:34:29 -0700 Subject: Newbie wxPython questions. In-Reply-To: <1144438889.111109.20490@u72g2000cwu.googlegroups.com> References: <1144431488.217852.132790@j33g2000cwa.googlegroups.com> <1144438889.111109.20490@u72g2000cwu.googlegroups.com> Message-ID: <1144838069.856722.237250@i40g2000cwc.googlegroups.com> And why don?t you use Pythoncard, it takes the headache out of messing with wxPyhthon From jstroud at ucla.edu Fri Apr 14 20:29:37 2006 From: jstroud at ucla.edu (James Stroud) Date: Fri, 14 Apr 2006 17:29:37 -0700 Subject: Writing backwards compatible code In-Reply-To: References: Message-ID: Steven D'Aprano wrote: > I came across an interesting (as in the Chinese curse) problem today. I > had to modify a piece of code using generator expressions written with > Python 2.4 in mind to run under version 2.3, but I wanted the code to > continue to use the generator expression if possible. > > My first approach was to use a try...except block to test for generator > expressions: > > try: > gen = (something for x in blah) > except SyntaxError: > def g(): > for x in blah: > yield something > gen = g() > > > This failed to work under 2.3, because the SyntaxError occurs at compile > time, and so the try block never happens. > > I've been burnt by making assumptions before, so I tried a second, > similar, approach: > > if sys.version_info >= (2, 4): > gen = (something for x in blah) > else: > # you know the rest > > As expected, that failed too. > > The solution which worked was to put the generator expression in a second > module, then import that: > > try: > import othermodule > except SyntaxError: > # fall back code > > > What techniques do others use? > > Here is one every one will have fun lambasting: try: exec('gen = (something for x in blah)') except: def g(): # etc. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From steven.bethard at gmail.com Thu Apr 13 20:14:11 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 13 Apr 2006 18:14:11 -0600 Subject: namespace issue In-Reply-To: References: Message-ID: Daniel Nogradi wrote: > I would like to give the same name to a keyword argument of a class > method as the name of a function, with the function and the class > living in the same namespace and the class method using the > aforementioned function. So far I've been unsuccesfully trying to go > along these lines: > > def great_name( x ): > return x.upper( ) > > class myclass: > def mymethod( self, great_name=False ): > if great_name: > return great_name( 'something' ) > else: > return 'something' > >>> def great_name(x): ... return x.upper() ... >>> class myclass(object): ... def mymethod(self, great_name=False): ... if great_name: ... return globals()['great_name']('something') ... else: ... return 'something' ... >>> myclass().mymethod() 'something' >>> myclass().mymethod(True) 'SOMETHING' STeVe From tim at pollenation.net Sun Apr 2 05:00:46 2006 From: tim at pollenation.net (Tim Parkin) Date: Sun, 02 Apr 2006 10:00:46 +0100 Subject: Python 2.4.3 Documentation: Bad link In-Reply-To: <1143881841.044273.221050@g10g2000cwb.googlegroups.com> References: <1143879203.136199.32840@e56g2000cwe.googlegroups.com> <1143881841.044273.221050@g10g2000cwb.googlegroups.com> Message-ID: <442F92BE.5030009@pollenation.net> bones17 at gmail.com wrote: > Now, it works well... I really don't know why it before report 404 Not > Found... I was tested it 5x... I'm sorry for unwanted false bug report. Hi Bones, It really was a bug!! I'd seen it reported on the bug tracker and made a quick fix which is why I hadn't closed the issue in the bug tracker (it was you that reported it?). Thanks Tim From tim.hochberg at ieee.org Fri Apr 14 16:44:50 2006 From: tim.hochberg at ieee.org (Tim Hochberg) Date: Fri, 14 Apr 2006 13:44:50 -0700 Subject: PEP 359: The "make" Statement In-Reply-To: References: Message-ID: <444009C2.3020407@ieee.org> Steven Bethard wrote: > Steven Bethard wrote: > >>Duncan Booth wrote: >> >>>Steven Bethard wrote: >>> >>> >>>>Should users of the make statement be able to determine in which dict >>>>object the code is executed? The make statement could look for a >>>>``__make_dict__`` attribute and call it to allow things like:: >>>> >>>> make Element html: >>>> make Element body: >>>> make Element h1: >>>> '''First heading text''' >>>> make Element h1: >>>> '''Second heading text''' >>> >>[snip] >> >>>There is another effect which should be considered here. If you allow >>>Element to create an object to be used as the namespace, then as well >>>as doing special tracking when values are set in the namespace it can >>>also pre-seed it with names which magically appear in scope within the >>>make. >>> >>>e.g. >>> >>>make Element html: >>> make Element body: >>> make Element p: >>> text('But this ') >>> make Element strong: >>> text('could') >>> text(' be made to work') >> >>This is nice. I'll have to play around with it a bit to see how hard it >>would be to make it work. > > > Okay, I think it'll work[1]. I'm going to update this section to > something more like: > > > Open Issues > =========== > > ... > > Should users of the make statement be able to determine in which dict > object the code is executed? This would allow the make statement to > be used in situations where a normal dict object would not suffice, > e.g. if order and repeated names must be allowed. Allowing this sort > of customization could allow XML to be written like:: I think this PEP is going off the rails. It's primary virtue was that it was a simpler, clearer way to write: class Foo(args): __metaclass__ = some_metaclass #... Once it starts calling secret magic methods behind the scenes it's losing that virture. And for what? Supporting some use cases that have reasonable solutions already? > > make Element html: > make Element body: > text('before first h1') > make Element h1: > attrib(style='first') > text('first h1') > tail('after first h1') > make Element h1: > attrib(style='second') > text('second h1') > tail('after second h1') What's the virtue of this form? Is it the indentation? If so, I suspect some relatively pretty solution could be manufactured using the 'with' syntax. Does anyone really write html 'by hand' in this manner anyway? I think this approach may start looking a lot less appealing when you are generating the HTML from some other data. Then you have loops inside the body. Somehow you have to clean up all the leftover loop variables so they don't end up in your document. However, that would require some surgery and increased complexity in Element. It all looks like it would be messy and perhaps useless in real life. Regards, -tim > > assert etree.ElementTree.tostring(body) == '''\ > \ > \ > before first h1\ >

first h1

\ > after first h1\ >

second h1

\ > after second h1\ > \ > \ > ''' > > Assuming that the make statement calls the callable's > ``__make_dict__`` to get the dict in which to execute the code, the > following should make the above make statements work:: > > class Element(object): > > class __make_dict__(dict): > > def __init__(self, *args, **kwargs): > self._super = super(Element.__make_dict__, self) > self._super.__init__(*args, **kwargs) > self.elements = [] > self.text = None > self.tail = None > self.attrib = {} > > def __getitem__(self, name): > try: > return self._super.__getitem__(name) > except KeyError: > if name in ['attrib', 'text', 'tail']: > return getattr(self, 'set_%s' % name) > else: > return globals()[name] > > def __setitem__(self, name, value): > self._super.__setitem__(name, value) > self.elements.append(value) > > def set_attrib(self, **kwargs): > self.attrib = kwargs > > def set_text(self, text): > self.text = text > > def set_tail(self, text): > self.tail = text > > def __new__(cls, name, args, edict): > get_element = etree.ElementTree.Element > result = get_element(name, attrib=edict.attrib) > result.text = edict.text > result.tail = edict.tail > for element in edict.elements: > result.append(element) > return result > > > > [1] Here's the code I used to test it. > > >>> def make(callable, name, args, block_string): > ... try: > ... make_dict = callable.__make_dict__ > ... except AttributeError: > ... make_dict = dict > ... block_dict = make_dict() > ... exec block_string in block_dict > ... return callable(name, args, block_dict) > ... > >>> class Element(object): > ... class __make_dict__(dict): > ... def __init__(self, *args, **kwargs): > ... self._super = super(Element.__make_dict__, self) > ... self._super.__init__(*args, **kwargs) > ... self.elements = [] > ... self.text = None > ... self.tail = None > ... self.attrib = {} > ... def __getitem__(self, name): > ... try: > ... return self._super.__getitem__(name) > ... except KeyError: > ... if name in ['attrib', 'text', 'tail']: > ... return getattr(self, 'set_%s' % name) > ... else: > ... return globals()[name] > ... def __setitem__(self, name, value): > ... self._super.__setitem__(name, value) > ... self.elements.append(value) > ... def set_attrib(self, **kwargs): > ... self.attrib = kwargs > ... def set_text(self, text): > ... self.text = text > ... def set_tail(self, text): > ... self.tail = text > ... def __new__(cls, name, args, edict): > ... get_element = etree.ElementTree.Element > ... result = get_element(name, attrib=edict.attrib) > ... result.text = edict.text > ... result.tail = edict.tail > ... for element in edict.elements: > ... result.append(element) > ... return result > ... > >>> body = make(Element, 'body', (), textwrap.dedent("""\ > ... text('before first h1') > ... h1 = make(Element, 'h1', (), textwrap.dedent(''' > ... attrib(style='first') > ... text('first h1') > ... tail('after first h1') > ... ''')) > ... h1 = make(Element, 'h1', (), textwrap.dedent(''' > ... attrib(style='second') > ... text('second h1') > ... tail('after second h1') > ... ''')) > ... """)) > >>> assert etree.ElementTree.tostring(body) == '''\ > ... \ > ... before first h1\ > ...

first h1

\ > ... after first h1\ > ...

second h1

\ > ... after second h1\ > ... \ > ... ''' > > > STeVe From mitsura at skynet.be Thu Apr 13 10:06:08 2006 From: mitsura at skynet.be (mitsura at skynet.be) Date: 13 Apr 2006 07:06:08 -0700 Subject: trying to grasp OO : newbie Q? Message-ID: <1144937168.508799.67410@i40g2000cwc.googlegroups.com> Hi, I just started with Python and I am new to OO programming. Here is a simple code: " class Obj: myVar = 1 def __init__(self): myVar = 2 # myObj = Obj() print myObj.myVar " The output is of this script is '1'. I would except it to be '2'. I not understanding something fundamentally here. Can anybody explain? With kind regards, Kris From sandravandale at yahoo.com Fri Apr 7 12:52:04 2006 From: sandravandale at yahoo.com (Sandra-24) Date: 7 Apr 2006 09:52:04 -0700 Subject: Why did someone write this? Message-ID: <1144428724.372163.240450@t31g2000cwb.googlegroups.com> try: exc_type, exc_value, exc_traceback = sys.exc_info() # Do something finally: exc_traceback = None Why the try/finally with setting exc_traceback to None? The python docs didn't give me any clue, and I'm wondering what this person knows that I don't. Thanks, -Sandra From nephish at xit.net Fri Apr 28 00:49:24 2006 From: nephish at xit.net (nephish at xit.net) Date: 27 Apr 2006 21:49:24 -0700 Subject: can i set up a mysql db connection as a class ? In-Reply-To: References: <1146183359.932904.298760@g10g2000cwb.googlegroups.com> Message-ID: <1146199764.328276.241320@j33g2000cwa.googlegroups.com> This is great ! ok, i dont really have a lot of time to get into the ORMS (before your post, this is the first i have heard of it) and my stuff is due on Monday. he he. but, if i am able to make a global db connection, and multiple cursors pointing to the same connection object, how do i pull that off without making new db connections? something like class db(self): def __init__(self): db = MySQLdb.connect(host="localhost", user="MyUser", passwd="MyPassword", db="Stuff") def cursor(self): cursor = db.cursor() return cursor then have in my threads that need to connect cursor = db.cursor() cursor2 = db.cursor() and so on ? i may be way outta whack here. i am still new at classes, methods, and modules. i do have Essential Reference on the way from Amazon though ! :) thanks again From maxm at mxm.dk Wed Apr 12 07:18:20 2006 From: maxm at mxm.dk (Max M) Date: Wed, 12 Apr 2006 13:18:20 +0200 Subject: datetime: the date of the day one month ago...how? In-Reply-To: <3b246$443cddda$c32e4536$21664@news.flashnewsgroups.com> References: <3b246$443cddda$c32e4536$21664@news.flashnewsgroups.com> Message-ID: <443ce140$0$38644$edfadb0f@dread12.news.tele.dk> gabor wrote: > hi, > > i'm trying to get the date of the day one month ago. > > for example: > > today = 12.apr.2006 > one-month-ago = 12.mar.2006 > > so: > > one-month-ago(12.apr.2006) = 12.mar.2006 > > of course sometimes it gets more complicated, like: > > one-month-ago(31.mar.2006) > > or > > one-month-ago(1.jan.2006) > > the datetime.timedelta objects only work with hours or days or weeks, > not month (i understand why)... > > but is there a way to calculate this in python? > > i really don't want to calculate it by myself :-)) It is application specific. So how *do* you want one-month-ago(31.mar.2006) or one-month-ago(28.feb.2006) to work? No one can know but you. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science Phone: +45 66 11 84 94 Mobile: +45 29 93 42 96 From kairosenthal at tiscali.de Tue Apr 11 06:11:50 2006 From: kairosenthal at tiscali.de (kai) Date: 11 Apr 2006 03:11:50 -0700 Subject: dircache.listdir() or os.listdir() References: <1144745896.553391.74910@i39g2000cwa.googlegroups.com> Message-ID: <1144750310.927988.246430@g10g2000cwb.googlegroups.com> sorry, my posting was crazy From python at rcn.com Thu Apr 13 12:34:46 2006 From: python at rcn.com (Raymond Hettinger) Date: 13 Apr 2006 09:34:46 -0700 Subject: list.clear() missing?!? References: <1144767680.583085.310160@v46g2000cwv.googlegroups.com> <1144792144.168802.146310@i39g2000cwa.googlegroups.com> <1144870852.886477.238570@u72g2000cwu.googlegroups.com> Message-ID: <1144946086.185381.274320@e56g2000cwe.googlegroups.com> > > * the request is inane, the underlying problem is trivial, and the > > relevant idiom is fundamental (api expansions should be saved for rich > > new functionality and not become cluttered with infrequently used > > redundant entries) > > Is this sort of editorialising fair, or just a way of not-so-subtly > encouraging Guido to reject the whole idea, now and forever? Bah. Guido is not stupid, nor easily misled. Both the pros and cons were quipped with abrupt perjoratives so the bullet points could be stated succinctly and with a bit of levity. The translation to verbose, soft, politically correct statements is self-evident. "request is inane" --> "A generation of python programmers has found list clearing to be like other parts of the language that you get used to very quickly and do not prove to be a problem in practice. The request is in the same category as others which challenge api choices made 16 years ago; in particular, the decision to have compact APIs where the named methods do not duplicate functionality provided by syntax using operators and keywords. The request is less of a bug report and more a rejection of Guido's sense of design and his subsequent experience using his own language." "underlying problem is trivial" --> "Books such as the Python Pocket Reference or Python in a Nutshell are able to cover this idiom with just a single sentence. Once known and understood, the application of the current-way-to-do-it is immediate, compact, and effective." "the existing alternatives are a bit perlish" --> "Both alternatives involve a bit of inventiveness in combining two ideas (either the del keyword and its interaction with slicing notation or the assignment of an emtpy list to a slice). Each approach has a visual appearance of being a syntax trick. The effect contrasts with much of the rest of the language where it is usually possible to write code is a way that can be read and understood by non-python programmers. The existing solution trades readability for the succinctness of a compact syntactical idiom." > A list.clear method will make deleting items from a list more OO, > consistent with almost everything else you do to lists, and less > procedural. This is especially true if clear() takes an optional index (or > two), allowing sections of the list to be cleared, not just the entire > list. Don't shoot yourself in the foot here. If you want to advocate list.clear(), then you're hurting your chances by pushing for it to take an optional argument. Essentially, this amounts to an unwillingness to use the del-keyword and to duplicate its functionality with a named method. Also, in the python-dev world, making something "more OO" is neither a virtue nor a vice. It is better to argue for rich functionality, succeptibility to errors, or dramatic improvements of existing real-world code. From nkammah at yahoo.fr Sun Apr 9 09:00:04 2006 From: nkammah at yahoo.fr (kepioo) Date: 9 Apr 2006 06:00:04 -0700 Subject: fnmatch on filename (without specific extension) In-Reply-To: References: <1144561560.831490.160010@z34g2000cwc.googlegroups.com> Message-ID: <1144587604.337701.249630@i39g2000cwa.googlegroups.com> i agree with you, it is better to find by ourself. i managed to do it, but i left the code at work. i used the re module , using a re.match("Results Log") and a re.search(date) with a function to find the date og the day with the appropriate format. Is it ok to use re for file names? or fnmatch is more efficient? thanks anyway! Nassim From uval at rz.uni-karlsruhe.de Wed Apr 26 21:24:04 2006 From: uval at rz.uni-karlsruhe.de (=?ISO-8859-1?Q?Sch=FCle_Daniel?=) Date: Thu, 27 Apr 2006 03:24:04 +0200 Subject: can this be done without eval/exec? Message-ID: Hello group, >>> lst=[] >>> for i in range(10): ... lst.append(eval("lambda:%i" % i)) ... >>> lst[0]() 0 >>> lst[1]() 1 >>> lst[9]() 9 >>> >>> lst=[] >>> for i in range(10): ... exec "tmp = lambda:%i" % i # assignment is not expression ... lst.append(tmp) ... >>> lst[0]() 0 >>> lst[1]() 1 >>> lst[9]() 9 >>> and now the obvious one (as I thought at first) >>> lst=[] >>> for i in range(10): ... lst.append(lambda:i) ... >>> lst[0]() 9 >>> i 9 >>> I think I understand where the problem comes from lambda:i seems not to be fully evalutated it just binds object with name i and not the value of i thus lst[0]() is not 0 are there other solutions to this problem without use of eval or exec? Regards, Daniel From banaouas.medialog at wanadoo.fr Sun Apr 9 16:00:41 2006 From: banaouas.medialog at wanadoo.fr (m.banaouas) Date: Sun, 09 Apr 2006 22:00:41 +0200 Subject: Calling Web Services from Python In-Reply-To: References: Message-ID: <443966e2$0$19693$8fcfb975@news.wanadoo.fr> Can you tell us more about SOAPpy bug ? Is it about authentication ? Ivan Zuzak a ?crit : >... > I need a package/tool that generates web service proxies that will do > all the low-level HTTP work. (Someting like the WSDL.EXE tool in .NET > Framework) The ZSI and SOAPy packages [1] that i found (should) have > those functionalities but either have a bug (SOAPy) or either do not > work for arbitrary web services (ZSI). > ... From peter at engcorp.com Mon Apr 10 10:45:43 2006 From: peter at engcorp.com (Peter Hansen) Date: Mon, 10 Apr 2006 10:45:43 -0400 Subject: Is this code snippet pythonic In-Reply-To: <1144666334.053780.164660@e56g2000cwe.googlegroups.com> References: <1144666334.053780.164660@e56g2000cwe.googlegroups.com> Message-ID: jnair at ensim.com wrote: > My Tead Lead my object counter code seen below is not pythonic I'm guessing this was supposed to say "My team lead says my ...." (?) > class E(object): > _count = 0 > def __init__(self): > E._count += 1 > count = property(lambda self: E._count ) Is this supposed to work in a threaded environment? If so, you'll at least need to add an acquire/release pair using a threading.Lock()... > if not waht woutld be the pythonic way Other comments: 1. Why the property? Can't you just access ._count directly? 2. You don't need the "self" in the lambda, since you're not using it anyway. 3. There aren't any comments. At the least there ought to be one above "_count = 0" telling the reader what the variable is for. 4. Why are you asking us? The term "pythonic" doesn't have a fixed definition, so asking your "Tead Lead" makes more sense. From us you might learn something, but the result might still not satisfy the one person you need to satisfy with this. Maybe all he wants is to see a getter method instead of the lambda... -Peter From peace.is.our.profession at gmx.de Thu Apr 6 05:18:55 2006 From: peace.is.our.profession at gmx.de (Mirco Wahab) Date: Thu, 06 Apr 2006 11:18:55 +0200 Subject: "The World's Most Maintainable Programming Language" In-Reply-To: References: <44331897$0$12009$c3e8da3@news.astraweb.com> Message-ID: Hi Ralf >> Perl, named after Pearl Biggar (Larry Wall?s fianc?e), > > His wife was Gloria since at least 1979, perl was published > in 1987. This seems to be an insider joke (he wanted to call > the language "Gloria" first, then "pearl", then "perl"). Thanks for pointing this out ;-) This makes perfectly sense - then. I mean, its 'chromatic' who wrote about that, so at least something has to hide in each of the jokes ;-) >> set a high standard for naming techniques. > > So we should rename Python into Cottonmouth > to get more attention. No, always take some word that relates to something more or less 'feminine', its about 96% of young males who sit hours on programming over their beloved 'languages' ;-) Pythia? (http://en.wikipedia.org/wiki/Pythia) Regards, M. From prikryl at skil.cz Thu Apr 13 02:12:27 2006 From: prikryl at skil.cz (Petr Prikryl) Date: Thu, 13 Apr 2006 08:12:27 +0200 Subject: Why new Python 2.5 feature "class C()" return old-style class ? References: <1144752553.305591.88050@j33g2000cwa.googlegroups.com> <443bbdbe$0$15517$626a54ce@news.free.fr> <443c22d1$0$11341$636a55ce@news.free.fr> Message-ID: "Aahz" wrote... > Bruno Desthuilliers wrote: > >Aahz a ?crit : [...] > >>>Please repeat this 101 times each morning: > >>>"thou shall not use old-style classes for they are deprecated". > >> Classic classes are *NOT* deprecated. > >Perhaps not *officially* yet... > > Not even unofficially. The point at which we have deprecation is when > PEP8 gets changed to say that new-style classes are required for > contributions. My question: Could the old classes be treated in a new Python treated as new classes with "implicit" base object? (I know the Zen... ;-) Example: I use usually a very simple classes. When I add "(object)" to my class definitions, the code continues to works fine -- plus I have new features to use. Why this cannot be done automatically? What could be broken in the old code if it was threated so? Thanks for explanation, pepr From python.list at tim.thechases.com Mon Apr 17 17:32:50 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 17 Apr 2006 16:32:50 -0500 Subject: scanning through page and replacing all instances of 00:00:00.00 In-Reply-To: References: Message-ID: <44440982.7030901@tim.thechases.com> > I have a python-cgi file that pulls data from an sql > database, i am wondering what is the easiest way to > remove all instances of '00:00:00.00' in my date column. > > how would i write a python script to scan the entire page > and delete all instances of '00:00:00.00', would i use > regular expressions? No need for a regexp: someString = someString.replace("00:00:00.00", "") I'd recommend doing it before you print the values out, rather than try and "scan the entire page" after you've printed them. Easy 'nuff. -tkc From pmartin at snakecard.com Mon Apr 10 16:47:04 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Mon, 10 Apr 2006 15:47:04 -0500 Subject: swig-style utility Message-ID: Hi, I need to add a feature to an existing C wrapper that is not based on swig (pycsc:http://homepage.mac.com/jlgiraud/pycsc/Pycsc.html) I'm not the best with C wrapper and would love it if there were some type of utility that would generate the correct code (most) for a specific C function that I could then incorporate into the existing package. Thanks. Philippe From brandon.mcginty at gmail.com Mon Apr 17 00:08:31 2006 From: brandon.mcginty at gmail.com (brandon.mcginty at gmail.com) Date: Sun, 16 Apr 2006 21:08:31 -0700 Subject: Decode html, or is it unicode, how? Message-ID: <009a01c661d4$976fb7c0$6400a8c0@D1FWTS61> Hi All, I've done a bunch of searching in google and in python's help, but, I haven't found any function to decode a string like: Refresh! (ihenvyr) In to plain english. I'd also looked for the urldecode function in urllib, but that had been deprecated. If anyone here can give me a hand, I'd aprishiate it; it's probably very simple, but... Thx, ---------- Brandon McGinty Feel free to contact me for technical support, or just to chat; I always have time to talk and help, and an open ear. Email:Brandon.mcginty at gmail.com Skype:brandon.mcginty Msn:brandon_mcginty at hotmail.com Aim:brandonmcginty (Not currently available.) Cell:(480)-202-5790 (Weekends and nights only, please.) "Kindness is a language that the deaf can hear and the blind can see." Mark Twain -- No virus found in this outgoing message. Checked by AVG Free Edition. Version: 7.1.385 / Virus Database: 268.4.1/313 - Release Date: 4/15/2006 From wrffruntre at tznvy.pbz.ROT13 Thu Apr 27 15:58:21 2006 From: wrffruntre at tznvy.pbz.ROT13 (Jesse Hager) Date: Thu, 27 Apr 2006 15:58:21 -0400 Subject: midipy.py on linux In-Reply-To: References: Message-ID: <12528iroqrq631e@corp.supernews.com> Will Hurt wrote: > Hi > Ive been using midipy in my blender3d python scripts on windowsXP, now > im trying to run them from ubuntu and i cant find the midipy.py module > compiled for linux anywhere. > Is it possible to complie it under linux and how would i go about doing > it --or-- > Is there another module which does the same thing available for linux[ie > i can get raw midi data in as a list] and thats why no-ones bothered to > compile midipy under linux? > > Thanks > Will > The MIDI IO module I use pyPortMidi, supposedly supports Linux, but I have only ever used it on Windows. The links in the Python Cheese Shop seem broken, so here's the site address: http://alumni.media.mit.edu/~harrison/code.html The C library it is based on is here: http://www.cs.cmu.edu/~music/portmusic/ There doesn't seem to be any documentation for pyPortMidi, so you will need to read the comments in the portmidi.h from the original C library and the test.py file included in the distribution. http://www.cs.cmu.edu/~music/portmusic/portmidi/portmidi.h The Read() method of the input stream object returns a list of events, each event consists of 4 bytes of data and a timestamp. Each event contains a single MIDI message (not all of the 4 bytes will be used for most messages). Sysex commands are broken up into 4 byte pieces and returned as multiple events, one for each 4 bytes. Format is like this: [[[byte0,byte1,byte2,byte3],time],...] Not sure if it uses lists or tuples, since I use it mainly for output and I don't have MIDI input on this machine to test it... Hope this helps. -- Jesse Hager email = "wrffruntre at tznvy.pbz".decode("rot13") From rogerb at rogerbinns.com Mon Apr 10 23:32:43 2006 From: rogerb at rogerbinns.com (Roger Binns) Date: Mon, 10 Apr 2006 20:32:43 -0700 Subject: Help on exceptions (was: Convertion of Unicode to ASCII NIGHTMARE) References: <1144079830.734516.8390@z34g2000cwc.googlegroups.com> <1144081137.137744.253790@i39g2000cwa.googlegroups.com> <34b9g3-ku8.ln1@home.rogerbinns.com> <1144150561.389856.302670@v46g2000cwv.googlegroups.com> <2enbg3-kr8.ln1@home.rogerbinns.com> <1144658233.045395.213570@j33g2000cwa.googlegroups.com> <1144659373.400071.293290@j33g2000cwa.googlegroups.com> <1144678273.036360.144000@e56g2000cwe.googlegroups.com> <1144718544.134817.126720@i39g2000cwa.googlegroups.com> Message-ID: <4kkrg3-35l.ln1@home.rogerbinns.com> "Serge Orlov" wrote in message news:1144718544.134817.126720 at i39g2000cwa.googlegroups.com... > It can be like this. Notice special url, it is pointing to a > non-existing :) tutorial about why concatenating byte strings with > unicode strings can produce UnicodeDecodeError An alternate is to give an error code that people can use to look up (and users can report). It also has the advantage of being language neutral. You can see this kind of approach on IBM systems (mainframe, AIX etc) and Oracle. Roger From jparlar at cogeco.ca Thu Apr 6 18:25:11 2006 From: jparlar at cogeco.ca (Jay Parlar) Date: Thu, 6 Apr 2006 15:25:11 -0700 Subject: Missing C modules in 2.5 on OS X? Message-ID: <88edbc6803fde62c9f3b1517d0714f14@cogeco.ca> I just downloaded, built, and installed the new 2.5 alpha on OS X 10.3, and it seems that the new 'functional' didn't get installed. I know that it got built (done from the 2.5 source directory): Jay-Computer:~/Desktop/Python-2.5a1 jayparlar$ find . -iname functional* ./build/lib.darwin-7.9.0-Power_Macintosh-2.5/functional.so ./build/temp.darwin-7.9.0-Power_Macintosh-2.5/functionalmodule.o ./Modules/functionalmodule.c But it doesn't seem to have been installed, as the same 'find' from /usr/local/lib/python2.5 produces nothing at all. I used the 'make altinstall' option when installing. Now that I'm looking closer at it, it seems that *no* modules implemented in C have been installed... Jay P. From bdesth.quelquechose at free.quelquepart.fr Tue Apr 4 20:36:25 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 05 Apr 2006 02:36:25 +0200 Subject: Binary tree problem (searching) In-Reply-To: References: Message-ID: <4432e344$0$21634$636a55ce@news.free.fr> pyguy at speakeasy.net a ?crit : > Hi all, > > I am running into a conceptual glitch in implementing a simple binary tree class. My insertion and printing (sorting) seems to be ok, but when I search the tree, my find method isn't doing what I thought it should. > > Here is the output of running my tests: > > >>python -i trees.py > > ********************************************************************** > File "trees.py", line 70, in __main__.BinaryTree.find > Failed example: > t.find('Leo') > Expected: > -1 > Got nothing > ********************************************************************** > File "trees.py", line 72, in __main__.BinaryTree.find > Failed example: > t.find('Cancer') > Expected: > 1 > Got nothing > ********************************************************************** > 1 items had failures: > 2 of 7 in __main__.BinaryTree.find > ***Test Failed*** 2 failures. > >>>> (snip) You forgot to return the result of calls to self.left.find() and self.right.find() > > def find(self, key, child=None): > """ > >>> t=BinaryTree('Capricorn') > >>> t.addNode('Aquarius') > >>> t.addNode('Pices') > >>> t.addNode('Cancer') > >>> t.find('Capricorn') > 1 > >>> t.find('Leo') > -1 > >>> t.find('Cancer') > 1 > """ > if self.key == key: > return 1 > elif key < self.key: > if self.left: #self.left.find(key) return self.left.find(key) > else: > return -1 > elif key > self.key: > if self.right: #self.right.find(key) return self.right.find(key) > else: > return -1 > From grante at visi.com Sat Apr 15 22:30:34 2006 From: grante at visi.com (Grant Edwards) Date: Sun, 16 Apr 2006 02:30:34 -0000 Subject: How to Convert a string into binary References: <4441905D.3070401@lexicon.net> Message-ID: <1243b2ann57ue2e@corp.supernews.com> On 2006-04-16, John Machin wrote: > On 16/04/2006 5:25 AM, HNT20 wrote: >> >> hi --> 0110100001101001 >> > > This implies that the bits in a byte are transmitted MSB first. I > haven't done anything anywhere near this area since about the time that > acoustic couplers went the way of buggy whips, but my vague recollection > is LSB first. It depends. "Normal" UARTs send LSB first. Some other types of serial links are MSB first. -- Grant Edwards grante at visi.com From mahs at telcopartners.com Wed Apr 19 00:27:10 2006 From: mahs at telcopartners.com (Michael Spencer) Date: Tue, 18 Apr 2006 21:27:10 -0700 Subject: temporary scope change In-Reply-To: References: Message-ID: Edward Elliott wrote: ... > > for x in list1: > i += 1 > # for y in list2: > print x * i > > and have the print line execute as part of the for x block. In other > words, I want the block with print to be in the scope of the for x loop. > But instead it raises a SyntaxError because the indentation is different. > Just replace: for y in list2: with: if True: But, in a real debugging situation, y would probably be used in the inner loop, so you could instead, precede the y loop with: list2 = [One_object_that_list2_could_contain] so that that the loop executes once. Once that works, you might then selectively add items to your temporary list2. Note that neither the `if` nor the `for` statement actually creates a new scope. Michael From onurb at xiludom.gro Fri Apr 7 04:30:29 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 07 Apr 2006 10:30:29 +0200 Subject: Partially unpacking a sequence In-Reply-To: <1144352710.190839.165580@z34g2000cwc.googlegroups.com> References: <1144352710.190839.165580@z34g2000cwc.googlegroups.com> Message-ID: <4436236d$0$29651$636a55ce@news.free.fr> tkpmep at hotmail.com wrote: > I have a list y > >>>>y > > ['20001201', 'ARRO', '04276410', '18.500', '19.500', '18.500', > '19.500', '224'] > > from which I want to extract only the 2nd and 4th item > > by partially > unpacking the list. So I tried > >>>>a,b = y[2,4] Mmm, so lovely and meaningful names !-) FWIW, and since nobody seemed to mention it, list indexes are zero-based, so the second element of a list is at index 1 and the fourth at index 3. Also, a GoodPractice(tm) is to use named constants instead of magic numbers. Here we don't have a clue about why these 2 elements are so specials. Looking at the example list (which - semantically - should be a tuple, not a list) I could wild-guess that the 2nd item is a reference and the fourth a price, so: REF_INDEX = 1 # lists are zero-based PRICE_INDEX = 3 ref, price = y[REF_INDEX], y[PRICE_INDEX] And finally, since this list is clearly structured data, wrapping it into an object to hide away implementation details *may* help - depending on the context, of course !-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From my_email_is_posted_on_my_website at munged.invalid Sat Apr 1 00:28:17 2006 From: my_email_is_posted_on_my_website at munged.invalid (Roedy Green) Date: Sat, 01 Apr 2006 05:28:17 GMT Subject: DO NOT USE JAVA BECAUSE IT IS NOT OPEN SOURCE References: <1143867556.814290.321740@i40g2000cwc.googlegroups.com> Message-ID: On 31 Mar 2006 20:59:16 -0800, atbusbook at aol.com wrote, quoted or indirectly quoted someone who said : >Programing Languiges Are Ment to be free. That is why i am starting The >Coo De Tar thats french for Blow of state it is a flash/java >alternative and if you are going to use a server side languige use >Perl,Python or better yet Ruby. What is the point of a languige without >a standerd and without a open source distrabution. Coo De Tar will be >released as a api for perl,python and ruby. Java sucks because it IS >NOT FREE. I AM A GNU GUY I BELEVE THAT SOFTWARE MUST AND SHALL BE >FREE!!!!!!!!!!!!!! do not use java because it is an oxymoron If you can't even spell, how do you hope to create a language better than Java? Oxymoron? Look that up in the dictionary. Why NOT open source? Check how many upturned turtle icons there are in the Java glossary next to free software. Without money coming in to support it, the project dies when the original author gets bored. Java has a standard, see the JLS see http://mindprod.com/jgloss/jls.html What it lacks is an INDEPENDENT standards body. However Java is in much tighter shape than C++, SQL or any of the languages that DO have a standards body. -- Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching. From aahz at pythoncraft.com Mon Apr 3 16:09:00 2006 From: aahz at pythoncraft.com (Aahz) Date: 3 Apr 2006 13:09:00 -0700 Subject: MOO meets Python Message-ID: http://playsh.org/ http://sourceforge.net/projects/playsh -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Look, it's your affair if you want to play with five people, but don't go calling it doubles." --John Cleese anticipates Usenet From clodoaldo.pinto at gmail.com Fri Apr 7 15:45:48 2006 From: clodoaldo.pinto at gmail.com (Clodoaldo Pinto) Date: 7 Apr 2006 12:45:48 -0700 Subject: Programming Tutorial for absolute beginners Message-ID: <1144439148.751062.16590@t31g2000cwb.googlegroups.com> I'm starting a programming tutorial for absolute beginners using Python and I would like your opinions. http://programming-crash-course.com Regards, Clodoaldo Pinto From kent at kentsjohnson.com Thu Apr 6 13:53:04 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Thu, 06 Apr 2006 13:53:04 -0400 Subject: Quickie: converting r"\x2019" to int In-Reply-To: References: Message-ID: <4435501d$1_2@newspeer2.tds.net> Robin Haswell wrote: > Hey guys. This should just be a quickie: I can't figure out how to convert > r"\x2019" to an int - could someone give me a hand please? Is this what you mean? In [9]: int(r'\x2019'[2:], 16) Out[9]: 8217 or maybe you meant this: In [6]: ord(u'\u2019') Out[6]: 8217 Kent From groups at theyoungfamily.co.uk Wed Apr 19 05:15:18 2006 From: groups at theyoungfamily.co.uk (Ben) Date: 19 Apr 2006 02:15:18 -0700 Subject: Missing interfaces in Python... In-Reply-To: <4445f7f8$0$9451$626a54ce@news.free.fr> References: <1145306373.781129.305840@z34g2000cwc.googlegroups.com> <1145430546.625634.194710@g10g2000cwb.googlegroups.com> <7lrb429tg5c6dt1bt99d1131cafuulvqap@4ax.com> <4445f7f8$0$9451$626a54ce@news.free.fr> Message-ID: <1145438118.179643.140390@e56g2000cwe.googlegroups.com> bruno at modulix wrote: > Rene Pijlman wrote: > > Kay Schluehr: > > > >>You won't find many deep class hierarchies and extensive frameworks. > > > > > > Zope comes to mind. > > > > > >>This has the advantage that a classification you have done once at > >>the beginning of your project in the design phase is not considered > >>to be carved in stone. > > > > > > Zope 3 comes to mind. > > Yeps. Now Zope is a world in itself, and is not really pythonic IMHO. > It seems to me that a lot of python projects reimplement interfaces or adaption of some kind once they reach a certain size (Zope, PEAK, eggs, TurboGears, etc), which implies that they really do have some benefits, particularly in documentation. Cheers, Ben > -- > bruno desthuilliers > python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for > p in 'onurb at xiludom.gro'.split('@')])" From deets at nospam.web.de Wed Apr 12 08:30:32 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 12 Apr 2006 14:30:32 +0200 Subject: Python2CPP ? References: Message-ID: <4a4a98FrjdvlU1@uni-berlin.de> > 1) Curiosity. I would like to see how well the translation goes. If there is something that works, it will look awful to the eye. Code-generators are generally not very idiomatic - they mapping is to localized to e.g. factorize out a more complex loop to something a generator might to much better. I suggest you take a look at pyrex, a python-like language that bridges python and C by generating C. > 2) Efficiency. It is alot quicker to code something in Python. If I can > write it in Python and auto-convert it to C++. I would save time > coding. Then let it run in python. > 3) Education. I would learn more about Python, C++, their similarities and > differences. I also doubt that. digging into generated, non-idiomatic code won't do much for you to grasp what is behind Python or C++ as well. Think e.g. of templating, a major feature in C++ that certainly won't be utilized by a code-generator that does everything based on python C-structures and their C-API. Regards, Diez From aleaxit at yahoo.com Mon Apr 17 23:58:16 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 17 Apr 2006 20:58:16 -0700 Subject: Ironpython book? References: <1145329406.419299.12780@i40g2000cwc.googlegroups.com> Message-ID: <1hdyh5s.1ithyei4n7ucmN%aleaxit@yahoo.com> wrote: > Anyone know if there is a book for Ironpython in the works? A good > knowledge of .NET and Python is enough to get started but just poking > around Ironpython homepage it seems like there are some new language > features added to handle some quirks with working within the CLR. > Although I could be wrong. I don't know of any such books, but if M$ is willing to slip me a suitable sweetener (to make it worth my while to install Windows again after years of blissfully Windows-free existence: it must at least cover the expense of the extra Zantac and Maalox consumption, plus suitable compensation for pain and suffering), AND lend me the consulting expertise of the Ironpython team, hey, I _could_ be persuaded to write "IronPython in a Nutshell" (not that I'd ever admit it in public, of course...). Alex From deets at nospam.web.de Thu Apr 27 10:53:34 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 27 Apr 2006 16:53:34 +0200 Subject: begging for a tree implementation References: <1146091386.013265.153660@v46g2000cwv.googlegroups.com><1146127110.773347.222270@e56g2000cwe.googlegroups.com> <4bbh68F10a2lbU1@uni-berlin.de> Message-ID: <4bc47gFvcrgcU1@uni-berlin.de> Fredrik Lundh wrote: > Diez B. Roggisch wrote: > >> This is not to discourage you - just don't expect people to greet you as >> the next messiah who finally brought one of CS most fundamental data >> structures to Python... :) > > xml.etree was added to Python 2.5 before christmas :-) Can't wait until etree grows some tree optimization algorithms like AVL or red-black. Those degenerated XML-documents of mine always annoyed me.. :) Diez From sjmachin at lexicon.net Fri Apr 28 06:27:47 2006 From: sjmachin at lexicon.net (John Machin) Date: Fri, 28 Apr 2006 20:27:47 +1000 Subject: time conversions [hh:mm:ss.ms <-> sec(.ms) In-Reply-To: <1146213549.597990.115220@y43g2000cwc.googlegroups.com> References: <1146213549.597990.115220@y43g2000cwc.googlegroups.com> Message-ID: <4451EE23.9010802@lexicon.net> On 28/04/2006 6:39 PM, kpp9c wrote: > Hi, > > I was looking at python & datetime and hoping that it would already > have > a method/func to translate time formats. I need to translate seconds to > hh:mm:ss.ms and vice versa and would like the ability to do some basic > arithmetic in these formats. Could you please be a little more specific? I guess that you have seconds-and-a-fraction in a float eg 3723.456 seconds, which is equivalent to 1 hour, 2 minutes and 3.456 seconds. How do you want that represented? You say hh:mm:ss.ms which could be interpreted as a string "01:02:03.456" -- but this format is not very useful for "basic arithmetic". OTOH a tuple representation like (1, 2, 3.456) can accommodate "arithmetic" of some sort or other more easily -- is that what you had in mind? Next question: exactly what basic arithmetic operations do you want to do in the hour-minute-second format, and why do you want to do them in that format, and not the seconds-only format? > I think that there just has to be a > package > or module out there that already does this with reasonable speed and > accuracy. Get the specification right first. Get the accuracy right second. Then worry about the speed. The "arithmetic" of which you speak can't be so mind-boggling that you can't write it in Python and test it yourself. You may find the specification changes under the influence of the implementation :-) > > Sadly, i do indeed need both reasonable speed and accuracy since i will > be adding up huge masses of small events (around 10 to 60 ms > milliseconds > in length) to create cloud like textures for real time audio/video at > high sampling rates. So why not keep it in seconds (or milliseconds)? Have you considered an extension, using C or Pyrex? > > i googled for hh:mm:ss.ms + python and didn't find much... > > best, > > -kp--- > > [mac os x w/ python 2.4.1] From tomerfiliba at gmail.com Mon Apr 24 18:10:59 2006 From: tomerfiliba at gmail.com (gangesmaster) Date: 24 Apr 2006 15:10:59 -0700 Subject: Announce: Construct has moved Message-ID: <1145916659.084814.119880@e56g2000cwe.googlegroups.com> Construct, the "parsing made fun" library, has moved from it's sourceforge home to wikispaces: http://pyconstruct.wikispaces.com (the sf page redirects there) -tomer From cesugden at fastmail.co.uk Wed Apr 26 10:40:11 2006 From: cesugden at fastmail.co.uk (Chris Sugden) Date: Wed, 26 Apr 2006 15:40:11 +0100 Subject: Twisted and wxPython integration problems Message-ID: <20060426143928.9B7513EB1@frontend3.messagingengine.com> Hi, I'm a university student creating a python Chat server and client using twisted. The server works great. However I'm trying to create the client with a gui using wxpython and twisted. The code for the client is attached bellow. I'm working with a partner and he already tried posting our problem on comp.lang.python but we didn't receive a successful reply so I thought I would try the mailing list. Here's the problem: I can get my client to connect to my server, but can't get it to disconnect or send messages to the server. I am getting the following error when I click on the 'Disconnect' button - AttributeError: 'NoneType' object has no attribute 'loseConnection' I have attached the code for the client below this. We are both fairly new to Python so would appreciate any help anyone can offer. Thanks, Chris & Peter client.py ---------- from wxPython.wx import * import wx from twisted.internet import wxreactor wxreactor.install() from twisted.internet import reactor from twisted.internet.protocol import Protocol, ClientCreator class imApp(wxApp, Protocol): def buildMe(self): frame = wx.Frame(None, title="IM Client", size=(800, 550)) bkg = wx.Panel(frame) global ipAdd global portNo global messages global newMsg ipAddLab = wx.StaticText(bkg, -1, 'IP Address: ') ipAdd = wx.TextCtrl(bkg) ipAdd.SetToolTipString('Please enter the server IP address here.') spacer1 = wx.StaticText(bkg, -1, ' ') portNoLab = wx.StaticText(bkg, -1, 'Port No: ') portNo = wx.TextCtrl(bkg) portNo.SetToolTipString('Please enter the port number the server is using here.') spacer2 = wx.StaticText(bkg, -1, ' ') connectButton = wx.Button(bkg, label='Connect') connectButton.SetToolTipString('Click this button to connect to the server.') connectButton.Bind(wx.EVT_BUTTON, self.connectMe) disconnectButton = wx.Button(bkg, label='Disconnect') disconnectButton.SetToolTipString('Click this button to disconnect from the server.') disconnectButton.Bind(wx.EVT_BUTTON, self.disconnectMe) messages = wx.TextCtrl(bkg, style=(wx.TE_MULTILINE | wx.HSCROLL)) newMsg = wx.TextCtrl(bkg) sendButton = wx.Button(bkg, label='Send') sendButton.SetToolTipString('Click this button to send a message to the server.') sendButton.Bind(wx.EVT_BUTTON, self.sendMe) hbox1 = wx.BoxSizer() hbox1.Add(ipAddLab, proportion=0, flag=wx.EXPAND) hbox1.Add(ipAdd, proportion=0, flag=wx.EXPAND) hbox1.Add(spacer1, proportion=0, flag=wx.EXPAND) hbox1.Add(portNoLab, proportion=0, flag=wx.EXPAND) hbox1.Add(portNo, proportion=0, flag=wx.EXPAND) hbox1.Add(spacer2, proportion=0, flag=wx.EXPAND) hbox1.Add(connectButton, proportion=0, flag=wx.LEFT, border=5) hbox1.Add(disconnectButton, proportion=0, flag=wx.LEFT, border=5) hbox2 = wx.BoxSizer() hbox2.Add(newMsg, proportion=1, flag=wx.EXPAND | wx.LEFT | wx.LEFT | wx.LEFT, border=5) hbox2.Add(sendButton, proportion=0, flag=wx.LEFT, border=5) vbox = wx.BoxSizer(wx.VERTICAL) vbox.Add(hbox1, proportion=0, flag=wx.EXPAND | wx.ALL, border=5) vbox.Add(messages, proportion=1, flag=wx.EXPAND | wx.LEFT | wx.LEFT | wx.LEFT, border=5) vbox.Add(hbox2, proportion=1, flag=wx.EXPAND | wx.ALL, border=5) bkg.SetSizer(vbox) ipAdd.WriteText('localhost') portNo.WriteText('1234') frame.Show(true) return true def sendMe(self, e): msg = newMsg.GetValue() + '\n' messages.WriteText(msg) newMsg.SetValue('') def disconnectMe(self, e): messages.WriteText('Disconnecting from server...\n') self.transport.loseConnection() def connectMe(self, e): messages.WriteText('Connecting to server...\n') c = ClientCreator(reactor, imApp) ip = str(ipAdd.GetValue()) port = int(portNo.GetValue()) c.connectTCP(ip, port) def mainProg(): app = imApp(0) app.buildMe() reactor.registerWxApp(app) reactor.run() if __name__ == '__main__': mainProg() -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve.horsley at gmail.com Mon Apr 17 17:39:34 2006 From: steve.horsley at gmail.com (Steve Horsley) Date: Mon, 17 Apr 2006 22:39:34 +0100 Subject: XPath/Screen Scraping Gurus.. In-Reply-To: References: <237101c65d84$c0c54da0$0301a8c0@Mesa.com> Message-ID: Peter Hansen wrote: > bruce wrote: >> I'm not that familiar with Pythin, but I wasn wondering if there are any >> XPath/Python Gurus that I might be able to talk to regarding screen >> scraping >> applications... > > Since you mention XPath, it seems likely you are really interested in > *web-scraping*. > > Screen-scraping refers, I believe, to the process of identifying what is > onscreen in GUI programs, possibly even at the pixel level, and trying > to translate that back into a higher level model (e.g. text in fields) > of what is going on. > > Web-scraping, on the other hand, generally doesn't need to involve the > graphic representation of anything, and can work at the level of HTML, > XML, and ... XPath. > > (Disclaimer: I know these terms are not really standardized, but I think > the defacto standard definitions match what I've described fairly closely.) > > -Peter > Back in the days of DOS when I first came across the term screen scraping, it meant a program that emulated a terminal like a VT100, sending keystrokes and reading from an internal screen buffer. This was very much text and character oriented. Steve From mystilleef at gmail.com Sat Apr 1 03:48:37 2006 From: mystilleef at gmail.com (Mystilleef) Date: 1 Apr 2006 00:48:37 -0800 Subject: Best IDE for Python? References: <1143783179.361616.76750@i39g2000cwa.googlegroups.com> Message-ID: <1143881317.038743.297520@i39g2000cwa.googlegroups.com> Good luck finding the best Python IDE. :-) While you are at it, have a look at Scribes. It's great for Python editing and it's even written in Python. If you appreciate KISS, I'm positive you'd appreciate Scribes. And if you yearn for an editor that doesn't get in your way, or that allows you to focus exclusively on coding, then it is for you. http://scribes.sf.net/ GIF Demo: http://www.minds.may.ie/~dez/images/blog/scribes.html Flash Demo: http://scribes.sf.net/snippets.htm From sluggoster at gmail.com Mon Apr 24 17:56:23 2006 From: sluggoster at gmail.com (Mike Orr) Date: 24 Apr 2006 14:56:23 -0700 Subject: Looking for resources for making the jump from Java to Python easier and more productive References: <1145691651.385835.298600@u72g2000cwu.googlegroups.com> Message-ID: <1145915783.444709.38420@y43g2000cwc.googlegroups.com> Lawrence D'Oliveiro wrote: > "ToddLMorgan" wrote: > >Are there python specific equivalents to the common Patterns, > >Anti-Patterns and Refactoring books that are so prevalent as > >reccomended reading in C++ and Java? > I don't think they exist. Such books are targeted more towards > development in a corporate environment, where every proposal has to go > through multiple layers of management, and nothing is ever done by > individuals working alone, always by "teams" working on separate parts > of the project Hey, patterns are important. They keep people from reinventing the wheel and banging their head against the wall. Perhaps the best source for Python patterns is the Python Cookbook. http://www.oreilly.com/catalog/pythoncook/ http://aspn.activestate.com/ASPN/Python/Cookbook/ I recommend at least going through the table of contents so you'll know where to go when you're wondering, "How do I do X in Python?" --Mike From tjreedy at udel.edu Mon Apr 17 14:26:33 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 17 Apr 2006 14:26:33 -0400 Subject: Queue can result in nested monitor deadlock References: <1145284326.177062.230120@v46g2000cwv.googlegroups.com> Message-ID: "Jonathan Amsterdam" wrote in message news:1145284326.177062.230120 at v46g2000cwv.googlegroups.com... > As I'm new to the Python community, I'm not sure that this is the right > forum for this suggestion. Is it the sort of thing one would put on the > SourceForge bug list? Advice appreciated. As a sometimes bug reviewer who has noticed that a substantial fraction of 'bug' reports do not actually report CPython bugs, I wish more people would do as you did and post here first and get opinions from the wider variety of readers here. A CPython bug is a discrepancy between a reasonable interpretation of the doc and the behavior of the CPython implementation. Your post did not even claim such a discrepancy that I could see. A request for a design change can be put on the RFE (request for enhancement) list. Patches, whether to fix bugs or implement enhancements, usually go on the patch list. Note that you do not necessarily need to convince people that the current design is 'flawed' to demonstrate that a change would be good. Perhaps your recipe should be added to the oreilly online python cookbook. Terry Jan Reedy From paul at boddie.org.uk Mon Apr 10 06:26:51 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 10 Apr 2006 03:26:51 -0700 Subject: Convertion of Unicode to ASCII NIGHTMARE References: <1144079830.734516.8390@z34g2000cwc.googlegroups.com> <1144081137.137744.253790@i39g2000cwa.googlegroups.com> <34b9g3-ku8.ln1@home.rogerbinns.com> <1144169929.449801.98520@t31g2000cwb.googlegroups.com> <1144658351.434852.259350@e56g2000cwe.googlegroups.com> Message-ID: <1144664811.810297.176950@u72g2000cwu.googlegroups.com> ChaosKCW wrote: > > > > There's an Oracle environment variable that appears to make a > > difference: NLS_CHARSET, perhaps - it's been a while since I've had to > > deal with Oracle, and I'm not looking for another adventure into > > Oracle's hideous documentation to find out. > > That is an EVIL setting which should not be used. The NLS_CHARSET > environment variable causes so many headaches its not worth playing > with it at all. Well, at this very point in time I don't remember the preferred way of getting Oracle, the client libraries and the database adapter to agree on the character encoding used for communicating data between applications and the database system. Nevertheless, what you need to do is to make sure that you know which encoding is used so that if you either get plain strings (ie. not Unicode objects) out of the database, or if you need to write plain strings to the database, you can provide the encoding to the unicode built-in function or to the decode/encode methods; this is much better than just stripping out characters that can't be represented by ASCII. Anyway, despite my objections to digging through Oracle documentation, I found the following useful documents: the "Globalization Support" index [1], an FAQ about NLS_LANG [2], and a white paper about Unicode support in Oracle [3]. It may well be the case that NLS_LANG might help you do what you want, but since the database systems I have installed (PostgreSQL, sqlite3) seem to "do Unicode" without such horsing around, I'm not really able to offer much more advice on this subject. Paul [1] http://www.oracle.com/technology/tech/globalization/index.html [2] http://www.oracle.com/technology/tech/globalization/htdocs/nls_lang faq.htm [3] http://www.oracle.com/technology/tech/globalization/pdf/TWP_AppDev_Unicode_10gR2.pdf From samantha7395 at hotmail.com Tue Apr 4 11:54:05 2006 From: samantha7395 at hotmail.com (Samantha) Date: Tue, 4 Apr 2006 08:54:05 -0700 Subject: Help with display placement References: <0v-dnVDsAaY-F6_Z4p2dnA@adelphia.com> <1144163990.760020.312370@g10g2000cwb.googlegroups.com> Message-ID: I want to be able to control where the dialog is displayed . X,Y location from the upper left corner of the screen. S wrote in message news:1144163990.760020.312370 at g10g2000cwb.googlegroups.com... > This code come up, fairly centered in my screen. What do you mean by > move? > From kent at kentsjohnson.com Fri Apr 14 08:36:47 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Fri, 14 Apr 2006 08:36:47 -0400 Subject: requestion regarding regular expression In-Reply-To: <1145006270.632156.144790@j33g2000cwa.googlegroups.com> References: <1145006270.632156.144790@j33g2000cwa.googlegroups.com> Message-ID: <443f91d7$1_2@newspeer2.tds.net> Kelie wrote: > Hello, > > I'm trying to analyze some autolisp code with python. In the file to > be analyzed there are many functions. Each function begins with a > "defun" statement. And before that, there may or may not have comment > line(s), which begins with ";". My goal is to export each function > into separate files, with comments, if there is any. Below is the code > that I'm struggling with: > > [code] > > path = "C:\\AutoCAD\\LSP\\Sub.lsp" > string = file(path, 'r').read() > > import re > pat = "\\;+.+\\n\\(DEFUN" > p = re.compile(pat,re.I) > > iterator = p.finditer(string) > spans = [match.span() for match in iterator] > > for i in range(min(15, len(spans))): > print string[spans[i][0]:spans[i][1]] > > [/code] > > The code above runs fine. But it only takes care of the situation in > which there is exactly one comment line above the "defun" statement. ISTM you don't need regex here, a simple line processor will work. Something like this (untested): path = "C:\\AutoCAD\\LSP\\Sub.lsp" lines = open(path).readlines() # Find the starts of all the functions starts = [i for i, line in enumerate(lines) if line.startswith('(DEFUN')] # Check for leading comments for i, start in starts: while start > 0 and lines[start-1].startswith(';'): starts[i] = start = start-1 # Now starts should be a list of line numbers for the start of each function Kent From kay.schluehr at gmx.net Sun Apr 30 03:38:24 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 30 Apr 2006 00:38:24 -0700 Subject: best way to determine sequence ordering? In-Reply-To: <2eqdnbgOAqcjm8nZnZ2dnUVZ_umdnZ2d@comcast.com> References: <70q4g.2006$No6.43783@news.tufts.edu> <2eqdnbgOAqcjm8nZnZ2dnUVZ_umdnZ2d@comcast.com> Message-ID: <1146382704.343619.122450@j73g2000cwa.googlegroups.com> > * building a dict of indicies:: > > positions = dict((item, i) for i, item in enumerate(L)) > > if positions['A'] < positions['D']: > # do some stuff > > You'll only get a gain from this version if you need to do several > comparisons instead of just one. Hi Steven, your solution may not create the correct answer if an item occurs twice in the list because the later occurrence overwrites the former during dict creation: >>> L = ['C', 'A', 'D', 'B', 'A'] >>> dict((item, i) for i, item in enumerate(L)) {'A': 4, 'C': 0, 'B': 3, 'D': 2} This gives the impression that 'D' always precedes 'A' which is wrong. From neurogasm at gmail.com Mon Apr 17 00:23:43 2006 From: neurogasm at gmail.com (Kun) Date: Mon, 17 Apr 2006 00:23:43 -0400 Subject: passing string from one file to another Message-ID: I have a python-cgi form whose sole purpose is to email. It has the fields 'to', 'from', 'subject', 'body', etc. and if the user fills them out and clicks submit, it will invoke another file called mail.py which uses smtplib to send the message. This works fine but instead of typing in a 'body', i would like the initial python program to just send a string as the body of the email. now normally i'd just set the msg in the mail.py file equal to the string, however, i do not know how to link a string from another python file to the mail.py file. does anyone know a solution to this? From prouleau at impathnetworks.com Sat Apr 29 20:12:48 2006 From: prouleau at impathnetworks.com (Pierre Rouleau) Date: Sat, 29 Apr 2006 20:12:48 -0400 Subject: Can we create an_object = object() and add attribute like fora class? In-Reply-To: References: <1hek76f.48x7rvw33771N%aleaxit@yahoo.com> Message-ID: Fredrik Lundh wrote: > Pierre Rouleau wrote: > > >>I can understand the design decision not to give object a __dict__, but >>I wonder if i'd be a good idea to have a class that derives from object >>and has a __dict__ to be in the standard library. > > > so you can replace one line of code in some of your programs with > an import statement ? > ok... I should have said "something like the built-in object type" instead of "standard library"... -- Pierre Rouleau From tanghaibao at gmail.com Wed Apr 5 16:50:37 2006 From: tanghaibao at gmail.com (Haibao Tang) Date: 5 Apr 2006 13:50:37 -0700 Subject: How to parse a name out of a web page? Message-ID: <1144270237.256664.46120@t31g2000cwb.googlegroups.com> with high accuracy... My temporary plan is to first recognized consecutive two or three initial-capitalized words, but certainly we need to do more than that? Anyone has suggestions? Thanks first. From rpdooling at gmail.com Tue Apr 25 13:02:17 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 25 Apr 2006 10:02:17 -0700 Subject: How do I open a mysql database with python References: Message-ID: <1145984537.422410.310490@i39g2000cwa.googlegroups.com> Or mxODBC http://www.egenix.com/files/python/mxODBC.html rpd From aleaxit at yahoo.com Mon Apr 17 23:28:14 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 17 Apr 2006 20:28:14 -0700 Subject: Slicing matrix References: <20060418020438.18419.qmail@web35814.mail.mud.yahoo.com> Message-ID: <1hdygsq.1b0nmhxph8p5rN%aleaxit@yahoo.com> Robert Kern wrote: ... > array([[ 0, 1, 2, 3, 4], > [ 5, 6, 7, 8, 9], > [10, 11, 12, 13, 14], > [15, 16, 17, 18, 19], > [20, 21, 22, 23, 24]]) > > > How do I easily slice out [0,1,2] > > In [7]: p[0, :3] > Out[7]: array([0, 1, 2]) > > > or [1,2,3] > > In [9]: p[0, 1:4] > Out[9]: array([1, 2, 3]) > > > or [2,7,12] > > In [10]: p[:3, 2] > Out[10]: array([ 2, 7, 12]) > > > or [7,12,17] and put it in a list? > > In [11]: p[1:4, 2] > Out[11]: array([ 7, 12, 17]) And for the "put it in a list" part, if you truly need that (which is rarely the case), just call list(p[1:4, 2]) and so on. BTW, all of these work with good old Numeric just as with numarray and numpy. Alex From vinjvinj at gmail.com Fri Apr 21 07:38:19 2006 From: vinjvinj at gmail.com (vj) Date: 21 Apr 2006 04:38:19 -0700 Subject: PyLint 0.11 / astng 0.16 In-Reply-To: References: Message-ID: <1145619499.588154.161390@t31g2000cwb.googlegroups.com> It does. In my case I'm thinking of embedding pylint to check user scripts which are written in python. From jdc at uwo.ca Tue Apr 11 20:58:37 2006 From: jdc at uwo.ca (Dan Christensen) Date: Tue, 11 Apr 2006 20:58:37 -0400 Subject: list.clear() missing?!? In-Reply-To: <1144774431.11151.5.camel@kenshin.CASA> References: <1144767680.583085.310160@v46g2000cwv.googlegroups.com> <1144774431.11151.5.camel@kenshin.CASA> Message-ID: <87hd4zd2yq.fsf@uwo.ca> Felipe Almeida Lessa writes: > I love benchmarks, so as I was testing the options, I saw something very > strange: > > $ python2.4 -mtimeit 'x = range(100000); ' > 100 loops, best of 3: 6.7 msec per loop > $ python2.4 -mtimeit 'x = range(100000); del x[:]' > 100 loops, best of 3: 6.35 msec per loop > $ python2.4 -mtimeit 'x = range(100000); x[:] = []' > 100 loops, best of 3: 6.36 msec per loop > $ python2.4 -mtimeit 'x = range(100000); del x' > 100 loops, best of 3: 6.46 msec per loop > > Why the first benchmark is the slowest? I don't get it... could someone > test this, too? I get similar behaviour. No idea why. $ python2.4 -mtimeit 'x = range(100000); ' 100 loops, best of 3: 6.99 msec per loop $ python2.4 -mtimeit 'x = range(100000); del x[:]' 100 loops, best of 3: 6.49 msec per loop $ python2.4 -mtimeit 'x = range(100000); x[:] = []' 100 loops, best of 3: 6.47 msec per loop $ python2.4 -mtimeit 'x = range(100000); del x' 100 loops, best of 3: 6.6 msec per loop Dan From onurb at xiludom.gro Wed Apr 26 11:04:20 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 26 Apr 2006 17:04:20 +0200 Subject: Inherit from array In-Reply-To: References: <1146057315.721573.196140@u72g2000cwu.googlegroups.com> <444f79a8$0$5191$626a54ce@news.free.fr> Message-ID: <444f8c49$0$13219$626a54ce@news.free.fr> Philippe Martin wrote: > > bruno at modulix wrote: >>TG wrote: >> >>>Hi there. >>> >>>I'm trying to create a simple class called Vector which inherit from >>>array. >> >>Which array ? > > I think he did > > from array import * > > oops ! Sorry, I forgot this was in the standard lib (well, I never used this module, so....) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From steve at REMOVETHIScyber.com.au Sat Apr 1 05:40:54 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 01 Apr 2006 20:40:54 +1000 Subject: why doesn't is work?a script to backup a directory References: <1143859031.679813.94400@i40g2000cwc.googlegroups.com> Message-ID: On Fri, 31 Mar 2006 18:37:11 -0800, obeeker wrote: > """there is threee directories,one of these is used for the base > directory,decided by the user, default is d0""" [snip code] It doesn't work? Have you tried running it to see what it does? When you do, please post a description of what it does, including any exception tracebacks, and just as importantly, what you expect it to do. -- Steven. From tim.golden at viacom-outdoor.co.uk Thu Apr 6 06:11:17 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 6 Apr 2006 11:11:17 +0100 Subject: Using PythonWin32 to copy text to Windoze Clipboard for Unix-stylerandom .sig rotator? Message-ID: [dananrg at yahoo.com] | | I want to write a Python script that, when launched, will choose a | random .sig (from a list of about 30 cool ones I've devised), | and store | the .sig text in the Windows Clipboard, so I can then paste | it into any | Windows application. Very quick and untested answer. Look at the win32clipboard module. Something like this (very untested): import win32clipboard sig = "whatever you got from your file" win32clipboard.OpenClipboard () try: win32clipboard.SetClipboardText (sig) finally: win32clipboard.CloseClipboard () | This way, it'll work for Outlook e-mails, Yahoo, Gmail, etc. | | Also, could I use Python to programmatically set key combos to do | certain things? You want to look at the WM_HOTKEY message. There's an example here: http://timgolden.me.uk/python/win32_how_do_i/catch_system_wide_hotkeys.h tml HTH TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From nospam at hotmail.com Sun Apr 30 17:12:58 2006 From: nospam at hotmail.com (Digital) Date: Sun, 30 Apr 2006 22:12:58 +0100 Subject: WAP page, Python and creating a file on file system - Newbie Message-ID: HELP!! All I need to do is to create a file in a folder. I am running Abyss WEB server and Python. and googling many sites has taught me how to create a file in a folder. BUT. I need to do this from a WML file - This is proving difficult... I can setup an index.wml and a deck of cards. Each card points to a .py file. This file creates a file in the folder of my choice but always returns an error to the WAP browser. I have tried PRINTing WML content within the Python code and thought I had formed a WML output but still the WAP browser returns an error. It seems an awful lot of trouble to go to, load Python to create a file in a folder. Is there any way I can easily do this? Before people reply with how to do stuff in OOP. I have no knowledge of OOP and class instantiation etc etc. I really do need a noddy guide in what I am doing. Regards Dave From ryang at gol.com Mon Apr 24 19:40:17 2006 From: ryang at gol.com (Ryan Ginstrom) Date: Tue, 25 Apr 2006 08:40:17 +0900 Subject: Hooking things up in GUI application Message-ID: <006e01c667f8$71a002a0$030ba8c0@RYAN> Apropos recent threads about GUI editors, coming from a Win32/WTL C++ background, I actually like the idea of being able to (easily) create GUIs programmatically. But I still see a lot of the same tedium: hooking up events to handlers, and getting data into and out of dialogs. In C++, this is generally handled through code generation and/or macros, but IMO these are brittle and ugly. So my question: Is there a Pythonic way to make these tedious hookups easier? --- Regards, Ryan Ginstrom From webraviteja at gmail.com Sat Apr 22 00:48:46 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 21 Apr 2006 21:48:46 -0700 Subject: what has python added to programming languages? (lets be esoteric, shall we ; ) In-Reply-To: References: <1145663274.488586.5780@g10g2000cwb.googlegroups.com> Message-ID: <1145681326.510700.78760@i39g2000cwa.googlegroups.com> > Well, Java does have this great feature called "market-hype"... I ... concede. From steve at REMOVETHIScyber.com.au Sat Apr 8 07:45:11 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 08 Apr 2006 21:45:11 +1000 Subject: calculating system clock resolution References: <1144434899.840346.220780@z34g2000cwc.googlegroups.com> <1144452910.634097.117310@e56g2000cwe.googlegroups.com> <1144494980.132199.237290@i39g2000cwa.googlegroups.com> Message-ID: On Sat, 08 Apr 2006 04:16:20 -0700, jUrner wrote: > def calc_time_res(): > now = time.time > start = now() > x = start > while start == x: > x = now() > print x, start # <-- > print x - start > > print calc_time_res() >>> 1.50203704834e-05 > > Something is going wrong here. > If you look at the function ,time.time() returns time in microseconds > (most oses and so does mine). >From help(time.time): time() -> floating point number Return the current time in seconds since the Epoch. Fractions of a second may be present if the system clock provides them. Seconds, not microseconds. > So the calculation goes, lets say 1.23 - 1.24 How can the time *after* the while loop be less than the time *before* the while loop? > How can the result be something like 1.50203704834e-05 ? Have you looked at the output of time.time()? >>> time.time() 1144496209.3221531 Of course, Python only prints a certain number of digits; to see the full amount, use string formatting: >>> '%40.30f' % time.time() '1144496642.905987024307250976562500000000' This brings me to an even simpler method of getting the resolution of time.time(), without the overhead of a while loop: >>> abs(time.time() - time.time()) 1.0013580322265625e-05 which is approximately 0.01ms, just as you expected. -- Steven. From pmartin at snakecard.com Mon Apr 10 11:38:51 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Mon, 10 Apr 2006 10:38:51 -0500 Subject: python + access + odbc + linux Message-ID: Hi, I understand that access can be accessed through an ODBC driver under windows (instead of Jet). I am wondering if the same can be done under Linux. Regards, Philippe From grante at visi.com Sun Apr 30 14:44:39 2006 From: grante at visi.com (Grant Edwards) Date: Sun, 30 Apr 2006 18:44:39 -0000 Subject: basic python programing References: <1146376141.767029.17850@j73g2000cwa.googlegroups.com> Message-ID: <125a1cneqrb5qec@corp.supernews.com> On 2006-04-30, fxlogx at gmail.com wrote: > here we discuss the most basic concepts about python. Yes we do. As well as the most basic concepts about Usenet. -- Grant Edwards grante at visi.com From auch-ich-m at g-kein-spam.com Mon Apr 24 16:40:35 2006 From: auch-ich-m at g-kein-spam.com (=?UTF-8?B?QW5kcsOp?= Malo) Date: Mon, 24 Apr 2006 22:40:35 +0200 Subject: C API - tp_getattro and tp_methods References: <1145910179.468987.266850@u72g2000cwu.googlegroups.com> Message-ID: <2341353.ZoQ3i2GqUK@news.perlig.de> * williams.jasonscott at gmail.com wrote: > I'm using a tp_getattro function to call into a C library and get > values the the lib keeps track of. This works: [...] > Thats great but I also want to expose some instance methods and I'm > having trouble. > > But when I set tp_methods nothing shows up? If I unset tp_getattro I > can use my methods. I'm not understanding the relationship between the > two, tp_methods and tp_getattro. Could someone point me in the right > direction? tp_getattro is like defining __getattribute__, i.e. it gets called on every attribute read access. You can use PyObject_GenericGetAttr inside the function to find predefined attributes before applying your own rules. nd -- "Die Untergeschosse der Sempergalerie bleiben w?hrenddessen aus statistischen Gr?nden geflutet." -- Spiegel Online From matt at biggmatt.com Mon Apr 17 14:59:42 2006 From: matt at biggmatt.com (Biggmatt) Date: Mon, 17 Apr 2006 18:59:42 GMT Subject: piping question Message-ID: I have been working on a little frontend for newspost. It runs newspost just fine and gets it's output. The problem is that i want it to get the stdout as the program runs, not hold it all till it's finished. I've tried a few variations of popen , and others with no luck. Here is the subroutine that executes newspost: def on_BT_go_clicked(self,obj): self.notebook.set_current_page(3) newspost = "newspost -i " + self.newsserver.get_text() + " " newspost += "-z " + self.port.get_text() + " " if self.username.get_text() != "": newspost += "-u " + self.username.get_text() + " " if self.password.get_text() != "": newspost += "-p " + self.password.get_text() + " " newspost += "-f " + self.email.get_text() + " " newspost += "-n " + self.newsgroup.get_text() + " " newspost += "-s \"" + self.subject.get_text() + "\" " if self.include_file_x_of_y.get_active(): newspost += "-q " if self.yenc.get_active(): newspost += "-y " for row in self.listmodel: newspost += "\"" + row[0] + "\" " pipe = os.popen(newspost) while 1: output = pipe.read() if not(output): break textiter = self.textbuffer.get_end_iter() self.textbuffer.insert(textiter, output) pipe.close() From podi.ex at gmail.com Thu Apr 13 22:48:14 2006 From: podi.ex at gmail.com (Podi) Date: 13 Apr 2006 19:48:14 -0700 Subject: How to create a single executable console application? In-Reply-To: <1144689721.446219.300610@i39g2000cwa.googlegroups.com> References: <1144689721.446219.300610@i39g2000cwa.googlegroups.com> Message-ID: <1144982894.348912.166330@z34g2000cwc.googlegroups.com> Alright, pythoneers, here is what I have found from http://wiki.wxpython.org/index.cgi/CreatingStandaloneExecutables. This is much easier than the py2exe + nullsoft combo :) Cheers! The mcillian installer development is discontinued. mirror: http://davidf.sjsoft.com/mirrors/mcmillan-inc/installer_dnld.html Continued development(not tested yet): http://pyinstaller.hpcf.upr.edu/cgi-bin/trac.cgi This works on Win32. Unzip the Installer in a directory of your choice, and cd there. Configure the Installer by running: python Configure.py Python must be in your PATH for this to work, if it's not, type from the command prompt: PATH=%PATH%;c:\python23 where c:\python23 must be replaced with the root of your python installation. Then, assuming the source code is app.py (placed in c:\source): python Makespec.py --upx --onefile --noconsole c:\source\app.py python Build.py app\app.spec Replace 'app' everywhere above with your application name. You will end up with app\app.exe under the Installer dir.This is a one file .exe containing all the application. If you don't want a one-file build, suppress the option --onefile above. If you don't have upx installed (or don't want to use it), suppress the option --upx above. The option --noconsole is needed to produce a windows gui application, instead of a console one (so the command shell won't pop up when you run the application). From tjreedy at udel.edu Sat Apr 22 01:06:02 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 22 Apr 2006 01:06:02 -0400 Subject: lambda References: <1145642409.389741.39680@g10g2000cwb.googlegroups.com> Message-ID: wrote in message news:1145642409.389741.39680 at g10g2000cwb.googlegroups.com... > Hello, > > I need your help understanding lambda (and doing it a better way > without). > > f = lambda x : x*x There is no reason to ever write name=lambda... def f(x): return x*x is better because it attaches the name to the function for tracebacks. > # this is a list of functions > [f for y in range(1,5)] > > [f for y in range(1,5)][0](2) > # returns 4, as expected > > > # ok now I want a list like > # [x^2, 2*x^2, 3*x^2,...] Given: def makef(multiplier): def f(x): return multiplier*x*x return f > [f*y for y in range(5)] I believe [makef(y) for y in range(5)] will do what you want. The slightly abbreviated lambda form is never necessary, that I know of, and notoriously confusing when used in list comprehensions. So I advise don't. Terry Jan Reedy From johnjsal at NOSPAMgmail.com Sun Apr 30 23:19:52 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sun, 30 Apr 2006 23:19:52 -0400 Subject: ending a string with a backslash In-Reply-To: References: <445546c8$0$13341$c3e8da3@news.astraweb.com> Message-ID: <44557f3f$0$5357$c3e8da3@news.astraweb.com> Edward Elliott wrote: > John Salerno wrote: >> Obviously the single backslash at the end of 'path' will cause a >> problem, and escaping it with a backslash seems to fix this problem, but >> how does escaping work when I already have it as a raw string? > > see the first two items here: > http://www.ferg.org/projects/python_gotchas.html #2 was very helpful. But if I want to use forward slashes instead, can I just replace the backslashes with them, or must I use the os.path.normcase() function to do it? From deets at nospam.web.de Wed Apr 5 08:36:40 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 05 Apr 2006 14:36:40 +0200 Subject: [pyqt] How to copy the content of a QPopupMenu ? References: <1144237849.881072.220870@i40g2000cwc.googlegroups.com> Message-ID: <49hruqFoguidU1@uni-berlin.de> kobayashi at netcourrier.com wrote: > Dear all, > > For a particuliar case, I need to copy all the items of > an existing menu (including the separators and sub-menus) > in a new empty one ... Does someone knows how to do that ? > I've tried : > item = menu_orig.findItem(item_id) > menu_new.insertItem(item, item_id) > but it fails with : > TypeError: argument 1 of QMenuData.insertItem() has an invalid type >From the docs: """ QMenuItem * QMenuData::findItem ( int id ) const Returns the menu item with identifier id, or 0 if there is no item with this identifier. Note that QMenuItem is an internal class, and that you should not need to call this function. Use the higher level functions like text(), pixmap() and changeItem() to get and modify menu item attributes instead. See also indexOf(). """ Diez From larry.bates at websafe.com Thu Apr 20 19:51:57 2006 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 20 Apr 2006 18:51:57 -0500 Subject: Phython and graphing In-Reply-To: <1145573583.333670.300930@v46g2000cwv.googlegroups.com> References: <1145573583.333670.300930@v46g2000cwv.googlegroups.com> Message-ID: <44481E9D.9000508@websafe.com> mostro wrote: > Hello, > > Can someone lead me to an easy way to create a graph in Python. > > For example, I have a script running that creates a list of dates, > times and values. I would like to turn this into a graph. > > I can grep the info into a new file creating two columns (x,y) but the > issue is the graph. > > P.S. I'm a Python newbie so keep that in mind. > > Thanks in advance... > Another possibility would be ReportLab Graphics (www.reportlab.com). It can create bar charts, line graphs, etc. It is lesser known than its big brother ReportLab PDF generator, but works equally well. In addition, it works well if you want to put graphs into .PDF documents. -Larry Bates From cesugden at gmail.com Thu Apr 27 14:07:47 2006 From: cesugden at gmail.com (Chris) Date: 27 Apr 2006 11:07:47 -0700 Subject: Twisted and Tkinter In-Reply-To: References: <1146104350.843046.186230@v46g2000cwv.googlegroups.com> <1146151958.731021.177480@e56g2000cwe.googlegroups.com> Message-ID: <1146161267.955195.308200@g10g2000cwb.googlegroups.com> it now comes up with the error message Traceback (most recent call last): File "C:\Python24\lib\lib-tk\Tkinter.py", line 1345, in __call__ return self.func(*args) File "C:\Documents and Settings\chris\Desktop\Python\client.py", line 30, in sendMessage self.sendLine("Test") AttributeError: ChatFactory instance has no attribute 'sendLine' From no-spam at no-spam-no-spam.com Mon Apr 24 16:47:39 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Mon, 24 Apr 2006 22:47:39 +0200 Subject: threads and sys.exit() In-Reply-To: References: <1145897992.091952.326970@e56g2000cwe.googlegroups.com> <1145909825.231565.42250@j33g2000cwa.googlegroups.com> Message-ID: robert wrote: > killing hard (SIGKILL etc ) is low level. it should be OS-specific, as > Python should not make itself inconsistent (and os._exit() is that at mid-low level ; better not to say; no finalizations etc.) -robert From debl2NoSpam at verizon.net Sun Apr 30 17:45:03 2006 From: debl2NoSpam at verizon.net (David Lees) Date: Sun, 30 Apr 2006 21:45:03 GMT Subject: How to efficiently read binary files? Message-ID: I want to process large binary files (>2GB) in Python. I have played around with prototypes in pure Python and profiled the code. Most of the time seems to be spent converting back and forth to and from strings using the struct module. Is there a way to directly read into an array of integers in Python? TIA David Lees From first180 at gmail.com Mon Apr 10 14:27:52 2006 From: first180 at gmail.com (Jay) Date: 10 Apr 2006 11:27:52 -0700 Subject: Python Shell window Message-ID: <1144693672.676045.193680@i40g2000cwc.googlegroups.com> Is their any way of setting wear the Python Shell window appears on the screen when I run my program? I am testing a full screen program with no Window Frame on a comp with 2 monitors and I have to keep pressing the Key to bring the Shell to the front and then moving it manually to the other screen every time I restart the program. I would like it to just appear on the other screen from the start. Any ideas From siona at chiark.greenend.org.uk Wed Apr 19 10:35:19 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 19 Apr 2006 15:35:19 +0100 (BST) Subject: items in an array References: <1145455441.531332.295700@e56g2000cwe.googlegroups.com> Message-ID: shkelley at gmail.com wrote: >I can get list to be how I want it if I use the index value as follows: > > list = ("%s" + "," + "%s", ...) % (list_array[0], list_array[1], ... > >However, the list_array will never contain a constant number of items. >So my dilema is how to loop/iterate through list_array to create list >in the format I want. I think what you want is: list_string = ",".join(list_array) (Don't use the name "list" as it shadows the builtin "list".) -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From paul at boddie.org.uk Sun Apr 2 16:21:27 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 2 Apr 2006 13:21:27 -0700 Subject: DOM and HTML References: <1143988451.239828.75900@i39g2000cwa.googlegroups.com> <4OydnTJnfJp5gq3ZnZ2dnUVZ_vGdnZ2d@comcast.com> Message-ID: <1144009287.871687.17490@j33g2000cwa.googlegroups.com> Larry Bates wrote: > robert.differentone at gmail.com wrote: > > > > I am looking for any Python library which can help to get DOM > > tree from HTML. Is there any way to access HTML DOM, just like > > accessing it using javascript. [...] > Since the browser can't execute anything except Javascript, you Who said anything about the browser? Accessing a DOM "just like [...] javascript" can mean a number of things: using an API like the one JavaScript uses, for example, as well as actually accessing a DOM associated with a page in a browser. > can't get to/manipulate the DOM with anything but Javascript code. > There have been attempts at getting a browser that can execute > Python code, but I don't think they ever really got anywhere. Actually, this isn't strictly true either. Disregarding, perhaps unfairly, recent work on PyXPCOM to integrate Python more tightly with Mozilla, there are various packages which do access browser DOMs: if the questioner uses a KDE desktop and isn't averse to installing some packages, there's qtxmldom [1] which can access the DOM in Konqueror in association with the kpartplugins distribution [2]; otherwise, I believe there's a Python package for accessing Internet Explorer's DOM. And outside browsers, one can still use various packages already mentioned, in addition to libxml2dom [3] which provides support via libxml2 for reading HTML and XML, producing a DOM which resembles the standardised DOM typically available to JavaScript. It shouldn't be forgotten that PyXML also supports HTML parsing [4], either. Paul [1] http://www.boddie.org.uk/python/qtxmldom.html [2] http://www.boddie.org.uk/python/kpartplugins.html [3] http://www.boddie.org.uk/python/libxml2dom.html [4] http://www.boddie.org.uk/python/HTML.html From martin at v.loewis.de Wed Apr 26 13:10:48 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 26 Apr 2006 19:10:48 +0200 Subject: Can one query full name (or version) of selected packages at pypi? In-Reply-To: <1146000912.061888.264870@v46g2000cwv.googlegroups.com> References: <1145525161.975827.277860@u72g2000cwu.googlegroups.com> <444b268e$0$9543$9b622d9e@news.freenet.de> <1146000912.061888.264870@v46g2000cwv.googlegroups.com> Message-ID: <444FA998.3000000@v.loewis.de> Caleb Hattingh wrote: > How up-to-date does Debian keep its package list for python addons, > or are you running Unstable? I'm running unstable indeed. > My big problem, being in South Africa, is that I have to get any > distros on cover CDs or order from distro-resellers, and they never > have Testing or Unstable. Broadband hasn't exactly hit the local > market, although things might be looking up in a few years or so. That's indeed a problem, then. In this part of the world, an "always online" attitude is fairly common-place, ignoring that this does not apply to the whole world (yet). Regards, Martin From siona at chiark.greenend.org.uk Wed Apr 5 10:38:57 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 05 Apr 2006 15:38:57 +0100 (BST) Subject: using range() in for loops References: <443324dc$0$11257$c3e8da3@news.astraweb.com> <7x1wwc237g.fsf@ruckus.brouhaha.com> Message-ID: AndyL wrote: >Paul Rubin wrote: >> Normally you'd use range or xrange. range builds a complete list in >> memory so can be expensive if the number is large. xrange just counts >> up to that number. >so when range would be used instead of xrange. if xrange is more >efficient, why range was not reimplemented? If you actually want the list for some reason: $ python2.4 -mtimeit 'list(xrange(100))' 100000 loops, best of 3: 4.54 usec per loop $ python2.4 -mtimeit 'range(100)' 100000 loops, best of 3: 2.61 usec per loop -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From jmeile at hotmail.com Thu Apr 13 04:58:28 2006 From: jmeile at hotmail.com (Josef Meile) Date: Thu, 13 Apr 2006 10:58:28 +0200 Subject: how to install PYCURL 7.15.2 on windows 2003? In-Reply-To: <1144897073.908587.95180@e56g2000cwe.googlegroups.com> References: <1144897073.908587.95180@e56g2000cwe.googlegroups.com> Message-ID: <443E12B4.7040503@hotmail.com> > I download it from http://pycurl.sourceforge.net/ > and then extract it to D:\usr\pycurl-7.15.2 > then > D:\usr\pycurl-7.15.2>setup.py install --curl-dir=d:\usr\pycurl-7.15.2 > Using curl directory: d:\usr\pycurl-7.15.2 > Traceback (most recent call last): > File "D:\usr\pycurl-7.15.2\setup.py", line 197, in ? > assert os.path.isfile(o), o > AssertionError: d:\usr\pycurl-7.15.2\lib\libcurl.lib I would say you need to install libcurl first. "--curl-dir" isn't the directory where you want to install pycurl; it is the location of the curl library, which isn't implemented in python. You can find the binaries (or the sources) here: http://curl.haxx.se/dlwiz/ Regards Josef From ptmcg at austin.rr._bogus_.com Thu Apr 6 08:46:01 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Thu, 06 Apr 2006 12:46:01 GMT Subject: Simple string formatting question References: <4434DCEC.4080308@REMOVEMEcyber.com.au> Message-ID: "Fredrik Lundh" wrote in message news:mailman.4181.1144326919.27775.python-list at python.org... > Steven D'Aprano wrote: > > > Here is a (quick and dirty) reference implementation: > > > > def format(f, width=3): > > fs = '%%.%df' % width > > s = fs % f > > return s.rstrip('0').rstrip('.') > > > > Is there a way of getting the same result with just a > > single string format expression? > > not with % itself, but you can do it all in one line: > > def format(f, width=3): return ("%.*f" % (width, f)).rstrip(".0") > > > > > Ooops, don't combine the two calls to rstrip(). def format(f, width=3): return ("%.*f" % (width, f)).rstrip(".0") print format(3.140) print format(3.000) print format(3.0000001) print format(30.0000) print format(300000.000) Gives: 3.14 3 3 3 3 But this works fine: def format(f, width=3): return ("%.*f" % (width, f)).rstrip("0").rstrip(".") -- Paul From dadapapa at googlemail.com Thu Apr 27 13:23:27 2006 From: dadapapa at googlemail.com (harold) Date: 27 Apr 2006 10:23:27 -0700 Subject: how do I make a class global? In-Reply-To: References: Message-ID: <1146158607.221810.98350@g10g2000cwb.googlegroups.com> basically, you can create new types on the fly using type() with three arguments: my_class = type("className",(BaseClass,),class_dict) then, you can assign this vlass to the golbal namespace using globals(): globals()["className"] = my_class In your case, you would need to populate the class_dict by a function object that you parameterize to your needs, e.g. def create_class(name,params) : def cls_init(self) : BaseClass.__init__(self) self.params = params cls_dict = { "__init__" : cls_init } new_cls = type(name,(BaseClass,),cls_dict) globals()[name] = new_cls the result would be like this: >>> create_class("test_class",42) >>> instance = test_class() >>> print instance.params 42 From onurb at xiludom.gro Tue Apr 25 07:55:47 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 25 Apr 2006 13:55:47 +0200 Subject: OOP / language design question In-Reply-To: <1145961248.794496.80220@j33g2000cwa.googlegroups.com> References: <1145961248.794496.80220@j33g2000cwa.googlegroups.com> Message-ID: <444e0e97$0$2052$626a54ce@news.free.fr> cctv.star at gmail.com wrote: > I was wondering, why you always have to remember to call bases' > constructors s/constructors/__init__/ the __init__() method is *not* the constructor. Object's instanciation is a two-stage process: __new__() is called first, then __init__(). -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From adam2new at yahoo.com Fri Apr 21 15:58:45 2006 From: adam2new at yahoo.com (Anony) Date: 21 Apr 2006 12:58:45 -0700 Subject: Tkinter hiding/showing widgets Message-ID: <1145649525.027965.148840@t31g2000cwb.googlegroups.com> Is it possible to hide and show widgets while the window is open? From Serge.Orlov at gmail.com Wed Apr 12 03:33:29 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 12 Apr 2006 00:33:29 -0700 Subject: list.clear() missing?!? In-Reply-To: References: <1144767680.583085.310160@v46g2000cwv.googlegroups.com> <443BE426.20501@v.loewis.de> Message-ID: <1144827208.841644.148130@v46g2000cwv.googlegroups.com> Felipe Almeida Lessa wrote: > Em Qua, 2006-04-12 ?s 11:36 +1000, Steven D'Aprano escreveu: > > On Tue, 11 Apr 2006 19:15:18 +0200, Martin v. L?wis wrote: > > > > > Felipe Almeida Lessa wrote: > > >> I love benchmarks, so as I was testing the options, I saw something very > > >> strange: > > >> > > >> $ python2.4 -mtimeit 'x = range(100000); ' > > >> 100 loops, best of 3: 6.7 msec per loop > > >> $ python2.4 -mtimeit 'x = range(100000); del x[:]' > > >> 100 loops, best of 3: 6.35 msec per loop > > >> $ python2.4 -mtimeit 'x = range(100000); x[:] = []' > > >> 100 loops, best of 3: 6.36 msec per loop > > >> $ python2.4 -mtimeit 'x = range(100000); del x' > > >> 100 loops, best of 3: 6.46 msec per loop > > >> > > >> Why the first benchmark is the slowest? I don't get it... could someone > > >> test this, too? > > > > > > In the first benchmark, you need space for two lists: the old one and > > > the new one; > > > > Er, what new list? I see only one list, x = range(100000), which is merely > > created then nothing done to it. Have I missed something? > > He's talking about the garbage collector. To be exact the reason for two array is timeit.py. It doesn't place the code to time into a separate namespace but injects it into a for loop, so the actual code timed is: for _i in _it: x = range(100000) and that makes two arrays with 100.000 items exist for a short time starting from second iteration. From onurb at xiludom.gro Thu Apr 27 10:50:36 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 27 Apr 2006 16:50:36 +0200 Subject: Editing a function in-memory and in-place In-Reply-To: References: <1146115733.082702.106380@t31g2000cwb.googlegroups.com> Message-ID: <4450da92$0$468$626a54ce@news.free.fr> Peter Otten wrote: (snip) > > Can you cheat and just assign another known good func_code object? >>>>def hello(): print "hello" > ... >>>>def world(): print "world" > ... >>>>def use_it(hello=hello, world=world): > ... hello() > ... world() > ... >>>>use_it() > hello > world >>>>world.func_code = hello.func_code >>>>use_it() > hello > hello >>>>hello, world > (, ) +1 H2OTW !-) (NB : H2 -> Horrible Hack) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From fabiofz at gmail.com Mon Apr 24 20:59:47 2006 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Mon, 24 Apr 2006 21:59:47 -0300 Subject: Coming from delphi - looking for an IDE - willing to spend money In-Reply-To: <1145925252.766752.86640@e56g2000cwe.googlegroups.com> References: <1145925252.766752.86640@e56g2000cwe.googlegroups.com> Message-ID: Hi James, Take a look at: http://wiki.python.org/moin/IntegratedDevelopmentEnvironments Cheers, Fabio p.s. I'd reccomend Pydev + Pydev Extensions -- Has debugger, code-analysis, refactoring, code-completion, and all the other niceties you'd expect from an IDE. On 24 Apr 2006 17:34:12 -0700, Just call me James wrote: > > Hi, > > Coming away from the luxury of the delphi IDE has been something of a > shock. > > As a consequence I've become aware that maybe I need to spend some > money on a python IDE. > > As a beginner I reckon integrated debugging would be helpful. > > Does anyone have any advice or suggestions? So far I've glanced at > Komodo, but as a beginner I'm not in a positon to evaluate it. > > thanks for exprienced advice, > > Greg > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From paddy3118 at netscape.net Sun Apr 2 10:37:17 2006 From: paddy3118 at netscape.net (Paddy) Date: 2 Apr 2006 07:37:17 -0700 Subject: DO NOT USE JAVA BECAUSE IT IS NOT OPEN SOURCE In-Reply-To: References: <1143867556.814290.321740@i40g2000cwc.googlegroups.com> Message-ID: <1143988637.442322.208690@i40g2000cwc.googlegroups.com> LoL :-) From johnjsal at NOSPAMgmail.com Wed Apr 5 17:01:26 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 05 Apr 2006 21:01:26 GMT Subject: Filters like old skool Jive, Fudd, Valspeak... Text transformation in Python In-Reply-To: References: <1144237161.700762.75630@e56g2000cwe.googlegroups.com> <4433b3f1$0$24162$636a55ce@news.free.fr> <1144269888.887561.247620@v46g2000cwv.googlegroups.com> Message-ID: Dave Hansen wrote: > Don't forget the famous American philosopher who contemplated the > meaning of is. Unfortunately, until he gives us a definition, we'll never really know who he is... :) From aleaxit at yahoo.com Sun Apr 16 02:09:14 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 15 Apr 2006 23:09:14 -0700 Subject: Help for a complete newbie References: <7xY%f.1245$kz3.903@twister.nyroc.rr.com> <1145107031.283066.172300@j33g2000cwa.googlegroups.com> Message-ID: <1hdudf8.v3lfqo1onqxldN%aleaxit@yahoo.com> Steve Bergman wrote: ... > Both are a bit out of date. The current python version is 2.4. > Learning Python covers 2.3. Nutshell covers up to 2.2. > > One of these days Alex will come out with a 2nd Edition of Nutshell and > there will be much rejoicing. ;-) If everything goes according to plan, the Nutshell's 2nd Edition should be out at OSCON (O'Reilly's Open Source Convention, end of July in Portland, OR -- check it out, it's really a good conference!). The book's text is about ready to get into O'Reilly's production queue (and they take about 3 months to get to paper, so we should make it), save for a few technical issues with cross-chapter cross-references, and we're working on those; so it's basically out of my hands, save for various intermediate-checking stages. "Python in a Nutshell", 2nd edition, focuses on Python 2.4, but I've managed to just about cover the forthcoming 2.5 as well (currently out in alpha-1 stage) -- no doubt some 2.5 details in the book will prove incorrect (particularly if there are any changes between alpha1 and the final version), and for some crucial new libraries due for inclusion in 2.5 (such as ElementTree and ctypes) I've just barely managed a "mention" rather than real "coverage"; nevertheless, I do hope the amount of 2.5 coverage I've been able to add will be useful to future readers (and save me from doing a 3rd edition any time soon;-). Alex From phddas at yahoo.com Tue Apr 25 19:09:55 2006 From: phddas at yahoo.com (Gary Wessle) Date: 26 Apr 2006 09:09:55 +1000 Subject: help finding Message-ID: <87y7xt5k1o.fsf@localhost.localdomain> Hi I am going through some tutorials, how do I find out about running a script from the python prompt? is there a online ref and how to access it? thank you From kadeko at gmail.com Tue Apr 11 07:59:34 2006 From: kadeko at gmail.com (looping) Date: 11 Apr 2006 04:59:34 -0700 Subject: Why new Python 2.5 feature "class C()" return old-style class ? References: <1144752553.305591.88050@j33g2000cwa.googlegroups.com> Message-ID: <1144756774.177225.311120@z34g2000cwc.googlegroups.com> Peter Hansen wrote: > Georg Brandl wrote: > > class C(): > > > > is meant to be synonymous with > > > > class C: > > > > and therefore cannot create a new-style class. > > I think "looping" understands that, but is basically asking why anyone > is bothering with a change that involves a part of the language that is > effectively deprecated. In other words, class(): never used to be > valid, so why make it valid now? > > -Peter Exact. But I think that if we make "class C():" a synonym of "class C(object):", it will save lot of keystrokes ;-) So I think the idea is great but the result is not actually very usefull. Delphi (Pascal?) use almost the same concept: TTest = class is a synonym of TTest = class(TObject) From gh at ghaering.de Sat Apr 29 08:40:55 2006 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sat, 29 Apr 2006 14:40:55 +0200 Subject: Recommendations for a PostgreSQL db adapter, please? In-Reply-To: References: Message-ID: <44535ED7.4010007@ghaering.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Keen Anthony wrote: > Hello, > > I am currently using psycopg 2 as my db adapter for a mod_python & > PostgreSQL web app. It's works fine, and I haven't any complaints. I > would appreciate some input on what other pythonistas like in an > adapter. There were several different options available to me, but there > was no particular informed reason for me to choose psycopg. Am I missing > anything? Considering pyPgSQL, psycopg1, PyGreSQL and psycopg2 - psycopg2 is a good choice. There's also interesting development happening here: http://python.projects.postgresql.org/ - but it seems to be in the midst of development. - -- Gerhard -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.1 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFEU17XdIO4ozGCH14RAsQyAKCS5opydZzciB8bCDbKqDWTLWeRHgCgmLpQ e40YgQmGCJfApvBNSVYX5kk= =L1El -----END PGP SIGNATURE----- From timothy.williams at nvl.army.mil Tue Apr 11 14:47:12 2006 From: timothy.williams at nvl.army.mil (timw.google) Date: 11 Apr 2006 11:47:12 -0700 Subject: installing pyodbc Message-ID: <1144781232.762308.177500@z34g2000cwc.googlegroups.com> I just downloaded the pyodbc source to try and install on my Linux FC3 box. I see that there is a setup.py file, but when I try to do a 'python setup.py build' (or just 'python setup.py') I get Traceback (most recent call last): File "setup.py", line 27, in ? revision = latest_revision('.') File "setup.py", line 25, in latest_revision return int(output) ValueError: invalid literal for int(): exported The README.txt doesn't really say anything about how to install, exept that the easiest way is to use the Windows installer. That's fine for Windows, but what about Linux? Thanks for any help. From sjmachin at lexicon.net Wed Apr 19 19:55:24 2006 From: sjmachin at lexicon.net (John Machin) Date: Thu, 20 Apr 2006 09:55:24 +1000 Subject: accessing a classes code In-Reply-To: <1145480053.936364.187470@e56g2000cwe.googlegroups.com> References: <444666af$0$12280$626a54ce@news.free.fr> <4446788a$0$31457$626a54ce@news.free.fr> <1145480053.936364.187470@e56g2000cwe.googlegroups.com> Message-ID: <4446ce05@news.eftel.com> On 20/04/2006 6:54 AM, bruno de chez modulix en face wrote: >> It turns out that what I want to do can be done using the inspect >> module which has methods for getsourcecode among other things. > > I never said that what you wanted to do was impossible (nor even > difficult, and FWIW, there are simpler alternatives than using inspect > - using a templating system like empy comes to mind...). I only suggest > that there are possibly far better solutions, that you seem to dismiss > for some unknown reason... > I'm with bruno -- IMHO, the OP's "solution" seems Byzantine, bizarre, ... Suggestion: the initial investigator gadget writes out the discovered parameters into a case-specific config file, whose name is later passed as an arg to the [only one] class's __init__ method() From diffuser78 at gmail.com Thu Apr 6 09:02:32 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 6 Apr 2006 06:02:32 -0700 Subject: GUI issues in Python Message-ID: <1144328552.221998.230480@g10g2000cwb.googlegroups.com> Hi, I want to create a GUI where a user can select drag and drop kind of boxes, circles and make connections between them. This is basically for depicting states and dependencies. I am writing a program where I let the user input states and dependencies in a certain domain. Based on input given by user in the GUI, I grab it and run my algorithm to generate the output. I am wondering if there is any library like that in Python, or if anybody of you has done something similar in past, could you post some pointers. thanks From fredrik at pythonware.com Wed Apr 5 16:24:24 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 5 Apr 2006 22:24:24 +0200 Subject: efficiency of range() and xrange() in for loops References: Message-ID: Steve R. Hastings wrote: > If Python actually allocates the list, then clearly we should all use > "for i in xrange". clearly we should all? speak for yourself. the difference isn't very large, xrange is actually slower in some python versions, and you'll need the integer objects sooner or later anyway... > If Python doesn't currently optimize this case, is there any chance this > optimization could be added? in Python 2.X, range is defined to return a list. if you start returning something else, you'll break stuff. From __peter__ at web.de Fri Apr 7 03:17:12 2006 From: __peter__ at web.de (Peter Otten) Date: Fri, 07 Apr 2006 09:17:12 +0200 Subject: Difference in Python and Ruby interactive shells References: <1144159204.450444.297870@t31g2000cwb.googlegroups.com> <1144164876.820737.229810@i40g2000cwc.googlegroups.com> <1hd9i36.lujm07nwr9r1N%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Michele Simionato wrote: > >> You want this recipe from Michael Hudson: >> >> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/160164 >> >> "automatically upgrade class instances on reload()" > > Note that the version in the printed Cookbook (2nd edition) was > substantially enhanced (mostly by me and Michael working together), I > don't know if Michael updated his ASPN recipe to reflect that but at any > rate you can download all the code from the printed Cookbook as a > zipfile from O'Reilly's site (sorry, I don't recall the URL). http://examples.oreilly.com/pythoncook2/cb2_examples.zip The files are named cb2_6_21_*.py, but the book has the recipe in chapter 20.15. Peter From nospam at jollans.com Thu Apr 6 12:29:57 2006 From: nospam at jollans.com (Thomas Jollans) Date: Thu, 06 Apr 2006 18:29:57 +0200 Subject: GUI issues in Python References: <1144328552.221998.230480@g10g2000cwb.googlegroups.com> <49kjiaFopo00U1@uni-berlin.de> <1144331796.505663.289910@e56g2000cwe.googlegroups.com> Message-ID: diffuser78 at gmail.com wrote: > My question basically revolves around... that I dont want to draw > circles and boxes for drawing purposes. > > I want the end user to be able to draw the GUI boxes and circles and > makes connection to depict states and dependencies. So its a little > unconventional and more like a SIMULATION TOOL. > > I am pretty sure Python must have something like this. Any idea how to > go about it. a tkinter canvas can be hooked up via events with your simulation algorithm easily. So, user clicks some point -> the program/simulation gets the coordinates and action -> does something -> draws something -> ... -- Thomas Jollans - http://jollybox.de/ GNU/Linux - freedom, functionality, power - what more do you want ? When in doubt, follow the penguins. From spamspam at spam.eggs Thu Apr 27 04:03:42 2006 From: spamspam at spam.eggs (Ben C) Date: 27 Apr 2006 08:03:42 GMT Subject: Events in Python? References: <1146065995.016939.187440@i40g2000cwc.googlegroups.com> <1146071232.275024.5310@e56g2000cwe.googlegroups.com> Message-ID: On 2006-04-26, nikie wrote: > redefined.horizons at gmail.com wrote: > >> Here is another non-pythonic question from the Java Developer. (I beg >> for forgiveness...) >> >> Does Python have a mechanism for events/event-driven programming? >> >> I'm not necessarily talking about just GUIs either, I'm interested in >> using events for other parts of an application as well. >> >> If there isn't some sort of event mechanism built into Python, where >> might I find some information about implementing one? > > Maybe I got your question wrong, but why not simply use something like: > > class Sender: > def __init__(self, event): > self.event = event > > def raiseEvent(self): > self.event("Event") > > class Receiver: > def receiveEvent(self, msg): > print "Received %r" % msg > > r = Receiver() > s = Sender(r.receiveEvent) > s.raiseEvent() > > You can pass around functions and bound methods, I always found that's > often a really good substitute for full-blown event mechanisms. Actually I'd say full-blown event mechanisms are a poor substitute for passing around bound-methods :) From b83503104 at yahoo.com Tue Apr 18 20:25:53 2006 From: b83503104 at yahoo.com (b83503104 at yahoo.com) Date: 18 Apr 2006 17:25:53 -0700 Subject: extracting a substring Message-ID: <1145406353.280681.134630@t31g2000cwb.googlegroups.com> Hi, I have a bunch of strings like a53bc_531.txt a53bc_2285.txt ... a53bc_359.txt and I want to extract the numbers 531, 2285, ...,359. One thing for sure is that these numbers are the ONLY part that is changing; all the other characters are always fixed. I know I should use regular expressions, but I'm not familar with python, so any quick help would help, such as which commands or idioms to use. Thanks a lot! From pmartin at snakecard.com Fri Apr 14 12:08:34 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Fri, 14 Apr 2006 11:08:34 -0500 Subject: Passing a packed C structure to a c module Message-ID: <3OP%f.811$9c6.333@dukeread11> Hi, Is it possible to define a packed C structure in python and pass it to the c module, or should the wrapper do that ? Regards, Philippe From fredrik at pythonware.com Thu Apr 6 01:32:03 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 6 Apr 2006 07:32:03 +0200 Subject: efficiency of range() and xrange() in for loops References: Message-ID: Steve R. Hastings wrote: > > the difference isn't very > > large, xrange is actually slower in some python versions, and you'll > > need the integer objects sooner or later anyway... > > Actually, for many uses of "for i in (range|xrange)", you only need the > value of i, and you aren't doing anything with the integer object. so you're saying that the value of i isn't an integer object? if you don't need the index value at all, itertools.repeat is sometimes faster than xrange. > for i in range(10**6): > pass > > and produced code equivalent to this: > > for i in iter(range(10**6)) > pass > > How would this break stuff? how would that speed anything up? From godoy at ieee.org Tue Apr 25 16:17:18 2006 From: godoy at ieee.org (Jorge Godoy) Date: Tue, 25 Apr 2006 17:17:18 -0300 Subject: Plotting package? References: Message-ID: <1755548.v3dIpK3sT5@jupiter.g2ctech> Andrew Koenig wrote: > This may be a foolish question, but what's the most straightforward way to > plot a bunch of data in Python? > > That is, I want to write a program that does some number crunching, and > then I want to change some parameters and watch how the changes affect the > results. I could produce a file to hand to gnuplot, but that's a bit of a > pain; so I'm wondering if there is a widely used package to which I can > give my x-y pairs and have it produce a graph for me with axes, scaling, > etc. I liked the output of PyChart. It is pretty easy to use. Also, I don't know what you're doing with numbers, but there's rpy to use with R. -- Jorge Godoy "Quidquid latine dictum sit, altum sonatur." - Qualquer coisa dita em latim soa profundo. - Anything said in Latin sounds smart. From jparlar at cogeco.ca Thu Apr 20 19:38:33 2006 From: jparlar at cogeco.ca (Jay Parlar) Date: Thu, 20 Apr 2006 16:38:33 -0700 Subject: Mouse control in OS X In-Reply-To: <1145564524.970753.319470@j33g2000cwa.googlegroups.com> References: <1145389728.419328.109680@i40g2000cwc.googlegroups.com> <1145564524.970753.319470@j33g2000cwa.googlegroups.com> Message-ID: <7f80621a416e71a8a5c4b53c274b9127@cogeco.ca> On Apr 20, 2006, at 1:22 PM, Mateo wrote: > I've played around with pygame, and it seems to have much of what I > need. Still, is there any way to initiate a mouse click from Python? > > Thanks. > In OS X, you'll probably need PyObjC. I've never had a chance to try it myself, but if any package is going to let you control things like native mouse clicks (outside of a custom GUI environment like PyGame, wx, gtk, QT, etc.), it will probably be PyObjC. Jay P. From neurogasm at gmail.com Tue Apr 18 20:34:07 2006 From: neurogasm at gmail.com (Kun) Date: Tue, 18 Apr 2006 20:34:07 -0400 Subject: scanning for numerals / letters Message-ID: I have the following if statement that checks if a form is empty: if form.has_key("date") and form["date"].value != "": date=form['date'].value else: print "ERROR: No date entered!" raise Exception I would also like to add another if statement checking if 'date' has any letters (a-z) in it, and if so, would like to say that "you have to enter a date with numbers". I am not sure how to alter my current if statement to do that check so any assistance would be appreciated. On the flip side, I also have a field called 'purchases' where the user must enter non-numerals, thus i would also like to know how to scan to see if their entry has numerals and print 'please do not use numbers' if they did. Thanks for your help. From deets at nospam.web.de Sun Apr 30 14:06:49 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 30 Apr 2006 20:06:49 +0200 Subject: setting file permissions on a web server In-Reply-To: <4454f1e1$0$1963$c3e8da3@news.astraweb.com> References: <445449f6$0$9437$c3e8da3@news.astraweb.com> <4454f1e1$0$1963$c3e8da3@news.astraweb.com> Message-ID: <4bkclpF11jcm6U1@uni-berlin.de> > I suppose I could write a script that would set the permissions of all > the files in a particular folder on my computer to 755, but is there a > Windows equivalent command for chmod to do this? Or am I stuck having to > do it on the server side? The chmod has to be executed on the machine the file resides on - aka the server. If your plan includes a ssh-account you can use that. Otherwise you might be able to create an ftplib-based script that will automate this over ftp. Diez From duncan.booth at invalid.invalid Tue Apr 11 10:12:20 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 11 Apr 2006 14:12:20 GMT Subject: RIIA in Python 2.5 alpha: "with... as" References: Message-ID: Alexander Myodov wrote: > Or maybe you have an idea how this can be fixed? The > simplest way I see is putting all the "controlled" variables into a > dedicated class... and do that each time for each block of variables I > need control lifetime. Is there any simpler way? I wouldn't use the word "fixed", but I suppose if you must you could do something like: >>> import contextlib >>> @contextlib.contextmanager def controlled(**kw): class Bunch: pass obj = Bunch() obj.__dict__.update(kw) yield obj obj.__dict__ = {} >>> with controlled(a=5, b=[1, 2, 3]) as k: print k.a, k.b, dir(k) 5 [1, 2, 3] ['__doc__', '__module__', 'a', 'b'] >>> print dir(k) ['__doc__', '__module__'] So the lifetime of the variable is still not limited, but the lifetime of its attributes is. I still don't see what that buys you though. From rogerb at rogerbinns.com Tue Apr 4 01:00:11 2006 From: rogerb at rogerbinns.com (Roger Binns) Date: Mon, 3 Apr 2006 22:00:11 -0700 Subject: Convertion of Unicode to ASCII NIGHTMARE References: <1144079830.734516.8390@z34g2000cwc.googlegroups.com> <1144081137.137744.253790@i39g2000cwa.googlegroups.com> Message-ID: <34b9g3-ku8.ln1@home.rogerbinns.com> "Paul Boddie" wrote in message news:1144081137.137744.253790 at i39g2000cwa.googlegroups.com... > It looks like you may have Unicode objects that you're presenting to > sqlite. In any case, with earlier versions of pysqlite that I've used, > you need to connect with a special unicode_results parameter, He is using apsw. apsw correctly handles unicode. In fact it won't accept a str with bytes >127 as they will be an unknown encoding and SQLite only uses Unicode internally. It does have a blob type using buffer for situations where binary data needs to be stored. pysqlite's mishandling of Unicode is one of the things that drove me to writing apsw in the first place. Roger From tim.hochberg at ieee.org Tue Apr 18 01:03:45 2006 From: tim.hochberg at ieee.org (Tim Hochberg) Date: Mon, 17 Apr 2006 22:03:45 -0700 Subject: PEP 359: The "make" Statement In-Reply-To: <1145334078.388898.301110@g10g2000cwb.googlegroups.com> References: <1145318176.952461.203240@i39g2000cwa.googlegroups.com> <1145327067.281826.250030@j33g2000cwa.googlegroups.com> <1145334078.388898.301110@g10g2000cwb.googlegroups.com> Message-ID: <44447331.3070004@ieee.org> Carl Banks wrote: > Tim Hochberg wrote: > >>Carl Banks wrote: >> >>>Mike Orr wrote: >>> >>> >>>>>I think this PEP is going off the rails. It's primary virtue was that it >>>> >>>>was a simpler, clearer way to write: >>>> >>>> class Foo(args): >>>> __metaclass__ = some_metaclass >>>> #... >>>> >>>>And it doesn't even do that. What's wrong with "class Foo: >>>>__metaclass__ = blah"? Two lines of code, and the double underscores >>>>indicate something special is happening. >>> >>> >>>I think you're missing the point somewhat. The real point isn't to >>>make using metaclasses easier; it's to let the useful semantics of the >>>class statement be used for things that aren't classes. >> >>I can see how you might get the impression from the above paragraph, but >>you'd be wrong. > > > ??? > >>From the above post, I got the impression that it was Mike Orr that > wrote it, not you. If you and he are really the same person, you must > admit I would have no reasonable way to get any other impression. :) > > No really, are you sure I was replying to what you think I was replying > to? I totally agree with you about the XML thing; it'd be a terrible > misuse of the make statement. But the post I responded to had nothing > to do with that. My bad. I had a stack overflow or something when reading the nesting of the post and missed who was replying to what. Sorry, -tim From bdesth.quelquechose at free.quelquepart.fr Tue Apr 25 20:04:40 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 26 Apr 2006 02:04:40 +0200 Subject: Zope 3 In-Reply-To: References: <1145965796.432891.274310@i39g2000cwa.googlegroups.com> <444e3cf6$0$401$626a54ce@news.free.fr> Message-ID: <444e8a9e$0$1106$626a54ce@news.free.fr> Steve Juranich a ?crit : > bruno at modulix wrote: > > >>Actually, the OP was asking about Zope3, which is a *very* different >>beast. > > > Okay, so my ignorance is showing (/me pauses to stuff it back where it > belongs). So is there some big master diff, along the lines of "What's new > in Python X.X" that I could look at to get an idea of what z3 has that 2.9 > (which I'm currently still cutting my teeth on) doesn't? This is not an incremental change, it's a complete redesign and rewrite and a different architecture. Almost nothing of what you learn with Zope 2.x will hold with Zope3. > I've looked at > the documentation on the main Zope page (zope.org) and all of the documents > I've seen are apparently geared towards Zope 2.X. Where are the Zope3 > docs? You can start here: http://www.zope.org/DevHome/Wikis/DevSite/Projects/ComponentArchitecture/FrontPage HTH From felipe.lessa at gmail.com Sun Apr 2 13:55:30 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Sun, 02 Apr 2006 14:55:30 -0300 Subject: print() in Python 3000 return value? In-Reply-To: <1143999680.091690.253340@g10g2000cwb.googlegroups.com> References: <1143997643.857261.186430@i40g2000cwc.googlegroups.com> <44300797$0$28451$9b622d9e@news.freenet.de> <1143999680.091690.253340@g10g2000cwb.googlegroups.com> Message-ID: <1144000530.9449.0.camel@kenshin.CASA> Em Dom, 2006-04-02 ?s 10:41 -0700, James Thiele escreveu: > Martin chimedin: > > James Thiele wrote: > > > I noticed in PEP 3000 that print will become a function. The PEP > > > references a thread where Guido explains this decision. The thread does > > > not specify what the function will return. Has this been decided? > > > > My intuition is that it should be a procedure (i.e. returning None). > > What do you want it to return? > > > > Regards, > > Martin > > The string that was printed. It could be useful inside expessions: > > message = "I don't need to see all of this:%s" % print(s) Or maybe: for i in sequence: mylist.append(print(i)) -- Felipe. From aahz at pythoncraft.com Tue Apr 11 17:46:09 2006 From: aahz at pythoncraft.com (Aahz) Date: 11 Apr 2006 14:46:09 -0700 Subject: Why new Python 2.5 feature "class C()" return old-style class ? References: <1144752553.305591.88050@j33g2000cwa.googlegroups.com> <443bbdbe$0$15517$626a54ce@news.free.fr> <443c22d1$0$11341$636a55ce@news.free.fr> Message-ID: In article <443c22d1$0$11341$636a55ce at news.free.fr>, Bruno Desthuilliers wrote: >Aahz a ?crit : >> In article <443bbdbe$0$15517$626a54ce at news.free.fr>, >> bruno at modulix wrote: >>> >>>Please repeat this 101 times each morning: >>>"thou shall not use old-style classes for they are deprecated". >> >> Classic classes are *NOT* deprecated. > >Perhaps not *officially* yet... Not even unofficially. The point at which we have deprecation is when PEP8 gets changed to say that new-style classes are required for contributions. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "LL YR VWL R BLNG T S" From ldo at geek-central.gen.new_zealand Sat Apr 22 18:24:42 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 23 Apr 2006 10:24:42 +1200 Subject: Can you create an instance of a subclass with an existing instance of the base class? References: <1145650105.664762.321560@j33g2000cwa.googlegroups.com> <1145736124.831082.34550@v46g2000cwv.googlegroups.com> Message-ID: In article <1145736124.831082.34550 at v46g2000cwv.googlegroups.com>, "Sandra-24" wrote: >Now that is a clever little trick. I never would have guessed you can >assign to __class__, Python always surprises me in it's sheer >flexibility. That's because you're still thinking in OO terms. From srijit at yahoo.com Mon Apr 24 02:47:03 2006 From: srijit at yahoo.com (Srijit Kumar Bhadra) Date: 23 Apr 2006 23:47:03 -0700 Subject: MinGW and Python Message-ID: <1145861223.509630.247350@y43g2000cwc.googlegroups.com> Is there any specific reason for not using MinGW to build the official distribution of Python for Win32? A quick Google search did not reveal the answer to my question. If a link is available, please post it. Best Regards, Srijit From deets at nospam.web.de Thu Apr 6 06:47:25 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 06 Apr 2006 12:47:25 +0200 Subject: Cleaning the current environment after a fork References: Message-ID: <49k9u6Fp6as8U1@uni-berlin.de> > I want to fork a process, but my scope has lots of stuff that the child > won't need. Is it possible to clean the current environment of cruft so it > is collected and freed? Basically I want it to go something like this. > This is my first forking Python app, by the way: I'm not an expert of this - but if all the reason you want to do this are memory concerns, AFAIK forking will only make a copy of those memory-pages that are actually written to by the forked process - for efficiency reasons. And even if that wasn't the case: I think as long as you don't run into memory-troubles, don't do it. Its complex, flaky and thus an unnecessary source of failure. Diez From malvert at telenet.be Tue Apr 4 11:52:55 2006 From: malvert at telenet.be (malv) Date: 4 Apr 2006 08:52:55 -0700 Subject: Difference in Python and Ruby interactive shells References: <1144159204.450444.297870@t31g2000cwb.googlegroups.com> Message-ID: <1144165975.142564.25850@j33g2000cwa.googlegroups.com> I think reload should be preceded by import. Example: Online code modification: upon modifying and saving mytest.py issue on the interactive shell: >>>import mytest >>>reload(mytest) The shell should respond with "" (NOT:mytest.pyc) Note that modules importing mytest should not use 'import * from mytest' but 'import mytest'; This requires qualifying all objects as mytest.obj From grflanagan at yahoo.co.uk Wed Apr 12 03:53:12 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 12 Apr 2006 00:53:12 -0700 Subject: turning python-cgi into an html output In-Reply-To: References: Message-ID: <1144828392.601061.157470@i40g2000cwc.googlegroups.com> Kun wrote: > i have a python cgi script that displays tables from a mysql database in > html. > > the problem is, i want to use excel's web query to pull this data and > the web query doesn't read .py files. > > thus i am wondering what is the easiest way to just turn my .py html > output into a .html output. > Have you tried using GET instead of POST in your form? Gerard From reply.in.the.newsgroup at my.address.is.invalid Sat Apr 22 12:34:03 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Sat, 22 Apr 2006 18:34:03 +0200 Subject: problems when unpacking tuple ... References: <1145722900.647531.272680@i39g2000cwa.googlegroups.com> Message-ID: harold: >The output (when given the data I want to parse) is: If you'd told us that data, and told us what version of Python you're using, we could have reproduced the problem to look into it. >ValueError: need more than 3 values to unpack > >Why does python think that I want to unpack the outcome of >line.split() into three values instead of four? That's not what it says. It says there are only 3 values in the outcome, and it needs more (4 to be precise). -- Ren? Pijlman From finite.automaton at gmail.com Fri Apr 7 02:23:14 2006 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 6 Apr 2006 23:23:14 -0700 Subject: how to make a generator use the last yielded value when it regains control References: <4435cde3$0$11677$c3e8da3@news.astraweb.com> Message-ID: <1144390994.551650.31490@v46g2000cwv.googlegroups.com> Here's my take on the thing. It only prints one term, though. http://www.magicpeacefarm.com/lonnie/code/morris.py.html (a bit too long to post) From Aiwass333 at gmail.com Fri Apr 7 11:18:08 2006 From: Aiwass333 at gmail.com (RunLevelZero) Date: 7 Apr 2006 08:18:08 -0700 Subject: ftplib question References: <1144396557.737326.78240@v46g2000cwv.googlegroups.com> Message-ID: <1144423088.757826.146100@t31g2000cwb.googlegroups.com> Well I am not too familiar with ftplib but I have done some minimal work. Example: try: server=FTP() server.connect('ftp.mcafee.com', 21) except: print "Could not connect to server" raw_input("Hit Enter to quit:") sys.exit(0) login = server.login('anonymous', 'foo at example.com') workdir = server.cwd("/pub/datfiles/english") ## Set the current directory server.delete("*.*") End Example: I hope it helps From johnjsal at NOSPAMgmail.com Tue Apr 18 22:42:32 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 18 Apr 2006 22:42:32 -0400 Subject: Best Python web-hosting? In-Reply-To: <1144764674.977833.30210@i40g2000cwc.googlegroups.com> References: <1144605832.364688.305300@j33g2000cwa.googlegroups.com> <4439870a$0$4206$c3e8da3@news.astraweb.com> <1144710859.872630.297820@u72g2000cwu.googlegroups.com> <443b15dd$0$11701$c3e8da3@news.astraweb.com> <1144764674.977833.30210@i40g2000cwc.googlegroups.com> Message-ID: <4445A398.9060804@NOSPAMgmail.com> walterbyrd wrote: > I emailed them, they say they have mod_python. > Hi. I was just wondering if you been able to use mod_python at Dollar Hosting. I'm having some trouble with it. The handlers don't seem to be set up correctly and I've been in contact with the administrators, but they aren't sure what to do either. How is it on your end? Thanks, John From admin at angerona.cult.cu Fri Apr 7 20:34:22 2006 From: admin at angerona.cult.cu (=?iso-8859-1?Q?Tom=E1s_Rodriguez_Orta?=) Date: Fri, 7 Apr 2006 18:34:22 -0600 Subject: enviroment for Python similar to Visual C++ Message-ID: <004901c65aa4$2e394780$d21900c8@zeus> Hello friends I am new programator in python, and I am looking for an enviroment graphics similar to visual c++, or delphi, where Can I create application and forms, but over python? sombody have any idea? thanks for you help. TOMAS ------------------------------------------------------------------------- Este correo fue escaneado en busca de virus con el MDaemon Antivirus 2.27 en el dominio de correo angerona.cult.cu y no se encontro ninguna coincidencia. From http Tue Apr 4 17:50:19 2006 From: http (Paul Rubin) Date: 04 Apr 2006 14:50:19 -0700 Subject: Best way to create a copy of a list References: <1144130464.918371.143160@u72g2000cwu.googlegroups.com> <1144134473.327848.307040@g10g2000cwb.googlegroups.com> <1hd9hda.1n89sie1ckqtk9N%aleaxit@yahoo.com> Message-ID: <7x64lpqack.fsf@ruckus.brouhaha.com> aleaxit at yahoo.com (Alex Martelli) writes: > I vastly prefer to call list(xxx) in order to obtain a new list with the > same items as xxx -- couldn't be more obvious than that. > > You can't claim it's obvious that xxx[:] *copies* data Heh, it wasn't obvious that list(xxx) copies data either (I thought of it as being like a typecast), but I just checked, and it does copy. I'll have to remember to do it like that. I do like it better than xxx[:] which is what I'd been using because I remember seeing that the copy module does it that way. From python at rcn.com Tue Apr 11 14:47:19 2006 From: python at rcn.com (Raymond Hettinger) Date: 11 Apr 2006 11:47:19 -0700 Subject: Manipulating sets from the 2.4 C API? References: Message-ID: <1144781239.581839.174460@e56g2000cwe.googlegroups.com> Dave Opstad wrote: > I just looked through the Python/C API reference for 2.4.3 and didn't > see anything about using sets. I'd been expecting things like PySet_New, > PySet_Check etc. In Py2.4, there was not a custom set C API because the module was still ungoing significant development. For 2.4, the best way to access sets from C is to use the abstract API: s=PyObject_CallObject(PySet_Type, NULL) // s=set() PyObject_TypeCheck(o, &PySet_Type) // isinstance(o, set) PyObject_GetIter(s) // iter(s) PyObject_Hash(f) // hash of frozenset PyObject_Length(s) // len(s) PyNumber_Subtract(s,t) // s - t PyObject_CallMethod(s, "pop", NULL) // s.pop() > If I want to handle sets should I just use a dictionary's keys and > ignore the values, or is there some more explicit set support somewhere > I'm not seeing? In Py2.4, set objects are based on dictionaries so the performance is about the same, so the only advantage of using set objects instead of dictionaries is that they provide methods like union, intersection, etc which are not defined for dictionaries. In Py2.5, set objects are no longer based on dictionaries and tend to have better speed/space performance than equivalent dictionary code. There is also a more full-blown C API including PySet_New(), PySet_Size(), PySet_Add(), PySet_Contains(), ... From fredrik at pythonware.com Wed Apr 19 12:57:46 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 19 Apr 2006 18:57:46 +0200 Subject: C API - Conversions from PyInt or PyFloat to a char * References: <1145465141.985789.139010@e56g2000cwe.googlegroups.com> Message-ID: williams.jasonscott at gmail.com wrote: > I'm looking at the C API and wanting to know a good way to convert > Python numeric types to native c types. For strings I've been using > PyString_AsString(v) and thats great, but I would like to do the same > for ints and floats. double d = PyFloat_AsDouble(v); long i = PyInt_AsLong(v); double real = PyComplex_RealAsDouble(v); double imag = PyComplex_ImagAsDouble(v); Py_complex c = PyComplex_AsCComplex(v); long i = PyLong_AsLong(v); unsigned long y = PyLong_AsUnsignedLong(v); double d = PyLong_AsDouble(v); PY_LONG_LONG l = PyLong_AsLongLong(v); // and others; see include/longobject.h for details the float and int versions also available as "unsafe" macro versions double d = PyFloat_AS_DOUBLE(v); int i = PyInt_AS_LONG(op); (the macro versions assume that that v points to a python object of the right type; it's up to you to do the type check) From fredrik at pythonware.com Tue Apr 18 05:24:31 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 18 Apr 2006 11:24:31 +0200 Subject: Error using tkinter References: <1145348834.820408.130890@j33g2000cwa.googlegroups.com> Message-ID: "JyotiC" wrote: > I am getting the error > > Exception in Tkinter callback > Traceback (most recent call last): > File "/usr/lib/python2.3/lib-tk/Tkinter.py", line 1345, in __call__ > return self.func(*args) > File "gui.py", line 248, in writescript > f = open('crossManual.sh','w') > TypeError: an integer is required > > Couldn't understand what it means let me guess: gui.py contains the line "from os import *" ? this means that "open" refers to os.open, which is not the same thing as the built-in open function. the solution? use "import os", and add "os." in front of all functions from that module. never use from-import in application code, unless you have very good reasons: http://effbot.org/zone/import-confusion.htm#which-way-should-i-use From exarkun at divmod.com Sat Apr 1 23:47:22 2006 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Sat, 1 Apr 2006 23:47:22 -0500 Subject: Scatter/gather on sockets? In-Reply-To: Message-ID: <20060402044722.22481.1787923605.divmod.quotient.8997@ohm> On 1 Apr 2006 14:56:02 -0500, Roy Smith wrote: >I've got a bunch of strings in a list: > >vector = [] >vector.append ("foo") >vector.append ("bar") >vector.append ("baz") > >I want to send all of them out a socket in a single send() call, so >they end up in a single packet (assuming the MTU is large enough). I >can do: > >mySocket.send ("".join (vector)) > >but that involves creating an intermediate string. Is there a more >efficient way, that doesn't involve that extra data copy? There is a thing called "scatter-gather I/O", but it has nothing to do with lumping things together in a single packet. It's all about minimizing memory copying on the way to the network. The underlying call is writev(), and it is not exposed to Python applications in the standard library. There are, however, several third-party modules which provide access to it (google for "python writev" - you'll find plenty of material). You can also call it via the dl module, and in Python 2.5, the ctypes module. Twisted also exposes this functionality via ITransport.writeSequence (silently falling back to writing "".join(iovec) if a more efficient scatter-gather mechanism is not available (which it isn't in any of the official Twisted reactors (but someday it will be and your program will magically go faster))). Jean-Paul From peter at engcorp.com Mon Apr 3 09:32:39 2006 From: peter at engcorp.com (Peter Hansen) Date: Mon, 03 Apr 2006 09:32:39 -0400 Subject: Oserror: [Errno 20] In-Reply-To: References: Message-ID: k r fry wrote: > Sorry for not copying the whole traceback before, I hop I have done it > right this time. > > I am now getting: > > Traceback (most recent call last): > File "katiescint.py", line 153, in ? > for subdir in os.path.istdir(DATADIR): #loop through > list of strings > AttributeError: 'module' object has no attribute 'istdir' > > I did think maybe it was meant to be "listdir" instead of "istdir", but > that doesn't work either. > Sorry to be a pain. You'll get the hang of it... :-) There are two functions required here: os.listdir(), and os.path.isdir(). The first one is the correct one for the purpose, as you originally used it. The second one (which I suppose someone with a German background might try to spell "istdir" ;-) ) is to test whether a given path "is [a] dir[ectory]". If you read the documentation on those two functions, and experiment at the interactive prompt, you'll shortly notice that os.listdir() returns only the names of the items in the directory, not the full paths. os.path.isdir(), on the other hand, requires a full path (since of course it can't know what directory you looked in with os.listdir), so you'll have to join the names together before testing them, something like this (and I'll rely on you to actually *read the docs* and *experiment at the interactive prompt* this time, instead of giving up so quickly and asking for help again when you could figure this out yourself with a little more effort): for name in os.listdir(DATADIR): path = os.path.join(DATADIR, name) if os.path.isdir(path): filename = os.path.join(path, 'flux.fits') data = FITS.Read(filename) # etc.... -Peter From jelleferinga at gmail.com Fri Apr 21 06:36:04 2006 From: jelleferinga at gmail.com (jelle) Date: 21 Apr 2006 03:36:04 -0700 Subject: are docstrings for variables a bad idea? Message-ID: <1145615763.943050.170950@j33g2000cwa.googlegroups.com> That's basically the idea... Often i find myself annotating what variables actually stand for, so to refer back to the code in half a year or so. # check if ID's or coords self.pointIDs = ptIDs self.coords = [tuple(RS.PointCoordinates(i)) for i in ptIDs] # map ids/coords and coords/ids self.pointID_2_Coord, self.coord_2_pointID = {}, {} for id, coord in zip(self.pointIDs,self.coords): self.coord_2_pointID[coord] = id self.pointID_2_Coord[id] = coord # initiate kdtree self.kdTREE = kdtree.kdtree(3) for i in self.coords: self.kdTREE.addPoint(i) # break down interfaceCrvID self.segments = list(RS.ExplodeCurves(interfaceCrvID)) # dictionary with a midpoint for each segment self.segmentCoords = {} for i in self.segments: self.segmentCoords[i] = list(RS.CurveMidPoint(i)) and so on... Please don't say that naming variables properly suffices for any skilled programmer... really... When programming a more complex class, it would be quite helpful that these annotations would pop-up as a docstring. Often I find myself referring back to a module containing the class to read back what data the variable holds exactly. A time consuming activity that could be seriously sped up by a proper IDE (I'm on SPE, thanks Stani!) Would that make sense to anyone? cheers, -jelle From martin at v.loewis.de Wed Apr 26 12:58:35 2006 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Wed, 26 Apr 2006 18:58:35 +0200 Subject: MinGW and Python In-Reply-To: References: <1145861223.509630.247350@y43g2000cwc.googlegroups.com> <444C79D7.4060007@v.loewis.de> <444DC62B.7000702@v.loewis.de> <1145985979.369429.114040@i39g2000cwa.googlegroups.com> <444e7d85$0$12131$9b622d9e@news.freenet.de> Message-ID: <444FA6BB.40109@v.loewis.de> Edward Elliott wrote: >> Well, there is no native C library on Microsoft Windows: the system >> simply doesn't include an official C library (I know there is crtdll.dll >> and msvcrt.dll, but these aren't "endorsed" system C libraries). > > don't know what you mean by "endorsed". does it lack features of the C89 > ANSI standard? There isn't an import library for these DLLs anywhere, and Microsofts documents it (msvcrt.dll) as not intended for application use: http://msdn2.microsoft.com/en-us/library/abx4dbyh(VS.80).aspx 'The msvcrt.dll is now a "known DLL," meaning that it is a system component owned and built by Windows. It is intended for future use only by system-level components.' >> For Windows, that would require not to use any of the standard C >> functionality, since the system doesn't provide that functionality out >> of the box. > > That would be a problem then. So what happens when you compile python with > msvc, and why can't mingw just replicate that? I link with msvcr71.dll (currently). To distribute Python, I need to include a copy of msvcr71.dll, which I can, because the MSVC license allows me to redistribute that DLL. When I link with mingw, I have a choice of DLLs to link with, including msvcrt.dll, msvcrt4.dll, msvcr71.dll, and perhaps others - I don't even need the DLLs on my system to link with them. However, I cannot redistribute these DLLs when I compile with MingW (unless I also have a copy of VS.NET - I would have to reread its license to find out whether it requires that the application is actually built with MSVC to allow for redistribution). Regards, Martin From brieuc.gorin at gmail.com Thu Apr 13 08:52:44 2006 From: brieuc.gorin at gmail.com (brieuc.gorin at gmail.com) Date: 13 Apr 2006 05:52:44 -0700 Subject: py2exe wx.lib.activexwrapper win32com Message-ID: <1144932764.700816.129020@t31g2000cwb.googlegroups.com> I try to create an exe using py2exe, but i've got some troubles. In my application, i use a flash activex control with wxPython (wx.lib.activexwrapper). I get the following lines in the log when i run my executable Code: Traceback (most recent call last): File "main.py", line 8, in ? File "misc.pyc", line 10, in ? File "xmlconfig.pyc", line 10, in ? File "window.pyc", line 13, in ? File "wxPython\lib\activexwrapper.pyc", line 5, in ? File "wx\lib\activexwrapper.pyc", line 24, in ? ImportError: ActiveXWrapper requires PythonWin. Please install the win32all-xxx.exe package. On my XP with the python installation, i don't have any problems. I really don't understand what happen, PythonWin is an ide, the real name of the modules is pywin32. I use python 2.3 and wxPython 2.6, py2exe 0.6 with the bundle option. Some modules aren't correctly imported i guess. This is my code to import the activex and I makepy the file axflash if wxPlatform == '__WXMSW__': from wxPython.lib.activexwrapper import MakeActiveXClass import axflash flashControl = axflash Thanks for your help ;) From aahz at pythoncraft.com Tue Apr 18 15:57:55 2006 From: aahz at pythoncraft.com (Aahz) Date: 18 Apr 2006 12:57:55 -0700 Subject: 2.5 excitement (was Re: Java Developer Exploring Python) References: <1145290449.735642.120860@i40g2000cwc.googlegroups.com> <1204021.LzRF60KP7e@jupiter.g2ctech> Message-ID: In article , Jon Ribbens wrote: >In article , Aahz wrote: >> >> On that front, I think that pysqlite is much more important because >> it finally gets rid of the excuse for using Berkeley for simple >> database purposes. > >Apologies if I'm being obtuse, but how does including the pysqlite >wrapper module change anything? You still need to download and install >SQLite, so what's the point of including a wrapper for something you >may or may not have? Why is pysqlite included, for example, and not >MySQL-Python or postgresql or whatever? SQLite will be included with the Windows distribution. Not sure about Macs; as Fredrik pointed out, most Linux/BSD distros should make that simple. As for why SQLite, there seems to be a consensus that it's the only truly zero-admin SQL solution that provides decent SQL compatibility and performance. For more about the decision, I suggest you read the python-dev archives. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "LL YR VWL R BLNG T S" From Andre_Mikulec at Hotmail.com Thu Apr 13 21:58:34 2006 From: Andre_Mikulec at Hotmail.com (AIM) Date: 13 Apr 2006 18:58:34 -0700 Subject: setup.py on unix/linux and converting to windows Message-ID: <1144979914.803533.204600@j33g2000cwa.googlegroups.com> Hi all, I have a general question and some advice is needed. Over time, I am running into python modules with setups that are just made for linux/unix. I have python installed on windows. To get these modules into windows, should I do the following? (1) Install cygwin. (2) compile/setup the python modules in the cygwin enviroment. (3) Copy the new (installed) files to my python on windows environment (specifically and most likely the site-packages directory. What do you think about this? In most cases will this work? In what cases will this not work? Sometimes threading will not work? Thank you very much. AIM From onurb at xiludom.gro Thu Apr 27 10:40:46 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 27 Apr 2006 16:40:46 +0200 Subject: String Exceptions (PEP 352) In-Reply-To: References: Message-ID: <4450d844$0$27293$626a54ce@news.free.fr> Thomas Guettler wrote: > Hi, > > I like python because it is compatible to old versions. That's way I think > string exceptions should not be deprecated. > > I use string exceptions if the condition for an assertion is > to complex: > > if foo and bar and i>10: > raise "if foo and bar i must not be greater than 10" What's wrong with: assert foo and bar and i > 10, \ "if foo and bar i must not be greater than 10" (snip) > > Please keep Python compatible to old versions. When there's too much hysterical cruft and warts accumulated from the past, it's time to throw away and clean up, even if it breaks a lot of things. Trying to keep compatibility at any price would be just suicidal IMHO - time to get rid of old warts and come back to simplicity. "one obvious way to do it" rules. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From steve at holdenweb.com Mon Apr 3 15:25:38 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 03 Apr 2006 15:25:38 -0400 Subject: Python 2.5 licensing: stop this change In-Reply-To: References: Message-ID: Philippe Martin wrote: > That was nasty Steve - at least I'm ready for any kind of bad new today ;-) > Sorry ;-) regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd www.holdenweb.com Love me, love my blog holdenweb.blogspot.com From martin at v.loewis.de Tue Apr 11 13:15:18 2006 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Tue, 11 Apr 2006 19:15:18 +0200 Subject: list.clear() missing?!? In-Reply-To: References: <1144767680.583085.310160@v46g2000cwv.googlegroups.com> Message-ID: <443BE426.20501@v.loewis.de> Felipe Almeida Lessa wrote: > I love benchmarks, so as I was testing the options, I saw something very > strange: > > $ python2.4 -mtimeit 'x = range(100000); ' > 100 loops, best of 3: 6.7 msec per loop > $ python2.4 -mtimeit 'x = range(100000); del x[:]' > 100 loops, best of 3: 6.35 msec per loop > $ python2.4 -mtimeit 'x = range(100000); x[:] = []' > 100 loops, best of 3: 6.36 msec per loop > $ python2.4 -mtimeit 'x = range(100000); del x' > 100 loops, best of 3: 6.46 msec per loop > > Why the first benchmark is the slowest? I don't get it... could someone > test this, too? In the first benchmark, you need space for two lists: the old one and the new one; the other benchmarks you need only a single block of memory (*). Concluding from here gets difficult - you would have to study the malloc implementation to find out whether it works better in one case over the other. Could also be an issue of processor cache: one may fit into the cache, but the other may not. Regards, Martin (*) plus, you also need the integer objects twice. From godoy at ieee.org Sun Apr 9 10:42:34 2006 From: godoy at ieee.org (Jorge Godoy) Date: Sun, 09 Apr 2006 11:42:34 -0300 Subject: Decorators, Identity functions and execution... References: Message-ID: <87fykm7qud.fsf@ieee.org> Chance Ginger writes: > On Sun, 09 Apr 2006 09:51:18 +0200, Fredrik Lundh wrote: > >> Chance Ginger" wrote: >> >>> If I define a decorator like: >>> >>> def t(x) : >>> def I(x) : return x >>> return I >> >> ... you get a syntax error. >> > > It isn't a syntax error...I tried it before I posted. In fact > def t(x) : > def I(x) : return x > return I > > is correct. Indeed. This is correct. Fredrick's comment was related to the lack of indentation in your code. > >>> and use it like: >>> >>> @t(X) >>> def foo(a) : >>> # definition of foo... >>> pass >> >> that's also a syntax error. > > Once again this isn't an error assuming you pass in a valid 'X'. If your indentation is broken as above it doesn't matter what 'X' is. -- Jorge Godoy "Quidquid latine dictum sit, altum sonatur." - Qualquer coisa dita em latim soa profundo. - Anything said in Latin sounds smart. From onurb at xiludom.gro Thu Apr 13 06:45:23 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 13 Apr 2006 12:45:23 +0200 Subject: Iterating command switches from a data file - have a working solution but it seems inefficient In-Reply-To: <123s5qm84atdf5d@corp.supernews.com> References: <123r6925duev9b2@corp.supernews.com> <443e0edc$0$20655$636a55ce@news.free.fr> <123s5qm84atdf5d@corp.supernews.com> Message-ID: <443e2c0f$0$11337$636a55ce@news.free.fr> News wrote: > bruno at modulix wrote: > >>News wrote: >> >>>Hi everyone, >>> >>>My goal is to pull command switches/options from a file and then assign >>>the values to select variables which would eventually be included in a >>>class object. >>> >>>The data file looks something like this but the switches could be in any >>>order and not all may be used. >>> >>>-m quemanager -s server -p port -k key -o object -c 20 -t test at email.com >> >>Have you looked at optparse ? >> > > I have. > > In the interactive version of the code, I use: > > # > # Parse command line options and automatically build help/usage > # > parser = OptionParser() > > parser.add_option("-q", "--quiet", > action="store_false", dest="verbose", default=1, > help="don't print status messages to stdout") > parser.add_option("-m", dest="qmanager", > help="Queue Manager to inquire against") > parser.add_option("-s", dest="host", > help="Host the que manager resides on") > parser.add_option("-p", dest="port", > help="Port queue manager listens on"), > parser.add_option("-o", dest="object", > help="Queue object being inquired on"), > parser.add_option("-k", dest="key", > help="object attribute to be inquired about"), > parser.add_option("-t", type="string",dest="mto", > help="e-mail address the report will go to"), > parser.add_option("-d", action="store_false",dest="report", > help="optional switch - enabling this sends output > to e-mail") > (options, args) = parser.parse_args() > So why do you inflict yourself the pain of rewriting all the parsing etc??? > The module optparse seemed to be aimed at reading from commandline > versus pulling attributes from a read line. http://www.python.org/doc/2.4.2/lib/optparse-parsing-arguments.html: """ The whole point of creating and populating an OptionParser is to call its parse_args() method: (options, args) = parser.parse_args(args=None, options=None) where the input parameters are args the list of arguments to process (sys.argv[1:] by default) """ what about something like : line = myfile.readline() options = parser.parse_args(line.split()) But what, if you prefer to rewrite (and maintain) a custom parser doing exactly the same thing, please do !-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From onurb at xiludom.gro Tue Apr 25 05:49:54 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 25 Apr 2006 11:49:54 +0200 Subject: RESOLVED Re: PYTHONPATH In-Reply-To: References: <1145535721.138411.145790@z34g2000cwc.googlegroups.com> <44478f30$0$12862$626a54ce@news.free.fr> Message-ID: <444df116$0$21533$626a54ce@news.free.fr> Brian van den Broek wrote: > Hi all, > > As a fairly new linux user running ubuntu 5.10 I'd had problems > persistently setting my PYTHONPATH environment variable. bruno and > Edward got me most of the way (thanks!); I'm posting what worked for > future googling. > (snip) > The syntax that worked for me was *almost* what bruno suggested. It > didn't work here until I used ':' rather than bruno's ';' as the path > element separator. oops, my bad :( Sorry for the typo - it's of course ':'. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From laurent.pointal at limsi.fr Mon Apr 24 09:12:13 2006 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Mon, 24 Apr 2006 15:12:13 +0200 Subject: Writing backwards compatible code - when? In-Reply-To: <44455670$1@nntp0.pdx.net> References: <44455670$1@nntp0.pdx.net> Message-ID: Scott David Daniels a ?crit : > Bob Greschke wrote: >> Is there a list of all of the Python commands and modules that tell >> when (what version) they were added to Python? I was hoping the new >> Essential Reference would have it, but it doesn't. > > Here's a reference that stops at 2.3: > > http://rgruet.free.fr/PQR2.3.html Remove the 2.3, and you get the 2.4 :-) http://rgruet.free.fr/ A+ Laurent. From claudio.grondi at freenet.de Sat Apr 15 16:14:46 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Sat, 15 Apr 2006 22:14:46 +0200 Subject: ANN: 3 new ShowMeDo.com videos on Python Objects In-Reply-To: References: Message-ID: Ian Ozsvald wrote: > Summary: > At http://ShowMeDo.com we have 3 new videos by Jerol Harrington > introducing Python Objects: > http://showmedo.com/videoListPage?listKey=IntroductionToPythonObjectsUsingIPython_JerolH > > and 5 videos for beginners to wxPython: > http://showmedo.com/videoListPage?listKey=PythonWxPythonBeginnersSeries > making a total of 20 ShowMeDo videos, mostly about Python, all free. > > Detail: > Jerol Harrington's ShowMeDos use the IPython shell to give an > introduction to using 'class', '__init__', inheritance and attributes. > I have been using Python for 3 years and I got something out of each of > the videos. These videos represent our first user-contribution - thanks > Jerol! > > In the 5 wxPython videos Kyran Dale walks you through the first steps > of using wxPython - from downloading, installing (MS Windows), a first > application and on to menubars and event handling. > > Also, in our latest update we have enabled voting on other user's requests: > http://showmedo.com/requests > There are 14 requests right now, feel free to share your view on which > videos you would like to see. Some of the requests include List > Comprehensions, py2exe, wxGlade, PyDev and other IDEs. > Please get in touch if we're missing a topic that ought to be included, > we will do our best to have new ShowMeDos made. > > About ShowMeDo.com: > Free videos (we call them ShowMeDos) showing you how to do things. The > videos are made by us and our users, for everyone. > > Ian Ozsvald, Kyran Dale > > ian at ShowMeDo.com > http://ShowMeDo.com (http://blog.showmedo.com) > A small hint for everyone interested in gaining deep understanding about Python objects: To gain deep understanding of what objects in Python are is one of the biggest challenges when learning Python. There are so many different ways of understanding what Python objects are and how Python works with them (depending on how deep you want your understanding to be, how deep you are ready to dig into this subject and how experienced in programming and smart you are), that whenever in the past someone asked a question related to such deep understanding in this or other Python related newsgroups, the outcome was a never ending discussion thread with many controversial postings. Please be aware, that the video about Python objects (I have checked out myself part I) is not consistent in using terms and explaining things, so take care assuming that you get enlightened about Python objects watching it. Claudio From lists at fabis-site.net Mon Apr 10 12:33:01 2006 From: lists at fabis-site.net (Fabian Steiner) Date: Mon, 10 Apr 2006 18:33:01 +0200 Subject: twisted.web and a Message-ID: Hello! I am currently working on a quite complicated application (at least for me) and unfortunately I don't know how to go on. I wrapped a Windows-dll by using the ctypes module so that I can access different functions that are used to control a network device (open, close, write/read values). Now I was asked to write something like a GUI for it which should be based on a CGI script that calls the different functions (read/write) with parameters entered in a text-input of a HTML-Template. Therefore I wrote a small HTTP-Server class based on twisted.web. In its constructor the network device is opened (--> the wrapper class is initiated) and is closed by the server's destructor. Now I need the same wrapper class instance in my CGI script so that read() and write() can be called on exactly the same instance - otherwise these methods would fail since the network device hasn't been opened so far. Do you have any idea how to solve this problem? I am looking forward to any responses. Cheers, Fabian From steve at hastings.org Thu Apr 6 16:25:04 2006 From: steve at hastings.org (Steve R. Hastings) Date: Thu, 06 Apr 2006 13:25:04 -0700 Subject: efficiency of range() and xrange() in for loops References: <1144300109.813835.320110@i39g2000cwa.googlegroups.com> Message-ID: On Wed, 05 Apr 2006 22:08:29 -0700, Carl Banks wrote: >> for i in range(n) >> >> into compiled code equivalent to >> >> for i in itr >> >> where "itr" is a lightweight iterator that returns the same values as >> iter(range(n)). > Nope, out of the question for Python 2.x. Note that the the builtin > range could be rebound, or a global range could appear in the module, > at run time. Ah! Of course. Thank you very much for explaining this. -- Steve R. Hastings "Vita est" steve at hastings.org http://www.blarg.net/~steveha From robert.kern at gmail.com Mon Apr 24 17:32:36 2006 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 24 Apr 2006 16:32:36 -0500 Subject: MinGW and Python In-Reply-To: References: <1145861223.509630.247350@y43g2000cwc.googlegroups.com> <444C79D7.4060007@v.loewis.de> Message-ID: Brian Elmegaard wrote: > Robert Kern writes: > >>- gcc does not optimize particularly well. > > But well enough for other platforms. Well, it tends to optimize just as poorly for other platforms, too. It's just frequently the only compiler widely available on those platforms. The goal of the gcc project is to provide a portable compiler, not one that generates the best code for any given platform. And in that goal, it succeeds remarkably well. -- Robert Kern robert.kern at gmail.com "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From girodt at gmail.com Fri Apr 14 08:16:54 2006 From: girodt at gmail.com (Thomas Girod) Date: 14 Apr 2006 05:16:54 -0700 Subject: GdkColor : the phantom class ? In-Reply-To: <1145015353.707935.28350@u72g2000cwu.googlegroups.com> References: <1145015353.707935.28350@u72g2000cwu.googlegroups.com> Message-ID: <1145017014.554805.248030@j33g2000cwa.googlegroups.com> I found an answer : color = gtk.gdk.Color() and then use color for fg et bg From redefined.horizons at gmail.com Mon Apr 17 16:32:05 2006 From: redefined.horizons at gmail.com (redefined.horizons at gmail.com) Date: 17 Apr 2006 13:32:05 -0700 Subject: Java Developer Exploring Python In-Reply-To: <1145292795.565277.288760@v46g2000cwv.googlegroups.com> References: <1145290449.735642.120860@i40g2000cwc.googlegroups.com> <1145292795.565277.288760@v46g2000cwv.googlegroups.com> Message-ID: <1145305925.055791.89650@e56g2000cwe.googlegroups.com> Ravi Teja wrote: > >> I've traditionally been a Java developer, although I play around with LISP. > > For most java developers, understanding dynamic typing is a big step. > Your Lisp background however would mean that you will pick up Python > very quickly. > > >> I recently migrated to Linux and I was exploring Mono as an > option for development on Linux. However, I've had some problems with > the maturity and support when working with Mono. > > IronPython (still a beta) BTW, runs on Mono as well and you can use > Mono through Python when you deem it ready. There is also Jython, which > runs on the Java platform if you feel married to Java platform or class > libraries. > > >> Is Python actively developed and supported on Linux? > > Yes and very well so. Many Linux distributions come with Python > pre-installed and Python has quite a bit of following in the Linux > crowd. Red Hat / Fedora installer - Anaconda, for example uses Python. > > >> Would it be a viable option for cross-platform application development? > > Python is a very good candidate for open source development. But then > again, most open source languages these days are. The culture is a bit > different though. Although Python is byte code compiled just like Java, > Python programmers are not averse to using native extensions (which in > most cases can be compiled painlessly on all popular platforms thanks > to Python's distutils). Java programmers on the other hand generally > extol 'Pure Java'. Both approaches have their own advantages and > disadvantages (Swing vs SWT) and you can use either with Python. > > >> Can anyone recommend an open source IDE for Python that runs on Linux? > > Most Python IDEs are open source along with a few commercial ones. > http://wiki.python.org/moin/IntegratedDevelopmentEnvironments > Everyone has their favorites and you should pick your own. > > Since you have a Java background, PyDev is probably the best choice for > you. JEdit also has a Python plugin. I just use SciTE (just an editor) > most of the time. Ravi, Thank you for taking the time to answer my questions. It sounds like Python may be the solution I am searching for. I took a look at lists of the IDEs on the wiki. Looks like I might be sticking with the IDLE editor for now. :] Perhaps I will have to write a simple IDE for Python that integrates Glade and supports pyGTK when I have some more programming experience... Scott Huey From joe.hrbek at gmail.com Sun Apr 30 19:32:33 2006 From: joe.hrbek at gmail.com (joe.hrbek at gmail.com) Date: 30 Apr 2006 16:32:33 -0700 Subject: python and xulrunner Message-ID: <1146439953.280364.309130@e56g2000cwe.googlegroups.com> Hi everyone, sorry, this post is a bit off topic. I posted this on a devel xul thread on the mozilla groups but didn't get a response. My hope is that some of you may have interest in this and have tried it yourself. I've been trying to get xulrunner compiled with python (in windows) but have been unsuccessful. I've been following this: . I know it's a linux based tutorial, but the steps are generally the same aside from required os linkers/compilers - which i've obtained reading the standard mozilla compile instructions for windows. Has anyone else tried this and had luck with it? -j From uymqlp502 at sneakemail.com Sat Apr 8 00:18:23 2006 From: uymqlp502 at sneakemail.com (Russ) Date: 7 Apr 2006 21:18:23 -0700 Subject: output formatting for user-defined types References: <1144283268.217968.316100@i39g2000cwa.googlegroups.com> <1144287077.109309.16300@z34g2000cwc.googlegroups.com> <1144346706.300959.123610@i40g2000cwc.googlegroups.com> <1144368862.466490.58240@v46g2000cwv.googlegroups.com> Message-ID: <1144469903.009434.217400@u72g2000cwu.googlegroups.com> >>>>> dist = 4 * ft >>>>> print >> out, dist/ft >> 4 >> Note, however, that this requires the user to explicity ask for the >> conversion. >How is this any more explicit and any less safe than: >dist = 4 * ft >print float(dist) Because the former specifies the actual units and the latter does not. If the base units were not feet, then the latter would not return the value in feet (which happens to be 4 here). It would return the value in whatever the base unit for length happened to be. So the former works even if the base unit is changed, but the latter does not. Secondly, allowing unconditional conversion to float allows any unit to be passed to trig functions. But any unit other than (dimensionless) radians passed to a trig function is an error. I explaned that already, but apparently you missed it. >But in any case, I suspect you do automatically convert units. What do you >do in this case: >x = 45*ft >y = 16*m >z = x+y >Do you raise an error? Nope. Works just fine. You obviously didn't look at the user guide. What happens is that any length unit is automatically converted to the chosen base unit for length, so everything is consistent. >All you are doing is making a rod for your own back, to no advantage. Wrong again. From kentilton at gmail.com Fri Apr 28 15:15:17 2006 From: kentilton at gmail.com (Ken Tilton) Date: Fri, 28 Apr 2006 15:15:17 -0400 Subject: Somebody report John [was Re: ] In-Reply-To: References: <1145992903.834316.198370@u72g2000cwu.googlegroups.com> <4GM3g.3084$TT.1768@twister.nyroc.rr.com> <1146231280.733609.143230@e56g2000cwe.googlegroups.com> <4452258e$0$655$bed64819@news.gradwell.net> <1146235544.218219.71430@j73g2000cwa.googlegroups.com> <87psj1ionl.fsf@rpi.edu> Message-ID: <9Rt4g.14$fM.3@fe08.lga> John Bokma wrote: > Bill Atkins wrote: > > >>John Bokma writes: >> >>>Isn't it crazy that one person is allowed to create such a huge mess >>>everytime he posts? >> >>Isn't it crazy that one person willfully creates such a mess every >>time Xah posts? Shush! > > > Since you're posting from an edu tld, why are you wasting time and money > instead of getting educated? It might stop you from acting like an idiot > like you did just now. > We have seen the enemy, and he is us. -- Pogo I love this entire thread. Thank you, Xah! ken -- Cells: http://common-lisp.net/project/cells/ "Have you ever been in a relationship?" Attorney for Mary Winkler, confessed killer of her minister husband, when asked if the couple had marital problems. From sullivanz.pku at gmail.com Sat Apr 1 15:52:57 2006 From: sullivanz.pku at gmail.com (Sullivan WxPyQtKinter) Date: 1 Apr 2006 12:52:57 -0800 Subject: Berkeley DB XML vs 4suite for fast searching in XML DB? Message-ID: <1143924777.638584.89800@z34g2000cwc.googlegroups.com> Storing XML in relational database with indexing feature is exactly what I need. But 4suite is mentioned from time to time and seemingly holding better support for python. I have no idea if 4 suite has provide strong support for random access or relatively random access for XML database and with indexing features, to support fast search. Who could compare the efficiency different between the two? From LuciferLeo at gmail.com Thu Apr 27 23:14:53 2006 From: LuciferLeo at gmail.com (LuciferLeo at gmail.com) Date: 27 Apr 2006 20:14:53 -0700 Subject: Why not BDWGC? Message-ID: <1146194093.309243.314490@y43g2000cwc.googlegroups.com> I've heard that the reason why python uses reference counting rather than tracing collector is because python cannot determine the root set for its various C extensions. But provided that BDWGC(full name: Boehm-Demers-Weiser conservative garbage collector) is conservative --- can be used for C, and opensourced, why python not adopt it as its gcmodule? From johnjsal at NOSPAMgmail.com Fri Apr 28 15:18:01 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 28 Apr 2006 19:18:01 GMT Subject: an error in commented code? In-Reply-To: <1146248368.855908.254870@u72g2000cwu.googlegroups.com> References: <1146248368.855908.254870@u72g2000cwu.googlegroups.com> Message-ID: Andr? wrote: > Tried adding a "\n" (i.e. press the enter key) after the last line > (i.e. right after the word "order") so that you don't end with a > comment. > > Andr? > Weird, but it worked! :) From neurogasm at gmail.com Tue Apr 11 03:34:52 2006 From: neurogasm at gmail.com (Kun) Date: Tue, 11 Apr 2006 03:34:52 -0400 Subject: modifying html input date for mysql, reg ex or string interpolation? Message-ID: I have an html form that takes dates and inserts them into a mysql file. Currently, users have to type in dates in the yyyy-mm-dd format. As of now, this process works with the sql. However, I would like to make this process easier by: 1) providing drop down menus for year, month, and date respectively. in a failed attempt, i tried made 3 drop down lists (dateyear, datemonth, dateday) respectively and then used string interpolation to tie them together into a yyyy-mm-dd string called 'date'. I then tried to use this 'date' string in my original sql query and it no longer worked. Is this because the new 'date' value is a string instead of an int? How can I go about solving this problem and making the new 'date' string work with my old sql query? Attached is my code: #!/usr/bin/env python import cgi print "Content-type: text/html" print form = cgi.FieldStorage() print form.keys() #gets value for each input price = form["price"] price = price.value purchasetype = form["purchasetype"] purchasetype = purchasetype.value date = form["date"] date = date.value comment = form["comment"] comment = comment.value dateyear = form["dateyear"] dateyear = dateyear.value datemonth = form["datemonth"] datemonth = datemonth.value dateday = form["dateday"] dateday = dateday.value #string interpolation for date date = "%d-%d-%d" % (dateyear, datemonth, dateday) print "
" for x in form.keys(): print "%s=%s" % (x, form[x].value) + "
" # make connection to MySQL import MySQLdb import re import urllib import sys try: connection = MySQLdb.connect(host="localhost", user="xxxx", passwd="xxxx", db ="xxxx") except MySQLdb.Error, e: print "Error %d: %s" % (e.args[0], e.args[1]) sys.exit (1) #take data and put it into table that you have created. cursor = connection.cursor() mysqlstatement = "" mysqlstatement = "INSERT INTO dir (date, purchasetype, price, comment) VALUES ('"+ date +"','"+ purchasetype +"','"+ price +"','"+ comment +"' )" print mysqlstatement cursor.execute (mysqlstatement) From tjreedy at udel.edu Tue Apr 25 19:55:08 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 25 Apr 2006 19:55:08 -0400 Subject: search an entire website given the homepage URL References: <2387F0EED10A4545A840B231BBAAC7226082CC@slcimail1.slcgov.com> Message-ID: "Bell, Kevin" wrote in message news:2387F0EED10A4545A840B231BBAAC7226082CC at slcimail1.slcgov.com... > I would like some feedback about my actual intention though, which is to > scrape local newspaper websites for the names of people that I work > with. Twice this month, colleagues have unknowingly been in the > newspaper, and only became aware of it because someone stumbled across > the line in the article. To write a script that would crawl around > testing for my own name, or that of my colleagues, wouldn't seem uncouth > to me, but I'm new at this stuff. It seems impolite for newspapers to > use someone's name without informing them of it, for sure, but you can't > count on journalists to call you up. Would this application of a spider > be impolite? If the site has an index, I would use that. If the site has pages at fixed urls accessible to public indexes (Google, Yahoo, etc) I would use one of those. (Google, at least, will search a specific site.) If the site has a robots.txt file requesting robots and spiders to restrict themselvres, I would honor the request. Failing the above, I might write something to once a day, during off hours, download and examine articles in the appropriate category. tjr From mtobis at gmail.com Wed Apr 12 17:46:17 2006 From: mtobis at gmail.com (Michael Tobis) Date: 12 Apr 2006 14:46:17 -0700 Subject: iPython and doctest Message-ID: <1144873720.777327.226710@e56g2000cwe.googlegroups.com> It appears that doctest does not work straightforwardly within iPython. I would like to be able to use doctest within a file conditionally, so that I can develop it within ipython and test it otherwise. It would seem that this would work: Python 2.4.1 (#2, Mar 31 2005, 00:05:10) [GCC 3.3 20030304 (Apple Computer, Inc. build 1666)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import testme >>> testme._test() >>> but it doesn't (the test above fails, but reports nothing) I am finding the documentation for doctest ironically impenetrable and **would** be interested in adding some examples and explanatory text to it, but I need to understand what is going on rather better than I do. Meanwhile I am settling for this: # testme.py def foo(): """ Should return 42 >>> foo() 42 """ return 43 def _test(): import doctest doctest.testmod() if __name__ == "__main__": try: __IP # check if we are in iPython except: _test() print "ok" #### Then In [4]:!python testme.py works (reports the error) just fine! So I don't even have to bail out of iPython to run the tests. mt From mahs at telcopartners.com Fri Apr 21 22:15:57 2006 From: mahs at telcopartners.com (Michael Spencer) Date: Fri, 21 Apr 2006 19:15:57 -0700 Subject: String To Dict Problem In-Reply-To: <1145670029.497083.203360@i40g2000cwc.googlegroups.com> References: <1143394114.182768.192970@g10g2000cwb.googlegroups.com> <1145670029.497083.203360@i40g2000cwc.googlegroups.com> Message-ID: Clodoaldo Pinto wrote: > Michael Spencer wrote: > >> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/364469 > > Very nice work. It will be very useful. Thanks. > > Only a small problem when I try to evaluate this: > > safe_eval('True') > > I get: > > Traceback (most recent call last): > File "safe_eval.py", line 63, in ? > safe_eval('True') > File "safe_eval.py", line 59, in safe_eval > return walker.visit(ast) > File "safe_eval.py", line 19, in visit > return meth(node, **kw) > File "safe_eval.py", line 23, in default > return self.visit(child, **kw) > File "safe_eval.py", line 19, in visit > return meth(node, **kw) > File "safe_eval.py", line 47, in visitName > node.name, node) > __main__.Unsafe_Source_Error: Line 1. Strings must be quoted: True > > This is just to let you know. I can live with that. I just replace True > for 1. > > Regards, Clodoaldo Pinto > Alternatively, you could edit visitName to allow 'True' and any other identifiers you specify e.g. (untested): allowed = {"True": True, "False": False} def visitName(self,node, **kw): try: return self.allowed[node.name] except KeyError: raise Unsafe_Source_Error("Strings must be quoted", node.name, node) Cheers Michael From wegwerp at gmail.com Fri Apr 14 07:04:54 2006 From: wegwerp at gmail.com (Bas) Date: 14 Apr 2006 04:04:54 -0700 Subject: List of all syntactic sugar? In-Reply-To: References: <1145008451.273827.293680@v46g2000cwv.googlegroups.com> Message-ID: <1145012694.084137.266180@j33g2000cwa.googlegroups.com> >That kind of depends on what you mean by syntactic sugar. Mightbe I was misusing the name of syntactic sugar, but I what I intended to say was "all the possible 'transformations' that can be made to reduce all the 'advanced' syntax to some sort of minimal core of the language". Bas From steven.bethard at gmail.com Tue Apr 18 13:44:35 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 18 Apr 2006 11:44:35 -0600 Subject: Updated PEP 359: The make statement Message-ID: <_aydnYpYE_rjuNjZRVn-og@comcast.com> I've updated PEP 359 with a bunch of the recent suggestions. The patch is available at: http://bugs.python.org/1472459 and I've pasted the full text below. I've tried to be more explicit about the goals -- the make statement is mostly syntactic sugar for:: class : __metaclass__ = so that you don't have to lie to your readers when you're not actually creating a class. I've also added some new examples and expanded the discussion of the old ones to give the statement some better motivation. And I've expanded the Open Issues discussions to consider a few alternate keywords and to indicate some of the difficulties in allowing a ``__make_dict__`` attribute for customizing the dict in which the block is executed. PEP: 359 Title: The "make" Statement Version: $Revision: 45366 $ Last-Modified: $Date: 2006-04-13 07:36:24 -0600 (Thu, 13 Apr 2006) $ Author: Steven Bethard Status: Draft Type: Standards Track Content-Type: text/x-rst Created: 05-Apr-2006 Python-Version: 2.6 Post-History: 05-Apr-2006, 06-Apr-2006, 13-Apr-2006 Abstract ======== This PEP proposes a generalization of the class-declaration syntax, the ``make`` statement. The proposed syntax and semantics parallel the syntax for class definition, and so:: make : is translated into the assignment:: = ("", , ) where ```` is the dict created by executing ````. This is mostly syntactic sugar for:: class : __metaclass__ = and is intended to help more clearly express the intent of the statement when something other than a class is being created. Of course, other syntax for such a statement is possible, but it is hoped that by keeping a strong parallel to the class statement, an understanding of how classes and metaclasses work will translate into an understanding of how the make-statement works as well. The PEP is based on a suggestion [1]_ from Michele Simionato on the python-dev list. Motivation ========== Class statements provide two nice facilities to Python: (1) They execute a block of statements and provide the resulting bindings as a dict to the metaclass. (2) They encourage DRY (don't repeat yourself) by allowing the class being created to know the name it is being assigned. Thus in a simple class statement like:: class C(object): x = 1 def foo(self): return 'bar' the metaclass (``type``) gets called with something like:: C = type('C', (object,), {'x':1, 'foo':}) The class statement is just syntactic sugar for the above assignment statement, but clearly a very useful sort of syntactic sugar. It avoids not only the repetition of ``C``, but also simplifies the creation of the dict by allowing it to be expressed as a series of statements. Historically, type instances (a.k.a. class objects) have been the only objects blessed with this sort of syntactic support. The make statement aims to extend this support to other sorts of objects where such syntax would also be useful. Example: simple namespaces -------------------------- Let's say I have some attributes in a module that I access like:: mod.thematic_roletype mod.opinion_roletype mod.text_format mod.html_format and since "Namespaces are one honking great idea", I'd like to be able to access these attributes instead as:: mod.roletypes.thematic mod.roletypes.opinion mod.format.text mod.format.html I currently have two main options: (1) Turn the module into a package, turn ``roletypes`` and ``format`` into submodules, and move the attributes to the submodules. (2) Create ``roletypes`` and ``format`` classes, and move the attributes to the classes. The former is a fair chunk of refactoring work, and produces two tiny modules without much content. The latter keeps the attributes local to the module, but creates classes when there is no intention of ever creating instances of those classes. In situations like this, it would be nice to simply be able to declare a "namespace" to hold the few attributes. With the new make statement, I could introduce my new namespaces with something like:: make namespace roletypes: thematic = ... opinion = ... make namespace format: text = ... html = ... and keep my attributes local to the module without making classes that are never intended to be instantiated. One definition of namespace that would make this work is:: class namespace(object): def __init__(self, name, args, kwargs): self.__dict__.update(kwargs) Given this definition, at the end of the make-statements above, ``roletypes`` and ``format`` would be namespace instances. Example: gui objects -------------------- In gui toolkits, objects like frames and panels are often associated with attributes and functions. With the make-statement, code that looks something like:: root = Tkinter.Tk() frame = Tkinter.Frame(root) frame.pack() def say_hi(): print "hi there, everyone!" hi_there = Tkinter.Button(frame, text="Hello", command=say_hi) hi_there.pack(side=Tkinter.LEFT) root.mainloop() could be rewritten to group the the Button's function with its declaration:: root = Tkinter.Tk() frame = Tkinter.Frame(root) frame.pack() make Tkinter.Button hi_there(frame): text = "Hello" def command(): print "hi there, everyone!" hi_there.pack(side=Tkinter.LEFT) root.mainloop() Example: custom descriptors --------------------------- Since descriptors are used to customize access to an attribute, it's often useful to know the name of that attribute. Current Python doesn't give an easy way to find this name and so a lot of custom descriptors, like Ian Bicking's setonce descriptor [2]_, have to hack around this somehow. With the make-statement, you could create a ``setonce`` attribute like:: class A(object): ... make setonce x: "A's x attribute" ... where the ``setonce`` descriptor would be defined like:: class setonce(object): def __init__(self, name, args, kwargs): self._name = '_setonce_attr_%s' % name self.__doc__ = kwargs.pop('__doc__', None) def __get__(self, obj, type=None): if obj is None: return self return getattr(obj, self._name) def __set__(self, obj, value): try: getattr(obj, self._name) except AttributeError: setattr(obj, self._name, value) else: raise AttributeError, "Attribute already set" def set(self, obj, value): setattr(obj, self._name, value) def __delete__(self, obj): delattr(obj, self._name) Note that unlike the original implementation, the private attribute name is stable since it uses the name of the descriptor, and therefore instances of class A are pickleable. Example: property namespaces ---------------------------- Python's property type takes three function arguments and a docstring argument which, though relevant only to the property, must be declared before it and then passed as arguments to the property call, e.g.:: class C(object): ... def get_x(self): ... def set_x(self): ... x = property(get_x, set_x, "the x of the frobulation") This issue has been brought up before, and Guido [3]_ and others [4]_ have briefly mused over alternate property syntaxes to make declaring properties easier. With the make-statement, the following syntax could be supported:: class C(object): ... make block_property x: '''The x of the frobulation''' def fget(self): ... def fset(self): ... with the following definition of ``block_property``:: def block_property(name, args, block_dict): fget = block_dict.pop('fget', None) fset = block_dict.pop('fset', None) fdel = block_dict.pop('fdel', None) doc = block_dict.pop('__doc__', None) assert not block_dict return property(fget, fset, fdel, doc) Example: interfaces ------------------- Guido [5]_ and others have occasionally suggested introducing interfaces into python. Most suggestions have offered syntax along the lines of:: interface IFoo: """Foo blah blah""" def fumble(name, count): """docstring""" but since there is currently no way in Python to declare an interface in this manner, most implementations of Python interfaces use class objects instead, e.g. Zope's:: class IFoo(Interface): """Foo blah blah""" def fumble(name, count): """docstring""" With the new make-statement, these interfaces could instead be declared as:: make Interface IFoo: """Foo blah blah""" def fumble(name, count): """docstring""" which makes the intent (that this is an interface, not a class) much clearer. Specification ============= Python will translate a make-statement:: make : into the assignment:: = ("", , ) where ```` is the dict created by executing ````. The ```` expression is optional; if not present, an empty tuple will be assumed. A patch is available implementing these semantics [6]_. The make-statement introduces a new keyword, ``make``. Thus in Python 2.6, the make-statement will have to be enabled using ``from __future__ import make_statement``. Open Issues =========== Keyword ------- Does the ``make`` keyword break too much code? Originally, the make statement used the keyword ``create`` (a suggestion due to Nick Coghlan). However, investigations into the standard library [7]_ and Zope+Plone code [8]_ revealed that ``create`` would break a lot more code, so ``make`` was adopted as the keyword instead. However, there are still a few instances where ``make`` would break code. Is there a better keyword for the statement? Some possible keywords and their counts in the standard library (plus some installed packages): * make - 2 (both in tests) * create - 19 (including existing function in imaplib) * build - 83 (including existing class in distutils.command.build) * construct - 0 * produce - 0 The make-statement as an alternate constructor ---------------------------------------------- Currently, there are not many functions which have the signature ``(name, args, kwargs)``. That means that something like:: make dict params: x = 1 y = 2 is currently impossible because the dict constructor has a different signature. Does this sort of thing need to be supported? One suggestion, by Carl Banks, would be to add a ``__make__`` magic method that if found would be called instead of ``__call__``. For types, the ``__make__`` method would be identical to ``__call__`` and thus unnecessary, but dicts could support the make-statement by defining a ``__make__`` method on the dict type that looks something like:: def __make__(cls, name, args, kwargs): return cls(**kwargs) Of course, rather than adding another magic method, the dict type could just grow a classmethod something like ``dict.fromblock`` that could be used like:: make dict.fromblock params: x = 1 y = 2 So the question is, will many types want to use the make-statement as an alternate constructor? And if so, does that alternate constructor need to have the same name as the original constructor? Customizing the dict in which the block is executed --------------------------------------------------- Should users of the make-statement be able to determine in which dict object the code is executed? This would allow the make-statement to be used in situations where a normal dict object would not suffice, e.g. if order and repeated names must be allowed. Allowing this sort of customization could allow XML to be written without repeating element names, and with nesting of make-statements corresponding to nesting of XML elements:: make Element html: make Element body: text('before first h1') make Element h1: attrib(style='first') text('first h1') tail('after first h1') make Element h1: attrib(style='second') text('second h1') tail('after second h1') If the make-statement tried to get the dict in which to execute its block by calling the callable's ``__make_dict__`` method, the following code would allow the make-statement to be used as above:: class Element(object): class __make_dict__(dict): def __init__(self, *args, **kwargs): self._super = super(Element.__make_dict__, self) self._super.__init__(*args, **kwargs) self.elements = [] self.text = None self.tail = None self.attrib = {} def __getitem__(self, name): try: return self._super.__getitem__(name) except KeyError: if name in ['attrib', 'text', 'tail']: return getattr(self, 'set_%s' % name) else: return globals()[name] def __setitem__(self, name, value): self._super.__setitem__(name, value) self.elements.append(value) def set_attrib(self, **kwargs): self.attrib = kwargs def set_text(self, text): self.text = text def set_tail(self, text): self.tail = text def __new__(cls, name, args, edict): get_element = etree.ElementTree.Element result = get_element(name, attrib=edict.attrib) result.text = edict.text result.tail = edict.tail for element in edict.elements: result.append(element) return result Note, however, that the code to support this is somewhat fragile -- it has to magically populate the namespace with ``attrib``, ``text`` and ``tail``, and it assumes that every name binding inside the make statement body is creating an Element. As it stands, this code would break with the introduction of a simple for-loop to any one of the make-statement bodies, because the for-loop would bind a name to a non-Element object. This could be worked around by adding some sort of isinstance check or attribute examination, but this still results in a somewhat fragile solution. It has also been pointed out that the with-statement can provide equivalent nesting with a much more explicit syntax:: with Element('html') as html: with Element('body') as body: body.text = 'before first h1' with Element('h1', style='first') as h1: h1.text = 'first h1' h1.tail = 'after first h1' with Element('h1', style='second') as h1: h1.text = 'second h1' h1.tail = 'after second h1' And if the repetition of the element names here is too much of a DRY violoation, it is also possible to eliminate all as-clauses except for the first by adding a few methods to Element. [9]_ So are there real use-cases for executing the block in a dict of a different type? And if so, should the make-statement be extended to support them? Optional Extensions =================== Remove the make keyword ------------------------- It might be possible to remove the make keyword so that such statements would begin with the callable being called, e.g.:: namespace ns: badger = 42 def spam(): ... interface C(...): ... However, almost all other Python statements begin with a keyword, and removing the keyword would make it harder to look up this construct in the documentation. Additionally, this would add some complexity in the grammar and so far I (Steven Bethard) have not been able to implement the feature without the keyword. Removing __metaclass__ in Python 3000 ------------------------------------- As a side-effect of its generality, the make-statement mostly eliminates the need for the ``__metaclass__`` attribute in class objects. Thus in Python 3000, instead of:: class : __metaclass__ = metaclasses could be supported by using the metaclass as the callable in a make-statement:: make : Removing the ``__metaclass__`` hook would simplify the BUILD_CLASS opcode a bit. Removing class statements in Python 3000 ---------------------------------------- In the most extreme application of make-statements, the class statement itself could be deprecated in favor of ``make type`` statements. References ========== .. [1] Michele Simionato's original suggestion (http://mail.python.org/pipermail/python-dev/2005-October/057435.html) .. [2] Ian Bicking's setonce descriptor (http://blog.ianbicking.org/easy-readonly-attributes.html) .. [3] Guido ponders property syntax (http://mail.python.org/pipermail/python-dev/2005-October/057404.html) .. [4] Namespace-based property recipe (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/442418) .. [5] Python interfaces (http://www.artima.com/weblogs/viewpost.jsp?thread=86641) .. [6] Make Statement patch (http://ucsu.colorado.edu/~bethard/py/make_statement.patch) .. [7] Instances of create in the stdlib (http://mail.python.org/pipermail/python-list/2006-April/335159.html) .. [8] Instances of create in Zope+Plone (http://mail.python.org/pipermail/python-list/2006-April/335284.html) .. [9] Eliminate as-clauses in with-statement XML (http://mail.python.org/pipermail/python-list/2006-April/336774.html) Copyright ========= This document has been placed in the public domain. .. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 coding: utf-8 End: From tomerfiliba at gmail.com Mon Apr 24 16:15:45 2006 From: tomerfiliba at gmail.com (gangesmaster) Date: 24 Apr 2006 13:15:45 -0700 Subject: threads and sys.exit() In-Reply-To: <3q2q42h1rc8bk48pvugjv4ql71ckqp79rn@4ax.com> References: <1145897992.091952.326970@e56g2000cwe.googlegroups.com> <4b4fdaFv61niU1@uni-berlin.de> <1145899303.174911.80770@u72g2000cwu.googlegroups.com> <1145899589.305060.104130@u72g2000cwu.googlegroups.com> <3q2q42h1rc8bk48pvugjv4ql71ckqp79rn@4ax.com> Message-ID: <1145909745.558490.263050@e56g2000cwe.googlegroups.com> i can't make the main thread daemonic. the situation is this: * the main thread starts a thread * the new thread does sys.exit() * the new thread dies, but the process remains i can do os.kill(os.getpid()), or TerminateProcess(-1) but that's not what i want -tomer From bdesth.quelquechose at free.quelquepart.fr Sat Apr 8 13:28:24 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 08 Apr 2006 19:28:24 +0200 Subject: Programming Tutorial for absolute beginners In-Reply-To: <1144485229.605504.12560@g10g2000cwb.googlegroups.com> References: <1144439148.751062.16590@t31g2000cwb.googlegroups.com> <1144485229.605504.12560@g10g2000cwb.googlegroups.com> Message-ID: <4437c4cc$0$405$626a54ce@news.free.fr> malv a ?crit : > Looks pretty good, except for your difficult to read examples. > Don't use black backrounds with green characters. > A plain white background with black text would be a major improvement. > May I suggest a system like Trac-Wiki, that knows how to display Python code with syntax-hilighting and line-numbering ?-) (Not sure but IIRC, MoinMoin as the same feature). From roy at panix.com Mon Apr 10 11:37:16 2006 From: roy at panix.com (Roy Smith) Date: Mon, 10 Apr 2006 11:37:16 -0400 Subject: About classes and OOP in Python References: <1144678797.749000.155010@t31g2000cwb.googlegroups.com> Message-ID: "fyhuang" wrote: > I've been wondering a lot about why Python handles classes and OOP the > way it does. From what I understand, there is no concept of class > encapsulation in Python, i.e. no such thing as a private variable. Any > part of the code is allowed access to any variable in any class, and > even non-existant variables can be accessed: they are simply created. > I'm wondering what the philosophy behind this is, and if this > behaviour is going to change in any future release of Python. There are advantages and disadvantages to C++/Java style encapsulation using private data. The advantages you (apparently) already know. The disadvantage is added complexity. There's a saying, "You can't have a bug in a line of code you never write". By having to write all those getter and setter methods, you just add bulk and complexity. That being said, you can indeed have private data in Python. Just prefix your variable names with two underscores (i.e. __foo), and they effectively become private. Yes, you can bypass this if you really want to, but then again, you can bypass private in C++ too. You can also intercept any attempt to access Python attributes by writing __getattr__() and __setattr__() methods for your class. > It seems to me that it is difficult to use OOP to a wide extent in > Python code because these features of the language introduce many > inadvertant bugs. For example, if the programmer typos a variable name > in an assignment, the assignment will probably not do what the > programmer intended. Yes, that is is a risk. Most people deal with that risk by doing a lot of testing (which you should be doing anyway). If you really want to, you can use the __slots__ technique to prevent this particular bug from happening (although the purists will tell you that this is not what __slots__ was designed for). > My main question is that of why Python chooses to use this type of OOP > model and if it is planned to change. It sounds like you are used to things like C++ and Java, which are very static languages. Everything is declared at compile time, and there are many safeguards in the language to keep you from shooting yourself in the foot. They problem is, they often prevent you from getting any useful work done either; you spend most of your time programming the language, not the problem you are trying to solve. In the past week, I've had two conversations with people about the nuances of C++ assignment operators. None of our customers give two figs about assignment operators. Getting them right is just a detour we need to take to keep our software from crashing. With Python, I write a = b and trust that it does the right thing. That lets me concentrate on adding value that our customer will see. From cginboston at hotmail.com Sun Apr 9 02:57:55 2006 From: cginboston at hotmail.com (Chance Ginger) Date: Sun, 09 Apr 2006 06:57:55 GMT Subject: Decorators, Identity functions and execution... Message-ID: If I define a decorator like: def t(x) : def I(x) : return x return I and use it like: @t(X) def foo(a) : # definition of foo... pass or maybe this: @t(X) @(Y) def bar(a) : # The definition of bar... Will in encounter much of a penalty in executing 'foo' or 'bar'? If so, is there a way to define t such that Python knows it is the identity function and short-circuit evaluation? Thanks in advance. From nobody at 127.0.0.1 Tue Apr 25 17:40:09 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Tue, 25 Apr 2006 21:40:09 GMT Subject: MinGW and Python References: <1145861223.509630.247350@y43g2000cwc.googlegroups.com> <444C79D7.4060007@v.loewis.de> <444DC62B.7000702@v.loewis.de> <1145985979.369429.114040@i39g2000cwa.googlegroups.com> <444e7d85$0$12131$9b622d9e@news.freenet.de> <1145999256.027851.132780@y43g2000cwc.googlegroups.com> Message-ID: Ross Ridge wrote: > MSVCRT.DLL ... It's not > exactly "endorsed", Microsoft would rather you use it's current > compiler and runtime, but it is the standard "official" Windows system > C library. Does it comply with the ANSI C89 standard? I'm still not seeing why mingw can't just link python to it. From kent at kentsjohnson.com Wed Apr 19 08:36:57 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Wed, 19 Apr 2006 08:36:57 -0400 Subject: extracting a substring In-Reply-To: <1145406353.280681.134630@t31g2000cwb.googlegroups.com> References: <1145406353.280681.134630@t31g2000cwb.googlegroups.com> Message-ID: <44462ecf$1_1@newspeer2.tds.net> b83503104 at yahoo.com wrote: > Hi, > I have a bunch of strings like > a53bc_531.txt > a53bc_2285.txt > ... > a53bc_359.txt > > and I want to extract the numbers 531, 2285, ...,359. > > One thing for sure is that these numbers are the ONLY part that is > changing; all the other characters are always fixed. In that case a fixed slice will do what you want: In [1]: s='a53bc_531.txt' In [2]: s[6:-4] Out[2]: '531' Kent From struggleyb at gmail.com Sat Apr 15 00:58:03 2006 From: struggleyb at gmail.com (Bo Yang) Date: Sat, 15 Apr 2006 12:58:03 +0800 Subject: A question about the urllib2 ? In-Reply-To: <1144831641.616081.72350@i40g2000cwc.googlegroups.com> References: <1144831641.616081.72350@i40g2000cwc.googlegroups.com> Message-ID: <44407D5B.6070403@gmail.com> Serge Orlov ??: > Bo Yang wrote: > >> Hi , >> Recently I use python's urllib2 write a small script to login our >> university gateway . >> Usually , I must login into the gateway in order to surf the web . So , >> every time I >> start my computer , it is my first thing to do that open a browser to >> login the gateway ! >> >> So , I decide to write such a script , sending some post information to >> the webserver >> directly to login automatic once the computer is on . And I write the >> code below : >> >> urllib2.urlopen(urllib2.Request(url="https://202.113.16.223/php/user_login.php", >> data="loginuser=0312889&password=o127me&domainid=1&refer=1& logintype= >> ?????")) >> >> In the five '#' above , I must submit some Chinese character , but the >> urllib2 complain >> for the non-ascii characters . >> > > I guess the server expect that a browser is coming from page > https://202.113.16.223/, so the url should be submitted in the encoding > of page https://202.113.16.223/ which is gb2312. > > urllib2.urlopen(urllib2.Request(url="https://202.113.16.223/php/user_login.php", > data=u"loginuser=0312889&password=o127me&domainid=1&refer=1& logintype= > ??".encode('gb2312'))) > > should work > > Yeah , and it works ! Thank you ! From claird at lairds.us Fri Apr 7 10:08:01 2006 From: claird at lairds.us (Cameron Laird) Date: Fri, 07 Apr 2006 14:08:01 GMT Subject: Farther OT: financial analytics (was: OT: job offering in Milan) References: <1144402806.087904.164860@i39g2000cwa.googlegroups.com> Message-ID: <7c7ig3-bco.ln1@lairds.us> In article , Robin Becker wrote: . . . >My math skills are now so degraded I have difficulty reading about conic >programming using Nesterov's barrier functions etc etc. . . . You've got me curious. I haven't yet located an adequate introduction to the topic, so I'll ask *you* about the basics: do these (*semi*definite?) cones arise in financial with time the privileged dimension? Does "cone" here mean necessarily with a quadratic cross-section? If so, why is that more compelling than the simplexes of more traditional LP? From jyoti.chhabra at gmail.com Tue Apr 18 05:38:53 2006 From: jyoti.chhabra at gmail.com (JyotiC) Date: 18 Apr 2006 02:38:53 -0700 Subject: Error using tkinter In-Reply-To: References: <1145348834.820408.130890@j33g2000cwa.googlegroups.com> Message-ID: <1145353133.194717.313930@e56g2000cwe.googlegroups.com> Thanx a lot, that was the problem From rpdooling at gmail.com Sat Apr 1 00:14:26 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 31 Mar 2006 21:14:26 -0800 Subject: running IDLE from another program? References: <442d7a45$1_2@newspeer2.tds.net> <442dba0f$0$11191$c3e8da3@news.astraweb.com> Message-ID: <1143868466.456521.53840@j33g2000cwa.googlegroups.com> John, If your file has the .py or .pyc extension on it, it should just run at the command line from its own directory, assuming your environment and path variables are set correctly. I use NoteTab which has a different way of doing it, but basically you should be able to run: c:\mydir>script.py You don't need the python.exe on the commandline. rick From johnjsal at NOSPAMgmail.com Wed Apr 12 17:02:13 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 12 Apr 2006 21:02:13 GMT Subject: Figure out month number from month abbrievation In-Reply-To: <1144873227.982973.18720@i40g2000cwc.googlegroups.com> References: <1144873227.982973.18720@i40g2000cwc.googlegroups.com> Message-ID: Bill wrote: > def month_number(monthabbr): > """Return the month number for monthabbr; e.g. "Jan" -> 1.""" > for index, day in enumerate(calendar.month_abbr): > if day == monthabbr: > return index > > which works well enough but isn't very clever. I'm pretty new to > Python; what am I missing here? > Thanks -- Bill. I'm curious, does that really work, or is there a problem with the first index being 0? Or is that avoided somehow? From tim.golden at viacom-outdoor.co.uk Fri Apr 28 04:01:04 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Fri, 28 Apr 2006 09:01:04 +0100 Subject: Importing modules through directory shortcuts on Windows Message-ID: [Roger Upole] | [... snipped ugly code ...] Thanks; I'll have to find the time to experiment with that a bit. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From grflanagan at yahoo.co.uk Fri Apr 21 08:21:27 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 21 Apr 2006 05:21:27 -0700 Subject: proposed Python logo References: <1145615455.477800.74730@i39g2000cwa.googlegroups.com> Message-ID: <1145622087.368682.16920@j33g2000cwa.googlegroups.com> Michael Yanowitz wrote: > How about having something from Monty Python in the logo rather > than something snakelike. Python was named after Monty Python and not > the snake. Snakes also don't appear friendly to me. > I used to have rats as pets. Snakes are murderers of rats. Which I Never mind rats, have you seen the Google ads for this thread? http://www.salfordadvertiser.co.uk/news/s/211/211961_goodness_snake.html http://www.dailyrecord.co.uk/news/tm_objectid=16959435&method=full&siteid=66633&headline=python-back-on-the-telly--name_page.html !!!-) From johnjsal at NOSPAMgmail.com Sat Apr 1 15:18:46 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sat, 01 Apr 2006 15:18:46 -0500 Subject: running IDLE from another program? In-Reply-To: <442e6011_3@newspeer2.tds.net> References: <442d7a45$1_2@newspeer2.tds.net> <442dba0f$0$11191$c3e8da3@news.astraweb.com> <442e0913$1_3@newspeer2.tds.net> <442e1333$0$2459$c3e8da3@news.astraweb.com> <442e6011_3@newspeer2.tds.net> Message-ID: <442ee151$0$9423$c3e8da3@news.astraweb.com> Kent Johnson wrote: > I'm not sure what you mean by a 'debug' type environment. If you mean, > you want to run the program in a debugger and step through it, then this > approach won't work. If you just mean that you want to see the output of > the program, it will work. No, just an environment like IDLE that shows errors instead of just killing the program. > OK, your program is reading from standard input and the environment set > up by UltraEdit doesn't support this. If you are trying to run > interactive programs this approach won't work. Oh, I see! I had the raw_input() in there so it would pause the DOS prompt for me, but after taking out that line, then it works how I want it to. > One thing that is really useful about running in an editor window is > that (in TextPad, anyway) I can double-click on an error message and go > directly to the line with the error. Interesting. The way I have it now, it shows errors the way I want to, but it shows them just in a text file, nothing special, and I don't seem to be able to double-click them. Is this just a feature of TextPad, or did you have to set it up so you can double-click the errors? > Anyway, it turns out IDLE has a command-line switch that lets you pass a > file to run. Try > C:\Python24\Lib\idlelib\idle -r C:\path\to\myprog.py I tried this but it said it couldn't find idle.pyw (even though it is there). From steven.bethard at gmail.com Tue Apr 11 12:22:43 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 11 Apr 2006 10:22:43 -0600 Subject: updated pre-PEP: The create statement In-Reply-To: <1144755714.001318.233020@z34g2000cwc.googlegroups.com> References: <1144741586.861381.190350@z34g2000cwc.googlegroups.com> <1144755714.001318.233020@z34g2000cwc.googlegroups.com> Message-ID: Michele Simionato wrote: > Peter Hansen wrote: >> Michele Simionato wrote: >> > You can pull out the example in the official >>> PEP, if you like. >> Please do. If this is supposed to have anything to do with namespaces, >> it has nothing to do with the type of data structures XML is capable of >> and the presence of this example would only lead some people to think >> there can't be a good use case for the whole idea if that's the best we >> can come up with to demonstrate its benefits. > > Sorry for the multiple posting (Google failed me) and yes, let's remove > the XML example. Done. And thanks again everyone for the careful eyes! STeVe From maximillou at msn.com Wed Apr 12 12:33:09 2006 From: maximillou at msn.com (maxou) Date: 12 Apr 2006 09:33:09 -0700 Subject: ftp connection and commands (directroy size, etc) References: Message-ID: <1144859589.128645.5530@t31g2000cwb.googlegroups.com> Hello Arne > 1. Connecting to ftp is OK > 2. Getting the directory structure and the size of each directory in the > root -If you want to get the structure of your directory you can simply do this: print ftp.dir(path_of_your_directory) or by creating a list do this a=ftp.dir(path_of_your_directory) print a - To get the size do this: import os.path size_directory=os.path.getsize(name_of_directory) or size_file=os.path.getsize(name_of_file) Max From girodt at gmail.com Wed Apr 26 09:52:37 2006 From: girodt at gmail.com (TG) Date: 26 Apr 2006 06:52:37 -0700 Subject: Inherit from array In-Reply-To: <444f79a8$0$5191$626a54ce@news.free.fr> References: <1146057315.721573.196140@u72g2000cwu.googlegroups.com> <444f79a8$0$5191$626a54ce@news.free.fr> Message-ID: <1146059557.692537.144820@v46g2000cwv.googlegroups.com> from array import array class Vector(array): def __init__(self,size): print "pouet" array.__init__('f') print "pouet" v = Vector('c') print repr(v) will output : pouet pouet array('c') From finite.automaton at gmail.com Mon Apr 10 13:05:40 2006 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 10 Apr 2006 10:05:40 -0700 Subject: how to make a generator use the last yielded value when it regains control In-Reply-To: <443a40e0$1_1@news.bluewin.ch> References: <4435cde3$0$11677$c3e8da3@news.astraweb.com> <1144390994.551650.31490@v46g2000cwv.googlegroups.com> <443a40e0$1_1@news.bluewin.ch> Message-ID: <1144688740.056988.183640@u72g2000cwu.googlegroups.com> > What's wrong with the following ? > > def morris(seed,n) : > """...""" > for k in xrange(n-1) : > seed=length_encode(seed) > return seed Nothing's wrong with it. I happen to think the recursive version is more elegant, but that's just me ;-) From johnjsal at NOSPAMgmail.com Sat Apr 8 19:06:32 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sat, 08 Apr 2006 19:06:32 -0400 Subject: how to make a generator use the last yielded value when it regains control In-Reply-To: References: <4435cde3$0$11677$c3e8da3@news.astraweb.com> <1144383206.576767.192570@g10g2000cwb.googlegroups.com> <4435e96d$0$17970$c3e8da3@news.astraweb.com> Message-ID: <44384257$0$11362$c3e8da3@news.astraweb.com> Michael Spencer wrote: > itertools.groupby makes this very straightforward: I was considering this function, but then it seemed like it was only used for determing consecutive numbers like 1, 2, 3 -- not consecutive equivalent numbers like 1, 1, 1. But is that not right? From struggleyb at gmail.com Wed Apr 12 04:05:05 2006 From: struggleyb at gmail.com (Bo Yang) Date: Wed, 12 Apr 2006 16:05:05 +0800 Subject: A question about the urllib2 ? In-Reply-To: <1144773828.273277.56750@i40g2000cwc.googlegroups.com> References: <1144773828.273277.56750@i40g2000cwc.googlegroups.com> Message-ID: <443CB4B1.3060401@gmail.com> Fuzzyman ??: > Bo Yang wrote: > >> Hi , >> Recently I use python's urllib2 write a small script to login our >> university gateway . >> Usually , I must login into the gateway in order to surf the web . So , >> every time I >> start my computer , it is my first thing to do that open a browser to >> login the gateway ! >> >> So , I decide to write such a script , sending some post information to >> the webserver >> directly to login automatic once the computer is on . And I write the >> code below : >> >> urllib2.urlopen(urllib2.Request(url="https://202.113.16.223/php/user_login.php", >> data="loginuser=0312889&password=o127me&domainid=1&refer=1& logintype= >> #####")) >> >> In the five '#' above , I must submit some Chinese character , but the >> urllib2 complain >> for the non-ascii characters . >> >> What do you think this ? >> >> > I haven't tried this, so I'm guessing :-) > > Do you pass in the string to urllib2 as unicode ? If so, try encoding > it to UTF8 first... > > Otherwise you might try escaping it using ``urllib.quote_plus``. (Note > ``urllib``, *not* ``urllib2``.) > > All the best, > > Fuzzyman > http://www.voidspace.org.uk/python/index.shtml > > >> Any help will be appreciated very much , thanks in advance ! >> > > Thank you , I have got it ! I quote the Chinese with urllib.quote() , Thanks again ! From deets at nospam.web.de Tue Apr 18 12:36:40 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 18 Apr 2006 18:36:40 +0200 Subject: Threading problem References: Message-ID: <4akit1Ft3sm1U1@uni-berlin.de> > Here the error message: >>>> Exception in thread Thread-1: > Traceback (most recent call last): > File "C:\Program Files\Python\lib\threading.py", line 442, in > __bootstrap > self.run() > File "G:\Robot teleskop\VRT\test\test2.py", line 25, in run > Document.OpenFile('F:/Images/VRT/'+name) > File "C:\Program > Files\Python\Lib\site-packages\win32com\client\dynamic.py", line 496, in > __getattr__ > raise AttributeError, "%s.%s" % (self._username_, attr) > AttributeError: MaxIm.Document.OpenFile Seems that you think it should doesn't impress the COM-object of type MaxIm.Document very much. Play around with that w/o threads if it works. Diez From kent at kentsjohnson.com Mon Apr 3 13:33:34 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Mon, 03 Apr 2006 13:33:34 -0400 Subject: String pattern matching In-Reply-To: References: <1143888648.234963.326000@j33g2000cwa.googlegroups.com> Message-ID: <4431571b$1_3@newspeer2.tds.net> Eddie Corns wrote: > Off topic I know but I've been learning snobol pattern matching recently so I > thought I'd give this one a bash. Here is my effort: > > define('foo(str)') > &fullscan = 1 > '/abcaaab/abca/eeabcac/' '/' arb $ x arb $ y arb $ z '/' *x *y '/' > + arb $ v *x arb $ w '/' *foo(v '/' w '/' x '/' y '/' z) :F(end) > foo output = str :(FRETURN) > > end > > If I get time I'll try to get this working in Sam Wilmott's Python pattern > matching library. > > What fun! Cool! I have to get in on the fun :-) This program uses Sam Wilmott's library to find one solution. It is a simple translation of your program above. I couldn't figure out how to get multiple solutions. http://www.wilmott.ca/python/patternmatching.html import string from patterns_b import * subject = MatchingInput ('/abcaaab/abca/eeabcac/') Letters = AnyOfP(string.letters)[1:] subject ^ IsP('/') & Letters >> 'x' & Letters >> 'y' & Letters >> 'z' & IsP('/') \ & AnotherP('x') & AnotherP('y') & IsP('/') \ & Letters >> 'v' & AnotherP('x') & Letters >> 'w' & IsP('/') print 'v =', subject['v'] print 'w =', subject['w'] print 'x =', subject['x'] print 'y =', subject['y'] print 'z =', subject['z'] Output is v = ee w = ac x = abc y = a z = aab Kent From marco.wahl at gmail.com Sat Apr 1 02:11:30 2006 From: marco.wahl at gmail.com (Marco Wahl) Date: 31 Mar 2006 23:11:30 -0800 Subject: a question on re In-Reply-To: <1143873454.705410.125300@u72g2000cwu.googlegroups.com> References: <1143873454.705410.125300@u72g2000cwu.googlegroups.com> Message-ID: <1143875490.100960.64350@v46g2000cwv.googlegroups.com> Hi, > i tried to search 2 patterns > > pat1 = re.compile("blah") > pat2 = re.compile("blah2") > > > if i do > if re.findall(pat1,something) and re.findall(pat2,something): > do something > > if does not work > > but when i do a nest if, > > if re.findall(pat1,something) : > if re.findall(pat2,something): > do something > > it works.. > > please advise on why the first code doesnt work. it's not perfectly clear to me what you mean with 'doesnt work'. The two if parts > if re.findall(pat1,something) and re.findall(pat2,something): > do something and > if re.findall(pat1,something) : > if re.findall(pat2,something): > do something look equivalent to me. Could you please reveal your value for text-string 'something'? Further I suggest to replace the 'do something'-parts with 'print 42'. Best wishes Marco From fredrik at pythonware.com Thu Apr 6 09:11:18 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 6 Apr 2006 15:11:18 +0200 Subject: help with designing an app. based on ConfigParser References: <44350C8A.5030802@magic.fr> Message-ID: Alexandre CONRAD wrote: > But now, how do I hold multiple servers ? In this case, I thought about > having multiple sections such as > > [SERVER 01] > [SERVER 02] > [SERVER 03] > > But it's not very efficient when I want to parse the WHOLE config file > to find which servers are available and retrive their options. ConfigParser will read the entire file in any case, so I'm not sure why sorting the entries by server rather than by parameter would make things less efficient... fwiw, I'd probably use [server ] where can be chosen freely by the user, as long as it's unique. e.g. [server server10] param = ... [server dinsdale.foo.org] param = ... [server nisse] param = ... but I'm the kind of programmer that prefer to keep things simple, so I'm sure you can find more complicated ways to do things ;-) From blais at furius.ca Thu Apr 13 22:52:26 2006 From: blais at furius.ca (Martin Blais) Date: Thu, 13 Apr 2006 22:52:26 -0400 Subject: Remove Whitespace In-Reply-To: <1144956776.803967.93540@v46g2000cwv.googlegroups.com> References: <9583ed900604131200n5c43829ckeb01ba4503763954@mail.gmail.com> <1144956776.803967.93540@v46g2000cwv.googlegroups.com> Message-ID: <8393fff0604131952h6161fdfam53396347865d72dd@mail.gmail.com> On 13 Apr 2006 12:32:56 -0700, thunderfoot at gmail.com wrote: > re.sub() doesn't do the substitution in place: it returns the resulting > string. Try this: In-place substitution is impossible in Python, strings are immutable. From cretin at des.alpes.ch Sun Apr 16 08:25:16 2006 From: cretin at des.alpes.ch (Azolex) Date: Sun, 16 Apr 2006 14:25:16 +0200 Subject: PEP 359: The "make" Statement In-Reply-To: <1qmdnTLsqL5ZlN3ZnZ2dnUVZ_vidnZ2d@comcast.com> References: <1qmdnTLsqL5ZlN3ZnZ2dnUVZ_vidnZ2d@comcast.com> Message-ID: <444237ae$1_6@news.bluewin.ch> Steven Bethard wrote: > Rob Williscroft wrote: >> I don't know wether this has been suggested or not, but what about def: >> >> def namespace ns: >> x = 1 >> >> def type blah(object): >> pass >> >> def property x: >> def get(): >> return ns.x > > I think that's probably a bad idea because it would make people think > that the statement acts like a function definition, when it actually > acts like a class definition. maybe this could be marked with an appropriate decorator ? @namespace(mytype) def ns(base1,base2) : ... the decorator could take the function object apart, recover the bases arguments, run the code with a referenced local dict... hum, since in 2.4 exec allows a dict-like object as locals, it should even be possible to hack together a pretty concise hierarchical xml builder syntax embedded in current python - using neither the 'with' nor the 'make' statement, but simply defs ! Note that only the root of the (sub)tree would need to be a decorated "def" since embedded defs could then be caught through the locals pseudo-dict. Looks possible... at a first glance, the one thing that's unclear (to me) is how to deal with closure variables. To learn more, my tendency would be to launch a challenge : "Simulate function call and execution using an exec statement, as precisely as possible" I'll repeat that question in another thread... Best, az. From john at castleamber.com Fri Apr 28 13:01:39 2006 From: john at castleamber.com (John Bokma) Date: 28 Apr 2006 17:01:39 GMT Subject: (was Re: Xah's Edu Corner: Criticism vs Constructive Criticism) References: <1145992903.834316.198370@u72g2000cwu.googlegroups.com> <4GM3g.3084$TT.1768@twister.nyroc.rr.com> <1146231280.733609.143230@e56g2000cwe.googlegroups.com> <4452258e$0$655$bed64819@news.gradwell.net> Message-ID: "Chris Uppal" wrote: > I'm inclined to agree. The problem is not Xah Lee (whom I have > killfiled), but the people who insist on making my killfile useless by > posting loads of follow-ups saying things amounting to "stop this > insane gibberish". Every bloody time. Yup, and since that never stops, I make sure the source is going to dry up. -- John Bokma Freelance software developer & Experienced Perl programmer: http://castleamber.com/ From Serge.Orlov at gmail.com Fri Apr 7 21:41:40 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 7 Apr 2006 18:41:40 -0700 Subject: How to call functions in Advapi32.dll using ctypes References: <1144454318.587516.210850@i40g2000cwc.googlegroups.com> Message-ID: <1144460500.156510.103180@t31g2000cwb.googlegroups.com> Podi wrote: > I have ctypes version 0.9.6 and Python 2.4.2 running on Windows XP > Professional. > > When I tried to use some functions in the Advapi32.dll, some functions > are available and some are not. Is this a bug or feature by design? Most likely feature by design. What you see in documentation for C library is not what your C code will actually use. For example when you write errno in C (that looks like global variable access) it is actually a call to __thread_safe_errno() function. Have you tried calling InitiateSystemShutdownA mentioned in the documentation? From deets at nospam.web.de Mon Apr 3 13:02:05 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 03 Apr 2006 19:02:05 +0200 Subject: Capturing stdout without waiting for the process end References: <1144078426.023838.25970@i39g2000cwa.googlegroups.com> <1144082065.389468.20800@j33g2000cwa.googlegroups.com> <1144083372.170752.275520@z34g2000cwc.googlegroups.com> Message-ID: <49d2t2Fnt213U1@uni-berlin.de> > fin, fout = os.popen4(arg) > > this is executed asyncronously? And how can I intercept a fout.write() > event? You don't intercept anything, you read from the child process stdin, which from your POV is a readable stream. Diez From nobody at 127.0.0.1 Wed Apr 19 13:59:29 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 19 Apr 2006 17:59:29 GMT Subject: multiline comments In-Reply-To: References: <1381517.XiSu08VAzt@jupiter.g2ctech> Message-ID: <5Uu1g.17154$tN3.203@newssvr27.news.prodigy.net> Sion Arrowsmith wrote: > Jorge Godoy wrote: >>Is it harder to remove "n" lines of code commented out with "#" than "n" >>lines of multiline commented code? How? > > I'd say it's harder to remove the latter, due to having to search for > the end of comment sequence, rather than simply looking for where the > block comment stops. Like I said, it's debatable. Depends on the editing conditions you assume. It's easy to imagine situations where either type comes out ahead. From steve at holdenweb.com Sat Apr 29 12:01:14 2006 From: steve at holdenweb.com (Steve Holden) Date: Sat, 29 Apr 2006 17:01:14 +0100 Subject: Can you create an instance of a subclass with an existing instance of the base class? In-Reply-To: References: <1145650105.664762.321560@j33g2000cwa.googlegroups.com> <444cb1e3$0$28592$626a54ce@news.free.fr> <444e0fff$0$7724$636a55ce@news.free.fr> Message-ID: Lawrence D'Oliveiro wrote: > In article <444e0fff$0$7724$636a55ce at news.free.fr>, > bruno at modulix wrote: > > >>Lawrence D'Oliveiro wrote: >> >>>In article <444cb1e3$0$28592$626a54ce at news.free.fr>, >>> bruno at modulix wrote: >>> >>> >>> >>>>Lawrence D'Oliveiro wrote: >>>>(snip) >>>> >>>> >>>>>I think you're taking Python's OO-ness too seriously. One of the >>>>>strengths of Python is that it can _look_ like an OO language without >>>>>actually being OO. >>>> >>>>According to which definition of OO ? >>> >>>Isn't there one? >> >>Your claim that Python "_look_ like an OO language without actually >>being OO" implicitely relies on a definition of OO - or is just >>meaningless. > > > Which nicely evades answering the question. Well I have to say you are also nicely evading answering the question, which is enough to make me suspect your are trolling (deliberately asking contentious questions for the purposes of creating futile argument and discussion). If you *aren't* trolling then what's your objection to saying what led you to make the assertion that Python could look like an OO language without being one? But sine you say later that "Python objects are basically dictionaries" it's clear your understanding of Python isn't terribly complete, which might cast doubt on your understanding of object orientation. For the record, Python *is* an object-oriented language, but it happens to offer convenient features for procedural programming as well. Since these features are orthogonal to its OO features, the fact that they exist doesn't stop Python from being an OO language. So why do you assert that it "merely looks like" one? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From martin at v.loewis.de Tue Apr 11 13:19:15 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 11 Apr 2006 19:19:15 +0200 Subject: list.clear() missing?!? In-Reply-To: <1144774544.177184.171080@u72g2000cwu.googlegroups.com> References: <1144767680.583085.310160@v46g2000cwv.googlegroups.com> <1144774544.177184.171080@u72g2000cwu.googlegroups.com> Message-ID: <443BE513.2040800@v.loewis.de> Ville Vainio wrote: > It's just that, when I have an object, and am wondering how I can clear > it, I tend to look what methods it has first and go to google looking > for "idioms" second. I guess del on a list is not that common, so people tend to not know that it works on lists (and slices!), too. It's too bad that lists have a pop() method these days, so people can do x.pop() even if they don't need the value, instead of doing del x[-1]. I don't think I ever needed to del a slice except for clearing the entire list (and I don't need to do that often, either - I just throw the list away). Regards, Martin From michaeltaft at gmail.com Fri Apr 21 18:18:05 2006 From: michaeltaft at gmail.com (mwt) Date: 21 Apr 2006 15:18:05 -0700 Subject: Finding Module Dependancies Message-ID: <1145657885.389499.232600@t31g2000cwb.googlegroups.com> When I'm rewriting code (cutting and pasting pieces from earlier modules), is there a quick way to determine if I have imported all the necessary modules? I am used to working in Java, where the compiler will tell you if you haven't imported everything, and also Eclipse, which has the handy "organize imports" feature. This is not the case in Python, since it's not compiled, of course, and also running it might not insure you've got all the imports, unless you go through every possible usage scenario -- which in some cases is quite a few, and could take a long time. So what I'm looking for is a command, like "check dependencies" or something, which will list all the modules needed for a source module to run. From onurb at xiludom.gro Thu Apr 20 05:26:23 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 20 Apr 2006 11:26:23 +0200 Subject: Method Call in Exception In-Reply-To: <1145493721.743646.287500@i39g2000cwa.googlegroups.com> References: <1145490879.789439.18030@t31g2000cwb.googlegroups.com> <1145493721.743646.287500@i39g2000cwa.googlegroups.com> Message-ID: <4447540e$0$2465$636a55ce@news.free.fr> mwt wrote: (snip) >>>This works when I try it, but I feel vaguely uneasy about putting >>>method calls in exception blocks. >> >>What do you put in exception blocks?! Whatever fits the specific case... (snip) > Normally I don't like to use exception blocks to do condition-statement > stuff. At least that is how my Java training has programmed me. http://dirtsimple.org/2004/12/python-is-not-java.html > But in > this case, the condition is whether the internet connection is working > or not, and I don't see any other way to do it. As Felipe wrote, you could also use a if/else. > And furthermore, I > don't know if the exceptions-as-logic is a no-no in Python. It's not. The main guideline here is that a else/if has a constant cost - the test is always executed -, while a try/except only adds overhead if it's fired. So - if you leave out purely stylistic or religious considerations - the 'good' choice depends mostly on the 'cost of the test'/'cost of the exception' ratio and the 'have connection'/'no connection' ratio. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From theller at python.net Fri Apr 7 14:36:02 2006 From: theller at python.net (Thomas Heller) Date: Fri, 07 Apr 2006 20:36:02 +0200 Subject: What does 'repair Python 2.5a1' do? Message-ID: What does the repair command in the 2.5a1 msi installer do? Apparently it does not replace changed files, although it seems to replace deleted files. Thomas From justin.azoff at gmail.com Sat Apr 29 19:47:34 2006 From: justin.azoff at gmail.com (Justin Azoff) Date: 29 Apr 2006 16:47:34 -0700 Subject: best way to determine sequence ordering? In-Reply-To: <70q4g.2006$No6.43783@news.tufts.edu> References: <70q4g.2006$No6.43783@news.tufts.edu> Message-ID: <1146354454.556181.203230@j73g2000cwa.googlegroups.com> John Salerno wrote: > If I want to make a list of four items, e.g. L = ['C', 'A', 'D', 'B'], > and then figure out if a certain element precedes another element, what > would be the best way to do that? > > Looking at the built-in list functions, I thought I could do something like: > > if L.index('A') < L.index('D'): > # do some stuff This actually performs pretty well since list.index is implemented in C. The obvious (to me) implementation of: def before(lst, a, b): for x in lst: if x == a: return True if x == b: return False runs about 10-50 times faster than the double index method if I use psyco. Without psyco, it ends up being faster for the cases where a or b appears early on in the list, and the other appears towards the end. From jjl at pobox.com Mon Apr 10 15:13:21 2006 From: jjl at pobox.com (John J. Lee) Date: 10 Apr 2006 19:13:21 +0000 Subject: HTMLParser fragility References: Message-ID: <87slolgs6m.fsf@pobox.com> "Lawrence D'Oliveiro" writes: > I've been using HTMLParser to scrape Web sites. The trouble with this > is, there's a lot of malformed HTML out there. Real browsers have to be > written to cope gracefully with this, but HTMLParser does not. Not only > does it raise an exception, but the parser object then gets into a > confused state after that so you cannot continue using it. [...] sgmllib.SGMLParser (or htmllib.HTMLParser) is more tolerant than HTMLParser.HTMLParser. BeautifulSoup derives from sgmllib.SGMLParser, and introduces extra robustness, of a sort. John From marcs2006 at gmail.com Mon Apr 10 13:07:00 2006 From: marcs2006 at gmail.com (marcello) Date: Mon, 10 Apr 2006 19:07:00 +0200 Subject: [fcntl]how to lock a file References: Message-ID: thank you a lot for your answering Bye Marcello From johnjsal at NOSPAMgmail.com Fri Apr 7 16:58:00 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 07 Apr 2006 20:58:00 GMT Subject: how you know you're a programming nerd In-Reply-To: <1144441665.834419.202530@e56g2000cwe.googlegroups.com> References: <3GuZf.1940$No6.41580@news.tufts.edu> <1144441665.834419.202530@e56g2000cwe.googlegroups.com> Message-ID: Levi Campbell wrote: > You know you're addicted to a programming language when you have dreams > about it. Me? Addicted? No! Now back to the Python Challenge...... From garabik-news-2005-05 at kassiopeia.juls.savba.sk Sun Apr 16 12:08:55 2006 From: garabik-news-2005-05 at kassiopeia.juls.savba.sk (garabik-news-2005-05 at kassiopeia.juls.savba.sk) Date: Sun, 16 Apr 2006 16:08:55 +0000 (UTC) Subject: Using Python To Create An Encrypted Container References: Message-ID: Michael Sperlle wrote: > Is it possible? Bestcrypt can supposedly be set up on linux, but it seems > to need changes to the kernel before it can be installed, and I have no > intention of going through whatever hell that would cause. > > If I could create a large file that could be encrypted, and maybe add > files to it by appending them and putting in some kind of delimiter > between files, maybe a homemade version of truecrypt could be constructed. > > Any idea what it would take? > you can either use fuse and its python bindings - this is rather trivial filesystem-wise, of course there are challenges in order to implement encryption effectively and efficiently (this is what encfs or phonebook do, but they are written in C) Or implement encrypted network block device in python - again, this should not be _that_ hard. Or implement either nfs or samba server with transparent encrypted storage - this is what (again in C) cfs does. If you go the samba way, it would be even cross-platform - but I have no idea how difficult it would be to implement a samba server in python. In all the cases, performance is going to be THE issue. -- ----------------------------------------------------------- | Radovan Garab?k http://kassiopeia.juls.savba.sk/~garabik/ | | __..--^^^--..__ garabik @ kassiopeia.juls.savba.sk | ----------------------------------------------------------- Antivirus alert: file .signature infected by signature virus. Hi! I'm a signature virus! Copy me into your signature file to help me spread! From me+python at modelnine.org Tue Apr 25 06:48:53 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Tue, 25 Apr 2006 12:48:53 +0200 Subject: OOP / language design question In-Reply-To: <1145961248.794496.80220@j33g2000cwa.googlegroups.com> References: <1145961248.794496.80220@j33g2000cwa.googlegroups.com> Message-ID: <200604251248.53591.me+python@modelnine.org> Am Dienstag 25 April 2006 12:34 schrieb cctv.star at gmail.com: > I was wondering, why you always have to remember to call bases' > constructors explicitly from the derived class constructor? Why hasn't > this been enforced by the language? Because sometimes you don't want to call the base classes constructors? The Python zen says: "Better explicit than implicit," and in this case it hits the nail on the head. Better to see right away what your code does (the explicit call to the base class), than to have to work around calling a bases constructor if you don't want to call it. --- Heiko. From godoy at ieee.org Fri Apr 21 14:51:44 2006 From: godoy at ieee.org (Jorge Godoy) Date: Fri, 21 Apr 2006 15:51:44 -0300 Subject: R Paul Johnson is out of the office. References: <1145644902.203297.124420@e56g2000cwe.googlegroups.com> Message-ID: <2083880.MsSyuGiAPz@jupiter.g2ctech> RK wrote: > ok, who's been playing with mailman? I thought you were going to say something like "I hope he turned off the lights before leaving the office"... :-) -- Jorge Godoy "Quidquid latine dictum sit, altum sonatur." - Qualquer coisa dita em latim soa profundo. - Anything said in Latin sounds smart. From nobody at 127.0.0.1 Fri Apr 21 01:25:48 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Fri, 21 Apr 2006 05:25:48 GMT Subject: perspective on ruby In-Reply-To: <1he41sz.r7aasv1oo5lfN%aleaxit@yahoo.com> References: <1145555339.316764.123210@i39g2000cwa.googlegroups.com> <1he41sz.r7aasv1oo5lfN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > The only "single language" I could see fitting that role is Mozart, > deliberately designed to be SUPER-multi-paradigm -- not even Lisp and > Scheme (the only real competition) can compare. Don't know Mozart. After 5 minutes of googling, it looks like strictly a high-level language. Features like network transparency are jumping the gun for undergrads. But it has potential. > While Mozart appears cool, I really think that a wider variety of > languages would help -- some machine code (possibly abstract a la > Mixal), C (a must, *SO* much is written in it!), at least one of C++, D, > or ObjectiveC, either Scheme or Lisp, either *ML or Haskell, either > Python or Ruby, and at least one "OOP-only" language such as Java, C#, > Eiffel, or Smalltalk. Yeah I agree that more is better. The problem is using a new language every couple courses without bogging down in implementation details. Personally I'd just say "Here's a book, learn it yourself". It's what they gotta do on the job anyway. > For a tipycal CS bachelor course, a set of over > half a dozen languages might be overkill, admittedly (particularly > because these are just the "general purpose" languages -- you no doubt > also want to present XML and friends, possibly XSLT, definitely SQL, and > several other *special*-purpose language classes, too....!!!); too much > time would end up devoted to semirelevant syntax differences... Here's where I disagree. XML? Conceptually (and more elegantly) covered as LISP s-expressions. XSLT? Just a bastardized spawn of Prolog. SQL will be covered in databases. My problem with most domain-specific languages is 1) they're usually too applied for a teaching environment and 2) they're easy to pick up once you master general programming concepts. The one exception that's really invaluable is regular expressions, but those are universal enough they get covered elsewhere. > Absolutely, I'm thinking about CS courses specifically -- for science > and engineering courses, I'd have much different sets (yes, Virginia, > there ARE fields where you still absolutely need to know Fortran!-), for > humanities and soft-sciences other ones yet, and the real world is a > different (and frightening;-) sort of place!-) Yep, I hate how schools lump the CS majors and science majors into one intro programming course. They both need to learn basic programming concepts, but the majors need to understand implementation while the non-majors need productivity. I'd put the majors on something like C and the non-majors on Python (or Fortran if need be). But that won't fly because non-majors who convert would have to retake the class. So maybe put them both on Python and switch languages for the second course. Rougher for the majors, but there's little reason for non-majors to know C/C++/Java/Pascal. Scheme is an interesting option, I'm not sure how that would work out. From notemester at gmail.com Thu Apr 27 08:03:52 2006 From: notemester at gmail.com (=?ISO-8859-1?Q?=D8yvind_=D8stlund?=) Date: Thu, 27 Apr 2006 12:03:52 +0000 Subject: urllib.urlopen() with pages that requires cookies. Message-ID: I am trying to visit a limited amount of web pages that requires cookies. I will get redirected if my application does not handle them. I am using urllib.urlopen() to visit the pages right now. And I need a push in the right direction to find out how to deal with pages that requires cookies. Anyone have any idea how to go about this? Thanks in advance. - ?? - -------------- next part -------------- An HTML attachment was scrubbed... URL: From rpdooling at gmail.com Mon Apr 10 09:14:51 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 10 Apr 2006 06:14:51 -0700 Subject: can't pass command-line arguments References: <1144636890.976327.253000@i39g2000cwa.googlegroups.com> <1144673310.017604.11630@t31g2000cwb.googlegroups.com> Message-ID: <1144674891.187477.235470@i39g2000cwa.googlegroups.com> Tim, I had not seen the thread you linked to. I learned something, but it still doesn't explain whatever is happening on my machine. When I run assoc and ftype I get exactly the results you say I need to run the scripts properly. However, this simple script (printargs.py) seems to work whether I type the .py extention or not. import os import sys print sys.argv print sys.argv[0] print sys.argv[1] print sys.argv[2] Whereas this more complex script (cbfindfiles.py) will NOT work unless I type the .py extension. Otherwise the arguments don't seem to pass. import os import fnmatch import sys def all_files(root, patterns='*', single_level=False, yield_folders=False): """walks the directory tree starting at root and finds all files matching patterns""" # Expand patterns from semicolon-separated string to list patterns = patterns.split(';') for path, subdirs, files in os.walk(root): if yield_folders: files.extend(subdirs) files.sort() for name in files: for pattern in patterns: if fnmatch.fnmatch(name, pattern): yield os.path.join(path, name) break if single_level: break if __name__ == "__main__": for path in all_files(sys.argv[1], sys.argv[2]): print path It's not big deal. I don't mind typing the .py extension. It's just a curious quirk. Thanks for your help. Rick From felipe.lessa at gmail.com Fri Apr 14 14:40:08 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Fri, 14 Apr 2006 15:40:08 -0300 Subject: skip item in list "for loop" In-Reply-To: <4aa88dFs6u2cU1@uni-berlin.de> References: <1145038171.945758.256600@j33g2000cwa.googlegroups.com> <4aa88dFs6u2cU1@uni-berlin.de> Message-ID: <1145040008.10779.22.camel@kenshin.CASA> Em Sex, 2006-04-14 ?s 20:33 +0200, Diez B. Roggisch escreveu: > def read_lines(inFile): > fg = iter(inFile) > for line in fg: > if "pmos4_highv" in line: > fg.next() > else: > yield line Just be aware that the "fb.next()" line can raise an StopIteration exception that would otherwise be caught by the for loop. If you have any resources that need to be cleaned up, try...finally is you friend. -- Felipe. From ldo at geek-central.gen.new_zealand Mon Apr 24 18:04:09 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 25 Apr 2006 10:04:09 +1200 Subject: Looking for resources for making the jump from Java to Python easier and more productive References: <1145691651.385835.298600@u72g2000cwu.googlegroups.com> <444cb3e1$0$21091$626a54ce@news.free.fr> Message-ID: In article <444cb3e1$0$21091$626a54ce at news.free.fr>, bruno at modulix wrote: >Lawrence D'Oliveiro wrote: >> In article <1145691651.385835.298600 at u72g2000cwu.googlegroups.com>, >> "ToddLMorgan" wrote: >> >>>I'm looking for the common types of mistakes that say a Java/C# or >>>even C++ developer may commonly make. >> >> Using subclassing when you don't have to. For instance, you might have a >> Java method which takes an argument of type java.io.OutputStream to >> which it writes. You might translate this to a Python method to which >> you are careful to only pass instances of subclasses of file objects. >> But in fact there is no necessity for this: you are free to pass any >> object which has appropriate members. >> >> I suppose this is an instance of the more general rule: "using OO when >> you don't have to". > >Lawrence, I'm afraid you're confusing OO with "statically-typed >class-based". FWIW, dynamic typing is part of OO since Smalltalk. I wasn't talking about dynamic typing, I was talking about subclassing, which is very much a part of OO. Unless you subscribe to the "OO is whatever looks like a good programming idea" definition . From panos.laganakos at gmail.com Thu Apr 27 13:16:30 2006 From: panos.laganakos at gmail.com (Panos Laganakos) Date: 27 Apr 2006 10:16:30 -0700 Subject: OOP techniques in Python Message-ID: <1146158190.320947.108480@t31g2000cwb.googlegroups.com> I've been thinking if there's a point in applying some specific OOP techniques in Python as we do in other languages. i.e. we usually define private properties and provide public functions to access them, in the form of: get { ... } set { ... } Should we do the same in Python: self.__privateAttr = 'some val' def getPrivateAttr(self): return self.__privateAttr Or there's no point in doing so? Some other techniques come to mind, but I think that Python tends to allow the programmer to access stuff he wants even though he shouldn't or in the form of a dict or list, rather than a method to do so. From thomasbartkus at comcast.net Fri Apr 14 10:21:37 2006 From: thomasbartkus at comcast.net (Thomas Bartkus) Date: Fri, 14 Apr 2006 09:21:37 -0500 Subject: nested functions References: <1145014674.717433.75100@t31g2000cwb.googlegroups.com> Message-ID: wrote in message news:1145014674.717433.75100 at t31g2000cwb.googlegroups.com... > hi > just curious , if i have a code like this? > > def a(): > def b(): > print "b" > def c(): > print "c" > > how can i call c() ?? Your function 'a' is it's own little world where functions 'b' and 'c' exist. Your code inside 'a' can call 'b' or 'c' - neat as you please. BUT 'b' and 'c' simply do not exist outside the 'a' world. This is perfect because you are in control - building worlds according to your own design. Had it not been your intention to hide 'b' and 'c', you would not have isolated them in this manner inside of 'a' . I, for one, am so glad to have nested functions again ;-) Thomas Bartkus From ralf at tecont.de Tue Apr 18 11:26:10 2006 From: ralf at tecont.de (Ralf Muschall) Date: Tue, 18 Apr 2006 17:26:10 +0200 Subject: [OT] Any Python lullabies? In-Reply-To: References: Message-ID: Christos Georgiou wrote: > Since there have been python limmericks, are there any Python lullabies that > I can sing to my newborn son (actually, born yesterday)? I tried to murmur > some select parts from the tutorial, but he somehow wasn't very interested > :) There is something near the end of the Camel book (p. 552ff). This isn't exactly python, but the baby probably won't see the difference. SCNR, Ralf From Mike.S.Duffy at gmail.com Wed Apr 12 02:17:31 2006 From: Mike.S.Duffy at gmail.com (pyGuy) Date: 11 Apr 2006 23:17:31 -0700 Subject: Best way to emulate ordered dictionary (like in PHP)? Message-ID: <1144822651.449335.128970@v46g2000cwv.googlegroups.com> I am dealing with user profiles, which are simply a set of field-value pairs. I've tried to many things to list, but for one, I tried creating a wrapper class which inherits the dictionary and overrides the iterator. Unfortunately I don't understand iterators enough to get this working and before I waste any more time trying I figured I should check wether there is a better way. I have run into a similar problem once, and I resolved it by creating a wrapper class for the 'list' class which overides the get_item method, checks for string parameter, then accesses the appropriate item via a lookup 'list' contained within the class which maps the string parameter to the index number (eh, it just doesn't seem practical though). Now, I'e never used PHP, but apparently, it's dictionaries retain the order in which the items are entered and regurgitates them in that order when you iterate over them. That is exactly what I want, but can't seem to get in Python. Any help? Thanks in advance. From nir1408 at gmail.com Thu Apr 20 10:03:04 2006 From: nir1408 at gmail.com (nir1408 at gmail.com) Date: 20 Apr 2006 07:03:04 -0700 Subject: How to stop winpdb programatically In-Reply-To: References: Message-ID: <1145541784.215970.290460@z34g2000cwc.googlegroups.com> Hello Uwe, You can use rpdb2.settrace() But in fact rpdb2 is not meant to be used like that. the pdb.set_trace() command belongs to the pdb debugging model, of a single threaded script that starts the debugger on demand. In rpdb2/winpdb the debugger works all the time and you break (pause) the script with breakpoints. Nir From python.list at tim.thechases.com Wed Apr 12 22:16:15 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 12 Apr 2006 21:16:15 -0500 Subject: quiet conversion functions Message-ID: <443DB46F.4050804@tim.thechases.com> Are there existing "quiet" conversion functions? Kin of int() and float()? My aim would be to call a function that would guarntee that the result was of the defined type, choosing sensible defaults if needed. Example problems include: int("3.14") int(None) int(__builtins__) int("hello") For the 2nd through 4th examples, I'd consider zero to be a reasonable response from this phantasmic function. For the first one, it would be sensible to return "3". Wrapping it in a float() call: int(float("3.14")) seems a little smarter, but is still more overhead than a mythical justGiveMeAStinkingInt() call. At the moment, I've churned my own helper functions, of the form def CInt(value): try: value = int(value) except (ValueError, TypeError): try: value = int(float(value)) except (ValueError, TypeError): value = 0 return value def CFloat(value): try: value = float(value) except (ValueError, TypeError): value = 0 return value Is there some set of preexisting functions that do this sort of "sensible" conversions without griping about crazy values passed to them? If not, are there other exceptions that might be thrown that I haven't considered yet? It would also be handy to have a CBool that is a little smarter about strings (though I18N'ing it becomes a little trickier...) CBool("Yes") # returns True CBool("No") # returns False CBool("True") # returns True CBool("False") # returns False CBool("Y") # returns True CBool("N") # returns False CBool("T") # returns True CBool("F") # returns False CBool(None) # returns False CBool(1) # returns True for any non-zero CBool(0) # returns False CBool("oui") # returns True? CBool("si") # returns True? CBool("Nyet") # returns False? Any tips in this direction as well? My first shot is something like the rather ugly def CBool(value): if value: # There's prob. a better way # to check if it's a string... if type(value) is type(""): return (value[0].lower() in "ytos") else: return True else: return False Thanks for any tips or hints towards deuglification, -tkc From patrohlf at adelphia.net Sat Apr 8 11:10:29 2006 From: patrohlf at adelphia.net (Pat) Date: Sat, 8 Apr 2006 08:10:29 -0700 Subject: Screen placement based on screen resolution References: Message-ID: Thanks a lot for you response. S "Fredrik Lundh" wrote in message news:mailman.4247.1144476288.27775.python-list at python.org... > "Pat" wrote: > >> I am trying to place a dialog in the center of the screen based on a >> users >> screen resolution. I can get the width and height of the screen, but I >> can't >> seem to use the following: >> >> root.geometry('WxH+X+Y') >> >> It appears the values for X and Y need to be integers and not a variable >> like width/2-40 > > Python doesn't look in string literals for things that might look > like expressions, but if you have the values, *creating* a string > with the right contents is pretty easy. see the tutorial for the > basics: > > http://docs.python.org/tut/node9.html > > if you have all the values in variables, this expression sets the > geometry in one step: > > root.geometry("%dx%d%+d%+d" % (width, height, xoffset, yoffset)) > > also see > > http://effbot.org/tkinterbook/wm.htm#Tkinter.Wm.geometry-method > > which includes code that parses a geometry string. > > > > > From michele.simionato at gmail.com Thu Apr 6 05:02:39 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 6 Apr 2006 02:02:39 -0700 Subject: RELEASED Python 2.5 (alpha 1) In-Reply-To: References: <200604052248.19094.anthony@python.org> <1144244505.471052.115200@i39g2000cwa.googlegroups.com> Message-ID: <1144314159.783939.21300@t31g2000cwb.googlegroups.com> Michael Ekstrand wrote: > Michele Simionato wrote: > > Michael Ekstrand wrote: > >> After reading AMK's survey of what's new in Python 2.5, I am suitably > >> impressed. As usual, I can't wait to start using the cool new > >> features... extended generators? (mind is currently swimming with the > >> question of "can I implement Scheme's call-with-current-continuation > >> using extended generators".) > > > > No. > > Oh well. I'll try not to think too hard about it then. > > The day Python (without using Stackless) has true continuations will be > a happy day. It is interesting that the support for full continuations was removed in recent versions of Stackless (I think there was support in version 1, not in versions 2 and 3, but I am not a Stackless user so please correct me if I am wrong). Coroutines give you more control on your program flow, but not as much as full continuations. With full continuations you can store the current state of your program (with some restrictions, the program should not have side effects or interact with an external environment) and at a later time go back to to that state. In a sense you can go back in time (but only in points that your program has already travelled) whereas with coroutine you can go just in one direction in the time. A nice thing you can do with full continuations is a modal Web server (seehttp://www.double.co.nz/scheme/modal-web-server.html). But this is definitely OT for this thread, so let me stop here ;) Michele Simionato From g.brandl-nospam at gmx.net Thu Apr 6 02:06:20 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Thu, 06 Apr 2006 08:06:20 +0200 Subject: efficiency of range() and xrange() in for loops In-Reply-To: References: Message-ID: Alan Morgan wrote: >>range is giving you a real list, while xrange is giving you an xrange object. >>Have you tried to slice an xrange object? Or using .append on it? > > No, I hadn't. I presume these could all be defined. How would xrange(100).remove(1) work? Georg From rridge at csclub.uwaterloo.ca Wed Apr 5 14:38:34 2006 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: 5 Apr 2006 11:38:34 -0700 Subject: Registration Code In-Reply-To: References: <1144177344.291061.257210@z34g2000cwc.googlegroups.com> Message-ID: <1144262314.023440.33450@e56g2000cwe.googlegroups.com> Steven D'Aprano wrote: > What are the odds that Vista will have it? Ross Ridge wrote; > About 100%. Steven D'Aprano wrote: > Considering that you can hardly walk into a university, school or > corporation without finding Windows or Office supplied without PA, would > you care to revise that number? No. Windows Vista is certain have product activation, just like Windows XP does. The fact that volume licence users of Vista won't be required to use product activatation, just like volume licence users of XP, doesn't make it any less certain. Ross Ridge From jerry2lily at yahoo.com Fri Apr 28 04:58:32 2006 From: jerry2lily at yahoo.com (Jerry Fleming) Date: Fri, 28 Apr 2006 16:58:32 +0800 Subject: python game with curses Message-ID: Hi, I have wrote a game with python curses. The problem is that I want to confirm before quitting, while my implementation doesn't seem to work. Anyone can help me? [code] #!/usr/bin/python # # Brick & Ball in Python # by Jerry Fleming # # This is a small game adapted from that in Motorola Mobile C289, and my first game in python :) # # This progrma is best run under linux. Since Windows port of Python has poor curses support, # play it under Windows is not recommended. If you have no linux box available, try Cygwin, # though it too has poor curses support. # # As I am a newbie to python, please tell me if you have a better implementation or any suggestions. # # TODO: # re-implemente it with wxPython, so one does not have to rely on the ugly curses. # session support. # pausing, especially when confirming # resize terminal at run time # # HISTORY # 2006-04-19: first version # # import curses import _curses import thread from time import sleep from string import split from random import randint # parameters: adjust them to fit you terminal brick_width = 7 brick_gap_x = 1 brick_gap_y = 1 speed = 0.05 # sleep time to control moving speed of the ball pause = 1 # time to pause # terminal initialization stdscr = curses.initscr() curses.noecho() curses.cbreak() curses.curs_set(0) stdscr.keypad(1) screen_height, screen_width = stdscr.getmaxyx() screen_height = screen_height - 1 screen_width = screen_width - 1 brick_rows = screen_height / 4 if brick_rows > 7: brick_rows = 7 brick_cols = (screen_width + brick_gap_x) / (brick_width + brick_gap_x) brick_margin = (screen_width - brick_cols * (brick_width + brick_gap_x) + brick_gap_x)/2 pad_position = randint(0, screen_width - brick_width) ball_position = [screen_height - 3, randint(0, screen_width - brick_width)] ball_direction = [-1, 1] # abs(tan(a)) must be 1 char = '' bricks = [] game_score = 0 ScreenSizeError = 'ScreenSizeError' tStart = ''' ______ _ _ ___ ______ _ _ _ ______ _ (____ \ (_) | | / _ \ (____ \ | | | (_) (_____ \ _ | | ____) ) ____ _ ____| | _ ( (_) ) ____) )_____| | | _ ____ _____) ) _ _| |_| |__ ___ ____ | __ ( / ___) |/ ___) |_/ ) ) _ ( | __ ((____ | | | | | _ \ | ____/ | | (_ _) _ \ / _ \| _ \ | |__) ) | | ( (___| _ ( ( (/ \ | |__) ) ___ | | | | | | | | | | | |_| | | |_| | | | |_| | | | | |______/|_| |_|\____)_| \_) \__/\_) |______/\_____|\_)_) |_|_| |_| |_| \__ | \__)_| |_|\___/|_| |_| (____/ by Jerry Fleming GAME STARTING ... (this assumes that your terminal be larger that 130x40) ''' tExit = ''' 88888 88888 88888888888 88 ad88888ba 88 8b d8 d8 88 88 "" ,d d8" "8b 88 Y8, ,8P ,8P' 88 88 88 "" a8P 88 Y8, ,8P d8" 88 88aaaaa 8b, ,d8 88 MM88MMM ,a8P" 88 "8aa8" ,8P' 8b,dPPYba, 88 88""""" `Y8, ,8P' 88 88 d8" 88 `88' d8" 88P' `"8a 88 88 )888( 88 88 "" 88 88 ,8P' 88 88 88 88 ,d8" "8b, 88 88, aa 88 88 d8" 88 88 88 88888888888 8P' `Y8 88 "Y888 88 88 88 8P' 88 88 88 88888 88888 ''' tOver = ''' ,ad8888ba, 88 d8"' `"8b 88 d8' 88 88 ,adPPYYba, 88,dPYba,,adPYba, ,adPPYba, ,adPPYba, 8b d8 ,adPPYba, 8b,dPPYba, 88 88 88888 "" `Y8 88P' "88" "8a a8P_____88 a8" "8a `8b d8' a8P_____88 88P' "Y8 88 Y8, 88 ,adPPPPP88 88 88 88 8PP""""""" 8b d8 `8b d8' 8PP""""""" 88 "" Y8a. .a88 88, ,88 88 88 88 "8b, ,aa "8a, ,a8" `8b,d8' "8b, ,aa 88 aa `"Y88888P" `"8bbdP"Y8 88 88 88 `"Ybbd8"' `"YbbdP"' "8" `"Ybbd8"' 88 88 ''' tGoon = ''' 88888 88888 ,ad8888ba, ad88888ba 88 8b d8 d8 88 d8"' `"8b d8" "8b 88 Y8, ,8P ,8P' 88 d8' "" a8P 88 Y8, ,8P d8" 88 88 ,adPPYba, ,adPPYba, 8b,dPPYba, ,a8P" 88 "8aa8" ,8P' 8b,dPPYba, 88 88 88888 a8" "8a a8" "8a 88P' `"8a d8" 88 `88' d8" 88P' `"8a 88 Y8, 88 8b d8 8b d8 88 88 "" 88 88 ,8P' 88 88 88 Y8a. .a88 "8a, ,a8" "8a, ,a8" 88 88 aa 88 88 d8" 88 88 88 `"Y88888P" `"YbbdP"' `"YbbdP"' 88 88 88 88 88 8P' 88 88 88 88888 88888 ''' def init_game(): '''Game initializing.''' global bricks # display the bricks for row in range(brick_rows): y = row * (1 + brick_gap_y) for col in range(brick_cols): x = col * (brick_gap_x + brick_width) + brick_margin stdscr.addstr(y, x, ' ' * brick_width, curses.A_REVERSE) bricks.append([y, x]) # move the pad to center of bottom at starting up stdscr.addstr(screen_height - 1, pad_position, ' ' * brick_width, curses.A_REVERSE) # move the ball to left bottom side at starting up stdscr.addstr(ball_position[0], ball_position[1], ' ', curses.A_REVERSE) # display score board stdscr.addstr(screen_height, 0, ' SCORE: '+ ('%03d' % game_score) + ' '* 4, curses.A_REVERSE) stdscr.addstr(screen_height, 15, 'USE q to quit' + ' '* (screen_width - 28), curses.A_REVERSE) # final step to init display stdscr.refresh() def move_pad(lock): '''Move the pad to catch the ball.''' global char, pad_position char = stdscr.getch() if char == ord('q'): quit_game(lock) if char == curses.KEY_LEFT: pad_position = pad_position - 1 if char == curses.KEY_RIGHT: pad_position = pad_position + 1 if pad_position < 0: pad_position = 0 if pad_position >= screen_width - brick_width: pad_position = screen_width - brick_width stdscr.addstr(screen_height - 1, 0, ' ' * screen_width) stdscr.addstr(screen_height - 1, pad_position, ' ' * brick_width, curses.A_REVERSE) stdscr.refresh() def move_ball(lock): '''Move the ball to a direction.''' global ball_position, ball_direction # clear the old position, do not if in pad if ball_position[0] != screen_height - 1: stdscr.addstr(ball_position[0], ball_position[1], ' ') ball_position[0] = ball_position[0] + ball_direction[0] ball_position[1] = ball_position[1] + ball_direction[1] stdscr.addstr(ball_position[0], ball_position[1], ' ', curses.A_REVERSE) detect_collision(lock) stdscr.refresh() sleep(speed) def detect_collision(lock): '''Detect whether the ball has hit something, change direction if yes.''' global bricks, ball_direction, game_score # hit upper wall if ball_position[0] == 0 : ball_direction = [- ball_direction[0], ball_direction[1]] # hit left and right wall if ball_position[1] == 0 or ball_position[1] == screen_width: ball_direction = [ball_direction[0], - ball_direction[1]] # hit brick for brick in bricks: # hit from bottom or upper direction if brick[1] <= ball_position[1] + ball_direction[1] <= brick[1] + brick_width \ and ball_position[0] + ball_direction[0] == brick[0]: ball_direction[0] = - ball_direction[0] stdscr.addstr(brick[0], brick[1], ' '* brick_width) game_score = game_score + 10 stdscr.addstr(screen_height, 8, '%03d' % game_score, curses.A_REVERSE) bricks.remove(brick) # another level to continue the game if not len(bricks): another_level() # hit body of pad if ball_position[0] == screen_height - 2 and pad_position <= ball_position[1] <= pad_position + brick_width: ball_direction[0] = - ball_direction[0] # hit bottom elif ball_position[0] == screen_height - 1: ball_direction[0] = - ball_direction[0] # hit left side of pad (hit bottom already) if ball_position[1] == pad_position and char == curses.KEY_LEFT and ball_direction[1]: ball_direction[1] = - ball_direction[1] # hit right side of pad (hit bottom already) if ball_position[1] == pad_position + brick_width and char == curses.KEY_RIGHT and not ball_direction[1]: ball_direction[1] = - ball_direction[1] # hit bottom wall, game over if ball_position[0] == screen_height - 1 and not pad_position <= ball_position[1] <= pad_position + brick_width: line_num = 0 for line in split(tOver, "\n"): stdscr.addstr(screen_height / 2 + line_num, 10, line) line_num = line_num + 1 stdscr.refresh() curses.flash() sleep(1) curses.flash() sleep(1) lock.release() def quit_game(lock): '''Confirm quit the game.''' global char, speed if char != ord('q'): return speed_old = speed # store the value for resume speed = pause # wait for a long time line_num = 0 for line in split(tExit, "\n"): stdscr.addstr(screen_height / 2 + line_num, 10, line) line_num = line_num + 1 stdscr.addstr(screen_height, 15, 'USE n to continue, any other key to quit' + ' '* (screen_width - 40), curses.A_REVERSE) stdscr.refresh() #char = stdscr.getch() ## fix me: why can't we use the global char? if char == ord('n'): speed = speed_old line_num = 0 for line in split(tExit, "\n"): stdscr.addstr(screen_height / 2 + line_num, 10, ' ' * len(line) ) line_num = line_num + 1 stdscr.refresh() else: lock.release() def another_level(): '''Confirm another level of the game.''' global speed, char speed_old = speed # store the value for resume speed = pause # wait for a long time line_num = 0 for line in split(tGoon, "\n"): stdscr.addstr(screen_height / 2 + line_num, 10, line) line_num = line_num + 1 stdscr.addstr(screen_height, 15, 'USE n to quit, any other key to continue' + ' '* (screen_width - 40), curses.A_REVERSE) stdscr.refresh() #char = stdscr.getch() if char == ord('n'): lock.release() else: stdscr.erase() speed = speed / 2 init_game() def looper(fun, lock): '''Dispatcher to drive th ball and pad.''' try: while lock.locked(): globals()[fun](lock) except _curses.error, diag: if lock.locked(): lock.release() # main loop starts here if __name__ == "__main__": try: line_num = 0 for line in split(tStart, "\n"): stdscr.addstr(screen_height /4 + line_num, 10, line) line_num = line_num + 1 stdscr.refresh() sleep(1) stdscr.erase() init_game() locks = [] for i in range(2): lock = thread.allocate_lock() lock.acquire() locks.append(lock) thread.start_new_thread(looper, ('move_ball', locks[0])) thread.start_new_thread(looper, ('move_pad', locks[1])) while locks[0].locked() and locks[1].locked: pass # main loop except _curses.error, diag: msg = 'Your terminal is too small: ' + str(diag) except 'dd': msg = 'Game exit abnormally.' else: msg = 'Game stopped.' # out of loop means stop for i in range(2): if locks[i].locked(): locks[i].release() height, width = stdscr.getmaxyx() if height - 1 < screen_height or width - 1 < screen_width: msg = 'Your terminal is shrinked.' # out of loop means stop curses.curs_set(1) stdscr.keypad(0) curses.nocbreak() curses.echo() curses.endwin() print msg [/code] From baas at ira.uka.de Thu Apr 13 16:16:48 2006 From: baas at ira.uka.de (Matthias Baas) Date: Thu, 13 Apr 2006 22:16:48 +0200 Subject: ANN: Python cgkit v2.0.0alpha6 & Maya Python package Message-ID: <8cct32ts4q5o88r2riam7rbtnkn3nkcpgn@4ax.com> The sixth alpha release of version 2 of the Python Computer Graphics Kit is available at http://cgkit.sourceforge.net This release also comes with a "preview" version of a Maya Python package that integrates Python into the 3D tool Maya. What is it? ----------- The Python Computer Graphics Kit is a generic 3D package written in C++ and Python that can be used for a variety of domains such as scientific visualization, photorealistic rendering, Virtual Reality or even games. The package contains a number of generic modules that can be useful for any application that processes 3D data. This includes new types such as vectors, matrices and quaternions. Furthermore, the package can read and store 3D models in memory where they can be manipulated by Python programs. The kit comes with tools that can be used to display the scene either interactively or by rendering it offline via a RenderMan renderer. What's new? ----------- - Smoother compilation under OSX - Some new modules like "glslangparams" to read shader parameters from an OpenGL 2 shader source file and "hammersley" to generate Hammersley and Halton points. - Initial support for Lightwave LWOB files. - + more bugfixes and enhancements (see the changelog). Windows binary versions are available for Python 2.3 - 2.5. For more information, visit: http://cgkit.sourceforge.net Feedback is most welcome... - Matthias - From robert.h.boyd at gmail.com Tue Apr 11 20:35:41 2006 From: robert.h.boyd at gmail.com (Robert Boyd) Date: Tue, 11 Apr 2006 20:35:41 -0400 Subject: Help...TT Python 2.4 decompiler In-Reply-To: <003501c65c49$7f16da90$8edbd5a5@LocalHost> References: <003501c65c49$7f16da90$8edbd5a5@LocalHost> Message-ID: On 4/9/06, ??? wrote: > > Hello, > > I am a sofware engineer in Korea. > > Would you kindly give me the way to receive(take) python deccomplier as an > urgent business? > > Thanks for help..^^ > My wife translated your Korean explanation for me - now I have a question for the list. It seems you are an embedded systems developer now working with Python, and you have a question about .pyc files and how to decompile them? Can anyone on the list shed light on this? I'm accustomed to having readable .py files with my .pyc files and I am unfamiliar with any scenario where one would need to turn the byte-compiled version back to the text version. Rob From workbee at gmail.com Sat Apr 8 20:36:14 2006 From: workbee at gmail.com (Enigma Curry) Date: 8 Apr 2006 17:36:14 -0700 Subject: How's python's web scraping capabilities (vs LWP) ... In-Reply-To: <0d7g32tgus9nv8ilbkr10fc7n1pnte3m5f@4ax.com> References: <0d7g32tgus9nv8ilbkr10fc7n1pnte3m5f@4ax.com> Message-ID: <1144542974.671789.111170@i40g2000cwc.googlegroups.com> I don't know much about LWP.. but Beautiful Soup is grand! http://www.crummy.com/software/BeautifulSoup/ Ryan McGuire From vivainio at gmail.com Wed Apr 12 18:22:46 2006 From: vivainio at gmail.com (Ville Vainio) Date: 12 Apr 2006 15:22:46 -0700 Subject: list.clear() missing?!? In-Reply-To: <1144880454.486061.167780@i40g2000cwc.googlegroups.com> References: <1144767680.583085.310160@v46g2000cwv.googlegroups.com> <1144792144.168802.146310@i39g2000cwa.googlegroups.com> <1144870852.886477.238570@u72g2000cwu.googlegroups.com> <1144880454.486061.167780@i40g2000cwc.googlegroups.com> Message-ID: <1144880566.745825.246730@j33g2000cwa.googlegroups.com> Ville Vainio wrote: > Assigning to slices is much less important, and is something I always > never do (and hence forget). ALMOST never, of course. From bartsimpson8882002 at yahoo.com Sat Apr 8 07:12:46 2006 From: bartsimpson8882002 at yahoo.com (bartsimpson8882002 at yahoo.com) Date: Sat, 8 Apr 2006 12:12:46 +0100 Subject: scipy/numpy inverse cumulative normal Message-ID: I was wondering if scipy/numpy has the inverse cumulative normal function, ie the function f in this expression f(scipy.stats.norm.cdf(1.2)) = 1.2 or more generally, a function f which fits the criteria f(scipy.stats.norm.cdf(x)) = x There is a distribution called invnorm, but I am not sure of how to use it. From Medieval.Tours at gmail.com Fri Apr 14 09:39:09 2006 From: Medieval.Tours at gmail.com (Medieval Tours) Date: 14 Apr 2006 06:39:09 -0700 Subject: Discover Medieval Romania /Vlad the Impaler/Dracula/ /www.medievaltours.ro Message-ID: <1145021949.528237.80420@g10g2000cwb.googlegroups.com>
Discover Medieval Romania

We have the pleasure and honour of presenting you
the opportunity to watch and participate in an authentic
medieval show and really discover
Medieval Romania
.

Why Romania?

Could this country located between the Balkans and the Carpathians,
between East and West, provide unforgetable moments?
 

Let me invite you to visit a land with untouched landscapes,
with villages and hospitable people - which rarely would you meet in some
 other countries - with vast flower meadows, with the most beautiful monasteries
 ever seen all over the world, with wonderful bird singing in the
Danube Delta,
 with the unique landscapes, with incomparable wood churches of
Maramures
 and last but not least,  last but not least, the unrivalled Medieval church-fortresses outliving over centuries.
  All this offers you, the traveller in this land, a sensation of timelessness which takes you
 away to far Medieval vanished worlds and yet, so close to you.
.

Let the sensation lead you to this country; try the steam train in the Vaser Valey in the highland of Maramures,
try a ride on the narrow railway in the Apuseni Mountains. Forget about accomodation in a 5***** hotel
and try to sleep overnight in a 100 years' house in the Transylvanian Saxon villages;
 live simply and cleanly for a couple of days in the countryside,
try rustic accomodation in private homes; ask the peasants about pottery, carpet weaving, painting on glass,
egg dyeing and painting. Ask them about the Merry Cemetery and ask them why they meet Death with a smile on their faces;
 have a meal at a sheepfold located in highlands, together with the shepherds and their livestock;
feel at least for one day the Medieval world in the unequaled Fortress of Sighisoara.
At the end of such intense journey you may have the answer to the question:

More info on www.medievaltours.ro



Medieval Art proposes the bringing back to life of precepts that animated the Age of the Knights:
honesty, honour, traditions, manhood, ...as well as relaxation, entertainment,
along with good music and poetry, spiced with deeds of arms, garments of the age,
frolics, words of wisdom - on the whole, a real show, where the guests become protagonists.

 

More on www.medievalart.ro


 

Be a part of this project

In order to take part in this project, you are invited to visit our sites and exchange banners or text links  with us.

www.medievalart.ro

www.medievaltours.ro

For a better position of our websites in Google, also consider links with:

www.astrobar.ro (PR4): Astrobar Project - Your Horoscope in an unconventional millieu

www.yinyangrestaurant.ro (PR3): Chinese Food

www.dontaco.ro (PR3): Mexican Food

From ryang at gol.com Mon Apr 24 19:56:47 2006 From: ryang at gol.com (Ryan Ginstrom) Date: Tue, 25 Apr 2006 08:56:47 +0900 Subject: Counting elements in a list wildcard In-Reply-To: <1145921582.526072.120480@u72g2000cwu.googlegroups.com> Message-ID: <006f01c667fa$bf8fe000$030ba8c0@RYAN> > Behalf Of hawkesed > If I have a list, say of names. And I want to count all the people > named, say, Susie, but I don't care exactly how they spell it (ie, > Susy, Susi, Susie all work.) how would I do this? Set up a regular > expression inside the count? Is there a wildcard variable I can use? > Here is the code for the non-fuzzy way: > lstNames.count("Susie") > Any ideas? Is this something you wouldn't expect count to do? > Thanks y'all from a newbie. If there are specific spellings you want to allow, you could just create a list of them and see if your Suzy is in there: >>> possible_suzys = [ 'Susy', 'Susi', 'Susie' ] >>> my_strings = ['Bob', 'Sally', 'Susi', 'Dick', 'Jane' ] >>> for line in my_strings: ... if line in possible_suzys: print line ... Susi I think a general solution to this problem is to use edit (also called Levenshtein) distance. There is an implementation in Python at this Wiki: http://en.wikisource.org/wiki/Levenshtein_distance You could use this distance function, and normalize for string length using the following score function: def score( a, b ): "Calculates the similarity score of the two strings based on edit distance." high_len = max( len(a), len(b) ) return float( high_len - distance( a, b ) ) / float( high_len ) >>> for line in my_strings: ... if score( line, 'Susie' ) > .75: print line ... Susi -- Regards, Ryan Ginstrom From invalidemail at aerojockey.com Sun Apr 9 11:52:18 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 9 Apr 2006 08:52:18 -0700 Subject: Decorators, Identity functions and execution... In-Reply-To: References: Message-ID: <1144597938.664642.133100@v46g2000cwv.googlegroups.com> Chance Ginger wrote: > On Sun, 09 Apr 2006 09:51:18 +0200, Fredrik Lundh wrote: > > > Chance Ginger" wrote: > > > >> If I define a decorator like: > >> > >> def t(x) : > >> def I(x) : return x > >> return I > > > > ... you get a syntax error. > > > > It isn't a syntax error...I tried it before I posted. In fact > def t(x) : > def I(x) : return x > return I > > is correct. You've made the unfortunate mistake of indenting it with tabs, which do not show up on some newsreaders. I see the tabs in Google; people using Microsoft Outlook do not. Always use spaces when posting, and use them in your code as well. Spaces are the current recommended practice, and in the future tabs might become illegal. I'd prefer tabs myself, but it's more important to respect community standards than to stick to some silly preference you have. > Decorators are a way to add "syntactic" sugar to Python, > extending it in ways that make it useful for tools. What > I am trying to do is lessen the impact on the time used > in executing Python code when I use some forms of decorators. One suggestion. Have you run the script, determined it's too slow, and are trying to optimize? If not (and it doesn't sound like you are), I suggest that it's too soon to worry about whether this decorator has any overhead. You may end up doing a lot of work optimizing that will ultimately have very little benefit. Having said that, this decorator will not affect calling overhead at all. The decorator is applied when the module is loaded, not when the decorated function is called. Carl Banks From callmebill at gmail.com Fri Apr 21 15:50:38 2006 From: callmebill at gmail.com (callmebill at gmail.com) Date: 21 Apr 2006 12:50:38 -0700 Subject: how to append to a list twice? In-Reply-To: References: <4282g.68392$H71.37777@newssvr13.news.prodigy.com> Message-ID: <1145649038.408067.46010@z34g2000cwc.googlegroups.com> I don't get it (the Elliot solution)... How is it that the first value is repeated once times, and the remaining values are repeated twice times? From tprimke at interia.pl Fri Apr 14 05:54:51 2006 From: tprimke at interia.pl (TPJ) Date: 14 Apr 2006 02:54:51 -0700 Subject: A problem with exec statement References: <1144996562.237621.110500@t31g2000cwb.googlegroups.com> Message-ID: <1145008491.056683.134970@i40g2000cwc.googlegroups.com> > Use the exec statement without the in-clause to get the desired effect: > > >>> def f(): > ... a = "a" > ... exec "a = 'B'" > ... print a > ... > >>> f() > B > Well... I *do* realize that. But this is *not* my problem. I have a function with another nested one. If I used "exec ..." instead of "exec ... in some_dict, some_dict" I would get the "SyntaxError: unqualified exec is not allowed in function 'f' it contains a nested function with free variables". To be honest, the message cited above is the answer to the question "Why have I put those globals(), locals() in the exec statments?". From chrisoh at zoominternet.net Thu Apr 27 22:19:35 2006 From: chrisoh at zoominternet.net (Chris Pesarchick) Date: Thu, 27 Apr 2006 22:19:35 -0400 Subject: gcc errors In-Reply-To: <1146155483.787362.58700@t31g2000cwb.googlegroups.com> References: <1146155483.787362.58700@t31g2000cwb.googlegroups.com> Message-ID: Thanks for your help. That is exactly what was wrong. All I had to do was download xcode 2.2.1 and that installed the universal sdk. -Chris On Apr 27, 2006, at 12:31 PM, Simon Percivall wrote: > It doesn't think you're on an intel box, it thinks you want to compile > universal libraries, since you installed a universal python. > > The problem is likely to be that you haven't installed SDK's for intel > as well as powerpc when you installed Apple's Developer Tools. Do > that, > and it should work ... I think. > > -- > http://mail.python.org/mailman/listinfo/python-list From akameswaran at gmail.com Thu Apr 20 14:18:43 2006 From: akameswaran at gmail.com (akameswaran at gmail.com) Date: 20 Apr 2006 11:18:43 -0700 Subject: charting In-Reply-To: <87zmigheo9.fsf@localhost.localdomain> References: <87zmigheo9.fsf@localhost.localdomain> Message-ID: <1145557123.341880.29590@j33g2000cwa.googlegroups.com> I have used matplotlib along with numpy numerics etc for some analysis. Just home projects, but I have found python a much faster/better language for such development than Java. That being said, i have found the network aspects of other apps i've written to be much easier/faster in java. This could be due to my relative inexperience with python networking libraries compared to Java. Python is likely a great choice. If you find some sections of the analytics performing poorly, you can implement those functions in C. A well modularized design in python will lend itself to relatively easy optimization via C libraries if you need them. FYI - I am not a C programmer, but the kind of mathematical functions that get written for optimization typically are trivial in C(meaning I could write them - and I still don't get pointer arithmatic). While Python may not be the "best" language/implementation stack to use. It is likely to still be a "good" choice for the type of app you describe. Is it THE langauge? couldn't tell you, that's decision that also entails a realistic look at the resources you have for development, the overall size/scale of the proposed system. External integration points etc. Additional things to thinka bout are licensing restrictions, IP issues. Is this something you want to sell in the future, a purely in-house tool? Most of my charting has been for personal purposes, so those considerations don't really matter to me - but are something to consider. From kent37 at tds.net Wed Apr 12 08:09:47 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 12 Apr 2006 08:09:47 -0400 Subject: Unicode, command-line and idle In-Reply-To: <443CEAA1.3030907@nord-com.net> References: <1144321375.901932.161330@v46g2000cwv.googlegroups.com> <1144333536.440072.13830@i40g2000cwc.googlegroups.com> <44359427.6080805@v.loewis.de> <1144391227.670210.221930@e56g2000cwe.googlegroups.com> <44363234_2@newspeer2.tds.net> <1144768769.790903.5330@j33g2000cwa.googlegroups.com> <443cd3a3_3@newspeer2.tds.net> <443CEAA1.3030907@nord-com.net> Message-ID: <443CEE0B.8020708@tds.net> Egon Frerich wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > What do you have in the IDLE options - General - Default source encoding? UTF-8 > > Egon > > Kent Johnson schrieb am 12.04.2006 12:40: > >> a.serrano at vielca.com wrote: >>> Hello again, I've investigated a little bit and this is what I found: >>> >>> If I run IDLE and type >>> >>>>>> import sys >>>>>> sys.stdin.encoding >>> I get >>> >>> 'cp1252' >>> >>> But if I have a whatever.py file (it can even be a blank file), I edit >>> it with IDLE, I press F5 (Run Module) and then type: >>> >>>>>> import sys >>>>>> sys.stdin.encoding >>> I get >>> >>> Traceback (most recent call last): >>> File "", line 1, in ? >>> sys.stdin.encoding >>> AttributeError: PyShell instance has no attribute 'encoding' >>> >>> So when I have the following code in a file: >>> >>> # -*- coding: cp1252 -*- >>> import sys >>> text1 = u'espa?a' >>> text2 = unicode(raw_input(), sys.stdin.encoding) >>> if text1 == text2: >>> print 'same' >>> else: >>> print 'not same' >>> >>> and I press F5 (Run Module) I get: >>> >>> Traceback (most recent call last): >>> File "C:\test.py", line 4, in ? >>> text2 = unicode(raw_input(), sys.stdin.encoding) >>> AttributeError: PyShell instance has no attribute 'encoding' >>> >>> This same code works if I just double-click it (run it in the windows >>> console) instead of using IDLE. >>> >>> I'm using Python 2.4.3 and IDLE 1.1.3. >> FWIW all of the above give me 'cp1252', not AttributeError, and the type >> of sys.stdin on my system is idlelib.rpc.RPCProxy, not PyShell. >> >> Python 2.4.3 and IDLE 1.1.3 on Win2k >> >> Kent > > - -- > Egon Frerich, Freudenbergstr. 16, 28213 Bremen > > E-Mail: e.frerich at nord-com.net > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.2.2 (MingW32) > Comment: GnuPT 2.7.2 > Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org > > iD8DBQFEPOpuuTzybIiyjvURAqKTAJ9omGK03L9p5dHpzjqN9Kz1w6cTYACghO6r > VG30LibkskG9M2boF/lTc0s= > =Xl96 > -----END PGP SIGNATURE----- > > > From johnjsal at NOSPAMgmail.com Sun Apr 30 19:33:52 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sun, 30 Apr 2006 19:33:52 -0400 Subject: critique this little script, if you like Message-ID: <44554a32$0$11750$c3e8da3@news.astraweb.com> # Create new subdomain directory (with subdirectories) in my 1and1 folder import os import sys subdirs = [r'\cgi-bin', r'\images', r'\styles'] #if len(sys.argv) == 1: # subdomain = raw_input('Enter subdomain name: ') #else: # subdomain = sys.argv[1] try: subdomain = sys.argv[1] except IndexError: subdomain = raw_input('Enter subdomain name: ') path = r'C:\Documents and Settings\John Salerno\My Documents\My Webs\1and1\johnjsalerno.com\\' + subdomain os.mkdir(path) for subdir in subdirs: os.mkdir(path + subdir) Just a simple script I wrote as an experiment, and it works nicely anyway. My two questions are these: 1. Like my other post, I'm wondering if it's okay to handle the ending backlash as I did in path 2. Between the if block or the try block, which is more Pythonic? The try block seems nicer because it doesn't have such an ugly-looking check to make. From sandravandale at yahoo.com Mon Apr 24 09:53:52 2006 From: sandravandale at yahoo.com (Sandra-24) Date: 24 Apr 2006 06:53:52 -0700 Subject: Can you create an instance of a subclass with an existing instance of the base class? In-Reply-To: References: <1145650105.664762.321560@j33g2000cwa.googlegroups.com> <1145736124.831082.34550@v46g2000cwv.googlegroups.com> <1145801642.764905.30020@v46g2000cwv.googlegroups.com> Message-ID: <1145886832.135894.309770@u72g2000cwu.googlegroups.com> Lawrence D'Oliveiro wrote: > > All you want is a dictionary, then. That's basically what Python objects > are. Yes, that's it exactly. I made a lazy wrapper for it, and I was really happy with what I was able to accomplish, it turned out to be very easy. Thanks, -Sandra From spamspam at spam.eggs Fri Apr 7 13:04:36 2006 From: spamspam at spam.eggs (Ben C) Date: 7 Apr 2006 17:04:36 GMT Subject: UnicodeDecodeError help please? References: Message-ID: On 2006-04-07, Robin Haswell wrote: > Okay I'm getting really frustrated with Python's Unicode handling, I'm > trying everything I can think of an I can't escape Unicode(En|De)codeError > no matter what I try. > > Could someone explain to me what I'm doing wrong here, so I can hope to > throw light on the myriad of similar problems I'm having? Thanks :-) > > Python 2.4.1 (#2, May 6 2005, 11:22:24) > [GCC 3.3.6 (Debian 1:3.3.6-2)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import sys >>>> sys.getdefaultencoding() > 'utf-8' >>>> import htmlentitydefs >>>> char = htmlentitydefs.entitydefs["copy"] # this is an HTML © - a copyright symbol >>>> print char > ? >>>> str = u"Apple" >>>> print str > Apple >>>> str + char > Traceback (most recent call last): > File "", line 1, in ? > UnicodeDecodeError: 'utf8' codec can't decode byte 0xa9 in position 0: unexpected code byte >>>> a = str+char > Traceback (most recent call last): > File "", line 1, in ? > UnicodeDecodeError: 'utf8' codec can't decode byte 0xa9 in position 0: unexpected code byte Try this: import htmlentitydefs char = htmlentitydefs.entitydefs["copy"] char = unicode(char, "Latin1") str = u"Apple" print str print str + char htmlentitydefs.entitydefs is "A dictionary mapping XHTML 1.0 entity definitions to their replacement text in ISO Latin-1". So you get "char" back as a Latin-1 string. Then we use the builtin function unicode to make a unicode string (which doesn't have an encoding, as I understand it, it's just unicode). This can be added to u"Apple" and printed out. It prints out OK on a UTF-8 terminal, but you can print it in other encodings using encode: print (str + char).encode("Latin1") for example. For your search engine you should look at server headers, metatags, BOMs, and guesswork, in roughly that order, to determine the encoding of the source document. Convert it all to unicode (using builtin function unicode) and use that to build your indexes etc., and write results out in whatever you need to write it out in (probably UTF-8). HTH. From pmartin at snakecard.com Mon Apr 10 12:11:53 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Mon, 10 Apr 2006 11:11:53 -0500 Subject: python + access + odbc + linux References: Message-ID: Thanks a lot Felipe. Regards, Philippe Felipe Almeida Lessa wrote: > Em Seg, 2006-04-10 ?s 10:38 -0500, Philippe Martin escreveu: >> I understand that access can be accessed through an ODBC driver under >> windows (instead of Jet). >> >> I am wondering if the same can be done under Linux. > > As far as I know, no. But there is that http://mdbtools.sourceforge.net/ > that may help you, but when I tried I had limited success. > > Cheers, > From sjmachin at lexicon.net Sun Apr 9 21:31:26 2006 From: sjmachin at lexicon.net (John Machin) Date: 9 Apr 2006 18:31:26 -0700 Subject: More pythonic circle? In-Reply-To: <1144628201.383509.249490@i39g2000cwa.googlegroups.com> References: <1144544696.577777.239130@e56g2000cwe.googlegroups.com> <1144560529.697224.151660@e56g2000cwe.googlegroups.com> <1144598199.816461.143540@i39g2000cwa.googlegroups.com> <1144625349.438773.152640@z34g2000cwc.googlegroups.com> <1144628201.383509.249490@i39g2000cwa.googlegroups.com> Message-ID: <1144632686.771246.116230@v46g2000cwv.googlegroups.com> [Pythor] Sure, I tested it. === I don't think that word means what you think it means :-) [Pythor] On the other hand, I'm not having any trouble producing a whole circle, while you seem to think I'm only producing half a circle. The code that limits itself to a 5x5 box is only expected to produce an eighth of the circle. The actual assignment portion uses reflection to plot points in the whole area. If there's some other problem with it, I haven't noticed. === Here's the problem: if field==None: field=numpy.zeros((radius,radius),'u') If radius is 5, field is 5x5 => train smash. From tim.golden at viacom-outdoor.co.uk Thu Apr 27 04:40:29 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 27 Apr 2006 09:40:29 +0100 Subject: blob problems in pysqlite Message-ID: [aldonnelley at gmail.com] | I'm trying to use cPickle.loads(data) (code attached), and I get a: | "TypeError: loads() argument 1 must be string, not list" | | Is there a workaround for this? I've tried converting the | List of files | to a String before cPickling it, but the same result (expected). OK, This one looks more straightforward. The result of fetchall () is a list of tuples (even if it is a list of one tuple and even if that tuple has only one element). This means that KnownFilesResult is a list. cPickle.loads wants a string. You can, obviously, convert the list to a string, but that would only result in something like "[(blah,), (blah,)]" which is clearly not what you want. Depending on what you think you're going to get back, you either need to use fetchone in place of fetchall, which will return one tuple -- in this case containing one buffer -- or you need to iterate over the list, or unpack it, again depending on your expectation of the data. Here, something like this fragment should work (untested): . . # Iterate over the result set and unpack # each tuple into its elements. KnownFilesResult = c.fetchall () for row in KnownFilesResult: (pickled_result,) = row unpickled_result = cPickle.loads (pickled_result) # do things with unpickled result | ps. Tim: Your clean take on my code made me realise that I | had stupidly included quotes in the URL argument passed to | sqlite ... It's the little things that matter... By the way, it's a lot easier for others (like me) to help if you post a self-contained code sample. In both cases, while your explanation has been lucid enough for me to see / guess what's going one, I've had to add bits to your posted code so that they work. It helps if you add enough to the top of the code to -- in this case -- create the table you're using so that all anyone has to do is to cut-and-paste the code into an interpreter. (I realise that I haven't actually done this in return this time, but that's partly because it might obscure the point I'm trying to make and partly because it's a drop-in replacement for your own code). TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From gh at ghaering.de Wed Apr 5 09:39:54 2006 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 05 Apr 2006 15:39:54 +0200 Subject: RELEASED Python 2.5 (alpha 1) In-Reply-To: <4433C764.3060503@elehack.net> References: <200604052248.19094.anthony@python.org> <4433C764.3060503@elehack.net> Message-ID: <4433C8AA.9020308@ghaering.de> Michael Ekstrand wrote: > [...] > Anyway, the more important question that came to mind: I see that 2.5 > will include the excellent ElementTree. Will cElementTree be included > where available? or is it only the pure-Python version that will be in > the standard library? Both elementtree as (xml.etree) and cElementTree (as _elementtree) are included. -- Gerhard From felipe.lessa at gmail.com Fri Apr 21 22:37:28 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Fri, 21 Apr 2006 23:37:28 -0300 Subject: String To Dict Problem In-Reply-To: <1145670029.497083.203360@i40g2000cwc.googlegroups.com> References: <1143394114.182768.192970@g10g2000cwb.googlegroups.com> <1145670029.497083.203360@i40g2000cwc.googlegroups.com> Message-ID: <1145673448.24485.16.camel@kenshin.CASA> Em Sex, 2006-04-21 ?s 18:40 -0700, Clodoaldo Pinto escreveu: > Only a small problem when I try to evaluate this: > > safe_eval('True') Change def visitName(self,node, **kw): raise Unsafe_Source_Error("Strings must be quoted", node.name, node) To otherNames = { 'True': True, 'False': False, 'None': None } def visitName(self, node, **kw): name = node.name try: return self.__class__.otherNames[name] except KeyError: raise Unsafe_Source_Error("Strings must be quoted", name, node) -- Felipe. From johnzenger at gmail.com Thu Apr 27 17:28:33 2006 From: johnzenger at gmail.com (johnzenger at gmail.com) Date: 27 Apr 2006 14:28:33 -0700 Subject: Regular Expression help References: <1146162048.903980.281290@y43g2000cwc.googlegroups.com> <1146172456.106195.243160@j33g2000cwa.googlegroups.com> <1146172914.383277.259940@u72g2000cwu.googlegroups.com> Message-ID: <1146173313.663586.258980@i39g2000cwa.googlegroups.com> If what you need is "simple," regular expressions are almost never the answer. And how simple can it be if you are posting here? :) BeautifulSoup isn't all that hard. Observe: >>> from BeautifulSoup import BeautifulSoup >>> html = '10:00am - 11:00am: ThePrice Is Right] >>> for show in soup('a'): print show.contents[0] The Price Is Right RunLevelZero wrote: > I considered that but what I need is simple and I don't want to use > another library for something so simple but thank you. Plus I don't > understand them all that well :) From g.brandl-nospam at gmx.net Sun Apr 2 15:36:41 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Sun, 02 Apr 2006 21:36:41 +0200 Subject: print() in Python 3000 return value? In-Reply-To: <1144004749.150519.284270@i39g2000cwa.googlegroups.com> References: <1143997643.857261.186430@i40g2000cwc.googlegroups.com> <44300797$0$28451$9b622d9e@news.freenet.de> <1143999680.091690.253340@g10g2000cwb.googlegroups.com> <1144004749.150519.284270@i39g2000cwa.googlegroups.com> Message-ID: bayerj wrote: > Expressions like > >>>> 2 + 2 > > return None, too. Sorry? 2+2 here returns 4, and certainly should with your Python. Georg From quentel.pierre at wanadoo.fr Thu Apr 13 05:00:50 2006 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: 13 Apr 2006 02:00:50 -0700 Subject: New Karrigel page in Wikipedia In-Reply-To: References: <1144867025.095969.92870@e56g2000cwe.googlegroups.com> <1144915559.734587.131140@e56g2000cwe.googlegroups.com> Message-ID: <1144918850.680444.198980@g10g2000cwb.googlegroups.com> I added an entry in Wikipedia for information, just like other Python web frameworks have already done. If the style doesn't fit Wikipedia's I'm sorry and willing to learn how to improve it ; the reason I read was "Obvious, if elaborate, link spam. Really should be speedied, but I can't find a CSD that fits this". I don't really understand why it's called a spam, I don't know what a CSD is and I don't know either who deleted the prod template, not me anyway. I'll take wikipedia people's advice into account anyway From jnair at ensim.com Mon Apr 10 06:54:56 2006 From: jnair at ensim.com (jnair at ensim.com) Date: 10 Apr 2006 03:54:56 -0700 Subject: Is this object counter code pythonic Message-ID: <1144666496.940311.148120@j33g2000cwa.googlegroups.com> My Team Lead says my object counter code seen below is not pythonic class E(object): _count = 0 def __init__(self): E._count += 1 count = property(lambda self: E._count ) def test(): if __name__ == "__main__": e1 = E() print e1.count e2 = E() print e2.count e3 = E() print e3.count test() if not what would be the pythonic way From alainpoint at yahoo.fr Mon Apr 3 09:17:15 2006 From: alainpoint at yahoo.fr (alainpoint at yahoo.fr) Date: 3 Apr 2006 06:17:15 -0700 Subject: DO NOT USE JAVA BECAUSE IT IS NOT OPEN SOURCE References: <1143867556.814290.321740@i40g2000cwc.googlegroups.com> Message-ID: <1144070235.149192.37600@v46g2000cwv.googlegroups.com> Bravo, yoo r write, a propriatary languish is an oxy-moron. I have a rekwest zou: witch languish do yoo rekomend, bikoos yoo seem so a grate programor, at list zis is wat eye beleve, judging by yoo spelling. Alain From s99999999s2003 at yahoo.com Wed Apr 12 07:24:43 2006 From: s99999999s2003 at yahoo.com (s99999999s2003 at yahoo.com) Date: 12 Apr 2006 04:24:43 -0700 Subject: a project to standardize script writing in my environment Message-ID: <1144841083.656362.219000@v46g2000cwv.googlegroups.com> hi in my environment, besides shell scripts written for sys admin tasks, there are shell scripts that call java programs which in turn will do various processing like connecting to databases and doing manipulation of data. My programmers all know only Java and so this is how the java programs come about. Also, some scripts were written in Perl by some admins who left, and successors have difficulty grasping perl syntax and how it works. My intention is to replace these scripts and java programs to python scripts, and in future, any processing of text or running queries to databases will be written in python using relevant modules. Browsing the clp newsgroup on the advantages and comparisons of shell,perl,java and of course python, as the language of choice for writing scripts, i chose python as i think it has many benefits, like readability etc etc... Now i am preparing to write a recommendation to my boss for "endorsing" python as the scripting language of choice. Is it a project worth doing at least for my environment? What are the things that i should consider if i were to go ahead? thanks From jdc at uwo.ca Wed Apr 12 22:00:10 2006 From: jdc at uwo.ca (Dan Christensen) Date: Wed, 12 Apr 2006 22:00:10 -0400 Subject: list.clear() missing?!? In-Reply-To: <1144871740.682517.239660@i40g2000cwc.googlegroups.com> References: <1144767680.583085.310160@v46g2000cwv.googlegroups.com> <1144774431.11151.5.camel@kenshin.CASA> <1144871740.682517.239660@i40g2000cwc.googlegroups.com> Message-ID: <87wtdub5g5.fsf@uwo.ca> Raymond Hettinger writes: > Felipe Almeida Lessa writes: > > > I love benchmarks, so as I was testing the options, I saw something very > > strange: > > > > $ python2.4 -mtimeit 'x = range(100000); ' > > 100 loops, best of 3: 6.7 msec per loop > > $ python2.4 -mtimeit 'x = range(100000); del x[:]' > > 100 loops, best of 3: 6.35 msec per loop > > > > Why the first benchmark is the slowest? I don't get it... could someone > > test this, too? > > It is an effect of the memory allocator and fragmentation. The first > builds up a list with increasingly larger sizes. I don't see what you mean by this. There are many lists all of the same size. Do you mean some list internal to the memory allocator? > It periodically > cannot grow in-place because something is in the way (some other > object) so it needs to move its current entries to another, larger > block and grow from there. In contrast, the other entries are reusing > a the previously cleared out large block. > > Just for grins, replace the first with" > 'x=None; x=range(100000)' > The assignment to None frees the reference to the previous list and > allows it to be cleared so that its space is immediately available to > the new list being formed by range(). It's true that this runs at the same speed as the del variants on my machine. That's not too surprising to me, but I still don't understand why the del variants are more than 5% faster than the first version. Once this is understood, is it something that could be optimized? It's pretty common to rebind a variable to a new value, and if this could be improved 5%, that would be cool. But maybe it wouldn't affect anything other than such micro benchmarks. Dan From t-meyer at ihug.co.nz Sat Apr 22 20:06:32 2006 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Sun, 23 Apr 2006 12:06:32 +1200 Subject: howto py2exe/py2app for self updating application In-Reply-To: <1145711005.836692.10220@v46g2000cwv.googlegroups.com> References: <1145711005.836692.10220@v46g2000cwv.googlegroups.com> Message-ID: <351328A3-C95D-4056-AB42-F2B6C67A3FEA@ihug.co.nz> > I'm creating a GUI program > with wxPython which will be distributed for Mac and Windows. [...] > The program should be able to update itself [...] By default, py2exe puts all the .pyc files used in a zip file. The simplest way to do this it let py2exe do what it normally does. Code all of the .py files as you would when running from source (i.e. you'll never explicitly use zipimport). To update, you then: 1. Download the new .pyc files. 2. Expand (use ZipFile) the existing py2exe zip. 3. Replace the old .pyc files with the new ones. 4. Rezip (use ZipFile) the .pyc files. 5. Replace the old py2xe zip with the one containing the new files. 6. Restart the program. This works (I use a more sophisticated version of this) well with py2exe. I haven't used py2app at all, but if it works much like py2exe, then all of the above still applies (certainly the steps are platform-agnostic). =Tony.Meyer From kadeko at gmail.com Tue Apr 11 09:49:58 2006 From: kadeko at gmail.com (looping) Date: 11 Apr 2006 06:49:58 -0700 Subject: Why new Python 2.5 feature "class C()" return old-style class ? In-Reply-To: <443ba5a9$0$14281$626a54ce@news.free.fr> References: <1144752553.305591.88050@j33g2000cwa.googlegroups.com> <1144756774.177225.311120@z34g2000cwc.googlegroups.com> <443ba5a9$0$14281$626a54ce@news.free.fr> Message-ID: <1144763398.243329.231380@g10g2000cwb.googlegroups.com> bruno at modulix wrote: > looping wrote: > > Peter Hansen wrote: > > > >>Georg Brandl wrote: > >> > >>>class C(): > >>> > >>>is meant to be synonymous with > >>> > >>>class C: > >>> > >>>and therefore cannot create a new-style class. > >> > >>I think "looping" understands that, but is basically asking why anyone > >>is bothering with a change that involves a part of the language that is > >>effectively deprecated. In other words, class(): never used to be > >>valid, so why make it valid now? > >> > >>-Peter > > > > > > Exact. > > But I think that if we make "class C():" a synonym of "class > > C(object):", it will save lot of keystrokes ;-) > > Since the class statement without superclass actually creates an > old-style class, I'd expect the "class MyClass():" variant to behave > the same. Sacrifying readability and expliciteness just to save half a > dozen keystrokes is not pythonic IMHO. > I don't think readability suffer and expliciteness could sometimes be sacrified to simplify the life of developer: ex "abcd"[0:3] -> "abcd"[:3]. And for newbies, the somewhat magic behavior of the "object" superclass is not so clear even that it is very explicit. When I write script I don't use new-style class cause is bother me to type "(object)" when I don't need their features. But in an other hand, I believe that new-style class are faster to instanciate (maybe I'm wrong...). So this new syntax is a good way to boost their uses without bother with compatibility of existing code IMHO. Well I stop to argue now and let Python Dev make their (very good) job. From maha.murali at gmail.com Thu Apr 27 23:56:10 2006 From: maha.murali at gmail.com (Murali) Date: 27 Apr 2006 20:56:10 -0700 Subject: append function problem? In-Reply-To: <1146196184.408569.197960@i40g2000cwc.googlegroups.com> References: <1146196184.408569.197960@i40g2000cwc.googlegroups.com> Message-ID: <1146196570.577607.227940@i40g2000cwc.googlegroups.com> A typo here? seed v/s seed1. Instead of "print(seed.append(5))", try "seed.append(5)" followed by "print seed" -- "print(seed)" also works. The append method does not return the appended value (like many C functions). - Murali From hgk at et.uni-magdeburg.de Sun Apr 9 06:09:48 2006 From: hgk at et.uni-magdeburg.de (Hans Georg Krauthaeuser) Date: Sun, 09 Apr 2006 12:09:48 +0200 Subject: How to determine if a line of python code is a continuation of the line above it In-Reply-To: <1144520644.233293.81050@u72g2000cwu.googlegroups.com> References: <1144520644.233293.81050@u72g2000cwu.googlegroups.com> Message-ID: Sandra-24 wrote: > I'm not sure how complex this is, I've been brainstorming a little, and > I've come up with: > > If the previous line ended with a comma or a \ (before an optional > comment) > > That's easy to cover with a regex > > But that doesn't cover everything, because this is legal: > > l = [ > 1, > 2, > 3 > ] > > and with dictionaries and tuples as well. > > Not sure how I would check for that programmatically yet. > > Is there any others I'm missing? > > Thanks, > -Sandra > Sandra, in a similar situation I used 'inspect' and 'compile' like so: import inspect def func(*arg, **kwarg): return get_cmd() def get_cmd(): frame = inspect.currentframe() outerframes = inspect.getouterframes(frame) caller = outerframes[1][0] ccframe = outerframes[2][0] ccfname = outerframes[2][1] ccmodule = inspect.getmodule(ccframe) slines, start = inspect.getsourcelines(ccmodule) clen = len(slines) finfo = inspect.getframeinfo(ccframe, clen) theindex = finfo[4] lines = finfo[3] theline = lines[theindex] cmd = theline for i in range(theindex-1, 0, -1): line = lines[i] try: compile (cmd.lstrip(), '', 'exec') except SyntaxError: cmd = line + cmd else: break return cmd if __name__ == '__main__': a=0 b="test" c=42 cmd=func(a) print cmd cmd=func(a, b, c) print cmd output: cmd=func(a) cmd=func(a, b, c) Regards Hans Georg From fulvio at pc.jaring.my Tue Apr 18 06:38:03 2006 From: fulvio at pc.jaring.my (Fulvio) Date: Tue, 18 Apr 2006 18:38:03 +0800 Subject: Translate Cpp into python code In-Reply-To: <1145280962.273214.36240@j33g2000cwa.googlegroups.com> References: <1145280962.273214.36240@j33g2000cwa.googlegroups.com> Message-ID: <200604181838.04248.fulvio@pc.jaring.my> Alle 21:36, luned? 17 aprile 2006, Ravi Teja ha scritto: > If you are looking for ways to access C++ code in Python, there are > several (Boost, SIP, CXX, SWIG, Weave etc). This way I knew about it. > People usually convert higher level languages to lower level > languages for performance Frankly I'm not looking for performances, but a viable python script which won't be tied up to a single platform. Those parts of the code which are calling proprietary functions will be removed. Probably the first step to make a port on a multiplatform concept. Another point will be a better chance to learn programming once I got the translation. F From johnjsal at NOSPAMgmail.com Tue Apr 4 13:48:20 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 04 Apr 2006 17:48:20 GMT Subject: how do you use pickle? In-Reply-To: References: <1144167350.837406.172430@i39g2000cwa.googlegroups.com> <1144169459.630621.240510@i40g2000cwc.googlegroups.com> <1144170857.069178.115440@i39g2000cwa.googlegroups.com> Message-ID: John Salerno wrote: > Pythor wrote: > >> Whis is why I said carefully ;) I missed it several times myself when >> I was working on the challenge. > > Ok, frustration has set in again. I see the file name in the source > code, but am I meant to actually access a file, or just use the name > itself? I also had to look up what 'banner' meant in Unix, which wasn't > a very fun thing to have to do for a Python puzzle. Ah, I should have known we weren't done with URL manipulation yet. Now I just need to figure out what to do with this source code. From steven.bethard at gmail.com Fri Apr 28 12:12:45 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 28 Apr 2006 10:12:45 -0600 Subject: OOP techniques in Python In-Reply-To: <0n7352hcbkucdnbgku759n5afnntb0na4v@4ax.com> References: <1146158190.320947.108480@t31g2000cwb.googlegroups.com> <3%84g.4111$B42.3689@dukeread05> <0n7352hcbkucdnbgku759n5afnntb0na4v@4ax.com> Message-ID: Dennis Lee Bieber wrote: > On Thu, 27 Apr 2006 14:32:15 -0500, Philippe Martin > declaimed the following in comp.lang.python: > >> What then is the point of the double underscore (if any) ?: > > To prevent masking/shadowing of inherited attributes... Note that it can fail to do this if you accidentally (or purposefully) name a class the same as a parent or ancestor class: >>> class Confusion(object): ... def __init__(self): ... self.__str = 'module 1' ... def get_module_1_confusion(self): ... return self.__str ... >>> module_1_confusion = Confusion >>> class Confusion(module_1_confusion): ... def __init__(self): ... self.__str = 'module 2' ... >>> module_2_confusion = Confusion >>> module_2_confusion().get_module_1_confusion() 'module 2' So you still need to at least check that the name of your subclass is different from the name of all its ancestors. This doesn't come up that often, but I know a few people have been bitten by it. STeVe From usidoesit at yahoo.com Fri Apr 21 11:02:14 2006 From: usidoesit at yahoo.com (RK) Date: 21 Apr 2006 08:02:14 -0700 Subject: proposed Python logo In-Reply-To: <1145585399.871299.31900@t31g2000cwb.googlegroups.com> References: <1145585399.871299.31900@t31g2000cwb.googlegroups.com> Message-ID: <1145631734.277338.138470@t31g2000cwb.googlegroups.com> That's a good try... Can we get some street pros? http://www.graffitifonts.com/ From onurb at xiludom.gro Tue Apr 11 10:30:10 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 11 Apr 2006 16:30:10 +0200 Subject: Why new Python 2.5 feature "class C()" return old-style class ? In-Reply-To: <1144763398.243329.231380@g10g2000cwb.googlegroups.com> References: <1144752553.305591.88050@j33g2000cwa.googlegroups.com> <1144756774.177225.311120@z34g2000cwc.googlegroups.com> <443ba5a9$0$14281$626a54ce@news.free.fr> <1144763398.243329.231380@g10g2000cwb.googlegroups.com> Message-ID: <443bbdbe$0$15517$626a54ce@news.free.fr> looping wrote: > bruno at modulix wrote: > >>looping wrote: >> >>>Peter Hansen wrote: >>> >>> >>>>Georg Brandl wrote: >>>> >>>> >>>>>class C(): >>>>> >>>>>is meant to be synonymous with >>>>> >>>>>class C: >>>>> >>>>>and therefore cannot create a new-style class. >>>> >>>>I think "looping" understands that, but is basically asking why anyone >>>>is bothering with a change that involves a part of the language that is >>>>effectively deprecated. In other words, class(): never used to be >>>>valid, so why make it valid now? >>>> >>>>-Peter >>> >>> >>>Exact. >>>But I think that if we make "class C():" a synonym of "class >>>C(object):", it will save lot of keystrokes ;-) >> >>Since the class statement without superclass actually creates an >>old-style class, I'd expect the "class MyClass():" variant to behave >>the same. Sacrifying readability and expliciteness just to save half a >>dozen keystrokes is not pythonic IMHO. >> > > > I don't think readability suffer It does. The statement "class X():" imply there's no superclass, so it definitiveley should behave the same as "class X:". > and expliciteness could sometimes be > sacrified to simplify the life of developer: ex "abcd"[0:3] -> > "abcd"[:3]. Here there's no ambiguity. > And for newbies, the somewhat magic behavior of the "object" superclass > is not so clear even that it is very explicit. There's no magic involved here. And I really doubt that having inconsistant behaviour for "class X():" wrt/ "class X:" will help here. > When I write script I don't use new-style class You should. > cause is bother me to > type "(object)" when I don't need their features. Please repeat this 101 times each morning: "thou shall not use old-style classes for they are deprecated". (snip) > So this new syntax is a good way to boost their uses without bother > with compatibility of existing code IMHO. It's mostly a good way to add inconsistency and confusion to a situation that's already confusing enough for newbies. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From girodt at gmail.com Fri Apr 14 04:45:03 2006 From: girodt at gmail.com (Thomas Girod) Date: 14 Apr 2006 01:45:03 -0700 Subject: create pixmap from data Message-ID: <1145004302.946824.14030@v46g2000cwv.googlegroups.com> Hi there. I have a list containing integer values from 0 to 255. With this list I have informations width and height, as width * height = len(my_list) What I want to do is to convert this array into a pixmap of dimension width * height in order to draw it inside a pygtk GUI. Any suggestions about a way to display those informations ? cheers Thomas From betatim at gmail.com Mon Apr 17 03:52:07 2006 From: betatim at gmail.com (Tim Head) Date: 17 Apr 2006 00:52:07 -0700 Subject: Async Sleep? References: Message-ID: <1145260326.953254.100760@t31g2000cwb.googlegroups.com> If your task is indeed to watch a directory for "activity" and thenact upon this activity then you would be much better of doing what Lawrence suggests. For linux there is the inotify bit in the kernel. As you are using win32com I'll assume you are using windows. This snippet in the cookbook seems to do the job http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/156178 if it doesn't do exactly what you wnat have a poke around win32 tim From nephish at xit.net Thu Apr 20 08:47:20 2006 From: nephish at xit.net (nephish at xit.net) Date: 20 Apr 2006 05:47:20 -0700 Subject: freakin out over C++ module in python In-Reply-To: <1145509280.238176.28780@g10g2000cwb.googlegroups.com> References: <1145324978.877495.12580@i40g2000cwc.googlegroups.com> <1145422931.445215.112930@j33g2000cwa.googlegroups.com> <1145431663.153449.53260@v46g2000cwv.googlegroups.com> <1145460274.238373.275710@t31g2000cwb.googlegroups.com> <1145509280.238176.28780@g10g2000cwb.googlegroups.com> Message-ID: <1145537240.541070.38900@e56g2000cwe.googlegroups.com> sounds cool, most stuff i write is strife with try - except thanks for the tip -sk From kent at kentsjohnson.com Sat Apr 1 00:23:38 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Sat, 01 Apr 2006 00:23:38 -0500 Subject: running IDLE from another program? In-Reply-To: <442dba0f$0$11191$c3e8da3@news.astraweb.com> References: <442d7a45$1_2@newspeer2.tds.net> <442dba0f$0$11191$c3e8da3@news.astraweb.com> Message-ID: <442e0913$1_3@newspeer2.tds.net> John Salerno wrote: > Kent Johnson wrote: >>You probably don't need to do that. Just run the file in python >>directly. I don't know UE, but when you configure an external tool, tell >>it to run python.exe and pass the current file as a command line parameter. >> > I've tried a lot of combinations for the command line to execute, but > nothing is working. What format should it be in? Should it look like this: > > C:\Python24\python.exe module ? C:\Python24\python.exe D:\full\path\to\myprogram.py There is a post on the UltraEdit forum from JohnJSal, is that not you? Whoever it is got this working... http://www.ultraedit.com/index.php?name=Forums&file=viewtopic&t=2732&highlight=python Kent From aahz at pythoncraft.com Tue Apr 18 13:51:04 2006 From: aahz at pythoncraft.com (Aahz) Date: 18 Apr 2006 10:51:04 -0700 Subject: 2.5 excitement (was Re: Java Developer Exploring Python) References: <1145290449.735642.120860@i40g2000cwc.googlegroups.com> <1204021.LzRF60KP7e@jupiter.g2ctech> Message-ID: In article <1204021.LzRF60KP7e at jupiter.g2ctech>, Jorge Godoy wrote: >Aahz wrote: >> In article , >> Roy Smith wrote: >>> >>>Indeed, I think the inclusion of ctypes is far and away the most exciting >>>thing in 2.5. >> >> Really? More than pysqlite? > >To me much more. After all, why would I need pysqlite if I use >PostgreSQL? ;-) Heh. Since we're just finally turning in our 100% first draft of Python for Dummies, I tend to think more in terms of what a Python newbie will find useful. On that front, I think that pysqlite is much more important because it finally gets rid of the excuse for using Berkeley for simple database purposes. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "LL YR VWL R BLNG T S" From robert.kern at gmail.com Tue Apr 25 02:58:04 2006 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 25 Apr 2006 01:58:04 -0500 Subject: MinGW and Python In-Reply-To: References: <1145861223.509630.247350@y43g2000cwc.googlegroups.com> <444C79D7.4060007@v.loewis.de> Message-ID: Brian Elmegaard wrote: > Robert Kern writes: > >>the gcc project is to provide a portable compiler, not one that >>generates the best code for any given platform. And in that goal, it >>succeeds remarkably well. > > Will a python program be slower on the same machine running windows > compared to linux? Dunno. Depends on the machine. Depends on the program. Depends on how the interpreter and any extension modules and underlying libraries were built. Depends on which Linux and which Windows. I'm sorry, but your question is a non sequitur. I don't understand its relevance to this thread. > What I don't understand is that it is not possible to distribute a > python compiled with gcc for windows. The main reason I saw in this > thread is that python uses mfc. So python requires api access, I > guess. It is possible. People have done it. http://jove.prohosting.com/iwave/ipython/pyMinGW.html > Once I asked about distutils here. Okay. Again, what's the relevance here? > The answer was that I had access to > the source so I could just extend it. After messing around I found I > couldn't because I don't have msvc. I'm not sure why this matters since distutils is pure Python. If you meant writing extension modules for Python instead of extending distutils, then you're in luck! You can indeed build extension modules with mingw for the standard Python distribution. Please see my post in the thread "MS VC++ Toolkit 2003, where?". -- Robert Kern robert.kern at gmail.com "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From k.r.fry at durham.ac.uk Mon Apr 3 07:33:27 2006 From: k.r.fry at durham.ac.uk (k r fry) Date: Mon, 03 Apr 2006 12:33:27 +0100 Subject: Oserror: [Errno 20] Message-ID: Hi, I am new to this list and also programming with python. I have an error: oserror [errno 20] not a directory "katiescint.py" The piece of code causing the problem is: [code] for subdir in os.listdir(DATADIR): #loop through list of strings file=FITS.Read(DATADIR+'/'+subdir+'/flux.fits') #opens flux.fits file and reads summation=open(DATADIR+'/'+subdir+'/flux.dat','w') #opens the summation results file for writing to spotbyspot=open(DATADIR+'/'+subdir+'/spotflux.dat','w') #opens the spot-by-spot file for writing to output='' print'\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n'+sys.argv[1]+' '+subdir+'\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n' [/code] The first line is the one with the error. Can anyone help? Thanks! From kruhftREMOVE at gmail.com Mon Apr 10 01:44:38 2006 From: kruhftREMOVE at gmail.com (Burton Samograd) Date: 09 Apr 2006 23:44:38 -0600 Subject: how to pipe to variable of a "here document" References: <1144641459.230416.104590@v46g2000cwv.googlegroups.com> Message-ID: <87fykmm1bt.fsf@gmail.com> eight02645999 at yahoo.com writes: > I need to execute sql command using a "here document" like in unix. > > os.popen("osql", "w").write("""\ > select * from table > go > """) > > how can i pipe these result of the select into a variable? popen doesn't work that way. you can only open them read or write. you'll have to create a couple of pipes (one for reading, one for writing), do a fork, execve, etc with the posix api. at least that's how one does it in C...i'm a bit new to python so there might be better ways. -- burton samograd kruhft .at. gmail kruhft.blogspot.com www.myspace.com/kruhft metashell.blogspot.com From bj_666 at gmx.net Fri Apr 28 16:56:15 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 28 Apr 2006 22:56:15 +0200 Subject: Can you create an instance of a subclass with an existing instance of the base class? References: <1145650105.664762.321560@j33g2000cwa.googlegroups.com> <1145736124.831082.34550@v46g2000cwv.googlegroups.com> <1145801642.764905.30020@v46g2000cwv.googlegroups.com> <444d4b92$0$7905$636a55ce@news.free.fr> Message-ID: In , Lawrence D'Oliveiro wrote: > In article <444d4b92$0$7905$636a55ce at news.free.fr>, > Bruno Desthuilliers wrote: > >>Nope. I mean : they don't overuse OO, they overuse *classes*. AFAIK, OO >>means *object* oriented - not class oriented. > > Oh great. Now we have someone redefining the concept of OO to evade the > point I was making. > >>There are OO languages that don't even have a notion of class. > > Sounds like stuff I was doing in C (a non-OO language) years ago. Unless > you want to count C as an OO language, I think you're going to have to > retract this claim. That sounds like stuff you do in a language that has objects but no classes. As C has no objects I would not count it as an OO language. But I count Io as an OO language:: #!/usr/bin/env io Foo := Object clone Foo value := 42 Foo setValue := method(newValue, self value = newValue; self) Foo beep := method("beep" linePrint) Foo asString := method("I'm a Foo. My value is " .. self value) Bar := Foo clone Bar asString := method("I'm a Bar and " .. super asString) foo := Foo clone foo beep foo asString linePrint bar := Bar clone setValue(23) bar beep bar asString linePrint Output is: beep I'm a Foo. My value is 42 beep I'm a Bar and I'm a Foo. My value is 23 That's OO IMHO. Clonable objects that know their "ancestors" so you can build an object hierarchy. Missing attributes are looked up in the "ancestors" and one can explicitly look up the inheritance tree with ``super``. There are no classes, just four objects. Convention in naming and usage makes two of them something like templates or "classes" for new objects but they are in no way special. Ciao, Marc 'BlackJack' Rintsch From g.horvath at gmx.at Fri Apr 28 00:20:56 2006 From: g.horvath at gmx.at (Gregor Horvath) Date: Fri, 28 Apr 2006 06:20:56 +0200 Subject: Protocols for Python? In-Reply-To: <1146165988.887502.243810@v46g2000cwv.googlegroups.com> References: <1146165988.887502.243810@v46g2000cwv.googlegroups.com> Message-ID: redefined.horizons at gmail.com schrieb: > > Is there a standard way to document protocols in Python? Of should I > come up with something tailored to my needs. > Write unittests or doctest strings. -- Servus, Gregor http://www.gregor-horvath.com From rpdooling at gmail.com Wed Apr 12 21:05:07 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 12 Apr 2006 18:05:07 -0700 Subject: can't pass command-line arguments References: <1144676885.317592.21780@e56g2000cwe.googlegroups.com> Message-ID: <1144890307.089706.111610@g10g2000cwb.googlegroups.com> Peter Hansen wrote: > But it is. To help others. Perhaps what you are encountering is a real > bug, and solving it could avoid us having to deal with the same issue in > the future (though it seems more likely it's something special to your > case, but at least then we'll have a clear answer). Please reconsider > and investigate further. Peter! You were right. It WAS a bug. See Trent's post: http://groups.google.com/group/comp.lang.python/browse_frm/thread/506df1e4404353f0/c927a5585baf55f3#c927a5585baf55f3 Man, this is a big day for me. I was convinced this thread was going to end with: "You moron! Don't you realize that is a lambda class inheritance instance generator of a Pythonic deprecation!" Thanks for the help and the education. Rick http://dooling.com From steven.bethard at gmail.com Thu Apr 6 15:22:52 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 06 Apr 2006 13:22:52 -0600 Subject: pre-PEP: The create statement In-Reply-To: References: <59Wdnbd8EazRCqnZnZ2dnUVZ_vudnZ2d@comcast.com><1144328362.729594.173160@z34g2000cwc.googlegroups.com> <1144331431.696334.248850@u72g2000cwu.googlegroups.com> Message-ID: Terry Reedy wrote: > "Michele Simionato" wrote in message > news:1144331431.696334.248850 at u72g2000cwu.googlegroups.com... >> This is a very relevant question. I would expect the new keyword would >> break lots >> of modules. However measuring is better than speculating. > > Please run also with alternatives, such as 'make'. I ran a check on my stdlib with 'make' and all I got was: $ count_names.py make "C:\Program Files\Python\Lib" *** C:\Program Files\Python\Lib\site-packages\win32\test\handles.py *** line 73: def make(): line 77: make() Found 2 occurrences of 'make' So it only happens in testing code in the stdlib, which isn't bad breakage-wise as far as I'm concerned. So it looks like 'make' is a much better option. I'll probably update the PEP and the patch to use 'make' soon unless I hear good reasons not to. FWIW, here's what I got with 'create': $ count_names.py create "C:\Program Files\Python\Lib" *** C:\Program Files\Python\Lib\imaplib.py *** line 379: def create(self, mailbox): *** C:\Program Files\Python\Lib\bsddb\dbtables.py *** line 132: def __init__(self, filename, dbhome, create=0, truncate=0, mode=0600, line 140: if create: *** C:\Program Files\Python\Lib\bsddb\test\test_dbtables.py *** line 54: filename='tabletest.db', dbhome=homeDir, create=1) *** C:\Program Files\Python\Lib\distutils\cmd.py *** line 312: def get_finalized_command (self, command, create=1): line 318: cmd_obj = self.distribution.get_command_obj(command, create) *** C:\Program Files\Python\Lib\distutils\dist.py *** line 828: def get_command_obj (self, command, create=1): line 835: if not cmd_obj and create: *** C:\Program Files\Python\Lib\lib-tk\Tkinter.py *** line 1569: self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use) *** C:\Program Files\Python\Lib\test\test_mhlib.py *** line 264: def create(n): line 268: create(7) line 269: create(8) line 270: create(9) line 285: create(10) line 286: create(11) line 287: create(12) *** C:\Program Files\Python\Lib\test\test_site.py *** line 75: pth_file.create() line 88: pth_file.create() line 109: def create(self): Found 19 occurrences of 'create' And here's my slightly modified version of Michele's script: import glob import optparse import os import sys import token import tokenize def count_name(name, filename): "Count the occurrences of a Python name in a script" counter = 0 tokens_gen = tokenize.generate_tokens(open(filename).readline) for tok_code, tok_value, (srow, scol), _, line in tokens_gen: if tok_code == token.NAME and tok_value == name: if not counter: print '*** %s ***' % filename counter += 1 print 'line %s: %s' %(srow, line), return counter if __name__ == '__main__': parser = optparse.OptionParser(usage='%prog name dir [dir ...]') options, args = parser.parse_args() try: name = args[0] args[1] # trigger an IndexError if no dirs are provided dirnames = args[1:] except IndexError: parser.error('wrong number of arguments') total = sum(count_name(name, os.path.join(dirpath, filename)) for dirname in dirnames for dirpath, _, filenames in os.walk(dirname) for filename in filenames if filename.endswith('.py')) print 'Found %d occurrences of %r' % (total, name) STeVe From anton.vredegoor at gmail.com Fri Apr 28 09:43:37 2006 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Fri, 28 Apr 2006 15:43:37 +0200 Subject: not quite 1252 In-Reply-To: <445214a1$1@usenet.zapto.org> References: <444f5e6b$1@usenet.zapto.org> <444f8781@usenet.zapto.org> <44507F68.7080804@lexicon.net> <4450e193$1@usenet.zapto.org> <1146228498.056632.168360@j73g2000cwa.googlegroups.com> <445214a1$1@usenet.zapto.org> Message-ID: <44521ab6$1@usenet.zapto.org> Anton Vredegoor wrote: > So, probably yes. If it doesn't have a text attribrute if you iterate > over it using OOopy for example: Sorry about that, I meant if the text attribute is None, but there *is* some text. Anton From rrr at ronadam.com Sat Apr 8 02:53:29 2006 From: rrr at ronadam.com (Ron Adam) Date: Sat, 08 Apr 2006 01:53:29 -0500 Subject: how you know you're a programming nerd In-Reply-To: <443734db$0$782$c3e8da3@news.astraweb.com> References: <3GuZf.1940$No6.41580@news.tufts.edu> <88FZf.44$B42.34@dukeread05> <443734db$0$782$c3e8da3@news.astraweb.com> Message-ID: John Salerno wrote: > Ron Adam wrote: >> When you are working on your programming project on Friday night >> instead of going out. > > Ok, you win. :) > > Oh wait, it's Friday night and I'm typing this message...dang it! Yep, Hah Hah... No wait, I'm here too. ;-) From jena.forum at centrum.cz Fri Apr 14 10:14:28 2006 From: jena.forum at centrum.cz (Jan Prochazka) Date: Fri, 14 Apr 2006 16:14:28 +0200 Subject: zlib && zip files Message-ID: <443FAE44.2020706@centrum.cz> Hi, I need to decompress zip archive. I wrote a parser of zip file, i obtain the compressed data, but when i call zlib.decompress(data) on them, it throws this error: decbuf = decompressor.decompress(compressed_data) error: Error -3 while decompressing: unknown compression method I try to compress by zlib the same data which are in that file, the result was 6 bytes bigger, '\x78\xda' on begin and '\xc9\x1f\x87\x0b' on end when i tried to put this extending data to zlib decompressor, it decompress some files of zip archive, but it fails, when i try to decompress 100MB file from archive could you help, please? thanks Honza From brian at sweetapp.com Mon Apr 17 06:10:15 2006 From: brian at sweetapp.com (Brian Quinlan) Date: Mon, 17 Apr 2006 12:10:15 +0200 Subject: XML-RPC server via xinetd In-Reply-To: <20060417115550.A22145@xos037.xos.nl> References: <4442a56a$0$31651$e4fe514c@news.xs4all.nl> <4442dc54$0$31651$e4fe514c@news.xs4all.nl> <20060417115550.A22145@xos037.xos.nl> Message-ID: <44436987.4020407@sweetapp.com> Jos Vos wrote: > The problem is that I do not see how to let an SimpleXMLRPCServer > instance *not* bind to a port or what other class I can use to just > build a XML-RPC request handler reading/writing from stdin/stdout, > i.s.o. carrying all the server class stuff with it. I think that the problem here is that we are confusing transport with request handling. If you take a look at CGIXMLRPCRequestHandler (http://docs.python.org/lib/node564.html), you will see an example of how to write an XMLRPCRequestHandler without HTTP. Cheers, Brian From pecoraREMOVE at THISanvil.nrl.navy.mil Thu Apr 6 07:01:14 2006 From: pecoraREMOVE at THISanvil.nrl.navy.mil (Lou Pecora) Date: Thu, 06 Apr 2006 07:01:14 -0400 Subject: python on Mac References: <1144284073.446005.53950@t31g2000cwb.googlegroups.com> Message-ID: In article , James Stroud wrote: > Thomas Nelson wrote: > > I just purchased a new macbook (os 10.4.6), and I'm trying to install > > python 2.4 on it. I downloaded and ran the two installers recommended > > at http://www.python.org/download/mac/. Now I have IDLE, which runs > > 2.4.1, but typing "python" at a terminal still opens 2.3.5, because it > > points to /usr/bin/python. Is there a way to run python 2.4 without > > idle? If I want to do a unix style script, something like > > #!/usr/bin/python > > print "hello world" > > what can I put on the first line that will cause python 2.4 to > > interpret my code? > > > > Thanks a lot. > > THN > > > > The python in /usr/bin is a link (to a link). You can do this: > > sudo rm /usr/bin/python > sudo ln -s \ > /System/Library/Frameworks/Python.framework/Versions/2.4/bin/python \ > /usr/bin/python YIKES! Don't do that. Don't mess with Apple's python. Not recommended. Check the MacPython FAQ and Wiki pages. Python 2.4 was installed in /usr/local/bin. You should put that in your $PATH variable Before /usr/bin. That will cause the new Python to be launched. -- Lou Pecora (my views are my own) REMOVE THIS to email me. From phpbird at gmail.com Wed Apr 5 11:57:34 2006 From: phpbird at gmail.com (Ju Hui) Date: 5 Apr 2006 08:57:34 -0700 Subject: is there any bug in this multi-thread script? Message-ID: <1144252654.358951.275720@t31g2000cwb.googlegroups.com> I wrote a script to do work with multi-thread in a queue reference others code. Is there any bug in this script? another question is : when we call start to run one thread extends from threading, it will call a join() by itself? I want to monitor the qsize() to ensure all work are finished. but when I commented the #############code start while q.qsize()>0: time.sleep(0.1) #############code end it works well too. any response is welcome. Thanks a lot. #############code start #!/usr/bin/env python import Queue import threading import time import random q=Queue.Queue(0) NUM_WORKERS = 3 class MyThread(threading.Thread): """A worker thread.""" def __init__(self, input, worktype): self._jobq = input self._work_type = worktype threading.Thread.__init__(self) def run(self): """ Get a job and process it. Stop when there's no more jobs """ while True: if self._jobq.qsize()>0: job = self._jobq.get() worktype=self._work_type self._process_job(job,worktype) else: break def _process_job(self, job,worktype): """ Do useful work here. worktype: let this thread do different work 1,do list 2,do item 3,,, """ doJob(job) def doJob(job): """ do work function 1 """ time.sleep(random.random()*3) print "doing ",job if __name__=='__main__': print "begin..." #put some work to q for i in range(NUM_WORKERS*2): q.put(i) #print total job q's size print "job q'size",q.qsize() #start threads to work for x in range(NUM_WORKERS): MyThread(q,x).start() #if q is not empty, wait #while q.qsize()>0: # time.sleep(0.1) From robert.kern at gmail.com Sun Apr 23 18:31:13 2006 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 23 Apr 2006 17:31:13 -0500 Subject: Generate a sequence of random numbers that sum up to 1? In-Reply-To: <1he93fn.5i2fpj162hs9uN%aleaxit@yahoo.com> References: <1145825688.099549.195040@j33g2000cwa.googlegroups.com> <1he93fn.5i2fpj162hs9uN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > fumanchu wrote: > >>I'm surprised noone has pursued a course of subtraction rather than >>division. Say you want 10 numbers: >> >>>>>s = 1.0 >>>>>n = [] >>>>>for x in xrange(9): >> >>... value = random.random() * s >>... n.append(value) >>... s -= value >>... >> >>>>>n.append(s) >>>>>n >> >>[0.7279111122901516, 0.082128708606867745, 0.0080516733577621798, >>0.12122060245902817, 0.0034460458833209676, 0.0021046234724371184, >>0.054109424914363845, 0.00035750970249204185, 0.00051175075536832372, >>0.00015854855820800087] >> >>>>>sum(n) >> >>1.0 >> >>Either: >> 1) Just because they're *ordered* doesn't mean they're not *random*, >>or >> 2) You all now know why I'm not a mathematician. ;) >> >>It seems to me that the only constraint on the randomness of my results >>is the OP's constraint: that they sum to 1. I'd be fascinated to learn >>if and why that wouldn't work. > > n[0] is uniformly distributed between 0 and 1; n[1] is not -- not sure > how to characterize its distribution, but it's vastly skewed to favor > smaller values -- and further n[x] values for x>1 are progressively more > and more skewed similarly. > > Such total disuniformity, where the very distribution of each value is > skewed by the preceding one, may still be "random" for some sufficiently > vague meaning of "random", but my intuition suggests it's unlikely to > prove satisfactory for the OP's purposes. [digression] All of this discussion about whether the distribution of values is uniform or not doesn't mean much until one has defined "uniformity," or equivalently, "distance" in the space we're talking about. In this case, we're talking about the unit n-simplex space (SS^n) which has elements S=(s_1, s_2, ... s_n) where sum(S) = 1 and s_i >= 0. I favor the Aitchison distance: import numpy as np def aitchison_distance(x, y): """ Compute the Aitchison distance between two vectors in simplex space. """ lx = np.log(x) ly = np.log(y) lgx = np.mean(lx, axis=-1) lgy = np.mean(ly, axis=-1) diff = (lx - lgx) - (ly - lgy) return np.sqrt(np.sum(diff*diff)) Note that zeros yield inifinities, so the borders of the unit simplex are infinitely farther away from other points in the interior. Consequently, generating "uniform" random samples from this space is as impractical as it is to draw "uniform" random samples from the entire infinite real number line. It's also not very interesting. However, one can transform SS^n into RR^(n-1) and back again, so drawing numbers from a multivariate normal of whatever mean and covariance you like will give you "nice" simplicial data and quite possibly even realistic data, too, depending on your model. I like using the isometric log-ratio transform ("ilr" transform) for this. Good Google search terms: "compositional data", Aitchison But of course, for the OP's purpose of creating synthetic Markov chain transition tables, generating some random vectors uniformly on [0, 1)^n and normalizing them to sum to 1 works a treat. Don't bother with anything else. -- Robert Kern robert.kern at gmail.com "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From mensanator at aol.com Sat Apr 8 22:27:27 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 8 Apr 2006 19:27:27 -0700 Subject: programming puzzles? In-Reply-To: <1144543413.421821.132730@e56g2000cwe.googlegroups.com> References: <44381f2f$0$4209$c3e8da3@news.astraweb.com> <1144532090.213069.191600@i39g2000cwa.googlegroups.com> <4438428e$0$11362$c3e8da3@news.astraweb.com> <1144543413.421821.132730@e56g2000cwe.googlegroups.com> Message-ID: <1144549647.938771.272110@g10g2000cwb.googlegroups.com> Michael Tobis wrote: > The first piece of code that I ever voluntarily wrote was intended to > solve this puzzle: > > Assign the number 2 to 'a', 3 to 'b' ... 27 to 'z'. To each word assign > the value of the product of its characters. Find the English (or > language of your choice) word whose product is closest to a million (or > number of your choice). > > I didn't have a lexicon handy. So I just printed out the letter > combinations closest to a million and manually played Jumble with them. > This was on a PDP-11 using Fortran, so you should have no problem doing > this in Python. > > The prize was a VCR, which was a big deal in those days, but I didn't > have a Green Card yet, so I didn't submit my answer, for (probably > unfounded) fear the immigration authorities would give me a hard time > for unauthorized income. My answer returned > 999856 for its product. Can you do better? dioxid = 1000000 ixodid = 1000000 > > You can go further. If you have a unix-like system you already have a > lexicon, probably at /usr/share/dict/words . Also check out www.puzzlers.org. There, and other places, you can find word lists, such as the one I used above to find words that numify to exactly 1000000. > > Compare various ways to solve this problem for performance, for > arbitrary ciphers, which you can pass in as a dictionary like > {'a':2,'b':4,'c':5 .... etc. > > To get you started here's the calculation, which may be interesting in > itself. I don't have the Fortran, but I'm sure it was MUCH longer than > this! > > ##### > cipher0= {} > > for i in range(ord('a'),ord('z')+1): > cipher0[chr(i)] = i - ord('a') + 2 > > from operator import mul > > def numify(word,cipher=cipher0): > return reduce(mul,[cipher[c] for c in word]) > > if __name__ == "__main__": > print numify("hello") > > # prints 146016 > > #### > > mt From sjmachin at lexicon.net Fri Apr 28 00:21:40 2006 From: sjmachin at lexicon.net (John Machin) Date: Fri, 28 Apr 2006 14:21:40 +1000 Subject: raw_input passing to fun In-Reply-To: <877j5agxca.fsf@localhost.localdomain> References: <877j5agxca.fsf@localhost.localdomain> Message-ID: <44519854.6@lexicon.net> On 28/04/2006 2:04 PM, Gary Wessle wrote: > > the output of this code below is not what one would expect, it outputs > all kind of numbers and it never stops, I want to ask the user for a > number and then print out the multiplication table up to that number. That's what you want, but not what you did. You asked them for a string. > > thanks > > **************************************************************** > import math Not used. > > def printMultiples(n, hight): > i = 1 > while i <= hight: > print n*i, '\t', > i = i + 1 > print > > > def printMultTable(hight): > i = 1 > while i <= hight: Temporarily, insert here: print "types:", type(i), type(hight) print "values:", i, hight if i > 100: return > printMultiples(i, i) > i = i + 1 > > num = raw_input ("produce a multiplication table up to: ") > printMultTable(num) Try this: printMultTable(int(num)) You may wish to consider changing "hight" to "height" :-) From brian at sweetapp.com Mon Apr 17 06:36:18 2006 From: brian at sweetapp.com (Brian Quinlan) Date: Mon, 17 Apr 2006 12:36:18 +0200 Subject: XML-RPC server via xinetd In-Reply-To: <20060417122001.B22258@xos037.xos.nl> References: <20060417122001.B22258@xos037.xos.nl> Message-ID: <44436FA2.1090709@sweetapp.com> Jos Vos wrote: > On Mon, Apr 17, 2006 at 03:30:04AM -0500, Nick Craig-Wood wrote: > >> UTSL ;-) >> >> Look at /usr/lib/python2.4/SimpleXMLRPCServer.py (adjust as per your >> distro) and in particular the definition of the CGIXMLRPCRequestHandler class. > > I did this before posting my question, in fact, but I did not look > good enough maybe, as at first sight I thought tghe CGI... class > would be too CGI-specific (it looks for environment variables etc. > given by the HTTP server), but maybe it's good enough. I don't know exactly what your usage pattern is, but you might be able to use SimpleXMLRPCDispatcher directly e.g. >>> s = SimpleXMLRPCDispatcher() >>> s.register_function(pow) >>> s._marshaled_dispatch('<1144560529.697224.151660@e56g2000cwe.googlegroups.com> <1144598199.816461.143540@i39g2000cwa.googlegroups.com> Message-ID: "Pythor" wrote: > > You aren't getting any benefit from numpy or python here. Are you > > aiming for speed or legibility? > > > Speed will be a necessity, eventually. I was just really aiming for > something that works, and that I am capable of writing. any special reason you cannot use an existing graphics library ? From peter at engcorp.com Mon Apr 10 11:25:00 2006 From: peter at engcorp.com (Peter Hansen) Date: Mon, 10 Apr 2006 11:25:00 -0400 Subject: can't pass command-line arguments In-Reply-To: <1144681621.999659.78880@z34g2000cwc.googlegroups.com> References: <1144676885.317592.21780@e56g2000cwe.googlegroups.com> <1144681621.999659.78880@z34g2000cwc.googlegroups.com> Message-ID: BartlebyScrivener wrote: > Well, I tried to let this die because I just KNEW I was going to look > like an idiot before it was over. It's the .pyc versus the .py file. > Obviously I don't understand how that works yet. The .pyc file lags > behind the .py file? So when I run cbfindfiles.py I'm running the .py > version and when I run cbfindfiles it's running the .pyc version which > is not the same between edits. I thought of that one, of course, but it can't cause exactly the trouble you describe above. If there's a .py in the same folder as the .pyc, it will not use the .pyc unless the timestamp encoded in it matches the one on the .py file (which, unless you go to extraordinary lengths, will never screw you up that way). On the other hand, if there was a .pyc in the current directory when you run it with "python cbfindfiles.py", but no cbfindfiles.py in the same folder, it will run the local one and not the .py which might be elsewhere, in your PATH. Any chance there are cbfindfiles.py* files in other folders or have you been doing this all from the same folder? > No need to explain. I'll go read up on how that .pyc file is generated. Don't think you look like an idiot (yet :-) ). Not only has everyone been caught out by this, sometimes repeatedly (ah... it happened to a "friend" of mine a number of times), but when you combine the weirdness of Windows PATHEXT and FTYPE and such, you can really get into awkward situations. I do hope you'll identify precisely what the issue was, so we can keep it in mind (if it's a new variant), or refresh our knowledge (if it's just the same old same old but we didn't realize it yet). Thanks. :-) -Peter From me+python at modelnine.org Tue Apr 11 15:31:12 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Tue, 11 Apr 2006 21:31:12 +0200 Subject: RegExp question In-Reply-To: <1144783001.905105.305220@z34g2000cwc.googlegroups.com> References: <1144781090.622493.252460@t31g2000cwb.googlegroups.com> <1144783001.905105.305220@z34g2000cwc.googlegroups.com> Message-ID: <200604112131.12384.me+python@modelnine.org> Am Dienstag 11 April 2006 21:16 schrieb Michael McGarry: > I am testing it with grep. (i.e., grep -e '(and|or|xor)\s*#' myfile) Test it with Python's re-module, then. \s for matching Whitespace is specific to Python (AFAIK). And as you've asked in a Python Newsgroup, you'll get Python-answers here. --- Heiko. From duncan.booth at invalid.invalid Mon Apr 10 09:08:16 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 10 Apr 2006 13:08:16 GMT Subject: can't pass command-line arguments References: <1144636890.976327.253000@i39g2000cwa.googlegroups.com> <1144637633.814788.150270@i40g2000cwc.googlegroups.com> <1144672498.920860.110000@u72g2000cwu.googlegroups.com> Message-ID: BartlebyScrivener wrote: >>> That is wrong on so many levels > > Including the level where I observed that I'd already been running > scripts without typing the .py extension for months, it's just that on > some scripts (seems to be the ones with functions defined in them) you > can't pass arguments unless you type the .py extension. > There is a problem (which I think is finally fixed in XP) where you couldn't redirect I/O when running Python scripts via PATHEXT, but that doesn't sound like your problem. Defining functions, or not, doesn't sound like it should affect the arguments, except maybe if making your script longer had an effect, but I have no problems running a long script with arguments. What does the command "ftype Python.File" print on your system? If it is wrong that could easily stop arguments being passed to scripts run by entering the script name, but it ought to break them all whether or not you type the extension explicitly. The only other thing I can think is that you might already have a findmyfiles.bat (or cmd/com/exe etc.) which is the one being picked up in place of the Python script when you don't specify an extension. That could certainly explain the behaviour. From uval at rz.uni-karlsruhe.de Tue Apr 11 08:08:51 2006 From: uval at rz.uni-karlsruhe.de (=?ISO-8859-1?Q?Sch=FCle_Daniel?=) Date: Tue, 11 Apr 2006 14:08:51 +0200 Subject: Help - strange behaviour from python list In-Reply-To: References: Message-ID: Sean Hammond schrieb: > > I've managed to create a scenario in which editing an object in a list > of objects seems to edit every object in the list, rather than just the > one. I'm totally stumped and wondered if anyone would be kind enough to > read my explanation and see if they have any suggestions. I have > probably stumbled into some typical newbie problem, but anyway: > just a hint >>> def foo(val,lst=[]): ... lst.append(val) ... print lst ... >>> >>> >>> foo(1) [1] >>> foo(2) [1, 2] >>> foo(3) [1, 2, 3] >>> foo(4,[0]) [0, 4] >>> here list lst is created and bound once compare with this one (which is what you really want) >>> def bar(val, lst=None): ... if lst is None: ... lst = [] ... lst.append(val) ... print lst ... >>> bar(1) [1] >>> bar(2) [2] >>> bar(3, [0]) [0, 3] >>> hth, Daniel From thomasbartkus at comcast.net Thu Apr 13 10:30:52 2006 From: thomasbartkus at comcast.net (Thomas Bartkus) Date: Thu, 13 Apr 2006 09:30:52 -0500 Subject: Python editing with emacs/wordstar key bindings. References: <1144887253.027194.198750@i39g2000cwa.googlegroups.com> Message-ID: "Carl Banks" wrote in message news:1144887253.027194.198750 at i39g2000cwa.googlegroups.com... > Thomas Bartkus wrote: > > Does anyone use emacs together with both WordStar key bindings and python > > mode? I'm afraid that Wordstar editing key commands are burned R/O into my > > knuckles! > > Old Borland C user? Worse than that! It starts with Wordstar itself on a terminal to cp/m. It continued with Borland Pascal -> Delphi. Wordstar key controls are the only key bindings that are ergonometric on a qwerty keyboard. If you do serious typing, you don't break stride to issue editing commands. > > I would like to play with emacs for Python editing but I'm having (2) > > problems. > > > > 1) When I load a .py file, emacs automatically overrides my wordstar-mode > > with python-mode, forcing all the keybindings back to emacs native keys. > > Why? > > > > Why should a python-mode care what key bindings are in use? > > Python and wordstar are both major modes. When python-mode is loaded, > it replaces (not sits atop of) wordstar-mode; you can't have two major > modes loaded at the same time. > > If you want just want to use wordstar mode, you can prevent Emacs from > loading python mode by putting -*- mode: wordstar -*- on the first line > of the Python file (or second line if it uses a #!). Or, you could > remove python mode from the auto-mode-alist and interpreter-mode-alists > in your .emacs file, which I leave as an exercise. I do notice that I can invoke wordstar-mode *after* loading the .py file and get the whole enchilada. The Wordstar key bindings with the syntax highlighting. It just strikes me as odd that key bindings should be reasserted by invoking python-mode. Perhaps python-mode shouldn't be an emacs "major mode". We just want syntax highlighting and some minor formatting assist. Key bindings have nothing to do with the language. I need to learn how to edit the key re-assignment out of python-mode.el . > > 2) We get for block indentation instead of the spaces I prefer. > > In your .emacs file: > > (setq indent-tabs-mode nil) Thank you. That helps > > Is there a better python-mode script I should be using other than the > > default that came with emacs? > > I doubt there's one that solves your problem. Yes. The *real* problem here is that I need to get down and dirty with emacs/lisp when all I started looking for was a more robust editor for Python ;-) > Carl Banks > From cyberco at gmail.com Sun Apr 9 16:39:10 2006 From: cyberco at gmail.com (cyberco) Date: 9 Apr 2006 13:39:10 -0700 Subject: mod_python + apache + winxp => nogo In-Reply-To: <443924A4.6060206@sympatico.ca> References: <1144445910.877992.80210@v46g2000cwv.googlegroups.com> <4436E2BE.8060802@sympatico.ca> <1144584361.462089.63170@v46g2000cwv.googlegroups.com> <443924A4.6060206@sympatico.ca> Message-ID: <1144615150.739802.68750@z34g2000cwc.googlegroups.com> Hi Jim, Thanks, I'll sign up for the mailinglist, but to finish the story here: - I only have one version of Python installed - From the Python interpreter I can import the mod_python module just fine - At starup the Apache log states: [Sun Apr 09 22:16:38 2006] [notice] Apache/2.0.55 (Win32) mod_python/3.2.5b Python/2.4.2 configured -- resuming normal operations [Sun Apr 09 22:16:38 2006] [notice] mod_python: Creating 8 session mutexes based on 0 max processes and 250 max threads. Cheers, cyberco From mooquack at suad.org Sun Apr 30 17:08:58 2006 From: mooquack at suad.org (Kirk McDonald) Date: Sun, 30 Apr 2006 14:08:58 -0700 Subject: setting file permissions on a web server In-Reply-To: References: <445449f6$0$9437$c3e8da3@news.astraweb.com> <4454f1e1$0$1963$c3e8da3@news.astraweb.com> Message-ID: <445523fd$1@nntp0.pdx.net> Daniel Nogradi wrote: > I have next to zero experience with windows but as far as I know > windows doesn't have file permissions at all (anyone, please correct > me if I'm wrong :)) so in windows land it doesn't make any sense to > "change file permissions". Even if it has some sort of a notion of > file permissions I wouldn't know how that gets translated into unix. This is getting a little off-topic, I admit, but the NT-derived versions of Windows do indeed have file permissions. The Windows-equivalent of chmod (and chown) is cacls ("Change Access Control Lists"): http://www.ss64.com/nt/cacls.html In essence, each file has an owner and a list of other users and groups, who may each have "Full control" (meaning they can change permissions), read-only, write-only, read-write, or no access. Windows 95 and its descendants don't have permissions any more than DOS does. (Except with respect to Windows network file-sharing.) (Heh, I checked just before posting this and someone beat me to it. Here's my post anyway.) :-) -Kirk McDonald From aleaxit at yahoo.com Mon Apr 3 23:15:22 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 3 Apr 2006 19:15:22 -0800 Subject: overloading constructor in python? References: <1144092500.618489.204740@e56g2000cwe.googlegroups.com> <1144098577.732202.314090@t31g2000cwb.googlegroups.com> Message-ID: <1hd8g42.t78sge1tuys90N%aleaxit@yahoo.com> Paddy wrote: > I guess in python we use two idioms to cover most of the uses of > mulltiple constructors: > 1) Duck typing were for example if you do: > > class C1(object): > def __init__(self, n): > n = float(n) > > n could be an integer, a floating point number,, or a string > representing a float. > > 2) Default values to parameters: > > class C2(object): > def __init__(self, x=None, y=None, s=""): > pass ... and classmethods. OK, _three_ idioms. Oh, and factory functions. Among the idioms we use are the following... Alex From gene.tani at gmail.com Mon Apr 17 11:23:51 2006 From: gene.tani at gmail.com (gene tani) Date: 17 Apr 2006 08:23:51 -0700 Subject: any update to this? In-Reply-To: <1145252124.494322.149040@g10g2000cwb.googlegroups.com> References: <1145252124.494322.149040@g10g2000cwb.googlegroups.com> Message-ID: <1145287431.717428.28950@i39g2000cwa.googlegroups.com> micklee74 at hotmail.com wrote: > hi > i was looking at this : > http://www.python.org/doc/essays/comparisons.html > on comparisons of python and other languages? are there any updates to > this doc? or is there > other reliable source for such comparison elsewhere? thanks lots of blogs out there, check artima, C2.com, http://reddit.com/search?q=python+lisp http://del.icio.us/tag/python+lisp From tim at pollenation.net Fri Apr 21 18:30:00 2006 From: tim at pollenation.net (Tim Parkin) Date: Fri, 21 Apr 2006 23:30:00 +0100 Subject: proposed Python logo In-Reply-To: <1145654590.571680.25040@j33g2000cwa.googlegroups.com> References: <1145585399.871299.31900@t31g2000cwb.googlegroups.com> <1145615455.477800.74730@i39g2000cwa.googlegroups.com> <1145639208.569365.135440@i40g2000cwc.googlegroups.com> <1145654590.571680.25040@j33g2000cwa.googlegroups.com> Message-ID: <44495CE8.3050504@pollenation.net> BartlebyScrivener wrote: >>>(and it's an older version of the logo) because >>>you can get T-Shirts from cafepress.com/pydotorg and any profits go to >>>the psf. > > > I just ordered some stuff from cafe press, are you saying I'm getting > an old version of the logo? > An alternate 'collectors' rendition of the new logo as used by Guido Van Rossum in his recent New York Google presentations and also as on t-shirts, mugs and flags handed out during EuroPython 2005! Tim Parkin p.s. was that good enough spin for you ;-) From ptmcg at austin.rr._bogus_.com Tue Apr 18 18:05:55 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Tue, 18 Apr 2006 22:05:55 GMT Subject: Better way to sift parts of URL . . . References: <1145392079.720766.122310@z34g2000cwc.googlegroups.com> Message-ID: <7pd1g.46$0Z4.8@tornado.texas.rr.com> "Ben Wilson" wrote in message news:1145392079.720766.122310 at z34g2000cwc.googlegroups.com... > I am working on a script that splits a URL into a page and a url. The > examples below are the conditions I expect a user to pass to the > script. In all cases, "http://www.example.org/test/" is the URL, and > the page comprises parts that have upper case letters (note, 5 & 6 are > the same as earlier examples, sans the 'test'). > > 1. http://www.example.org/test/Main/AnotherPage (page = > Main/AnotherPage) > 2. http://www.example.org/test/Main (page = Main + '/' + > default_page) > 3. http://www.example.org/test (page = default_group + '/' + > default_page) > 4. http://www.example.org/test/ (page = default_group + '/' + > default_page) > 5. http://www.example.org/ (page = default_group + '/' + > default_page) > 6. http://www.example.org/Main/AnotherPage (page = Main/AnotherPage) > > Right now, I'm doing a simple split off condition 1: > > page = '.'.join(in.split('/')[-2:]) > url = '/'.join(in.split('/')[:-2]) + '/' > > Before I start winding my way down a complex path, I wanted to see if > anybody had an elegant approach to this problem. > > Thanks in advance. > Ben > Standard Python includes urlparse. Possible help? -- Paul import urlparse urls = [ "http://www.example.org/test/Main/AnotherPage", # (page = Main/AnotherPage) "http://www.example.org/test/Main", # (page = Main + '/' + default_page) "http://www.example.org/test", # (page = default_group + '/' + default_page) "http://www.example.org/test/", # (page = default_group + '/' + default_page) "http://www.example.org/", # (page = default_group + '/' + default_page) "http://www.example.org/Main/AnotherPage", ] for u in urls: print u parts = urlparse.urlparse(u) print parts scheme,netloc,path,params,query,frag = parts print path.split("/")[1:] print prints: http://www.example.org/test/Main/AnotherPage ('http', 'www.example.org', '/test/Main/AnotherPage', '', '', '') ['test', 'Main', 'AnotherPage'] http://www.example.org/test/Main ('http', 'www.example.org', '/test/Main', '', '', '') ['test', 'Main'] http://www.example.org/test ('http', 'www.example.org', '/test', '', '', '') ['test'] http://www.example.org/test/ ('http', 'www.example.org', '/test/', '', '', '') ['test', ''] http://www.example.org/ ('http', 'www.example.org', '/', '', '', '') [''] http://www.example.org ('http', 'www.example.org', '', '', '', '') [] http://www.example.org/Main/AnotherPage ('http', 'www.example.org', '/Main/AnotherPage', '', '', '') ['Main', 'AnotherPage'] From kent at kentsjohnson.com Sun Apr 9 08:38:55 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Sun, 09 Apr 2006 08:38:55 -0400 Subject: Automated Graph Plotting in Python In-Reply-To: <1144552132.926125.222210@i39g2000cwa.googlegroups.com> References: <1144552132.926125.222210@i39g2000cwa.googlegroups.com> Message-ID: <4438faec$1_1@newspeer2.tds.net> diffuser78 at gmail.com wrote: > My python program spits lot of data. I take that data and plot graphs > using OfficeOrg spredsheet. I want to automate this task as this takes > so much of time. I have some questions. > > 1. Which is the best graph plotting utility in python or linux. Can I > write a code in such a way that my python code automatically gives me a > graph. I know little about gnuplot. If you know any better tool without > much learning curve please tell me in Linux. I don't know which is best but some options are listed here: http://wiki.python.org/moin/UsefulModules#head-a7e459aeb7e5672e6d431e972a3121670c4dcf1c > > 2. I want to write a script such that my python code writes to a file, > some graph utility like gnuplot takes that data from the file and I get > my graph ready made. Do you think its possible ? The Python modules are generally oriented towards a Python API where you pass the data to the plot package directly, rather than creating a file. Under the hood some of them do exactly what you describe; I think gnuplot.py works that way. Kent From ldo at geek-central.gen.new_zealand Sat Apr 15 03:24:42 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 15 Apr 2006 19:24:42 +1200 Subject: OneAtATime Message-ID: #!/usr/bin/python #+ # This script ensures there is only one instance of a particular command # running at a time. It may be useful, for example, for potentially # lengthy cron tasks, to ensure that a new task is not started if the # previous one has not finished yet. # # Invoke this script from the command line as follows: # # OneAtATime [opts] cmd # # where cmd is the Shell command line to execute. Valid options are: # # --id=s # use the string s as the unique identifier for this command # (should not contain "/" or nul characters). Any other execution # of OneAtATime specifying the same id will not proceed as long as # this instance is still executing. # If omitted, the id is computed as a hash on the cmd string. # # --timeout=n # If an existing instance has been executing for at least n # seconds, assume it's taking too long and try to kill it # before proceeding. If omitted, the timeout is infinity. # # --verbose # increases the verbosity level by 1 each time it is specified. # The initial default verbosity level is 0. # # --wait # If specified, then this invocation should sleep until any # previous instance is finished (or until the timeout elapses, # if specified). If not specified, then this invocation will # simply exit if an existing instance is already running. # Note that, if more than one invocation is waiting on a # previous instance to complete, there is no guarantee in # what order they'll execute. # # Start of development 2006 March 23 by Lawrence D'Oliveiro # . # First working version 2006 March 24. # Fix hang if previous process dies without freeing instance lock and # --timeout was not specified 2006 March 24. # Ensure lock-breaking recovery is still invoked even without --wait, # include effective user ID in instance lock name for uniqueness # 2006 March 25. # Last modified 2006 March 27. #- import sys import os import time import errno import signal import getopt import sha SignalName = {} for Name in dir(signal) : # collect symbolic names for all signals Value = getattr(signal, Name) if Name.startswith("SIG") and type(Value) == int : SignalName[Value] = Name #end if #end for #+ # Mainline #- (Opts, Args) = getopt.getopt \ ( sys.argv[1:], "", ["id=", "timeout=", "verbose", "wait"] ) if len(Args) != 1 : raise getopt.GetoptError("need exactly one arg, the cmd to execute") #end if Cmd = Args[0] ID = None Timeout = None Wait = False Verbosity = 0 for Keyword, Value in Opts : if Keyword == "--id" : ID = Value elif Keyword == "--timeout" : Timeout = int(Value) elif Keyword == "--verbose" : Verbosity += 1 elif Keyword == "--wait" : Wait = True #end if #end for if ID == None : ID = sha.new(Cmd).hexdigest()[:16] # less than 40-char file name should be OK #end if def Debug(Level, Msg) : if Verbosity >= Level : print Msg #end if #end Debug PidFileName = "/tmp/OneAtATime-pid-%d" % os.getpid() PidFile = file(PidFileName, "w") PidFile.write("%s\n" % os.getpid()) PidFile.close() InstanceLockName = "/tmp/OneAtATime-lock-%d-%s" % (os.geteuid(), ID) # presence of this file is used to guard against more than one # invocation of a task with the same id at once InstanceLock2Name = "/tmp/OneAtaTime-lock2-%s" % ID # presence of this file is used to serialize checking for # presence of InstanceLockName and of the process whose PID is # contained in that file GotLock = False GotLock2 = False LastLastMod = None OtherPid = None while True : # try to get instance lock if not GotLock2 : while True : # grab the secondary lock for checking the instance lock try : os.symlink(PidFileName, InstanceLock2Name) # guaranteed atomic operation that will fail if # destination name already exists. Note use of # symlink rather than link because my pid file # might be older than secondary lock timeout # if I've been waiting a while. GotLock2 = True break except OSError, (ErrNo, Msg) : if ErrNo != errno.EEXIST : # Not bothering to recover from privilege failures raise OSError(ErrNo, Msg) #end if #end try # Somebody else has the lock, check it looks reasonable try : LastMod = os.lstat(InstanceLock2Name).st_mtime # note use of lstat to find out how long symlink has # been present, not age of pid file except OSError, (ErrNo, Msg) : if ErrNo == errno.ENOENT : LastMod = None else : # Not bothering to recover from privilege failures raise OSError(ErrNo, Msg) #end if #end try if LastMod != None : if LastMod + 10 < time.time() : Debug(0, "Breaking secondary lock") try : os.unlink(InstanceLock2Name) except OSError, (ErrNo, Msg) : if ErrNo != errno.ENOENT : # Not bothering to recover from privilege failures raise OSError(ErrNo, Msg) #end if #end try else : # lock looks valid, wait awhile and try again time.sleep(1) #end if else : pass # disappeared while I was looking at it #end if #end while #end if not GotLock2 # At this point, I have the secondary lock, so nobody else will be # trying the following operations at the same time. try : LastMod = os.stat(InstanceLockName).st_mtime except OSError, (ErrNo, Msg) : if ErrNo == errno.ENOENT : os.link(PidFileName, InstanceLockName) GotLock = True else : # Not bothering to recover from privilege failures raise OSError(ErrNo, Msg) #end if #end try if GotLock : Debug(2, "Got the lock") break #end if if LastMod != LastLastMod : # instance lock file seems to have changed, (re)fetch OtherPid. Debug(2, "Getting existing process ID") try : PidFile = file(InstanceLockName, "r") except OSError, (ErrNo, Msg) : if ErrNo == errno.ENOENT : PidFile = None else : # Not bothering to recover from privilege failures raise OSError(ErrNo, Msg) #end if #end try if PidFile != None : OtherPid = PidFile.readline() OtherPid = int(OtherPid.replace("\n", "").replace(" ", "")) # not bothering to guard against bad pidfile contents PidFile.close() Debug(1, "Existing process ID is %d" % OtherPid) else : OtherPid = None #end if LastLastMod = LastMod #end if if OtherPid != None : # check the process still exists try : os.kill(OtherPid, 0) except OSError, (ErrNo, Msg) : if ErrNo == errno.ESRCH : OtherPid = None # nope, it's gone else : # Not bothering to recover from privilege failures raise OSError(ErrNo, Msg) #end if #end try #end if BreakLock = \ OtherPid == None \ or \ Timeout != None and time.time() > LastMod + Timeout if BreakLock : Debug(0, "Breaking lock and killing existing lock owner") if OtherPid != None : ExtremePrejudice = False while True : if ExtremePrejudice : Signal = signal.SIGKILL else : Signal = signal.SIGTERM # give it a chance to clean up #end if try : os.kill(OtherPid, Signal) except OSError, (ErrNo, Msg) : if ErrNo == errno.ESRCH : break # OK, it's gone else : # Not bothering to recover from privilege failures raise OSError(ErrNo, Msg) #end if #end try if ExtremePrejudice : break # it should be gone StartWait = time.time() while True : # wait up to a certain amount of time for process to # terminate by itself try : os.kill(OtherPid, 0) StillThere = True except OSError, (ErrNo, Msg) : if ErrNo == errno.ESRCH : StillThere = False else : # Not bothering to recover from privilege failures raise OSError(ErrNo, Msg) #end if #end try if not StillThere or time.time() - StartWait > 5.0 : # Note this timeout must be less than secondary lock timeout, # otherwise another invocation could take secondary lock # away from me break time.sleep(1) #end while if not StillThere : break # OK, it's gone ExtremePrejudice = True # out of patience #end while OtherPid = None #end if # Lock owner killed, now clean up lock file (if owner # didn't already clean it up) so I can grab it for myself try : os.unlink(InstanceLockName) except OSError, (ErrNo, Msg) : if ErrNo != errno.ENOENT : # Not bothering to recover from privilege failures raise OSError(ErrNo, Msg) #end if #end try elif OtherPid != None : if GotLock2 : # mustn't hang on to secondary lock for too long os.unlink(InstanceLock2Name) GotLock2 = False #end if if not Wait : Debug(1, "Can't get lock, exiting") break #end if time.sleep(1) #end if #end while if GotLock2 : os.unlink(InstanceLock2Name) #end if os.unlink(PidFileName) if GotLock : Debug(2, "Spawning \"%s\"" % Cmd) ChildPid = os.spawnl(os.P_NOWAIT, "/bin/bash", "/bin/bash", "-c", Cmd) if Timeout != None : StartWait = time.time() while True : time.sleep(5) (ChildPidAgain, ChildStatus) = os.waitpid(ChildPid, os.WNOHANG) if ChildPidAgain != 0 : break if time.time() > StartWait + Timeout : Debug(0, "Command taking too long, killing") os.kill(ChildPid, signal.SIGKILL) ChildStatus = os.waitpid(ChildPid, 0)[1] break #end if #end while else : ChildStatus = os.waitpid(ChildPid, 0)[1] #end if if os.WIFEXITED(ChildStatus) : if os.WEXITSTATUS(ChildStatus) != 0 : Debug(1, "Child exited with status %d" % os.WEXITSTATUS(ChildStatus)) #end if elif os.WIFSIGNALED(ChildStatus) : SigValue = os.WTERMSIG(ChildStatus) if SignalName.has_key(SigValue) : SigName = SignalName[SigValue] else : SigName = "?" #end if Debug(0, "Child died from signal %d (%s)" % (SigValue, SigName)) else : Debug(0, "Child ?terminated? status %d" % ChildStatus) #end if os.unlink(InstanceLockName) #end if From xah at xahlee.org Wed Apr 5 06:33:46 2006 From: xah at xahlee.org (Xah Lee) Date: 5 Apr 2006 03:33:46 -0700 Subject: A Lambda Logo Tour Message-ID: <1144233226.580090.216080@j33g2000cwa.googlegroups.com> A Lambda Logo Tour (and why LISP languages using ? as logo should not be looked upon kindly) Xah Lee, 2002-02 Dear lispers, The lambda character ?, always struck a awe in me, as with other mathematical symbols. In my mind, i imagine that those obscure math symbolism are etched in stone by god. A salient example is the book cover Concrete Mathematics by Ronald Graham et al. (See it here: http://xahlee.org/UnixResource_dir/bcb/concrete-math.jpg.) Here we see the summation sign ? etched in stone. The summation sign happens to be my favorite math symbol. (chosen as my website signet: http://xahlee.org/Icons_dir/icon_sum.gif XahLee.org signet) These symbols are not to be trifled with. If anyone puffs in as much half a snicker, i wish god strikes a thunder upon their impudence. The Greek lambda symbol is used in a branch of logic called lambda calculus. The theories of lambda calculus is what functional languages are based on, thus many functional languages's logo feature the lambda. Here is a sampling: MIT Scheme logo MIT Scheme's logo features a recursive shield with lambda http://www.swiss.ai.mit.edu/projects/scheme/ Schemer.org's logo Schemer.org's logo has a modernized look. It is a simple lambda inside a O figuration. http://www.schemers.org/ (the O figure is supposed to be a pair of parenthesis) PLT Scheme logo PLT Scheme logo, notable is the red/white/blue coloring scheme. http://www.plt-scheme.org/ MzScheme MzScheme logo features a lambda besides a Chinese character ? (wen2). The character means written language. http://www.cs.rice.edu/CS/PLT/packages/mzscheme/ Common Lisp HTTP server logo the Common Lisp HTTP server logo. http://www.ai.mit.edu/projects/iiip/doc/cl-http/home-page.html Scheme Shell logo Scheme shell scsh logo is a lamba inside a bivalve, perhaps most artistic of the bunch: http://www.scsh.net/ Haskell logo Haskell language logo is a plain lambda: http://haskell.org/ Hugs98 logo The Haskell interpreter Hugs98 features a 3D lambda with projected shadow http://www.haskell.org/hugs/ Yale Haskell logo Yale Haskell bullfrog Yale Haskell project used a logo that features symbols in lambda calculus including the lambda, and also a bullfrog head. Quite funny and beautiful. (the bullfrog logo origin is explained at the bottom. i.e. that of parody to Yale's bulldog logo) http://web.archive.org/web/20000301023909/http://www.cs.yale.edu/haskell/yale-fp.html The book cover Structure & Interpretation of Computer Programs by Abelson & Sussman, features a wizard and witch talking with prominent lambda, and a monster foot of the table showing: see: http://xahlee.org/UnixResource_dir/sicp-cover.jpg I love these lambda-featuring logos. However, i have a complaint. As most of you know, lisp languages are not purely functional languages. Subroutines in lisps easily have side-effects, and sometimes non-functional programing methodologies such as OOP are actually encouraged in lisp. As most of you know, the lambda symbol chosen by functional languages is to signify no side-effects. In this respect, i find the lisp languages not totally deserving the use of lambda in their logo. As i have expressed before, mathematical symbols are not to be trifled with, and the Schemers have tainted my mathematics, strickly speaking. Although i have these minor objections with lispers using the lambda symbol, but overall i think the lispers and i share a more important common goal. That is, to kill all imperative programing ignoramuses of the world. Once the unix and c and perl and otherwise idiots are all dead, then i'll formally raise my objection about Lisper's unfit borrowing of the math symbol and term lambda. (PS In America, imperative language programers are such not because they prefer such methodology, but because they know shit.) ---------------------------------- Addendum, 2003-05, 2006-04. Haskell logo above: Haskell language's new logo, inargurated in 2003-05. Superb! Haskell logo Haskell logo above: Two Web logos for Haskell. Someone has written a C++ library for functional programing, called FC++. (by Brian McNamara and Yannis Smaragdakis, 2003) Their website is http://www.cc.gatech.edu/~yannis/fc++/index.html. They have unsettled logos. Here's one of them: FC++ logo There's a Scheme-to-C compiler called Chicken (by Felix L Winkelmann, at http://www.call-with-current-continuation.org/chicken.html). Scheme Chicken logo This is getting silly and disrespectful. ---- This post is archived at: http://xahlee.org/UnixResource_dir/lambda_logo.html PS if you know any new lambda logo, please let me know. Thanks. Xah xah at xahlee.org ? http://xahlee.org/ From julien.arnoux at ext.cri74.org Mon Apr 24 03:03:12 2006 From: julien.arnoux at ext.cri74.org (Julien ARNOUX) Date: Mon, 24 Apr 2006 09:03:12 +0200 Subject: Read and extract text from pdf In-Reply-To: rlkh42d5i52r0uema0dd4vlvoth2v6gp15@4ax.com Message-ID: <1145862192.6006.1.camel@localhost.localdomain> Hi, Thanks I use that and is all right :) import commands txt = commands.getoutput('ps2ascii tmp.pdf') print txt From No.Spam at Spam.none Sat Apr 15 17:25:20 2006 From: No.Spam at Spam.none (I. Myself) Date: Sat, 15 Apr 2006 21:25:20 GMT Subject: Python used to animate a compiled C program Message-ID: <4xd0g.26264$WI1.21808@pd7tw2no> SailChallenge was originally a program in C. It simulates a sailboat being navigated by an ANN (Artificial Neural Network). Now a Python "front end" has been created which invokes the compiled C program, and then captures the real time text output, converting it into an animation. A screen shot can be seen on our website. SailChallenge-2.0 is a free download from http://sourceforge.net/projects/annevolve. All source code is included, both C and Python. It will run on linux or Windows. Windows .exe files are available for Windows users who don't wish to compile the C code. Mitchell Timin -- I'm proud of http://ANNEvolve.sourceforge.net. If you want to write software, or articles, or do testing or research for ANNEvolve, let me know. Humans may know that my email address is: (but remove the 3 digit number) zenguy at shaw666 dot ca From jelleferinga at gmail.com Fri Apr 21 08:20:21 2006 From: jelleferinga at gmail.com (jelle) Date: 21 Apr 2006 05:20:21 -0700 Subject: are docstrings for variables a bad idea? In-Reply-To: <4ars48Fucf8sU1@uni-berlin.de> References: <1145615763.943050.170950@j33g2000cwa.googlegroups.com> <4ars48Fucf8sU1@uni-berlin.de> Message-ID: <1145622021.708392.5490@g10g2000cwb.googlegroups.com> ---I don't know for sure what you mean by "pop up as doc-string" - I guess you want them magically merged into the functions doc string, at least inside your editor? That sure could be done - but I personally don't think that is too useful. Because you lose context.--- point taken. perhaps only variables declared in the __init__ should be made available as a doc string. ---IMHO commenting the parameters and results of a function is what someone needs who skims the docs for enlightenment--- these are two completely different things: f = instanceSomeClass() -> 'pops up the __init__ doc string in your IDE' now, when this class is instanced, i think this could be useful: f.someComplexMethod -> 'pops up the variable docstring' I'm all for DRY -dont repeat yourself-, but DHORYEBNPTMTRYCEBPTSWTITDS -don't have others repeat your efforts by not providing the means to reuse your code efficiently by providing them sparsely with the information to do so- could have some place in complex classes that are often subclassed. having the right information at the right time to do so would be quite a help. be fair: do you perfectly well know how to subclass a class without (extensively) reading it back? perhaps a variable doc here and there would make this slightly easier. -jelle From wrffruntre at tznvy.pbz.ROT13 Tue Apr 18 22:39:20 2006 From: wrffruntre at tznvy.pbz.ROT13 (Jesse Hager) Date: Tue, 18 Apr 2006 22:39:20 -0400 Subject: pywin32 : scheduled weakup from standby/hiberate ? In-Reply-To: References: Message-ID: <124b8mpcvjo5d4c@corp.supernews.com> robert wrote: > On Windows the task scheduler tool can program (the BIOS?) to weak up > the machine from standby/hibernate at certain pre-configured times. Can > this be done directly through the (py)win32 API? > > robert What you need is a Waitable Timer. The APIs to manipulate these are: win32event.CreateWaitableTimer() win32event.SetWaitableTimer() win32event.CancelWaitableTimer() The wakeup feature is enabled when the last parameter of the call to SetWaitableTimer is True. However, pywin32 seems to be missing a binding for the SetThreadExecutionState() function so unless a person moves the mouse or keyboard within a minute or two of the wakeup, the system just goes back to sleep. You should be able to call the SetThreadExecutionState function using ctypes. Search for Power Management in the MSDN library for info on these functions. -- Jesse Hager email = "wrffruntre at tznvy.pbz".decode("rot13") From http Thu Apr 13 06:02:17 2006 From: http (Paul Rubin) Date: 13 Apr 2006 03:02:17 -0700 Subject: New Karrigel page in Wikipedia References: <1144867025.095969.92870@e56g2000cwe.googlegroups.com> <1144915559.734587.131140@e56g2000cwe.googlegroups.com> <1144918850.680444.198980@g10g2000cwb.googlegroups.com> Message-ID: <7x1ww1lro6.fsf@ruckus.brouhaha.com> "Pierre Quentel" writes: > I added an entry in Wikipedia for information, just like other Python > web frameworks have already done. If the style doesn't fit Wikipedia's > I'm sorry and willing to learn how to improve it ; the reason I read > was "Obvious, if elaborate, link spam. Really should be speedied, but I > can't find a CSD that fits this". I don't really understand why it's > called a spam, I don't know what a CSD is and I don't know either who > deleted the prod template, not me anyway. I'll take wikipedia people's > advice into account anyway CSD = criteria for speedy deletion, Prod = proposed deletion. Anyone is allowed to un-prod it, and in this case someone did. If nobody un-prods it after 5 days, it gets deleted automatically. That doesn't apply here, because the article did get un-prodded. Next probably comes AFD, article for deletion. That's a consensus process: there's a 5 day community discussion about what to do about the article and then an admin comes along and implements the decision. This article will probably get AFD'd (i.e. entered into the discussion process). When that happens, I'll recommend keeping the article but editing it considerably. Basically it needs to be rewritten as a straightforward description that doesn't sound like advertising. If there's an AFD, a notice will appear at the top of the article announcing the AFD and giving a link to participate in the discussion. From jyoti.chhabra at gmail.com Tue Apr 18 04:27:14 2006 From: jyoti.chhabra at gmail.com (JyotiC) Date: 18 Apr 2006 01:27:14 -0700 Subject: Error using tkinter Message-ID: <1145348834.820408.130890@j33g2000cwa.googlegroups.com> Hi, I am making a gui, in which specifiction are taken from user, which are wriiten to a file. and that file will bw executed. finalstr is a string f = open('crossManual.sh','w') f.write(finalstr) f.close() I am getting the error Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python2.3/lib-tk/Tkinter.py", line 1345, in __call__ return self.func(*args) File "gui.py", line 248, in writescript f = open('crossManual.sh','w') TypeError: an integer is required Couldn't understand what it means Plz tell me how to correct it. Thanx in advance From robert.kern at gmail.com Mon Apr 24 01:52:49 2006 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 24 Apr 2006 00:52:49 -0500 Subject: MS VC++ Toolkit 2003, where? In-Reply-To: References: <1he8pss.1yk7ug81rv7pw2N%aleaxit@yahoo.com> <1145811839.042394.73260@t31g2000cwb.googlegroups.com> <1he8sbx.dqqp3q10n5thaN%aleaxit@yahoo.com> <1145849491.347970.112150@e56g2000cwe.googlegroups.com> <1he9m4m.9d8okx1x7mxeaN%aleaxit@yahoo.com> Message-ID: Edward Elliott wrote: > I think Apple switched to the Intel compiler for > x86 macs, was python built with that or with gcc? I'm pretty sure MacTel OS X still uses gcc 4 (although I think there is a beta version of the Intel compiler available). All of the Python builds floating around for it certainly use gcc. -- Robert Kern robert.kern at gmail.com "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From sullivanz.pku at gmail.com Thu Apr 6 03:20:15 2006 From: sullivanz.pku at gmail.com (Sullivan WxPyQtKinter) Date: 6 Apr 2006 00:20:15 -0700 Subject: Python CGI problem: correct result, but incorrect browser response. Message-ID: <1144308015.256501.80980@e56g2000cwe.googlegroups.com> title:Python CGI problem: correct result, but incorrect browser response. In one of my CGI program,named 'login.py', the script return a HEADER to web browser: Set-Cookie: sessionID=LAABUQLUCZIQJTZDWTFE; Set-Cookie: username=testuser; Status:302 Location:edit.py (blank line) but the IE prompted to let me choose to save the 'login.py'. When I save it, the file is just the header. That means the IE failed to parse the header. My IE has already enabled cookie read and write. I also tried Firefox, but the result is the same. How does this happen? From steve at hastings.org Wed Apr 5 20:54:27 2006 From: steve at hastings.org (Steve R. Hastings) Date: Wed, 05 Apr 2006 17:54:27 -0700 Subject: efficiency of range() and xrange() in for loops References: <443461d7$1_2@news.bluewin.ch> Message-ID: On Thu, 06 Apr 2006 02:33:16 +0200, Azolex wrote: > Don't. It's quite funny, thanks. I guess I should laugh. :-/ When you read my original articles, did *you* think I was proposing that range() be changed to always return an iterator? I thought what I wrote was pretty clear... -- Steve R. Hastings "Vita est" steve at hastings.org http://www.blarg.net/~steveha From tsaar2003 at yahoo.com Fri Apr 28 15:08:53 2006 From: tsaar2003 at yahoo.com (tsaar2003 at yahoo.com) Date: 28 Apr 2006 12:08:53 -0700 Subject: Possible constant assignment operators ":=" and "::=" for Python Message-ID: <1146251333.817862.94570@v46g2000cwv.googlegroups.com> Hi Pythonians, To begin with I'd like to apologize that I am not very experienced Python programmer so please forgive me if the following text does not make any sense. I have been missing constants in Python language. There are some workarounds available, for example the const-module. To me, this looks quite cumbersome and very unintuitive. For the interpreter, in the efficiency-wise, I just cannot tell. For the solution I came up with two new assignment operators to the language which would create a constant name and constant value: Let's welcome the new constant assignment operators := and ::= The := assignment operator says that "declare the name to be constant and immutable". However, there might be some side-effects and the constant may not always be constant as you will see below: a = [1, 2, 3] b := [4, 5, 6] # assign [4,5,6] to 'b' and declare name 'b' to be "constant" and "immutable" c := a # assign 'a' to 'c' and declare that name 'c' is "constant" and "immutable" d = c # assign 'c' to 'd' and 'd' inherits the "immutable"-attribute from 'c', but 'd' can be assigned later e = d # assign 'd' to 'e' and 'e' inherits the "immutable"-attribute from 'd', but 'e' can be assigned later a.append( b ) print a # prints [1, 2, 3, 4, 5, 6] print c # prints [1, 2, 3, 4, 5, 6] because of the side-effect print d # prints [1, 2, 3, 4, 5, 6] as well print e # prints [1, 2, 3, 4, 5, 6] no magic here c = b # 'c' cannot be assigned as 'c' is "constant" c := b # 'c' cannot be redefined either as 'c' is "constant" c.append( 7 ) # cannot be done as 'c' is "immutable" d.append( 7 ) # cannot be done as 'd' is "immutable" as it was inherited from 'c'. e.append( 7 ) # cannot be done as 'e' is "immutable" as it was inherited from 'd'. d = [7, 8, 9] # normal variable assignment because 'd' was not declared to be a "constant" d.append( 10 ) # now allowed as 'd' is not "immutable" any more The ::= copy&assign-operator says that "make a copy of the right-hand-side object and declare the name to be constant and immutable ". This would give us a true constant object which cannot be changed. Example follows: a = [1, 2, 3] b = [4, 5, 6] c ::= a # make copy of 'a' and assign that new copy to 'c' and declare that name 'c' is a "constant" and "immutable" d = c # assign 'c' to 'd' and 'd' inherits the "immutable"-attribute from 'c', but 'd' can be assigned later e := d # assign 'd' to 'e' and declare that name 'e' is "constant" and "immutable" a.append( b ) print a # prints [1, 2, 3, 4, 5, 6] print c # prints [1, 2, 3] as 'a' and 'c' are two different objects because of the ::= print d # prints [1, 2, 3] no magic here print e # prints [1, 2, 3] no magic here either c = b # 'c' cannot be assigned as 'c' is "constant" c := b # 'c' cannot be redefined either as 'c' is "constant" c.append( 7 ) # cannot be done as 'c' is "immutable" d.append( 7 ) # cannot be done as 'd' is "immutable" as it was inherited from 'c'. e.append( 7 ) # cannot be done as 'e' is "immutable" as it was inherited from 'd'. d = [7, 8, 9] # normal variable assignment because 'd' was not declared to be a "constant" d.append( 10 ) # now allowed as 'd' is not "immutable" any more The := operator would be computionally efficient as it creates only a reference to an existing object but it may suffer from side-effects. The ::= is less efficient as it makes a copy on an existing object, but gives truly constant objects. Does this make any sense to you, or are there some fatal issues that I just happened to overlook? Br, T.S. From g.horvath at gmx.at Thu Apr 27 11:15:28 2006 From: g.horvath at gmx.at (Gregor Horvath) Date: Thu, 27 Apr 2006 17:15:28 +0200 Subject: finding IP address of computer In-Reply-To: <1146150198.737288.37640@i40g2000cwc.googlegroups.com> References: <1146150198.737288.37640@i40g2000cwc.googlegroups.com> Message-ID: Chris schrieb: > How do I find and print to screen the IP address of the computer my > python program is working on? > IP adresses are bound to network interfaces not to computers. One Computer can have multiple network interfaces. -- Servus, Gregor http://www.gregor-horvath.com From andrea at rediff.com Thu Apr 27 20:15:13 2006 From: andrea at rediff.com (andrea at rediff.com) Date: 28 Apr 2006 00:15:13 -0000 Subject: Pattern_Recognition_School+Conf_2006:Deadline_Approaching Message-ID: <20060428001513.2257.qmail@rediff.com> Approaching Deadlines!!!!!! PATTERN RECOGNITION EVENTS THIS SUMMER, 2006 _______________________ 4TH INTERNATIONAL SUMMER SCHOOL ON PATTERN RECOGNITION (ISSPR, 2006), 23-28 JULY, UK WWW.PatternRecognitionSchool.com The 4th International Summer School on Pattern Recognition will be organised at the University of Plymouth, UK (23-28 July, 2006). The school programme is listed below. Please pass on this email to your interested colleagues and students. This is a great summer school which I would recommend for everyone to attend. DEADLINE: Register BEFORE 01 MAY, 2006 through the website to get a discount on the fee. More than 100 participants in 2005! Speakers at the Summer School (ISSPR'2006) Dr. Sam Roberts Mathworks, UK (Introduction to Matlab) Prof. Wojtek Krzanowski University of Exeter, UK (Multivariate Statistics: Data Description) Dr. Mike Tipping, Microsoft Research, UK (Bayesian Pattern Recognition: Principles and Practice) Prof. Chris Bishop, Microsoft Research, UK (Latent Variables, Mixture Models and EM) Dr. Richard Everson, University of Exeter, UK (Dimensionality Reduction) Dr. Peter Tino University of Birmingham, UK (Probabilistic framework for model-based topographic map formation) Prof. Chris Williams, University of Edinburgh, UK (Neural Networks and Kernel Machines) Dr. Colin Campbell, University of Bristol, UK (Support Vector Machines and Kernel Methods: An Introduction and Review) Prof. John Shawe- Taylor, University of Southampton, UK (Kernel Based Methods) Dr. Steve Gunn, University of Southampton, UK (Matlab for Support Vector Machines) Prof. Mahesan Niranjan, University of Sheffield, UK (Classifier Performance Particle Filters for Tracking and Sequential Problems) Dr. Andrew Webb Qinetiq, UK (Decision TreesData Clustering) Prof. Xin Yao, University of Birmingham, UK (A Gentle Introduction to Evolutionary Computation; ATutorial on Evolutionary Multi-objective Optimisation) Dr. Richard Deardon, University of Birmingham, UK (Sequential Decision Making; Markov Chains Monte Carlo Methods) Dr. Jeremy Wyatt, University of Birmingham, UK (An Introduction to Reinforcement Learning) Dr. Ludmila Kuncheva, University of Wales, UK (Classifier Combination) Prof. Joseph Kittler, University of Surrey, UK (Feature Selection and Extraction) Prof. Sameer Singh, Loughborough University, UK (Multiresolution Pattern Recognition) Prof. Susan Craw, Robert Gordon University, UK (Case Based Reasoning) SUPPORTED BY: Microsoft, Springer, British Computer Society, and Mathworks. _______________________ IEEE CVPR CONFERENCE www.CVPR.org/2006 17-22 June, 2006 _______________________ 18th INTERNATIONAL CONFERENCE ON PATTERN RECOGNITION www.comp.hkbu.edu.hk/~icpr06 August 20-24, 2006 ______________________ ICIAR CONFERENCE www.iciar.uwaterloo.ca/iciar06 18-20 September, 2006 ______________________ Please see the event websites to get FULL information. Compiled by: Dr. Heather Mclleland From tzot at sil-tec.gr Mon Apr 10 09:06:34 2006 From: tzot at sil-tec.gr (Christos Georgiou) Date: Mon, 10 Apr 2006 16:06:34 +0300 Subject: Python 3.0 or Python 3000? References: <4439aba9$0$18019$c3e8da3@news.astraweb.com> Message-ID: On Sun, 9 Apr 2006 22:15:15 -0400, rumours say that "Tim Peters" might have written: >[John Salerno] >> Is 'Python 3000' just a code name for version 3.0, or will it really be >> called that when it's released? >The smart money is on changing the name to Ecstasy, to leverage >marketing publicity from the hallucinogenic club drug of the same >name. "class" will be renamed to "rave", and the license will be >changed to prohibit use by people with bipolar disorder. Anything to do with recent rumours about license change? Will programming in Python finally be outlawed, as it should be from the start (it's so pleasing after all, it should be illegal)? There will be a charge per line (of code)? Shall we become code sniffers? >Either that, or the name will be Python 3.0. That's what we, as cautious merchands dealing with unknown clients, should call our product. Excellent. PS ("Mwa" + "ha"*sys.maxint) still won't work, though. -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From onurb at xiludom.gro Wed Apr 19 04:47:41 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 19 Apr 2006 10:47:41 +0200 Subject: Updated PEP 359: The make statement In-Reply-To: References: <_aydnYpYE_rjuNjZRVn-og@comcast.com> Message-ID: <4445f97c$0$9451$626a54ce@news.free.fr> Steven Bethard wrote: (snip) > Guido has pronounced on this PEP: > http://mail.python.org/pipermail/python-3000/2006-April/000936.html > Consider it dead. =) :( -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From pythor at gmail.com Tue Apr 4 16:00:03 2006 From: pythor at gmail.com (Pythor) Date: 4 Apr 2006 13:00:03 -0700 Subject: how do you use pickle? References: <1144167350.837406.172430@i39g2000cwa.googlegroups.com> <1144169459.630621.240510@i40g2000cwc.googlegroups.com> <1144170857.069178.115440@i39g2000cwa.googlegroups.com> <1144178139.765305.191440@e56g2000cwe.googlegroups.com> Message-ID: <1144180803.657781.53320@e56g2000cwe.googlegroups.com> John Salerno wrote: > Pythor wrote: > > John Salerno wrote: > >> John Salerno wrote: > >>> Pythor wrote: > >>> > >>>> Whis is why I said carefully ;) I missed it several times myself when > >>>> I was working on the challenge. > >>> Ok, frustration has set in again. I see the file name in the source > >>> code, but am I meant to actually access a file, or just use the name > >>> itself? I also had to look up what 'banner' meant in Unix, which wasn't > >>> a very fun thing to have to do for a Python puzzle. > >> Ah, I should have known we weren't done with URL manipulation yet. Now I > >> just need to figure out what to do with this source code. > > > > Incidentally, there's a forum specifically for posting an receiving > > hints on the challenges here: > > > > http://www.pythonchallenge.com/forums/viewforum.php?f=1 > > > > Not that I mind helping. ;) > > > > Yeah, I read the whole thread for this level and even posted a question, > but the forums are pretty dead. Not only that, but I'm starting to get > the feeling that these challenges are going to require a little more > programming expertise than I have, because all of the 'hints' are still > too vague for me. > > Like I said in my post on the hints forum, I really enjoy figuring out > how to use Python to solve the puzzles, but it's not very fun when I > don't know *what* to do in the first place, and I think knowing what to > do has a lot to do with how experienced you are with certain CS subjects > and how quickly you can identify the problem and a possible solution. > All I see is huge bunch of string characters with no idea what to do > with it to extract any kind of information. Only a bunch of string characters? If that's true, you missed something. I get a bunch of lists of tuples. Each tuple has a meaning associated with the original filename, and an old unix command. Which is what confused the heck out of me the first time, not knowing much Unix. The command is used to make large signs using old-style dot matrix printers. If you want a more coherent hint than that, email me at pythor @ pythor dot com From first180 at gmail.com Sun Apr 16 10:41:39 2006 From: first180 at gmail.com (Jay) Date: 16 Apr 2006 07:41:39 -0700 Subject: Tkinter Message-ID: <1145198499.259375.90030@i39g2000cwa.googlegroups.com> I wold like to be able to generate buttons from a list in a file. How would I go about making each button have a different command, Lets say make the button print its label instead of print "." The problem I have is I don't know what the list is going to be until it is opened or how big so I carnet make a def for each. And I don't know how to do it with a loop Thanks ------Code------- from Tkinter import * class App: def __init__(self, root): self.DisplayAreaListsFrame = Frame(root) self.DisplayAreaListsFrame.pack() Lists = ["A1","B2","C3","D4"] for i in Lists: self.DisplayAreaListButton = Button( self.DisplayAreaListsFrame, text=i, command=self.ListButtonCommand) self.DisplayAreaListButton.pack(side=LEFT,padx=10) def ListButtonCommand(self): print "." root = Tk() app = App(root) root.mainloop() From dadapapa at googlemail.com Thu Apr 27 06:18:29 2006 From: dadapapa at googlemail.com (harold) Date: 27 Apr 2006 03:18:29 -0700 Subject: how to free the big list memory In-Reply-To: References: Message-ID: <1146133109.600781.35500@g10g2000cwb.googlegroups.com> pydoc gc.collect pydoc xrange From john at castleamber.com Fri Apr 28 15:32:52 2006 From: john at castleamber.com (John Bokma) Date: 28 Apr 2006 19:32:52 GMT Subject: Somebody report John [was Re: ] References: <1145992903.834316.198370@u72g2000cwu.googlegroups.com> <4GM3g.3084$TT.1768@twister.nyroc.rr.com> <1146231280.733609.143230@e56g2000cwe.googlegroups.com> <4452258e$0$655$bed64819@news.gradwell.net> <1146235544.218219.71430@j73g2000cwa.googlegroups.com> <87psj1ionl.fsf@rpi.edu> <9Rt4g.14$fM.3@fe08.lga> Message-ID: Ken Tilton wrote: > I love this entire thread. Thank you, Xah! Me too. I hope he posts again soon :-p And good luck with the reporting business ;-) -- John MexIT: http://johnbokma.com/mexit/ personal page: http://johnbokma.com/ Experienced programmer available: http://castleamber.com/ Happy Customers: http://castleamber.com/testimonials.html From fredrik at pythonware.com Tue Apr 18 14:59:33 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 18 Apr 2006 20:59:33 +0200 Subject: 2.5 excitement (was Re: Java Developer Exploring Python) References: <1145290449.735642.120860@i40g2000cwc.googlegroups.com><1204021.LzRF60KP7e@jupiter.g2ctech> Message-ID: Jon Ribbens wrote: > Apologies if I'm being obtuse, but how does including the pysqlite > wrapper module change anything? You still need to download and install > SQLite I'm pretty sure the distributors will do this for you, just as they've included zlib, dbm, tcl/tk, openssl, and many other standard libraries over the years. From aahz at pythoncraft.com Tue Apr 11 10:17:07 2006 From: aahz at pythoncraft.com (Aahz) Date: 11 Apr 2006 07:17:07 -0700 Subject: Why new Python 2.5 feature "class C()" return old-style class ? References: <1144752553.305591.88050@j33g2000cwa.googlegroups.com> <1144756774.177225.311120@z34g2000cwc.googlegroups.com> <443ba5a9$0$14281$626a54ce@news.free.fr> <1144763219.936992.219110@g10g2000cwb.googlegroups.com> Message-ID: In article <1144763219.936992.219110 at g10g2000cwb.googlegroups.com>, wrote: > >In Python 3.0 I really hope the > >class C: pass >class C(): pass >class C(object): pass > >will mean the same thing. The BDFL made that one of the very first Pronouncements of 3.0. ;-) >(So in Python 2.5 the second version can be made to mean the same thing >of the third). Can, yes. But should it? The whole point of adding the () option to classes was to ease the learning process for newbies who don't understand why classes have a different syntax from functions. Having class C(): pass behave differently from class C: pass would be of no benefit for that purpose. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "LL YR VWL R BLNG T S" From kent at kentsjohnson.com Fri Apr 28 21:54:05 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Fri, 28 Apr 2006 21:54:05 -0400 Subject: best way to determine sequence ordering? In-Reply-To: References: <70q4g.2006$No6.43783@news.tufts.edu> <1146259620.636600.119710@u72g2000cwu.googlegroups.com> Message-ID: <4452c6f3$1_2@newspeer2.tds.net> I V wrote: > Incidentally, does python have a built-in to do a binary search on a > sorted list? Obviously it's not too tricky to write one, but it would be > nice if there was one implemented in C. See the bisect module. Kent From sluggoster at gmail.com Mon Apr 17 19:56:17 2006 From: sluggoster at gmail.com (Mike Orr) Date: 17 Apr 2006 16:56:17 -0700 Subject: PEP 359: The "make" Statement References: Message-ID: <1145318176.952461.203240@i39g2000cwa.googlegroups.com> > I think this PEP is going off the rails. It's primary virtue was that it was a simpler, clearer way to write: class Foo(args): __metaclass__ = some_metaclass #... And it doesn't even do that. What's wrong with "class Foo: __metaclass__ = blah"? Two lines of code, and the double underscores indicate something special is happening. What I would most like to see is 'type' become the default metaclass without having to type wait for Python 3000 or clutter the code with a soon-to-be-redundant "(object)" base class. That would obviate my main use of __metaclass__. How about "from __future__ import classic_classes" for those few programs that really need old-style classes? From bearophileHUGS at lycos.com Wed Apr 26 18:54:05 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 26 Apr 2006 15:54:05 -0700 Subject: do while loop References: <1146012542.166096.78690@g10g2000cwb.googlegroups.com> Message-ID: <1146092044.915626.38880@j33g2000cwa.googlegroups.com> Rick Zantow>In any case, what would you want to do that you can't do (in some way) now?< You can do all things already, that's not the point, I presume. Some things added in the last years were already possibile in different ways. Rick Zantow>If you have a compelling use case,< I agree that such use cases aren't much common, but I have found 2-3 of them every 6 months (but I was used with a Pascal-like language, where repeat-until is used often). I usually solve the problem with something like: while True: ... # things to do if condition: break That isn't nice, looks like coming from an old languge, but works. Dave Hansen: do: #or "repeat:" do_loop_stuff() until time_to_leave() I was used with Pascal (that uses repeat-until) but I think the version with do-while is better, you don't have to remember to invert the condition. I like the do-while version without the else. To me this seems a good simple syntax: do: val = source.read(1) process(val) while val != lastitem This is from PEP 315, I don't like it, but it's more general: do: while : I presume you end doing a lot of: do: # code while : pass Is the loop body used often in this situation? Bye, bearophile From g.brandl-nospam at gmx.net Wed Apr 5 11:20:52 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Wed, 05 Apr 2006 17:20:52 +0200 Subject: using range() in for loops In-Reply-To: References: <443324dc$0$11257$c3e8da3@news.astraweb.com> <7x1wwc237g.fsf@ruckus.brouhaha.com> Message-ID: Steven D'Aprano wrote: > On Wed, 05 Apr 2006 16:21:02 +0200, Georg Brandl wrote: > >> Because of backwards compatibility. range() returns a list, xrange() an >> iterator: list(xrange(...)) will give the same results as range(...). > > Georg is pretty much correct in his explanation, but just to dot all the > I's and cross all the T's, we should explain that xrange() doesn't return > an iterator, it returns a special xrange object: Ah yes, the old iterator <-> iterable problem ;) Georg From bencvt at gmail.com Wed Apr 19 20:05:29 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 19 Apr 2006 17:05:29 -0700 Subject: Confused by Python and nested scoping (2.4.3) References: Message-ID: <1145491529.220713.138370@e56g2000cwe.googlegroups.com> Sean Givan wrote: > def outer(): > val = 10 > def inner(): > print val > val = 20 > inner() > print val > > outer() > > ..I expected to print '10', then '20', but instead got an error: > > print val > UnboundLocalError: local variable 'val' referenced before assignment. > > I'm thinking this is some bug where the interpreter is getting ahead of > itself, spotting the 'val = 20' line and warning me about something that > doesn't need warning. Or am I doing something wrong? Short answer: No, it's not a Python bug. If inner() must modify variables defined in outer()'s scope, you'll need to use a containing object. E.g.: class Storage(object): pass def outer(): data = Storage() data.val = 10 def inner(): print data.val data.val = 20 inner() print data.val Long answer: The interpreter (actually, the bytecode compiler) is indeed looking ahead. This is by design, and is why the "global" keyword exists. See http://www.python.org/doc/faq/programming/#what-are-the-rules-for-local-and-global-variables-in-python Things get more complex than that when nested function scopes are involved. But again, the behavior you observed is a design decision, not a bug. By BDFL declaration, there is no "parentscope" keyword analogous to "global". See PEP 227, specifically the "Rebinding names in enclosing scopes" section: http://www.python.org/dev/peps/pep-0227/ Hope that helps, --Ben From steve at REMOVETHIScyber.com.au Sat Apr 8 12:05:18 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 09 Apr 2006 02:05:18 +1000 Subject: Working with decimal points References: <1144509666.471858.55160@v46g2000cwv.googlegroups.com> Message-ID: On Sat, 08 Apr 2006 08:21:06 -0700, Byte wrote: > How come: > > sum = 1/4 > print sum > > returns 0? 1/4=0.25, not 0. How do I fix this? By default, / does integer division, not floating point. In integer division, 1/4 is 0, exactly as calculated. (How many fours go into one? Zero fours go into one, with one remainder.) There are two ways to change this: (1) Convert at least one of the numbers to a float first: >>> 1.0/4 0.25 >>> 1/float(4) 0.25 but be careful, this one doesn't do what you want: >>> float(1/4) 0.0 (2) Run the following command at the start of your program or in your interactive session: >>> from __future__ import division Now division will behave as you expect: >>> 1/4 0.25 and you can use // for integer division. Now that you can do floating point division, I peer into my crystal ball and predict your next question: why is Python so inaccurate? >>> 1/10 0.10000000000000001 Answer: it isn't. You've discovered a mathematical limitation that 1/10 cannot be written exactly in any fixed number of binary places, just like 1/3 cannot be written exactly in any fixed number of decimal places. See also: http://www.python.org/doc/faq/general.html#why-are-floating-point-calculations-so-inaccurate http://docs.python.org/tut/node16.html Hope this helps. -- Steven. From michele.simionato at gmail.com Thu Apr 6 11:53:27 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 6 Apr 2006 08:53:27 -0700 Subject: pre-PEP: The create statement In-Reply-To: <3wF*W0udr@news.chiark.greenend.org.uk> References: <59Wdnbd8EazRCqnZnZ2dnUVZ_vudnZ2d@comcast.com> <1144328362.729594.173160@z34g2000cwc.googlegroups.com> <13B*uLudr@news.chiark.greenend.org.uk> <1144335440.387962.250960@u72g2000cwu.googlegroups.com> <3wF*W0udr@news.chiark.greenend.org.uk> Message-ID: <1144338807.683935.125850@i40g2000cwc.googlegroups.com> Sion Arrowsmith wrote: > Michele Simionato wrote: > >Sion Arrowsmith wrote: > >> A quick scan of the standard library suggests that it will have > >> a grand total of 3 modules requiring a fix (it's a method name > >> in imaplib and a named argument in a couple of places in bsddb > >> and distutils). Your own code my fare worse (mine does, but not > >> by much). > >This agrees with my scan (except I also found an occurrence of 'create' > >in Tkinter). > >BTW, I would be curious to see the script you are using for the > >scanning. > > Old-fashioned egrep '\Wcreate\W' and eyeball out the false positives > 8-) . I missed the Tkinter one because I don't appear to have it > installed. I am impressed by your eyeball ability! I was unable to disentangle the false positive, so I was forced to write the script ;) From mahs at telcopartners.com Mon Apr 10 23:33:41 2006 From: mahs at telcopartners.com (Michael Spencer) Date: Mon, 10 Apr 2006 20:33:41 -0700 Subject: updated pre-PEP: The create statement In-Reply-To: References: <443a9c60$1_1@news.bluewin.ch> Message-ID: Steven Bethard wrote: > Azolex wrote: >> Steven Bethard wrote: >>> and named, nested hierarchies like XML documents could be created >>> like:: >>> >>> create ETobject html: >>> "This statement would generate an ElementTree object" >>> >>> create ETobject head: >>> "generate the head" >>> ... >>> >>> create ETobject body: >>> "generate the body" >>> ... >> I think this is is a most important eventual use-case, and would like to >> see it better worked out - or else declared outside the scope of the >> proposed statement. As far as I can see, this does not cut it, since xml >> and html allow /sequencial repetition/ of tags and the results of the >> statement suites are passed as unordered namespaces/dicts. > > Good point. The code above would only work if you didn't care about the > order of elements. I'm half inclined to pull the example, but the > original was due to Michele Simionato, and I haven't quite convinced > myself yet that you couldn't hack it to have ETObject append to an > internal list somehow to keep order. Michele? Did you have a plan for > how this would work? > > STeVe You've probably considered this, but I didn't see it in the PEP. How about returning an dict with 'history' for the namespace, e.g. in essence: class HistoryDict(dict): def __init__(self, *a, **kw): self.history = [] super(HistoryDict, self).__init__(*a, **kw) def __setitem__(self, k, v): self.history.append((k, v)) super(HistoryDict, self).__setitem__(k, v) this would behave as a normal dict, but the additional history attribute could be useful in cases where order or duplicated names are significant, such as the xml example above, database table descriptions, overloaded function definitions... Michael From antroy at gmail.com Thu Apr 20 03:11:57 2006 From: antroy at gmail.com (Ant) Date: 20 Apr 2006 00:11:57 -0700 Subject: Lamdba forms In-Reply-To: <1145492986.738200.229690@i39g2000cwa.googlegroups.com> References: <1145492986.738200.229690@i39g2000cwa.googlegroups.com> Message-ID: <1145517117.216022.261360@g10g2000cwb.googlegroups.com> Why does the function have to be unnamed? you can easly nest function definitions and refer to them. IIRC the lambda form is probably going to be removed at some point, as it is not needed: def outerfn(): dostuff() def inner(x,y): out = (x^y) print out return out my_local_function = inner my_local_function(3,4) outerfn() From donn at u.washington.edu Fri Apr 7 20:06:36 2006 From: donn at u.washington.edu (Donn Cave) Date: Fri, 07 Apr 2006 17:06:36 -0700 Subject: Why did someone write this? References: <1144428724.372163.240450@t31g2000cwb.googlegroups.com> <1144446670.262116.315360@j33g2000cwa.googlegroups.com> Message-ID: In article <1144446670.262116.315360 at j33g2000cwa.googlegroups.com>, "Sandra-24" wrote: > I can't believe I missed it in the documentation. Maybe it wasn't in > the offline version I was using, but more likely it was just one of > those things. > > So the trouble seems to be that the traceback holds a reference to the > frame where the exception occurred, and as a result a local variable > that references the traceback in that frame now holds a reference to > it's own frame (preventing the frame from being recliamed) and can't be > cleaned up prior to python 2.2 with GC enabled. > > Which means it's fine to hold a reference to the traceback in a frame > not in the traceback, or (I think) to create a temporary unamed > reference to it. I don't think that's exactly it - the problem wasn't exactly circularity, and GC wouldn't help. But as I try to write a test program that demonstrates, it looks like current versions of Python have done something with sys.exc_traceback that avoids at least some of the problems. import sys class A: def __del__(self): print 'A.__del__' def f(): a = A() try: xyz except: print 'caught expected error' print 'returning from f' return sys.exc_traceback t = f() print 'Done' In order to get the traceback to preserve "a" past its natural lifetime, I had to return it to the caller, because today sys.exc_traceback disappears when f() returns. But it shows the effect on order of execution: 'A.__del__' will appear after 'Done', when it should appear before it. When I did this (sys.exc_traceback = None), the applications used a terminal graphics library, like curses, and I often depended on finalization (__del__) to run the "close" rendering for a graphic element. Worked fine until an exception, so I add this precaution to every I/O flush. Donn Cave, donn at u.washington.edu From e.frerich at nord-com.net Tue Apr 25 12:13:00 2006 From: e.frerich at nord-com.net (Egon Frerich) Date: Tue, 25 Apr 2006 18:13:00 +0200 Subject: Zope 3 In-Reply-To: <444e3c50$0$401$626a54ce@news.free.fr> References: <1145965796.432891.274310@i39g2000cwa.googlegroups.com> <444e1377$0$30724$636a55ce@news.free.fr> <444e3c50$0$401$626a54ce@news.free.fr> Message-ID: <444E4A8C.3040700@nord-com.net> What is pythonic? See: http://faassen.n--tree.net/blog/view/weblog/2005/08/06/0 bruno at modulix schrieb am 25.04.2006 17:10: > Benji York wrote: >> bruno at modulix wrote: >> >>> Zope is a world in itself - and is certainly not the simplest tool to >>> learn (nor the most pythonic). >> >> Those statements apply more to Zope 2 than Zope 3 (and Zope 2 is moving >> more and more toward Zope 3 these days). One of Zope 3's main goals was >> to focus on the Python programmer as a primary target. That being said >> there /are/ some powerful and novel concepts used in Z3 (the component >> framework). > > While it's true that Zope3 is more 'python-programmer oriented' than > Zope2 - and probably much safer wrt/ developper's sanity -, it's still a > world on it's own, it's still a complex framework, and it's still not > very pythonic (IMHO based on 2+ years experience with Zope2, with or > without the CMF, and some time spent evaluating Zope3). > >>> You may want to consider other options like Django, Pylon or Turbogears. >> >> It's true that Z3 is not currently focused very well on the >> "middle-class" developer. > > That's an understatement !-) > >> It's more of an industrial-strength kind of >> thing, but considerable thought has been given lately on how to build >> bridges so everyone can benefit without being full-time Zope masters. >> >> Toward that end, I wrote a little quick start guide that might help the >> OP: http://www.benjiyork.com/quick_start > > -- Egon Frerich, Freudenbergstr. 16, 28213 Bremen E-Mail: e.frerich at nord-com.net From osv at javad.com Fri Apr 14 00:55:55 2006 From: osv at javad.com (Sergei Organov) Date: Fri, 14 Apr 2006 08:55:55 +0400 Subject: Python editing with emacs/wordstar key bindings. References: <1144887253.027194.198750@i39g2000cwa.googlegroups.com> <1144949128.068372.129600@t31g2000cwb.googlegroups.com> Message-ID: "BartlebyScrivener" writes: >>> When all I started looking for was a more robust editor for Python ;-) > > Both WingIDE and Komodo Dragon allow for customization of keyboard > bindings. They aren't free, but they cost only $30.00 or so. Cheap for > what you get, especially in the case of Komodo because it makes a nice > editor for many languages--Perl, PHP, HTML etc. > > I tried Xemacs several times over the years on Win XP. Something > usually breaks, and then--yes--you have to learn Lisp to fix it. No, usually you just need to ask in one of (X)emacs groups/mailing lists, and get a recipe in about a day, making it similar to learning to use Python. And that drastically differs from trying to convince those $ companies to fix something for you ;) -- Sergei. From spamspam at spam.eggs Tue Apr 11 15:40:52 2006 From: spamspam at spam.eggs (Ben C) Date: 11 Apr 2006 19:40:52 GMT Subject: RegExp question References: <1144781090.622493.252460@t31g2000cwb.googlegroups.com> Message-ID: On 2006-04-11, Michael McGarry wrote: > Hi, > > I would like to form a regular expression to find a few different > tokens (and, or, xor) followed by some variable number of whitespace > (i.e., tabs and spaces) followed by a hash mark (i.e., #). What would > be the regular expression for this? re.compile(r'(?:and|or|xor)\s*#') From martin at v.loewis.de Thu Apr 27 01:48:10 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 27 Apr 2006 07:48:10 +0200 Subject: MinGW and Python In-Reply-To: <1146087513.773086.64370@u72g2000cwu.googlegroups.com> References: <1145861223.509630.247350@y43g2000cwc.googlegroups.com> <444C79D7.4060007@v.loewis.de> <444DC62B.7000702@v.loewis.de> <1145985979.369429.114040@i39g2000cwa.googlegroups.com> <444e7d85$0$12131$9b622d9e@news.freenet.de> <1145999256.027851.132780@y43g2000cwc.googlegroups.com> <444FA782.6040503@v.loewis.de> <1146087513.773086.64370@u72g2000cwu.googlegroups.com> Message-ID: <44505b1a$0$5432$9b622d9e@news.freenet.de> Ross Ridge wrote: > Martin v. L?wis wrote: >> http://msdn2.microsoft.com/en-us/library/abx4dbyh(VS.80).aspx >> >> 'The msvcrt.dll is now a "known DLL," meaning that it is a system >> component owned and built by Windows. It is intended for future use only >> by system-level components.' > > Exactly, it's the standard Windows system C library. That's not how I read it. To me, it says: it can be used by other parts of Windows itself (i.e. system-level components), but it is not intended to be used by third-party applications (such as Python), as these are not system-level components. >> Regardless, there is no version of the MS C++ library that links against >> msvcrt.dll. > > The version of the MS C++ library in Visual Studio C++ 6 links against > MSVCRT.DLL. I see (*). Unfortunately, that version isn't available anymore, and wasn't available anymore when Python 2.4 was released. >> So if Python is linked against msvcrt.dll, you can't really build C++ >> extensions anymore (with MSVC), unless you are certain that >> mixing CRTs causes no harm for your application. > > Python 2.4 is linked against MSVCR71.DLL, so you can't really build C > or C++ extensions anymore with Microsoft's current compiler either. Right: you need to use VS.NET 2003 (which was the current compiler when Python 2.4 was first released). Regards, Martin From martin at v.loewis.de Sun Apr 9 04:00:03 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 09 Apr 2006 10:00:03 +0200 Subject: how relevant is C today? In-Reply-To: <123gv8oh4lamb7c@corp.supernews.com> References: <44381ee4$0$4209$c3e8da3@news.astraweb.com> <44382711.10403@v.loewis.de> <123gv8oh4lamb7c@corp.supernews.com> Message-ID: <4438BF03.6030000@v.loewis.de> Grant Edwards wrote: >> As for *learning* the languages: never learn a language >> without a specific inducement. > > That's silly. Learning (weather a computer language, a natural > language, or anything else) is never a bad thing. The more > languages you know, the more you understand about languages in > general. Learning languages is like any other skill: the more > you do it, the better you get at it. Learning a language (whether a natural or a programming language) needs practice, both for reading and for writing. Natural languages are often taught under the guidance of a teacher, to make sure the student gets the practice she needs. In my experience, you won't learn a programming language effectively if you don't get practice (in particular, in writing programs - although reading them might even require *more* practice, especially for C). And, people often don't practice enough (either a natural language, nor a programming language) if they don't have a specific goal in mind what they want to learn the language for. > Geeze, when I think of all the things I've "wasted my time" > learning. That's everybody's choice, of course. If you enjoy programming languages on their own merits, you won't need further motivation. However, then you don't post to a newsgroup "should I learn this language", but you just go ahead and do it. Regards, Martin From mikelaskey at gmail.com Mon Apr 17 20:51:37 2006 From: mikelaskey at gmail.com (mikelaskey at gmail.com) Date: 17 Apr 2006 17:51:37 -0700 Subject: A 'Box' Function Message-ID: <1145321497.261653.62130@g10g2000cwb.googlegroups.com> Hey guys. I should warn you, first off, that I'm relatively new to Python. Basically, what I'm trying to do is create a word-wrapping function with the added complication that it add a character at the beginning and end of each line, so that it encloses the text in a sort of 'box': ---------------- | Like this | ---------------- The word-wrapping function I'm working with is similar to the one given here: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/148061 def wrap(text, width): return reduce(lambda line, word, width=width: '%s%s%s' % (line, ' \n'[(len(line)-line.rfind('\n')-1 + len(word.split('\n',1)[0] ) >= width)], word), text.split(' ') ) Does anyone have any ideas on how it could be modified? Am I approaching it the right way? Thanks a bunch! Mike From nuffnough at gmail.com Sat Apr 29 22:04:20 2006 From: nuffnough at gmail.com (nuffnough at gmail.com) Date: 29 Apr 2006 19:04:20 -0700 Subject: Need help removing list elements. In-Reply-To: <4453ded7$1@news.eftel.com> References: <1146316090.540227.278230@j73g2000cwa.googlegroups.com> <4453ded7$1@news.eftel.com> Message-ID: <1146362660.244186.274350@i39g2000cwa.googlegroups.com> Thanks to all those who responded. It has all helped immensely. :-) I didn't know about list comprehensions before I started. very warm regards to all. From mathweijzen at home.nl Mon Apr 3 14:53:30 2006 From: mathweijzen at home.nl (Math) Date: Mon, 3 Apr 2006 20:53:30 +0200 Subject: Registration Code Message-ID: <00fd01c6574f$e6b1e950$0202a8c0@MATH> Pffff..Philippe.. Where can I find some sample code if any? And I'm not a professional programmer... This is going to be hard...and my native is Dutch.. Thanks anyway Hi, A suggestion: I would use encryption (ex: AES): Hide a secret key in your code and generate an encrypted (readable: ex 07 7B 6F ....) version of the correct info (such as full release, or demo expire in ...) with that very same key. Have your software input that encrypted info (some GUI dialog box), decypher the info then act accordingly. The trick is: where to store that ? I would use some binary data file (encrypted bziped pickle ?) with a hash or CRC built in to prevent obvious tampering. Hope that helps, Philippe Math wrote: > Hello, > > I wonder if I can ask this particular question here... > I'm writing this piece of Python Software and I'm almost done...:-) > But now I want the end-user to register this software with a registration > code or perhaps something like an evaluation demo version which expires > after some period of time... > Is this the right place to ask or does anybody know where to look for more > on the subject? > > Thanks -- http://mail.python.org/mailman/listinfo/python-list From n.estner at gmx.de Sat Apr 29 13:31:31 2006 From: n.estner at gmx.de (nikie) Date: 29 Apr 2006 10:31:31 -0700 Subject: self modifying code References: <445399A1.9020506@jessikat.plus.net> Message-ID: <1146331891.693057.190920@j73g2000cwa.googlegroups.com> Robin Becker schrieb: > When young I was warned repeatedly by more knowledgeable folk that self > modifying code was dangerous. > > Is the following idiom dangerous or unpythonic? > > def func(a): > global func, data > data = somethingcomplexandcostly() > def func(a): > return simple(data,a) > return func(a) It took me quite a while to figure out how it works, so, yes, I'd say it's unpythonic ;-). It's not really dangerous, but it can get nasty if someone tries to rename the function, or put it into a class. But that's probably not the kind of "self-modifying code" you've been warned against anyway: I've only ever seen self-modifying code in assembly language or in lisp, the idea is that you really change the code (i.e. single opcodes in the function that's currently running), so you can e.g. make an infinite loop, and eventually overwrite the loop statement to do something else so the loop ends. I'm not sure if you can do the same thing in Python, maybe by changing the bytecode of a running function. > It could be replaced by > > data = somethingcomplexandcostly() > def func(a): > return simple(data,a) > > but this always calculates data. You could of course initialize data with None and calculate it only on demand. Or you could use: http://www.phyast.pitt.edu/~micheles/python/documentation.html#memoize This has the advantage of encapsulating the memoization logic so it can be tested (and understood) separately from your code. From aleaxit at yahoo.com Sat Apr 22 02:36:07 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 21 Apr 2006 23:36:07 -0700 Subject: how to append to a list twice? References: <1he4xao.1d6me4454w0xpN%aleaxit@yahoo.com> Message-ID: <1he63p0.15i0slyckj3lzN%aleaxit@yahoo.com> Fredrik Lundh wrote: > Alex Martelli wrote: > > > > But of course that only does it once, and I don't want to have to copy > > > and paste the append line. Perhaps there's a better way than this. > > > > def makeseries(N): > > series = [N] > > append = series.append > > for tailer in xrange(N-1, -1, -1): > > append(tailer) > > append(tailer) > > But Now You've Violated The DRY Principle!!! Just as with any other unrolled loop, yes -- loop unrolling is an optimization which is based exactly on exchanging some textual repetition for a tiny bit more speed. Of course, optimizations can easily be premature, and in any case need to be checked by measurement. E.g., here are a few variations: def makeseries_a(N): series = [N] append = series.append for tailer in xrange(N-1, -1, -1): append(tailer) append(tailer) return series def makeseries_b(N): series = [N] append = series.append for tailer in xrange(N-1, -1, -1): for x in (1,2): append(tailer) return series def makeseries_c(N): series = [N] extend = series.extend for tailer in xrange(N-1, -1, -1): extend((tailer,tailer)) return series def makeseries_d(N): series = [N] extend = series.extend for tailer in xrange(N-1, -1, -1): extend((tailer,)*2) return series And: brain:~/downloads alex$ python -mtimeit -s'import rep' 'rep.makeseries_a(100)' 10000 loops, best of 3: 31.7 usec per loop brain:~/downloads alex$ python -mtimeit -s'import rep' 'rep.makeseries_b(100)' 10000 loops, best of 3: 57.4 usec per loop brain:~/downloads alex$ python -mtimeit -s'import rep' 'rep.makeseries_c(100)' 10000 loops, best of 3: 36.2 usec per loop brain:~/downloads alex$ python -mtimeit -s'import rep' 'rep.makeseries_d(100)' 10000 loops, best of 3: 54.4 usec per loop So, it would seem that (at least among these few variations) I had guessed right, this time -- the loop-unrolling is beneficial and append is minutely better than extend. Of course, the yanking from the loopbody of the boundmethod is also a key optimization here -- with unyanked (more natural) versions [[i.e., calling series.append or series.extend right in the loop body]] I measure: brain:~/downloads alex$ python -mtimeit -s'import rep' 'rep.makeseries_a(100)' 10000 loops, best of 3: 57.3 usec per loop brain:~/downloads alex$ python -mtimeit -s'import rep' 'rep.makeseries_b(100)' 10000 loops, best of 3: 83.5 usec per loop brain:~/downloads alex$ python -mtimeit -s'import rep' 'rep.makeseries_c(100)' 10000 loops, best of 3: 48 usec per loop brain:~/downloads alex$ python -mtimeit -s'import rep' 'rep.makeseries_d(100)' 10000 loops, best of 3: 68.4 usec per loop Alex From michele.petrazzo at TOGLIunipex.it Thu Apr 6 08:00:01 2006 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Thu, 06 Apr 2006 14:00:01 +0200 Subject: shelve and ".bak .dat .dir" files Message-ID: <443502c0$0$29101$5fc30a8@news.tiscali.it> Hi, I'm trying a script on a debian 3.1 that has problems on shelve library. The same script work well on a fedora 2 and I don't know why it create this problem on debian: #extract from my code import shelve class XX: def __init__(self): self._data = shelve.open("/tmp/myfile") # do the work def onClose(self): self._data.close() Now I see that shelve create not my file, but three files that has the name that I want (/tmp/myfile) and also the extensions: .bak .dat .dir Of course, before say to shelve to open, I delete the previous file, and I have all the rights to do what I want into the directory. How solve it? Thanks, Michele From johnjsal at NOSPAMgmail.com Wed Apr 12 11:56:30 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 12 Apr 2006 15:56:30 GMT Subject: just one more question about the python challenge In-Reply-To: References: Message-ID: Georg Brandl wrote: > Have you found the file? You'll have to distribute that file bytewise > in 5 "piles". No, I haven't figured out anything for this puzzle. It seems I might have to change the filename of the image to something else, but I don't know what. But even after I find the image, I won't know what to do from there. I don't know what it means to distribute a file bytewise, but if I knew exactly which modules/functions to use, I'd be more than happy reading up on them myself. I just hate not knowing where to go to begin with (even though I know I probably won't know enough about images to use the right module properly either, but I can try). From steven.bethard at gmail.com Tue Apr 11 12:42:21 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 11 Apr 2006 10:42:21 -0600 Subject: list.clear() missing?!? In-Reply-To: <1144767680.583085.310160@v46g2000cwv.googlegroups.com> References: <1144767680.583085.310160@v46g2000cwv.googlegroups.com> Message-ID: Ville Vainio wrote: > I tried to clear a list today (which I do rather rarely, considering > that just doing l = [] works most of the time) and was shocked, SHOCKED > to notice that there is no clear() method. Dicts have it, sets have it, > why do lists have to be second class citizens? This gets brought up all the time (search the archives for your favorite), but your options are basically (renaming your list to lst for readability) one of:: del lst[:] lst[:] = [] or if you don't need to modify the list in place, lst = [] Personally, I tend to go Fredrik's route and use the first. If you feel really strongly about this though, you might consider writing up a PEP. It's been contentious enough that there's not much chance of getting a change without one. STeVe From brian at rkspeed-rugby.dk Tue Apr 25 06:53:36 2006 From: brian at rkspeed-rugby.dk (Brian Elmegaard) Date: Tue, 25 Apr 2006 12:53:36 +0200 Subject: MinGW and Python References: <1145861223.509630.247350@y43g2000cwc.googlegroups.com> <444C79D7.4060007@v.loewis.de> Message-ID: "Fredrik Lundh" writes: > a better optimizer usually results in programs that run faster, not slower. Got it the wrong after some editing ;-( -- Brian (remove the sport for mail) http://www.et.web.mek.dtu.dk/Staff/be/be.html http://www.rugbyklubben-speed.dk From tdw at tdw.net Sun Apr 30 11:38:49 2006 From: tdw at tdw.net (Tim Williams) Date: Sun, 30 Apr 2006 16:38:49 +0100 Subject: Converting tuple to String In-Reply-To: References: Message-ID: <9afea2ac0604300838o746e5befjedde1cafaf3a1972@mail.gmail.com> On 30 Apr 2006 08:32:47 -0700, Byte wrote: > > > xyz = "Hello", "There" > print xyz > > Is their any way of getting print to see xyz as being one string i.e. > "Hello There" rather than "Hello" and "There", despite "Hello" and > "There" being, in reality, seperate? > >>> print " ".join(xyz) Hello There HTH :) -- Tim Williams -------------- next part -------------- An HTML attachment was scrubbed... URL: From vinjvinj at gmail.com Thu Apr 20 07:43:32 2006 From: vinjvinj at gmail.com (vj) Date: 20 Apr 2006 04:43:32 -0700 Subject: PyLint 0.11 / astng 0.16 In-Reply-To: References: Message-ID: <1145533412.721246.65590@t31g2000cwb.googlegroups.com> Are there any plans to release pylint under the LGPL license? From Serge.Orlov at gmail.com Wed Apr 19 09:21:22 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 19 Apr 2006 06:21:22 -0700 Subject: Shell like syntax for subprocess.Popen # overloading >, <, | References: <1145349423.908658.53180@g10g2000cwb.googlegroups.com> Message-ID: <1145452882.626036.301900@t31g2000cwb.googlegroups.com> jelle wrote: > Hi, > > I use python quite a bit to couple different programs together. > Doing so has been a _lot_ easier since subprocess came around, but > would really like to be able to use the succinct shell syntax; >, <, | > > That really shouldn't be too hard to wrap in a class, but so far I > didn't succeed to do so this well, since I'm facing some trouble with > operator precedence that I do not know how to overcome. > > Consider the following: > > A = 'inputString' > B = Process('process.exe') > C = cStringIO.StringIO() # output bucket > > A > B > C > > A is being piped to B and processed, but the output of B is not being > piped to C > executing A > B; B > C works as expected however. > Which is disappointing, since what I'm trying to achieve is a sugar > syntax for Popen processes, where directly sees the chain of > commands... > > Any suggestions to overcome this issue are greatly appreciated! How about good old function call? A = Lines('inputString') B = Process('process.exe') C = Process('proc2.exe') result = pipeline(A, B, C, Lines()) # Text result result = pipeline(A, B, C, Bytes()) # Binary result pipeline(A, B, C, file("somefile","wb")) # dump to binary file From rpdooling at gmail.com Mon Apr 10 08:34:58 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 10 Apr 2006 05:34:58 -0700 Subject: can't pass command-line arguments In-Reply-To: References: <1144636890.976327.253000@i39g2000cwa.googlegroups.com> <1144637633.814788.150270@i40g2000cwc.googlegroups.com> Message-ID: <1144672498.920860.110000@u72g2000cwu.googlegroups.com> >> That is wrong on so many levels Including the level where I observed that I'd already been running scripts without typing the .py extension for months, it's just that on some scripts (seems to be the ones with functions defined in them) you can't pass arguments unless you type the .py extension. Anyway, thanks all. rpd From sijben at eemvalley.com Thu Apr 20 06:53:39 2006 From: sijben at eemvalley.com (Paul Sijben) Date: Thu, 20 Apr 2006 12:53:39 +0200 Subject: massive threading performance (was:Re: UDP performance) In-Reply-To: <44473787$0$31643$e4fe514c@news.xs4all.nl> References: <44473787$0$31643$e4fe514c@news.xs4all.nl> Message-ID: <44476832$0$31656$e4fe514c@news.xs4all.nl> OK the problem I posted about earlier is NOT a UDP/socket problem, it is a threading problem. Albeit one that only happens when you have many thrreads???? I have made two little scripts using the code I copied below, one client and one server (attached). If I run them concurrently on the same machine I see the following times: >>1145526192.825508 <<1145526192.825848 >>1145526193.829325 <<1145526193.834927 a transfer time in the milliseconds. Much less than the times I see in the full application. OK so I put them both in a multithreaded script (also attached) >>1145526971.619558 <<1145526971.619909 >>1145526972.619241 <<1145526972.619647 again transfer time in milliseconds. Not like this that I get from the profile of my code: << 1145517554.363850 send >> 1145517554.647485 recv which uses the same communication and threading but has 20+ threads? Now I am completely baffled! again I really appreciate if anyone can shed light on this! Paul Paul Sijben wrote: > I am stumped by the following problem. I have a large multi-threaded > server accepting communications on one UDP port (chosen for its supposed > speed). > > I have been profiling the code and found that the UDP communication is > my biggest drain on performance! Communication where the client and the > server are on the same machine still takes 300ms or sometimes much more > per packet on an Athlon64 3000+ running Linux (Fedora Core 5 x64). > > I must be doing something wrong and would really appreciate feedback on > my code below: > > I open the server port with > > self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) > self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) > self.s.bind((myaddress, myport)) > > I then open a client port with > > self.s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM) > self.s.connect((host, port)) > > the client sends data with > > self.s.sendall(data) > > and the server with > > self.s.sendto(data,link.remoteaddress) > > both receive with > > buf, address = socket.recvfrom(8192) > > The sender and receiver are in separate threads (threading.Thread). > > Does anyone know what is going wrong here, the socket communication, the > thread scheduling? > > Paul Sijben > -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: client.py URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: server.py URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: mthreadpy.py URL: From sturlamolden at yahoo.no Tue Apr 25 07:52:37 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 25 Apr 2006 04:52:37 -0700 Subject: Hooking things up in GUI application In-Reply-To: References: Message-ID: <1145965957.073830.320580@y43g2000cwc.googlegroups.com> Ryan Ginstrom wrote: > Apropos recent threads about GUI editors, coming from a Win32/WTL C++ > background, I actually like the idea of being able to (easily) create GUIs > programmatically. > > But I still see a lot of the same tedium: hooking up events to handlers, and > getting data into and out of dialogs. In C++, this is generally handled > through code generation and/or macros, but IMO these are brittle and ugly. > > So my question: Is there a Pythonic way to make these tedious hookups easier? If you use PyGTK (it also runs on Windows), you can design the GUI with GLADE and then use libglade to import the gui as an xml-resource. You have to write all handlers (you do anyway), but the GUI design becomes entirely visual and the hookup becomes one single like of code. It doesn't get easier than that. As a bonus you get an hardware accelerated GUI (Cairo takes care of that, currently through OpenGL but a DirectX backend is planned). I.e. a hardware accelerated GUI represented as an XML resource. Isn't that Microsoft's next 'big thing' codenamed 'Avalon'? I wonder where they got the idea. This should illustrate the level of tediousness when using PyGTK: import pygtk pygtk.require('2.0') import gtk import gtk.glade class MyGUI: def __init__(self): win1 = libglade.GladeXML('mygui.glade','window1') win1.signal_autoconnect(self) # hook event handlers, pass any class or dictionary win1.maximize() def on_win1_destroy(self): gtk.main_quit() if __name__ == '__main__' gui = MyGUI() gtk.main() You cannot make it less tedious in C++. Even if you use Visual Studio and all sorts of 'wizards' to autogenerate code. Actually, if you do use C, C++ or Ada, GLADE can autogenerate code just like Visual Studio. But since an XML resource us much easier to modify and maintain, it is not recommended. From amaltasb at gmail.com Tue Apr 11 08:58:48 2006 From: amaltasb at gmail.com (amaltasb at gmail.com) Date: 11 Apr 2006 05:58:48 -0700 Subject: MySQLdb module generating errors Message-ID: <1144760328.006157.224530@i39g2000cwa.googlegroups.com> I installed MySQLdb module on bsd and when I import I get the following error... Traceback (most recent call last): File "", line 1, in ? File "MySQLdb/__init__.py", line 27, in ? import _mysql ImportError: /usr/local/lib/liblthread.so.2: Undefined symbol "_sched_yield" Is any module missing ?? Thanks From markscala at gmail.com Mon Apr 24 09:53:58 2006 From: markscala at gmail.com (markscala at gmail.com) Date: 24 Apr 2006 06:53:58 -0700 Subject: error Message-ID: <1145886838.594093.102670@j33g2000cwa.googlegroups.com> Anyone know what this error means? C:/Python24/pythonw.exe -u "C:/Python24/MyProjects/HeadsUp/cls_Bot.py" File "C:/Python24/MyProjects/HeadsUp/cls_Bot.py", line 10246 elif handname == 'straightflush': SystemError: com_backpatch: offset too large thanks From derickvn at gmail.com Tue Apr 25 07:49:56 2006 From: derickvn at gmail.com (Derick van Niekerk) Date: 25 Apr 2006 04:49:56 -0700 Subject: Zope 3 Message-ID: <1145965796.432891.274310@i39g2000cwa.googlegroups.com> I have been developing in PHP for some time now and needed to look into application frameworks to speed up my development. I was looking into Horde and CakePHP before I was introduced to Python. I started learing python and within a few *hours* I already wrote my first small program and I still use it! I love Python! Then I was introduced to Zope by freak accident. While Zope looked like the answer to my dillemma, I still can't get my head wrapped around it. Is it because I don't know Python well enough? Or is it just that difficult to learn? I would like to start my next web project (a database of demographic info on scientists in Africa) on Zope 3. Could anybody point me in the right direction? Where should I start? From nephish at xit.net Fri Apr 21 14:50:20 2006 From: nephish at xit.net (nephish at xit.net) Date: 21 Apr 2006 11:50:20 -0700 Subject: another question about buffers Message-ID: <1145645420.014839.260540@g10g2000cwb.googlegroups.com> lo there all ! i finally got my script to receive info on a socket. but i need to somehow set up a loop that will continue to listen for more info comming across the same socket. the way it works is, i log in with a login and password, it shoots back an acknowlagement, then i send a request for data. every so often it will send a packet of data that i need to record. i know how to receive once, but i dont know how to go back to receive again. the messages all start with "STX" and end with "ETX" here is what i have so far. (it isn't working very well) #set a socket to communicate with the server serverhost = '10.10.10.4' serverport = 9550 print 'connecting to server' sockobj = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sockobj.connect((serverhost,serverport)) login = 'STXusernamepasswordETX' sockobj.send(login) login_ack = sockobj.recv(1028) if login_ack: print 'received login_ack' else: print 'login failure' req = "STXsendreqETX" sockobj.send(req) # send request for data stream databack = sockobj.recv(1028) if databack: print 'caught a message %s bytes ' % len(databack) else: print 'fail to recieve data from server' the output in the terminal runs fine until it fails to get the databack, it prints out the "fail to receive from server" bit. anything obvious that i am missing here? thanks From garylinux at gmail.com Sat Apr 1 09:07:20 2006 From: garylinux at gmail.com (garylinux at gmail.com) Date: 1 Apr 2006 06:07:20 -0800 Subject: Python 2.5 licensing: stop this change In-Reply-To: <1143878092.721896.225470@v46g2000cwv.googlegroups.com> References: <1143878092.721896.225470@v46g2000cwv.googlegroups.com> Message-ID: <1143900440.401597.93370@i40g2000cwc.googlegroups.com> Look at the date. Worry about this if it is still around tomarrow From johnjsal at NOSPAMgmail.com Sun Apr 30 23:29:18 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sun, 30 Apr 2006 23:29:18 -0400 Subject: critique this little script, if you like In-Reply-To: <44557f93$0$13307$c3e8da3@news.astraweb.com> References: <44554a32$0$11750$c3e8da3@news.astraweb.com> <874q0aa8em.fsf@localhost.localdomain> <44557f93$0$13307$c3e8da3@news.astraweb.com> Message-ID: <44558158$0$13341$c3e8da3@news.astraweb.com> John Salerno wrote: > Dave Jones wrote: >> Hi John! >> >> About the path and the \'s, take a look at the os.path.join function. >> The function is smart enough to add the correct slash when joining >> directories. >> >> Dave > > Interesting, thanks! I was reading about the normcase() function, but > your suggestion might be better. Excellent, works great! But one more question: do I need to import os.path for this? I tried it with and without it, and it worked both ways, so I'm a little uncertain about whether os.path is really a separate module, or if it is still contained within os and doesn't need to be imported separately (it seems like it doesn't, but it is listed separately in the docs). From s99999999s2003 at yahoo.com Thu Apr 6 06:07:25 2006 From: s99999999s2003 at yahoo.com (s99999999s2003 at yahoo.com) Date: 6 Apr 2006 03:07:25 -0700 Subject: How to work with directories and files with spaces Message-ID: <1144318045.363191.3010@t31g2000cwb.googlegroups.com> hi I am working in unix and i have some directories names with spaces eg ABC DEF A how can i work effectively with spaces in directory/file names in python? sometimes when i do os.path.join(dir_with_spaces,"-somestring" ) , it gives me "-somestring" as the name only...without ABC DEF A it should give me ABC DEF A-somestring as the directory name thanks From heather at rediff.com Thu Apr 13 12:00:44 2006 From: heather at rediff.com (heather at rediff.com) Date: 13 Apr 2006 16:00:44 -0000 Subject: Pattern_Recognition_School+Conf_2006:Deadline Message-ID: <20060413160044.2945.qmail@rediff.com> PATTERN RECOGNITION EVENTS THIS SUMMER, 2006 _______________________ 4TH INTERNATIONAL SUMMER SCHOOL ON PATTERN RECOGNITION (ISSPR, 2006), 23-28 JULY, UK WWW.PatternRecognitionSchool.com The 4th International Summer School on Pattern Recognition will be organised at the University of Plymouth, UK (23-28 July, 2006). The school programme is listed below. Please pass on this email to your interested colleagues and students. This is a great summer school which I would recommend for everyone to attend. DEADLINE: Register BEFORE 01 MAY, 2006 through the website to get a discount on the fee. More than 100 participants in 2005! Speakers at the Summer School (ISSPR'2006) Dr. Sam Roberts Mathworks, UK (Introduction to Matlab) Prof. Wojtek Krzanowski University of Exeter, UK (Multivariate Statistics: Data Description) Dr. Mike Tipping, Microsoft Research, UK (Bayesian Pattern Recognition: Principles and Practice) Prof. Chris Bishop, Microsoft Research, UK (Latent Variables, Mixture Models and EM) Dr. Richard Everson, University of Exeter, UK (Dimensionality Reduction) Dr. Peter Tino University of Birmingham, UK (Probabilistic framework for model-based topographic map formation) Prof. Chris Williams, University of Edinburgh, UK (Neural Networks and Kernel Machines) Dr. Colin Campbell, University of Bristol, UK (Support Vector Machines and Kernel Methods: An Introduction and Review) Prof. John Shawe- Taylor, University of Southampton, UK (Kernel Based Methods) Dr. Steve Gunn, University of Southampton, UK (Matlab for Support Vector Machines) Prof. Mahesan Niranjan, University of Sheffield, UK (Classifier Performance Particle Filters for Tracking and Sequential Problems) Dr. Andrew Webb Qinetiq, UK (Decision TreesData Clustering) Prof. Xin Yao, University of Birmingham, UK (A Gentle Introduction to Evolutionary Computation; ATutorial on Evolutionary Multi-objective Optimisation) Dr. Richard Deardon, University of Birmingham, UK (Sequential Decision Making; Markov Chains Monte Carlo Methods) Dr. Jeremy Wyatt, University of Birmingham, UK (An Introduction to Reinforcement Learning) Dr. Ludmila Kuncheva, University of Wales, UK (Classifier Combination) Prof. Joseph Kittler, University of Surrey, UK (Feature Selection and Extraction) Prof. Sameer Singh, Loughborough University, UK (Multiresolution Pattern Recognition) Prof. Susan Craw, Robert Gordon University, UK (Case Based Reasoning) SUPPORTED BY: Microsoft, Springer, British Computer Society, and Mathworks. _______________________ IEEE CVPR CONFERENCE www.CVPR.org/2006 17-22 June, 2006 _______________________ 18th INTERNATIONAL CONFERENCE ON PATTERN RECOGNITION www.comp.hkbu.edu.hk/~icpr06 August 20-24, 2006 ______________________ ICIAR CONFERENCE www.iciar.uwaterloo.ca/iciar06 18-20 September, 2006 ______________________ Please see the event websites to get FULL information. Compiled by: Dr. Heather McLelland From rpdooling at gmail.com Mon Apr 10 12:36:24 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 10 Apr 2006 09:36:24 -0700 Subject: can't pass command-line arguments In-Reply-To: References: <1144676885.317592.21780@e56g2000cwe.googlegroups.com> <1144681621.999659.78880@z34g2000cwc.googlegroups.com> <1144683970.374120.279670@t31g2000cwb.googlegroups.com> Message-ID: <1144686984.923495.314620@v46g2000cwv.googlegroups.com> It's ActiveState. I just did a fresh install on an old machine. It appends pyo;pyc;pyw;py in that order to PATHEXT Thanks again to everyone for the generous help. Rick From felipe.lessa at gmail.com Sat Apr 15 19:10:22 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Sat, 15 Apr 2006 20:10:22 -0300 Subject: How to Convert a string into binary In-Reply-To: References: Message-ID: <1145142622.21100.0.camel@kenshin.CASA> Em S?b, 2006-04-15 ?s 18:09 -0400, Terry Reedy escreveu: > # given string s > binchars = [] > for c in s: binchars.append(a2b[ord(c)]) Faster: binchars = [a2b[ord(c)] for c in s] -- Felipe. From steve at REMOVETHIScyber.com.au Fri Apr 7 21:09:45 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 08 Apr 2006 11:09:45 +1000 Subject: Characters contain themselves? References: Message-ID: On Fri, 07 Apr 2006 15:50:53 +0200, WENDUM Denis 47.76.11 (agent) wrote: > But let's go back to more earthly matters. I couldn't find any clue in a > python FAQ after having googled with the following "Python strings FAQ" > about why this design choice and how to avoid falling in this trap > without having to litter my code everywhere with tests for stringiness > each time I process a generic list of items. > > Any hints would be appreciated. Here is another suggestion. If you absolutely must use strings rather than sets or lists, create a custom string class: >>> class Mystr(str): ... def __contains__(self, other): ... if self == other: return False ... return super(Mystr, self).__contains__(other) ... >>> s = Mystr("hello world") >>> "x" in s False >>> "w" in s True >>> "hello" in s True >>> "hello world" in s False Hope this helps. -- Steven. From bignose+hates-spam at benfinney.id.au Thu Apr 6 20:01:02 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 07 Apr 2006 10:01:02 +1000 Subject: Simple string formatting question References: <4434DCEC.4080308@REMOVEMEcyber.com.au> Message-ID: <87r74atfsx.fsf@benfinney.id.au> "Steven D'Aprano" writes: > On Thu, 06 Apr 2006 22:16:05 +1000, Ben Finney wrote: > > "Steven D'Aprano" writes: 1> >> I'm looking for a format string similar to '%.3f' except that > >> trailing zeroes are not included. > > > > Can;t be done, to my knowledge. You specify a particular > > precision, and the number will be formatted at that > > precision. This matches the 'printf' behaviour that inspired > > string formatting operations. > > [...] would there be any interest in extending the formatting > operations to include such a feature? It would (presumably) break > compatibility with printf, but does that matter? -1 from me. The concept of "precision" is fairly well defined; you're talking about combining that with something more special-case. In general, "special cases aren't special enough to break the rules", and the programemr should be forced to spell out what he's doing so that it's obvious. In the specific cases of the string formatting codes, they're a special case that is a marginal win because of the large body of existing experience with the standard C printf codes. That's weighed against their considerable lack of readability; expand them to be special for Python, and that "marginal win" is gone. -- \ "My girlfriend has a queen sized bed; I have a court jester | `\ sized bed. It's red and green and has bells on it, and the ends | _o__) curl up." -- Steven Wright | Ben Finney From pmartin at snakecard.com Sat Apr 8 11:22:30 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Sat, 08 Apr 2006 10:22:30 -0500 Subject: Where python looks for path Message-ID: Hi, I am currently packaging python and a few libraries: PyWin32, PySerial, PIL, wxPython, HTML generator, numarray for U3 distribution. Basically that means that the complete system initially in $path1\host will be moved dynamically to $path2\at execution. To take PIL as an example, I notice when I launch Idle in a "relative" manner: I am in $path1\host that $path1\host\Lib\site-packages\PIL is in the sys.path before I do anything. I notice that there is a PIL.pch file in site-packages: Q1) is that read by python ? On the other hand, even after appending all I can think of in sys.path, I still get an error (cannot find module) trying to load win32com.client: it fails in the win32api import in win32com.client. pywin32.pch is there. I think all the .dlls are there also, so I'm a bit confused. Q2) what should I be looking for ? Also, I seemed to notice in the past that modules (my own) not listed in any __init__.py where found under Linux but not Windows for which I had to upgrade my __init__.py. Q3: is that true ? Regards, Philippe From paul at boddie.org.uk Sat Apr 8 14:03:10 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 8 Apr 2006 11:03:10 -0700 Subject: minidom + wxPython woes References: <1144448449.586601.293480@v46g2000cwv.googlegroups.com> <1144477016.011818.70290@e56g2000cwe.googlegroups.com> <1144503992.283231.305290@i40g2000cwc.googlegroups.com> Message-ID: <1144519390.080682.247970@e56g2000cwe.googlegroups.com> Frank Millman wrote: > Fredrik Lundh wrote: > > > > no, it's not a bug in the pyexpat module -- the problem is that > > wxPython uses it's own incompatible version of the expat library, > > and loads it in a way that causes problems for any library that's > > tries to use its own statically linked version. [...] > Firstly, it seems from various posts to the tracker item that the same > problem has been reported with pygtk, Qt, and VTK. There used to be issues with Expat, PyXML and mod_python which may be vaguely related to this, mostly because there was some usage of Expat within some Apache component which conflicted with PyXML's Expat configuration. In the end, I just dropped PyXML and started using other libraries not affected by such issues, and I'm not totally sure that anyone really resolved the problem definitively (although this was possibly four or five years ago, so a lot can have happened since). Paul From duncan.booth at invalid.invalid Wed Apr 26 04:09:20 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 26 Apr 2006 08:09:20 GMT Subject: Introspection Class/Instance Name References: Message-ID: *binarystar* wrote: > class Bollocks: > > def __init__( self ): > > print self.__method_that_returns_class_name__() > print self.__method_that_returns_instance_name__() > > > instance_of_bollocks = Bollocks() > > # Which outputs > > 'Bollocks' > 'instance_of_bollocks' > >>> class Bollocks(object): def name_of_instance(self): return "self" >>> instance_of_bollocks = Bollocks() >>> print instance_of_bollocks.__class__.__name__ Bollocks >>> print instance_of_bollocks.name_of_instance() self >>> At the time when the method is called, 'self' is a perfectly valid name for the instance. Seriously though, how do you expect a method to decide if you do: >>> another_name = instance_of_bollocks >>> print another_name.name_of_instance() ??? which name should appear here ??? >>> more = [another_name]*5 >>> print more[2] ??? and what name here ??? and did you want a global name, or a local variable from some function and if so which function and at which stack level? Python does actually give you sufficient introspection to do this, but you have to write some fairly complex code to iterate through the namespaces you are interested in searching for the object. A much more reasonable solution is to give your object a name attribute: >>> class Bollocks(object): def __init__(self, name): self.name = name >>> instance_of_bollocks = Bollocks('Archimedes') >>> print instance_of_bollocks.name Archimedes From anthony at python.org Wed Apr 5 08:48:00 2006 From: anthony at python.org (Anthony Baxter) Date: Wed, 5 Apr 2006 22:48:00 +1000 Subject: RELEASED Python 2.5 (alpha 1) Message-ID: <200604052248.19094.anthony@python.org> On behalf of the Python development team and the Python community, I'm happy to announce the first alpha release of Python 2.5. This is an *alpha* release of Python 2.5, and is the *first* alpha release. As such, it is not suitable for a production environment. It is being released to solicit feedback and hopefully discover bugs, as well as allowing you to determine how changes in 2.5 might impact you. If you find things broken or incorrect, please log a bug on Sourceforge. In particular, note that changes to improve Python's support of 64 bit systems might require authors of C extensions to change their code. More information (as well as source distributions and Windows installers) are available from the 2.5 website: http://www.python.org/2.5/ The plan from here is for a number of additional alpha releases, followed by one or more beta releases and moving to a 2.5 final release around August. PEP 356 includes the schedule and will be updated as the schedule evolves. The new features in Python 2.5 are described in Andrew Kuchling's What's New In Python 2.5. It's available from the 2.5 web page. Amongst the language features added include conditional expressions, the with statement, the merge of try/except and try/finally into try/except/finally, enhancements to generators to produce a coroutine kind of functionality, and a brand new AST-based compiler implementation. New major modules added include hashlib, ElementTree, sqlite3 and ctypes. In addition, a new profiling module cProfile was added. A large number of bugs, regressions and reference leaks have been fixed since Python 2.4. See the release notes for more. Enjoy this new (alpha!) release, Anthony Anthony Baxter anthony at python.org Python Release Manager (on behalf of the entire python-dev team) -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From deets at nospam.web.de Fri Apr 14 08:45:56 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 14 Apr 2006 14:45:56 +0200 Subject: List of all syntactic sugar? References: <1145008451.273827.293680@v46g2000cwv.googlegroups.com> Message-ID: <4a9js4Frcjv5U1@uni-berlin.de> > That kind of depends on what you mean by syntactic sugar. For instance, I > wouldn't call any of your examples syntactic sugar. AFAIK that is exactly what syntactic sugar means. Apart from non-strictness, all syntax can be expressed by function application. Even foo.bar() is nothing but bar(self) So - he used the term right I'd say. Regards, Diez From broek at cc.umanitoba.ca Mon Apr 24 18:17:01 2006 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Mon, 24 Apr 2006 17:17:01 -0500 Subject: PYTHONPATH In-Reply-To: References: <1145535721.138411.145790@z34g2000cwc.googlegroups.com> <44478f30$0$12862$626a54ce@news.free.fr> Message-ID: <444D4E5D.80604@cc.umanitoba.ca> Edward Elliott said unto the world upon 23/04/06 07:56 PM: > Brian van den Broek wrote: >>Only somewhat, as if I open a brand new shell: >> >>brian at Cedric:~$ python >> >>> from sys import path >> >>> path[0:3] >>['', '/usr/lib/python24.zip', '/usr/lib/python2.4'] > > > You realize this only prints the first 3 elements of path, right? Indeed :-) As the desired new path elements after running '. .bash_profile' were inserted starting at path[1], I did this to cut down on the size of the screen dump. > >>So, it seems that I currently have to invoke '. .bash_profile' >>manually with each new shell opened for this to have effect. > > > Your shell must not be opening as a login shell. From the bash man page: > When you do need ubuntu-specific help, you can try the > forums on > > http://ubuntuforums.org/ > > I don't think you'll need that for any Python-related questions though > (other than installing python packages with apt-get). Thanks again, Edward. If the information you've given me doesn't get me sorted out, I will try with the ubuntu folk. Best, Brian vdB From onurb at xiludom.gro Thu Apr 6 04:10:51 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 06 Apr 2006 10:10:51 +0200 Subject: pre-PEP: The create statement In-Reply-To: <59Wdnbd8EazRCqnZnZ2dnUVZ_vudnZ2d@comcast.com> References: <59Wdnbd8EazRCqnZnZ2dnUVZ_vudnZ2d@comcast.com> Message-ID: <4434cc48$0$4629$636a55ce@news.free.fr> Steven Bethard wrote: > The PEP below should be mostly self explanatory. I'll try to keep the > most updated versions available at: > > http://ucsu.colorado.edu/~bethard/py/pep_create_statement.txt > http://ucsu.colorado.edu/~bethard/py/pep_create_statement.html > > > > PEP: XXX > Title: The create statement > Version: $Revision: 1.4 $ > Last-Modified: $Date: 2003/09/22 04:51:50 $ > Author: Steven Bethard > Status: Draft > Type: Standards Track > Content-Type: text/x-rst > Created: 05-Apr-2006 > Python-Version: 2.6 > Post-History: 05-Apr-2006 > > > Abstract > ======== > > This PEP proposes a generalization of the class-declaration syntax, > the ``create`` statement. The proposed syntax and semantics parallel > the syntax for class definition, and so:: > > create : > > > is translated into the assignment:: > > = ("", , ) > > where ```` is the dict created by executing ````. > The PEP is based on a suggestion [1]_ from Michele Simionato on the > python-dev list. > Seems mostly clean. +1. (and I do prefer it with the 'create' statement - more explicit and readable than Michele's original proposition IMHO). -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From fredrik at pythonware.com Tue Apr 18 14:33:27 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 18 Apr 2006 20:33:27 +0200 Subject: Plug-Ins In A Python Application References: <1145379492.204367.38120@v46g2000cwv.googlegroups.com> Message-ID: redefined.horizons at gmail.com wrote: > Is it possible to load and use "modules" containing plug-in code > written by third party developers into a running instance of the > framework? How would I do this? Do I need to "dynamically load" the > module at runtime? (I will scan a folder in the application direcotry > for XML files containing information about the plug-ins, including the > modules that implement them.) a simple approach is to do something like for file in list_of_plugins: ns = {} execfile(file, ns) # pick up interesting objects from the namespace dictionary # e.g. callback = ns["callback"] where individual plugins might look something like # my plugin def callback(event): pass # do something here You can prepopulate the namespace to make application-specific objects available for the plugins: context = MyContext() for file in list_of_plugins: ns = dict(context=context) execfile(file, ns) which allows the plugins to do e.g. # my plugin def callback(event): pass context.register(callback) or you can use a plugin initialization function: context = MyContext() for file in list_of_plugins: ns = {} execfile(file, ns) setup = ns["setup"] setup(context) where the plugins look like: def callback(event): pass def setup(context): context.register(callback) and so on. To learn more about this, look up exec/execfile and __import__ in the library reference. From peter at engcorp.com Thu Apr 13 08:51:59 2006 From: peter at engcorp.com (Peter Hansen) Date: Thu, 13 Apr 2006 08:51:59 -0400 Subject: list.clear() missing?!? In-Reply-To: References: <1144767680.583085.310160@v46g2000cwv.googlegroups.com> Message-ID: Fredrik Lundh wrote: > Peter Hansen wrote: >>One of very first things newcomers learn (I believe, though I don't know >>how soon the tutorial teaches it) > > let's see. lists are introduced on page 19, a more extensive discussion of lists is > found on page 33, the del statement appears on page 34, and the dir() function > is introduced on page 46. You're spending a lot of time trying to convince me I'm wrong, yet until Georg did something about it just now, nowhere in those sections did it talk about [:] specifically, which is sort of the whole point. It is *not* obvious that although [x:] and [:y] and [x:y] take subsets of things, that leaving them both out is either legal or useful. Thankfully (to Georg), it now is. (Well, I haven't read it yet, but I'll take his word for it.) -Peter From paul at boddie.org.uk Thu Apr 6 14:16:40 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 6 Apr 2006 11:16:40 -0700 Subject: HTMLParser fragility References: Message-ID: <1144347400.318697.75980@i39g2000cwa.googlegroups.com> Richie Hindle wrote: > > But Tidy fails on huge numbers of real-world HTML pages. Simple things like > misspelled tags make it fail: > > >>> from mx.Tidy import tidy > >>> results = tidy("Hello world!") [Various error messages] > Is there a Python HTML tidier which will do as good a job as a browser? As pointed out elsewhere, libxml2 will attempt to parse HTML if asked to: >>> import libxml2dom >>> d = libxml2dom.parseString("Hello world!", html=1) >>> print d.toString() Hello world! See how it fixes up the mismatching tags. The libxml2dom package is available in the usual place: http://www.python.org/pypi/libxml2dom Paul From nogradi at gmail.com Wed Apr 12 06:41:33 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Wed, 12 Apr 2006 12:41:33 +0200 Subject: Problem with spawning an external process In-Reply-To: <1144836062.3376.42.camel@notamc2.snetsys.co.za> References: <1144834050.3376.35.camel@notamc2.snetsys.co.za> <1144834879.3376.39.camel@notamc2.snetsys.co.za> <5f56302b0604120253u2705a0fdo837a981d9930a635@mail.gmail.com> <1144836062.3376.42.camel@notamc2.snetsys.co.za> Message-ID: <5f56302b0604120341m1795e472l6bda5f2be91780bc@mail.gmail.com> > Daniel, thanks for your input. What version of the JDK/JRE and Python > are you using? So the previous test was on python 2.4, java 1.4.2, suse 9.3 but now I ran it on python 2.3.5, java 1.4.2, gentoo 1.4.16 and your code still does what it supposed to do. I'm not sure if that is good new for you though :) From larry.bates at websafe.com Mon Apr 17 17:38:38 2006 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 17 Apr 2006 16:38:38 -0500 Subject: scanning through page and replacing all instances of 00:00:00.00 In-Reply-To: References: Message-ID: <44440ADE.6060900@websafe.com> Kun wrote: > I have a python-cgi file that pulls data from an sql database, i am > wondering what is the easiest way to remove all instances of > '00:00:00.00' in my date column. > > how would i write a python script to scan the entire page and delete all > instances of '00:00:00.00', would i use regular expressions? You could use regular expressions or you might want to take a look at Beautiful Soup http://www.crummy.com/software/BeautifulSoup to parse the page and replace the offending text. -Larry Bates From clpy at russellsalsbury.com Thu Apr 6 16:21:25 2006 From: clpy at russellsalsbury.com (Russ Salsbury) Date: 6 Apr 2006 13:21:25 -0700 Subject: "definitive" source on advanced python? In-Reply-To: <1144339779.112572.55170@v46g2000cwv.googlegroups.com> References: <1144040231.239622.159630@j33g2000cwa.googlegroups.com> <1144339779.112572.55170@v46g2000cwv.googlegroups.com> Message-ID: <1144354884.982185.107160@j33g2000cwa.googlegroups.com> pruebauno at latinmail.com wrote: > vdrab wrote: > > Hi all, > > > > Is there some sort of coherent source (dead tree format, maybe?) on > > some of the more advanced features > > of python (decorators, metaclasses, etc)? I'm sort of looking for a > > If you just want a good book in feature description I recomend Python > in a Nutshell. It will explain everything you ever did (or didn't) want > to know without much fuzz. It will not have a long list of when you > should use them. For the later the Python Cookbook is probably more > appropiate. It is the book with the most amount and kind of advanced > stuff IMHO. The printed version is much better than the online because > it not only contains the examples but explains how they work. The > problem is that the cookbook is organized by problem domain and not by > implementation technique. To learn techniques you have to read it like > the Bible: you read the stories and try to deduce what it tells you > about Python. The Python Cookbook is the word of God as told to the Prophet. I can light a candle to that. -- Russ From bj_666 at gmx.net Sat Apr 29 18:13:28 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sun, 30 Apr 2006 00:13:28 +0200 Subject: Why does bufsize=1 not work in subprocess.Popen ? References: Message-ID: In , I. Myself wrote: > I read in the docs that "bufsize=1" causes line buffering. (for > subprocess.Popen) > > The following tiny program launches an executable file and then receives > its output. That works, but I want to > receive each line as it is ouput, not all of the lines at termination, > which is what is happening. >From the Python side you can only control Python's input buffer but not the output buffer of the external program you are starting. I guess that programs buffers its output. Ciao, Marc 'BlackJack' Rintsch From onurb at xiludom.gro Tue Apr 18 04:56:07 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 18 Apr 2006 10:56:07 +0200 Subject: Java Developer Exploring Python In-Reply-To: <1145290449.735642.120860@i40g2000cwc.googlegroups.com> References: <1145290449.735642.120860@i40g2000cwc.googlegroups.com> Message-ID: <4444a9f6$0$4272$626a54ce@news.free.fr> redefined.horizons at gmail.com wrote: > I've traditionally been a Java developer, although I play around with > LISP. I recently migrated to Linux and I was exploring Mono as an > option for development on Linux. However, I've had some problems with > the maturity and support when working with Mono. So I was considering > Python as an alternative development language. > > Is Python actively developed and supported on Linux? Yes. In fact, all distros I know ships with (and often depends on) Python. > Would it be a > viable option for cross-platform application development? Yes. Python runs on most platforms, and wxPython runs on Windows, MacOS X, and most Unices > Can anyone recommend an open source IDE for Python that runs on Linux? Emacs ?-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From sturlamolden at yahoo.no Fri Apr 28 06:55:44 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 28 Apr 2006 03:55:44 -0700 Subject: MinGW and Python In-Reply-To: References: Message-ID: <1146221744.792545.53680@y43g2000cwc.googlegroups.com> Ames Andreas wrote: > 1) psychological issues: 'convenient IDE', 'better debugger' I prefer Eclipse when using MinGW. That IDE is on par with Visual Studio. And Python will be developed for GCC anyway. > 2) legal issues: redistribution of msvcrXX That is indeed the problem. msvcrXX cannot be redistributed with MinGW binaries. On the other hand, msvcrXX cannot be redistributed with py2exe standalones either. The current dependency on msvcrXX makes it illegal (mostly) to distribute standalone applications made with py2exe. You have to rely on msvcrXX already being installed in a system folder. The solution must be to get the msvcrXX dependency out of Python. > There remains one technical issue that isn't a killer but would > be inconvenient, IMHO: Can pywin32 be made working with a > mingw-python (I'm quite sure it can't be made building on it)? > I'd appreciate any datapoints about that ... Two issues: 1. COM. MinGW is not know to be the best compiler for COM development. Although MinGW binaries are COM ABI compatible. 2. MFC. A MinGW compiled MFC cannot be legally redistributed. From grante at visi.com Sun Apr 30 17:54:22 2006 From: grante at visi.com (Grant Edwards) Date: Sun, 30 Apr 2006 21:54:22 -0000 Subject: How to efficiently read binary files? References: Message-ID: <125acgep357kbd8@corp.supernews.com> On 2006-04-30, David Lees wrote: > I want to process large binary files (>2GB) in Python. I have played > around with prototypes in pure Python and profiled the code. Most of > the time seems to be spent converting back and forth to and from strings > using the struct module. Is there a way to directly read into an array > of integers in Python? Perhaps the numarray module? -- Grant Edwards grante at visi.com From John-Whitlock at ieee.org Thu Apr 13 10:57:20 2006 From: John-Whitlock at ieee.org (JW) Date: 13 Apr 2006 07:57:20 -0700 Subject: just one more question about the python challenge In-Reply-To: References: Message-ID: <1144940240.587803.143410@e56g2000cwe.googlegroups.com> You said: > Sorry to post here about this again, but the hint forums are dead, and > the hints that are already there are absolutely no help (mostly it's > just people saying they are stuck, then responding to themselves saying > the figured it out! not to mention that most of the hints require > getting past a certain point in the puzzle before they make sense, and > i'm just clueless). I just went to the hint forums: http://www.pythonchallenge.com/forums/index.php There are SEVEN pages of clues for level 12. The most recent post (to challenge 1) was on April 11, so the forums are most certainly not dead. Yes, the hints don't spell out what step they are refering to, and a certain level of obfuscation is required to avoid giving away hints. Many can not be solved in a day - they require reading hints, thinking hard, then doing something else (reading, working, sleeping) to let the subconscious chew over the clues. This is the fun of the challenge - there is no secret knowledge gained, other than a list of URLs and passwords. If this isn't your definition of fun, then you can go on to other things with a clear conscious. From peter at engcorp.com Wed Apr 5 21:11:47 2006 From: peter at engcorp.com (Peter Hansen) Date: Wed, 05 Apr 2006 21:11:47 -0400 Subject: output formatting for user-defined types In-Reply-To: <1144283268.217968.316100@i39g2000cwa.googlegroups.com> References: <1144283268.217968.316100@i39g2000cwa.googlegroups.com> Message-ID: Russ wrote: > I'd like to get output formatting for my own classes that mimics the > built-in output formatting. For example, > > >>>>x = 4.54 >>>>print "%4.2f" % x > > > 4.54 > > In other words, if I substitute a class instance for "x" above, I'd > like to make the format string apply to an element or elements of the > instance. Is that possible? If so, how? Thanks. I believe implementing the special method __float__ on your class should be sufficient. class X: def __float__(self): return 3.14 >>> print '%f' % X() 3.140000 -Peter From first180 at gmail.com Sat Apr 8 11:07:30 2006 From: first180 at gmail.com (Jay) Date: 8 Apr 2006 08:07:30 -0700 Subject: Compleated Begginers Guide. Now What? In-Reply-To: References: <1144497870.999295.162450@i39g2000cwa.googlegroups.com> Message-ID: <1144508850.866725.281250@z34g2000cwc.googlegroups.com> Verry true but no help at all From johnzenger at gmail.com Wed Apr 19 03:52:33 2006 From: johnzenger at gmail.com (johnzenger at gmail.com) Date: 19 Apr 2006 00:52:33 -0700 Subject: scanning for numerals / letters In-Reply-To: References: Message-ID: <1145433153.279820.269900@t31g2000cwb.googlegroups.com> First, note that form["date"] is all you need. form["date"].value is redundant. I would do this with sets: import string if set(form["date"]) & set(string.ascii_letters) != set([]): print "You have to enter a date with numbers" if set(form["purchases"]) & set(string.digits) != set([]): print "Please do not use numbers" Sets take time to construct, but they test membership faster than strings. Plus, the code just reads logically. (The &, if you couldn't figure it out, does an intersection of sets. You could also use the .intersection method for even better readability). From Aiwass333 at gmail.com Fri Apr 7 11:01:38 2006 From: Aiwass333 at gmail.com (RunLevelZero) Date: 7 Apr 2006 08:01:38 -0700 Subject: wxPython Question In-Reply-To: <1144419812.960133.224010@t31g2000cwb.googlegroups.com> References: <1144419812.960133.224010@t31g2000cwb.googlegroups.com> Message-ID: <1144422098.382628.42440@i40g2000cwc.googlegroups.com> I think you are looking for a drag and drop GUI builder? If so then http://wxglade.sourceforge.net/ -- wxglade is what you need. There are some others but this is what I prefer myself. From kent at kentsjohnson.com Thu Apr 20 13:47:57 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Thu, 20 Apr 2006 13:47:57 -0400 Subject: how to transfer a python object to other computer? In-Reply-To: References: Message-ID: <4447c92e$1_3@newspeer2.tds.net> >> Hey, all.Now I wanna to transfer a object to other computer, Maybe I >> could serialize the object to a file by pickle moudle, then send the file >> and get it from the file.But I think the efficency is awful, because the >> disk io is very slow. >> Someone could do me a favor to give me some idea? Use pickle.dumps() and pickle.loads() to serialize to/from a string. Kent From sturlamolden at yahoo.no Wed Apr 26 14:29:53 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 26 Apr 2006 11:29:53 -0700 Subject: Pyrex installation on windows XP: step-by-step guide In-Reply-To: <1145449777.731155.181600@i40g2000cwc.googlegroups.com> References: <1145449777.731155.181600@i40g2000cwc.googlegroups.com> Message-ID: <1146076193.605314.70200@g10g2000cwb.googlegroups.com> Julien Fiore wrote: > > # step A.3 # > Install Mingw, the gcc compiler for Windows, available at > http://www.mingw.org/download.shtml. (we downloaded the file > MinGW-5.0.2.exe and installed only the "base tool" (this includes > mingw-runtime 3.9, w32api-3.6, binutils 2.15.91 and gcc-core 3.4.2). > Add Mingw path ("C:\MinGW\bin") to the Windows "Path" environment > variable. If you already have cygwin installed, add C:\MinGW\bin before > the Cygwin path. I don't think this is safe. MinGW links with msvcrt.dll whereas the main Python distribution links with msvcr71.dll (due to Visual C++ 2003). It is not safe to mix and blend different C runtime libraries. If you are to build a C extension with MinGW, you also need to build Python against msvcrt.dll, i.e. you have to use a Python built with MinGW or Visual C++ 6.0. There other option is to make MinGW link against msvcr71.dll. I don't know if that is feasible. From catseng at gmail.com Tue Apr 11 17:39:41 2006 From: catseng at gmail.com (CT) Date: 11 Apr 2006 14:39:41 -0700 Subject: trouble with Tkinter and Tix Message-ID: <1144791581.447835.22660@g10g2000cwb.googlegroups.com> Hi, I installed python 2.4.3, Tcl 8.4 Tk8.4 and also with Tix 8.4 I got some error like _tkinter.TclError:ambigous option "-col": must be column, etc with my LabelFrame from Tix. It seems that the python interpreter is mixing my Tix with Tkinter? If I put Tix.LabelFrame and use import Tix instead of from Tix import *, the problem seems to be gone. Any idea how to fix it without editing all the codes? thanks, CT From rpdooling at gmail.com Tue Apr 11 14:20:28 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 11 Apr 2006 11:20:28 -0700 Subject: Searching python-list and MySQL References: Message-ID: <1144779628.099891.149950@i39g2000cwa.googlegroups.com> >> Can someone tell me how to search this mailing list, short of >> downloading every month's archive and searching manually? Huh? How are you accessing it now? Just point your browser to: http://groups.google.com/group/comp.lang.python and look in the upper right hand corner where there's a box that says "Search This Group" rick From sdavies6 at nyc.rr.com Sat Apr 8 13:56:13 2006 From: sdavies6 at nyc.rr.com (sdavies6) Date: Sat, 08 Apr 2006 17:56:13 GMT Subject: Do I Need This? Message-ID: <1PSZf.18681$cY3.16958@news-wrt-01.rdc-nyc.rr.com> I have no idea how this got onto my month old HP computer; I must have downloaded something which uses it. It seems I have a folder and subfolders equaling about 29 MB, called PYTHON 22. The subfolders are "DLLs," "Lib," "libs," "Scripts," and, "td." I am not a programmer, so I'm wondering if I can safely remove this. From paul at boddie.org.uk Tue Apr 11 11:32:02 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 11 Apr 2006 08:32:02 -0700 Subject: minidom + wxPython woes In-Reply-To: <1144753067.607004.49170@e56g2000cwe.googlegroups.com> References: <1144448449.586601.293480@v46g2000cwv.googlegroups.com> <1144477016.011818.70290@e56g2000cwe.googlegroups.com> <1144503992.283231.305290@i40g2000cwc.googlegroups.com> <1144519390.080682.247970@e56g2000cwe.googlegroups.com> <1144753067.607004.49170@e56g2000cwe.googlegroups.com> Message-ID: <1144769521.999860.67410@i40g2000cwc.googlegroups.com> grah... at dscpl.com.au wrote: > > FYI, the incompatibility issues that arise with pyexpat in mod_python > are well documented at: > > http://www.dscpl.com.au/articles/modpython-006.html Nice document! Is there some possibly-similar explanation of character encoding issues with mod_python and Expat somewhere, too, or is that problem long forgotten? Paul From webraviteja at gmail.com Wed Apr 12 03:31:56 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 12 Apr 2006 00:31:56 -0700 Subject: executing perl script within python In-Reply-To: <1144817308.557404.305700@i40g2000cwc.googlegroups.com> References: <1144817308.557404.305700@i40g2000cwc.googlegroups.com> Message-ID: <1144827116.319254.102740@j33g2000cwa.googlegroups.com> This may help http://search.cpan.org/~gaas/pyperl-1.0/perlmodule.pod You can always use pipes (os.popen) to keep things simple. From michele.petrazzo at TOGLIunipex.it Wed Apr 26 10:02:35 2006 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Wed, 26 Apr 2006 16:02:35 +0200 Subject: wxpython warnings In-Reply-To: References: <1146054739.094951.278490@e56g2000cwe.googlegroups.com> Message-ID: <444f7d79$0$29099$5fc30a8@news.tiscali.it> Philippe Martin wrote: > I had a similar but simple problem (the file was missing) and had to > check by hand before calling wxPython. > > Can you check the tag by hand before calling wxPython ? > > > Philippe > > Hi, also I have the same problem with g3/g4 images. My solution was convert that image *before* to .png before... Very bad hack, but work. I think that is an internal wxWidgets message (warning), passed to the wxPython subsystem. Have you tried to wrote to the wxpython ml? Michele From girodt at gmail.com Thu Apr 27 06:56:42 2006 From: girodt at gmail.com (TG) Date: 27 Apr 2006 03:56:42 -0700 Subject: Inherit from array In-Reply-To: <444fa29d$0$21529$626a54ce@news.free.fr> References: <1146057315.721573.196140@u72g2000cwu.googlegroups.com> <444f79a8$0$5191$626a54ce@news.free.fr> <1146059557.692537.144820@v46g2000cwv.googlegroups.com> <3Ux*Gm+er@news.chiark.greenend.org.uk> <444fa29d$0$21529$626a54ce@news.free.fr> Message-ID: <1146135402.051057.88050@v46g2000cwv.googlegroups.com> Hmm ... I'm definitely not a python wizard, but it seems to be quite a special case that breaks the rules ... unpythonic, isn't it ? Has anyone seen a PEP on this subject ? Just in case a troll reads this message : i'm not saying python sucks or has huge design flaws here ... From arne.meissner at gmx.de Fri Apr 7 12:23:42 2006 From: arne.meissner at gmx.de (Arne) Date: Fri, 7 Apr 2006 18:23:42 +0200 Subject: FTP Message-ID: Hello! I want to connecto to a ftp server. There I woult like to read the directiroy and getting the filename, file owner and the file size. How can I do this in python and if possible please post the code for it. Thanks! Arne From phddas at yahoo.com Sun Apr 23 08:58:15 2006 From: phddas at yahoo.com (Gary Wessle) Date: 23 Apr 2006 22:58:15 +1000 Subject: debugging in emacs References: <87fyk44gyt.fsf@localhost.localdomain> Message-ID: <87bqus4ffc.fsf@localhost.localdomain> Gary Wessle writes: > Hi python users > > I am using emacs and python-mode.el under dabian testing. > is there a way to debug python code where I can step over each line > and watch the value of all the variables and be able to change > any during debugging. say you have a loop structure and want to see > what the values of your variables are during debugging when your code > is running as you step line by line. > > thanks what is the most used the older python-mode.el or the newer python.el? I am using eamcs 21.4.1 under dabian testing. From tjreedy at udel.edu Wed Apr 19 20:25:57 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 19 Apr 2006 20:25:57 -0400 Subject: Confused by Python and nested scoping (2.4.3) References: Message-ID: "Sean Givan" wrote in message news:AGy1g.62595$VV4.1170375 at ursa-nb00s0.nbnet.nb.ca... > Hi. I'm new to Python, and downloaded a Windows copy a little while > ago. I was doing some experiments with nested functions, and ran into > something strange. Experiments are good. Strange can be instructive. ... > I'm thinking this is some bug Blaming the interpreter is not so good, but amazingly common among newcomers ;-) > where the interpreter is getting ahead of itself, ... > Or am I doing something wrong? In a sense, you got ahead of yourself. And the issue has nothing to do with nested scopes per se. When things seem strange, try a simpler experiment. >>> x=1 >>> def f(): print x x = 2 >>> f() Traceback (most recent call last): File "", line 1, in -toplevel- f() File "", line 2, in f print x UnboundLocalError: local variable 'x' referenced before assignment The compiler compiles functions in two passes: the first to classify names as local or global (or nested if relevant, but not really so here), the second to generate bytecodes which depend on that classification. Terry Jan Reedy From tjreedy at udel.edu Sat Apr 1 18:29:52 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 1 Apr 2006 18:29:52 -0500 Subject: Doc suggestions References: <1142964085.356976.166620@t31g2000cwb.googlegroups.com><1143574346.354680.136060@i39g2000cwa.googlegroups.com> <1143762250.537475.115420@t31g2000cwb.googlegroups.com> Message-ID: wrote in message news:1143762250.537475.115420 at t31g2000cwb.googlegroups.com... > "Terry Reedy" wrote: > Not sure how premature it is. I've been reading > c.l.p. on and off for nearly a year. Yes, there have been claims that doc patches have to be in Latex or are otherwise not welcome. But these mostly (all?) have lacked relevant concrete data, which would be actual responses to actual submissions to the Python SourceForge change trackers. There have also been fact-based postings at least partly refuting such claims, including some by me. >> > I gather corrections of factual >> > errors are welcome, but stylistic, or organizational >> > ones are not. I would not be surprised if the volunteer doc editors see corrections and the writing of missing docs as higher priority than sylistic upgrades, but that is different from 'not welcome'. Some time ago, Alex Martelli submitted several style change suggestions for at least one of the docs. As I remember, at least most of them were accepted. In any case, all were considered. And there have since been other changes that I have been involved with that were arguably style upgrades rather than corrections. A few organizational changes might be considered, especially if accompanied by an offer to make at least a prototype, but someone with fundamentally different ideas should write their own doc under their own name. >> If you wish to become a volunteer Python improver, let me know either >> here or privately and I will respond with a suggestion and an offer. > > Yes, please do. Frederik has one idea. Here is what I was going to say, and will anyway. Suggestion: You could submit the one improved sentence you previously suggested. But the overhead of any change is a bit high for just that. So gather at least a few suggestions, put them in order, include section number and identifier for each, and cut-and-paste urls from current docs at python.org. Offer: If you submit your 'text patch' to SourceForge and let me know, I will review it right away. If you prefer, post or email to me and I will 'pre' review it before submission. You can collect ideas from others if you want; I only care about formating that make the proposed change sites and contexts easy to find. Terry Jan Reedy From onurb at xiludom.gro Wed Apr 19 04:38:40 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 19 Apr 2006 10:38:40 +0200 Subject: Missing interfaces in Python... In-Reply-To: <1145382654.423527.265160@v46g2000cwv.googlegroups.com> References: <1145306373.781129.305840@z34g2000cwc.googlegroups.com> <1145382654.423527.265160@v46g2000cwv.googlegroups.com> Message-ID: <4445f75f$0$9451$626a54ce@news.free.fr> olsongt at verizon.net wrote: (snip) > Everyone is getting off track here. Not that much... > Java has interfaces because it doesn't support multiple inheritance. Java as interfaces because it relies on type declaration for subtyping *and* doesn't support MI. > Python supports MI, so you don't need to use the seperate concept of an > interface. s/supports MI/doesn't rely on type declaration for subtyping/ Would we need interfaces in Python if Python did not support MI ? Of course not, duck typing would still work. (snip) > The general wisdom is that Abstract Base Classes aren't pythonic > though. *Pure* abstract base classes (ie: abc without any implementation) are not Pythonic. I often use abc's that provides the 'guts' for common stuff, but are meant to be specialized for use (this is pretty common in frameworks). (snip the rest - mostly agree) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From kent at kentsjohnson.com Fri Apr 14 08:05:17 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Fri, 14 Apr 2006 08:05:17 -0400 Subject: nested functions In-Reply-To: <1145014674.717433.75100@t31g2000cwb.googlegroups.com> References: <1145014674.717433.75100@t31g2000cwb.googlegroups.com> Message-ID: <443f8a72$1_1@newspeer2.tds.net> micklee74 at hotmail.com wrote: > hi > just curious , if i have a code like this? > > def a(): > def b(): > print "b" > def c(): > print "c" > > how can i call c() ?? c is a name in the local scope of a(). You can call c from within a, where the name is in scope, or you can return c or in some other way make the value available in some other scope: In [5]: def a(): ...: def c(): ...: print 'called c' ...: c() ...: return c ...: In [6]: cc=a() called c In [7]: cc() called c Kent From tomerfiliba at gmail.com Sun Apr 16 08:55:25 2006 From: tomerfiliba at gmail.com (gangesmaster) Date: 16 Apr 2006 05:55:25 -0700 Subject: PEP 359: The "make" Statement In-Reply-To: References: <1144960754.844409.233930@g10g2000cwb.googlegroups.com> Message-ID: <1145192125.699173.269230@i40g2000cwc.googlegroups.com> ? i really liked it -tomer From kruhftREMOVE at gmail.com Thu Apr 13 14:32:48 2006 From: kruhftREMOVE at gmail.com (Burton Samograd) Date: 13 Apr 2006 12:32:48 -0600 Subject: function prototyping? References: <87hd4x1hx4.fsf@gmail.com> <87bqv51h7i.fsf@gmail.com> <1144952839.369290.121470@e56g2000cwe.googlegroups.com> Message-ID: <873bgh1g33.fsf@gmail.com> "infidel" writes: > If you want the user to be able to (re)define them in config.py, why > not just define them there in the first place? I may be wrong, but I > think "global" means "module level" rather than "interpreter level". That's what I'm trying to do but I'm running into problems with the function values, since they haven't been defined yet. I'm a C programmer, so I'm doing it in a bit of a C like way; prototype the function, initalize the array using the prototypes, have the functions defined somewhere else and then let the linker work it all out for me. I was hoping that python had some sort of lazy evaluation scheme for this type of behaviour so that you could defer linkage (or variable evalutation) until runtime, or at least variable reference (through the use of thunks or some sort). Maybe I was hoping for too much :) -- burton samograd kruhft .at. gmail kruhft.blogspot.com www.myspace.com/kruhft metashell.blogspot.com From shay at shay-riggs.fsnet.co.uk Tue Apr 11 18:58:21 2006 From: shay at shay-riggs.fsnet.co.uk (SR) Date: 11 Apr 2006 15:58:21 -0700 Subject: How can I reduce the number of queries to my PostgreSQL database? References: <1144489087.794505.277930@v46g2000cwv.googlegroups.com> Message-ID: <1144796301.617380.125930@u72g2000cwu.googlegroups.com> >> Say I have three tables. > > Only three? Well, yeah, OK, it's more than that, but after years of being worn away by "Post a minimal example" requests on comp.text.tex, a minimal example is what you got... > Something like {untested... Might need to do a subselect for the > second JOIN}: > > SELECT book_id, title, subtitle, ISBN, surname, firstname, notes from > books > LEFT OUTER JOIN bookauthors on books.book_id = bookauthors.book_id > JOIN authors on bookauthors.author_id = authors.author_id > ORDER BY books.book_id > > The reason for the LEFT OUTER JOIN, if I recall the syntax, is to > ensure that you get any books that don't have any authors. The sort > order is to: one) make sure the records are grouped properly for later > processing Thanks for the stuff on LEFT OUTER JOIN. Authorless books would be one of those things I wouldn't have noticed going astray. > The output will duplicate the book information for those books that > have multiple authors (the simple meaning of "unnormalized"): > > 2,A Book, Of Nothing, 123, Who, Guess, something > 2,A Book, Of Nothing, 123, Second, I'm, or other I think this goes along with what I thought of immediately after posting the question: one query to gather all info needed, then post-process in Python to order it all (so *that's* why I posted here...). My thoughts had been to turn [ 1, "Puppetry", "Bill" ] [ 1, "Puppetry", "Ben" ] [ 1, "Puppetry", "Flowerpot Men" ] into [ 1, "Puppetry", [ "Bill", "Ben", "Flowerpot Men" ] ] (if that's not overcomplicating it a bit)... > To make your report, you would output the book specific information > only when it changes (this means you need to initialize a temp record to > null data, and compare each record to the temp; when the compare fails, > put out the new book data, and copy it into the temp -- in this example, > just saving the book ID number would be sufficient, as long as it is a > unique/primary key). THEN, put out the Author information. If the > comparison of book data passes, it is the same book with an additional > author, you just need to output the author data. > > tmp_bookID = None > for bk in theCursor: > if tmp_bookID != bk[0]: #assumes book_id is first field > Output_Book_Data(bk) > tmp_bookID = bk[0] > Output_Author_Data(bk) ... which appears to be along the lines of what your code does! (Where Output_Author_Data(bk) could append to the author list of the current book. I'll go away and see how I can 'adapt' your example code. Thanks! Shay From prasad.raghu.k at gmail.com Tue Apr 4 14:24:51 2006 From: prasad.raghu.k at gmail.com (K Raghu Prasad) Date: Tue, 04 Apr 2006 23:54:51 +0530 Subject: mod_python and PHP sharing same session Message-ID: <4432B9F3.8040904@gmail.com> Scott wrote: > I am trying to get a mod_python application to read an existing PHP > session. I need some data that was set in the session by the PHP > application. I am using the mod_python Session class but even when I > specify the session id that PHP uses the Session(req, sid) call > returns a new session id. The session file exists in /tmp as > mp_sess.dbm and I have verified that PHP is reading/writing it and from > what I have read mod_python will use the same file. I have used the > PythonOption session DbmSession in the Apache configuration to force > this and specified the filename as well but to no avail. PHP and Python stores the session data differently. One way to fix this problem without the issues of managing file locks is to use override file based session handler of PHP with database based one. You can use MySQL to store this data. Then you need to write a parser in Python to parse the session data of PHP. Since this data is plain text, you don't have to do any reverse engineering to understand its format. Once both these things are ready, you can access the values stored by PHP application from the Python one. By the way, won't it be easy to use cookies to shared data between these two applications? Raghu From aum at spam.me.please Sun Apr 16 02:37:51 2006 From: aum at spam.me.please (aum) Date: Sun, 16 Apr 2006 18:37:51 +1200 Subject: ANN: XMLObject Message-ID: Hi folks, I've just released an XML object wrapper called XMLObject, which aims to do for XML file handling what SQLObject does for database access. XMLObject wraps XML files as Python objects, and lets you work with XML data more quickly and easily, and with code that's shorter and much more readable than the raw python XML APIs. It borrows some ideas from 'xml_objectify', but uses none of its code. In addition to 'xml_objectify', it lets you make changes within the document, and to save back to an XML file. http://www.freenet.org.nz/python/xmlobject -- Cheers aum From albert at compuscan.co.za Tue Apr 4 09:01:59 2006 From: albert at compuscan.co.za (Albert Leibbrandt) Date: Tue, 04 Apr 2006 15:01:59 +0200 Subject: CD Burning Message-ID: <44326E47.6010504@compuscan.co.za> Hi Can anybody tell me which windows API or python module they are using for writing cd's / dvd's with python? Thanks Albert From nogradi at gmail.com Thu Apr 20 06:13:14 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Thu, 20 Apr 2006 12:13:14 +0200 Subject: Python IDE for linux In-Reply-To: <200604201807.41755.fulvio@pc.jaring.my> References: <20060419214307.2e63c5cd.neil.isaac@sympatico.ca> <200604201807.41755.fulvio@pc.jaring.my> Message-ID: <5f56302b0604200313l7c0523famce138170c5f9faba@mail.gmail.com> On 4/20/06, Fulvio wrote: > Alle 09:43, gioved? 20 aprile 2006, Neil Isaac ha scritto: > > At this point I'm thinking that I would like to start using a real IDE. > Idle, shipped with Python :-) > > F > -- > http://mail.python.org/mailman/listinfo/python-list > And there is also a long list of IDEs on the wiki: http://wiki.python.org/moin/IntegratedDevelopmentEnvironments From antroy at gmail.com Sun Apr 2 15:17:20 2006 From: antroy at gmail.com (Ant) Date: 2 Apr 2006 12:17:20 -0700 Subject: Assignment in a while? In-Reply-To: <123071lnngm15da@corp.supernews.com> References: <123071lnngm15da@corp.supernews.com> Message-ID: <1144005440.055665.14190@v46g2000cwv.googlegroups.com> There are various ways you could do this: If the number of results won't be too big: ... for result in sth.fetchall(): print result If it may be very large: ... result = sth.fetchone() while result: print result result = sth.fetchone() Or perhaps nicer: ... def result_iterator(result_set): yield result_set.fetchone() for result in result_iterator(sth): print result HTH. From dausha at gmail.com Wed Apr 19 14:44:53 2006 From: dausha at gmail.com (Ben Wilson) Date: 19 Apr 2006 11:44:53 -0700 Subject: Better way to sift parts of URL . . . In-Reply-To: <1145468802.471081.209840@u72g2000cwu.googlegroups.com> References: <1145392079.720766.122310@z34g2000cwc.googlegroups.com> <7pd1g.46$0Z4.8@tornado.texas.rr.com> <1145468802.471081.209840@u72g2000cwu.googlegroups.com> Message-ID: <1145469313.125759.142780@g10g2000cwb.googlegroups.com> In practice, I had to change this: if len(query) > 0 and query[-1] == query[-1].capitalize(): group = query.pop() to this: if len(query) > 0 and query[-1][0] == query[-1].capitalize()[0]: group = query.pop() This is because I only wanted to test the case of the first letter of the string. From g.brandl-nospam at gmx.net Sun Apr 2 17:10:51 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Sun, 02 Apr 2006 23:10:51 +0200 Subject: very very basic question In-Reply-To: <1144011650.148681.173910@t31g2000cwb.googlegroups.com> References: <1144011128.206400.275270@e56g2000cwe.googlegroups.com> <1144011650.148681.173910@t31g2000cwb.googlegroups.com> Message-ID: aghazalp wrote: > thanx george for the prompt answer... when you say add a call that > means what exactly?...here is the program I was supposed to > write...could you tell me what to add where in this program? > > def main(): > print "this program is crazy" > x=input ('enter a number betwenen 0 and 1: ') > for i range (10) > x=3.9*x*(1-x) > print x > > main() At the very end of the program, that is here, after main(), just insert raw_input() Georg From rubbishemail at web.de Fri Apr 21 14:00:09 2006 From: rubbishemail at web.de (rubbishemail at web.de) Date: 21 Apr 2006 11:00:09 -0700 Subject: lambda Message-ID: <1145642409.389741.39680@g10g2000cwb.googlegroups.com> Hello, I need your help understanding lambda (and doing it a better way without). f = lambda x : x*x # this is a list of functions [f for y in range(1,5)] [f for y in range(1,5)][0](2) # returns 4, as expected # ok now I want a list like # [x^2, 2*x^2, 3*x^2,...] [f*y for y in range(5)] # this causes an unsupported operand type because it cannot multiply a function and int # the idea is now to give the definition of the multiplication of functions and integers # (f * c)(xx) := f(x)*c [lambda xx: f(xx)*y for y in range(1,5)][0](1) # returns 4 # I would expect 1*x*x = 1 # Where is my mistake and what would be the correct way to do this without lambdas? If you are interested in the reason for the code: approxFunction gets a function and a list of x-values. It computes func on these points and returns an interpolating polynomial. (this form of interpolation is often not stable, the code demonstrates this) def lagrangeBase(i, points): """returns the i-th lagrange polynomial on the nodes points (list of xj) In Symbolic notation the result should be lagrangeBase(x)=\Pi_{j=0, j\ne i} (x-xj)/(xi-xj) """ xi = points[i] # all points without xi nums = [points[x] for x in range(len(points)) if x!=i ] # unsupported operand type * for functions, therefore the lambda xx # what is the proper way to do this ? return reduce(lambda a,b: lambda xx: a(xx)*b(xx) , map(lambda xj: lambda x: (x-xj)/(xi-xj), nums)) def approxFunction(func, points): """this returns an approximation polynomial for func on the nodes points \Sum lagrangeBase(x_i) func(x_i) """ funcValues = [func(x) for x in points] # this is the problem mentioned above # sumTerms = [lambda xx: lagrangeBase(i, points)(xx)*funcValues[i] for i in range(len(points))] # this works sumTerms = map(lambda i: lambda xx : lagrangeBase(i, points)(xx) * funcValues[i], range(len(points))) return reduce(lambda a,b: lambda xx: a(xx)+b(xx), sumTerms) I am using Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] Type "copyright", "credits" or "license" for more information. IPython 0.6.13 -- An enhanced Interactive Python. Many thanks Daniel From felipe.lessa at gmail.com Fri Apr 21 19:25:13 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Fri, 21 Apr 2006 20:25:13 -0300 Subject: PyLint results? In-Reply-To: References: Message-ID: <1145661913.24485.8.camel@kenshin.CASA> Em Sex, 2006-04-21 ?s 13:49 -0400, Michael Yanowitz escreveu: > I ran the new pylint and my code and I had a few questions on why those > are warnings or what I can do to fix them: You can ignore the warnings you don't like with the --disable-msg option. Also, you can add a header to the file to apply a rule just to it. > 1) W: 0: Too many lines in module (1587) > Why is 1587 considered too many lines? Would there be necessarily be an > advantage to split it up into 2 or 3 files? Can I up the limit? Because Python is terse, and this can be a really large module. Or not. PyLint is not perfect, maybe you should disable this warning. > 2) C: 0: Missing required attribute "__revision__" > What is this? Is that for CVS? I don't use CVS (we use SVN). I have not > seen any sample code which includes this tag yet. But if I include > __revision 1.0 somewhere in the code it will remove that warning? Don't include the variable just to remove the warning -- disable it. > 3) W:230:readDiscreteData: Using the global statement > What is wrong with using the global statement? Your code can get unmaintainable if you abuse of it. If you really need it and know how to use it well, disable the warning. > 4) W:261:getDiscreteData: Catch "Exception" > What is wrong with that? You may catch things you don't want to catch, like KeyboardInterrupt exceptions. > 5) R:547:readDiscreteData: Too many branches (28/12) > Python doesn't have the switch/case statements that C/C++ have. So I > could have a large block if/elif/else statements. > Is there any way to avoid that? Only splitting the method into 2 or more parts. If that's not possible, disable the warning. > 6) R:722:waitDiscretes: Too many local variables (38/15) > That's new to me. What is wrong with too many local variables? > Can anything be done to improve that besides having too many globals? The more local variables you have, the more difficult the code is to read. Or you use less variables, or you split the method into 2 or more parts, or you disable the warning. > 7) W:933:sendStringToSocket: Redefining name 'nPortNumber' from outer scope > (line > What is wrong with using the same variable name in a function that is > used by its caller? You are hiding something. For example, this code fails strangely (I know this example isn't that good, but you get the idea): files = glob('something/*') for file in files: # do_something filename = do_something_with_the_name(file) # do_something_more contents = file(filename).read() # fails here > 8) W:995:sendStringToSocket: Used builtin function 'map' > Is that a problem? Sometimes it's slower than list comprehensions, sometimes it's less legible than list comp. and IIRC GvR doesn't like it, but if you do, disable the warning. HTH, -- Felipe. From brianlum at gmail.com Sat Apr 29 06:35:20 2006 From: brianlum at gmail.com (brianlum at gmail.com) Date: 29 Apr 2006 03:35:20 -0700 Subject: Python "member of" function Message-ID: <1146306920.942286.35550@y43g2000cwc.googlegroups.com> Hi, I was wondering if anyone knew of a built in Python function that will check if an item is a member of a list, i.e., if item i is a member of list l. I read of a function "in" but I can't seem to get that to work and finding pages for "python in" does not reveal very many relevant sources. Thanks! From robert.kern at gmail.com Fri Apr 14 14:28:21 2006 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 14 Apr 2006 13:28:21 -0500 Subject: Writing backwards compatible code In-Reply-To: References: Message-ID: Steven D'Aprano wrote: > I came across an interesting (as in the Chinese curse) problem today. I > had to modify a piece of code using generator expressions written with > Python 2.4 in mind to run under version 2.3, but I wanted the code to > continue to use the generator expression if possible. Why? AFAICT, it really is just syntactic sugar. Very nice syntactic sugar, but not necessary at all. If you are going to have the ugly, syntactically bitter version in your code anyways, why clutter up your code even more trying to do both? > What techniques do others use? Personally, I write code that only uses the syntactic features of the Python version that I am targetting. -- Robert Kern robert.kern at gmail.com "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From aleaxit at yahoo.com Thu Apr 27 11:11:04 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 27 Apr 2006 08:11:04 -0700 Subject: Unpacking a list of strings References: <1146142566.330755.244840@i39g2000cwa.googlegroups.com> Message-ID: <1heg1c5.yzzjbqjwrnmyN%aleaxit@yahoo.com> Panos Laganakos wrote: > Is there some other practice than reading all the strings and slicing > them later? > > They're stored in the form of: > List Group[10]: > char[17] name; > > So I thought of doing: > unpacked = unpack('%s' % (10*17), data) > > And then slicing the list by a step of 17. > > Is there some way to have unpack return a tuple with each element > holding the name (char[17])? unpack by formatstring 10*'17s' ... Alex From roy at panix.com Mon Apr 24 10:23:52 2006 From: roy at panix.com (Roy Smith) Date: 24 Apr 2006 10:23:52 -0400 Subject: need a thread to keep a socket connection alive? References: <1145718638.526525.235090@i39g2000cwa.googlegroups.com> <1145885130.140370.166490@t31g2000cwb.googlegroups.com> Message-ID: Serge Orlov wrote: > sockobj.settimeout(550) > [...] > Also, as other people pointed out, you'd better make buffered socket > with .makefile() socket method. If I understand the docs for the socket module correctly, these two suggestions are mutually incompatable. From iainking at gmail.com Wed Apr 26 05:57:10 2006 From: iainking at gmail.com (Iain King) Date: 26 Apr 2006 02:57:10 -0700 Subject: Counting elements in a list wildcard In-Reply-To: References: <1145921582.526072.120480@u72g2000cwu.googlegroups.com> <1145953610.077361.320290@y43g2000cwc.googlegroups.com> <444DEEC8.7000001@lexicon.net> Message-ID: <1146045430.686430.65440@t31g2000cwb.googlegroups.com> Edward Elliott wrote: > John Machin wrote: > > On 25/04/2006 6:26 PM, Iain King wrote: > >> iain = re.compile("(Ia(i)?n|Eoin)") > >> steven = re.compile("Ste(v|ph|f)(e|a)n") > > > > IMHO, the amount of hand-crafting that goes into a *general-purpose* > > phonetic matching algorithm is already bordering on overkill. Your > > method using REs would not appear to scale well at all. > > Also compare the readability of regular expressions in this case to a simple > list: > ["Steven", "Stephen", "Stefan", "Stephan", ...] Somehow I'm the advocate for REs here, which: erg. But you have some mighty convenient elipses there... compare: steven = re.compile("Ste(v|ph|f|ff)(e|a)n") steven = ["Steven", "Stephen", "Stefen", "Steffen", "Stevan", "Stephan", "Stefan", "Steffan"] I know which I'd rather type. 'Course, if you can use a ready-built list of names... Iain From ryanlists at gmail.com Wed Apr 19 11:01:30 2006 From: ryanlists at gmail.com (Ryan Krauss) Date: Wed, 19 Apr 2006 11:01:30 -0400 Subject: accessing a classes code Message-ID: I have a set of Python classes that represent elements in a structural model for vibration modeling (sort of like FEA). Some of the parameters of the model are initially unknown and I do some system identification to determine the parameters. After I determine these unknown parameters, I would like to substitute them back into the model and save the model as a new python class. To do this, I think each element needs to be able to read in the code for its __init__ method, make the substitutions and then write the new __init__ method to a file defining a new class with the now known parameters. Is there a way for a Python instance to access its own code (especially the __init__ method)? And if there is, is there a clean way to write the modified code back to a file? I assume that if I can get the code as a list of strings, I can output it to a file easily enough. I am tempted to just read in the code and write a little Python script to parse it to get me the __init__ methods, but that seems like reinventing the wheel. Thanks, Ryan From fredrik at pythonware.com Tue Apr 18 04:09:00 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 18 Apr 2006 10:09:00 +0200 Subject: Ironpython book? References: <1145329406.419299.12780@i40g2000cwc.googlegroups.com> <1145332208.428363.199440@v46g2000cwv.googlegroups.com> Message-ID: BartlebyScrivener wrote: > I'll let somebody jump in and say, "You're crazy!" But it seems to me > the interest in IronPython on this list is pretty subdued. Maybe > because most people are running on Linux or Macs? umm. CPython runs just fine on Windows, and can talk to most Windows- specific stuff via the win32 extensions and ctypes and python for .net: http://www.zope.org/Members/Brian/PythonNet From nogradi at gmail.com Sat Apr 15 09:30:34 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Sat, 15 Apr 2006 15:30:34 +0200 Subject: Calling Python from Matlab In-Reply-To: References: Message-ID: <5f56302b0604150630y6f3b8a31ga08e82c20da23ae7@mail.gmail.com> > I am desperately looking for a way to call Python from Matlab. I have become > used to Python's rich syntax and large number of libraries, and feel > ridiculously clumsy being stuck with Matlab's rather restricted facilities > for doing other things than standard mathematical work. > > Does anyone know of good techniques (or readily available software) for > achieving a cross-language support between Python and Matlab? > > Carl Perhaps you will find this useful: http://claymore.engineer.gvsu.edu/~steriana/Python/pymat.html From iddw at hotmail.com Wed Apr 26 11:15:45 2006 From: iddw at hotmail.com (Dave Hansen) Date: Wed, 26 Apr 2006 10:15:45 -0500 Subject: A defense for bracket-less code References: Message-ID: On Wed, 26 Apr 2006 10:20:57 -0400 in comp.lang.python, Don Taylor wrote: >Found in a style guide (http://www.artlogic.com/careers/styleguide.html) >----------------------------------------------------------------------- >Another case where "unnecessary" braces should be used is when writing >an empty while loop: > >while (*p++ = *q++) >{ > // this loop intentionally left empty... >} FWIW, I usually code this like while (*p++ = *q++) continue; > >instead of the form that is more commonly found: > >while (*p++ = *q++); PC-lint picks this up (as well as the erroneous code in the elided example), but will allow the "continue" form shown above. [...] >loop exactly once. Python programmers can stop chuckling now. >----------------------------------------------------------------------- On 26 Apr 2006 07:54:38 -0700 in comp.lang.python, "aurelien.campeas at free.fr" wrote: >wrong group Not really. It was mostly a lead-in to that last sentence. Problems like this couldn't happen in Python. So it's an opportunity to get a giggle at the expense of programmers using a language that gives you enough rope to shoot yourself in the foot... Regards, -=Dave -- Change is inevitable, progress is not. From aleaxit at yahoo.com Tue Apr 4 11:56:05 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 4 Apr 2006 08:56:05 -0700 Subject: Difference in Python and Ruby interactive shells References: <1144159204.450444.297870@t31g2000cwb.googlegroups.com> <1144164876.820737.229810@i40g2000cwc.googlegroups.com> Message-ID: <1hd9i36.lujm07nwr9r1N%aleaxit@yahoo.com> Michele Simionato wrote: > You want this recipe from Michael Hudson: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/160164 > > "automatically upgrade class instances on reload()" Note that the version in the printed Cookbook (2nd edition) was substantially enhanced (mostly by me and Michael working together), I don't know if Michael updated his ASPN recipe to reflect that but at any rate you can download all the code from the printed Cookbook as a zipfile from O'Reilly's site (sorry, I don't recall the URL). Alex From kelvie at ieee.org Thu Apr 13 15:09:32 2006 From: kelvie at ieee.org (Kelvie Wong) Date: Thu, 13 Apr 2006 12:09:32 -0700 Subject: Remove Whitespace In-Reply-To: <9583ed900604131200n5c43829ckeb01ba4503763954@mail.gmail.com> References: <9583ed900604131200n5c43829ckeb01ba4503763954@mail.gmail.com> Message-ID: <94ccbe710604131209wa4a9ad2q8d5dfbc187c34e16@mail.gmail.com> try this: string = 'D c a V e r " = d w o r d : 0 0 0 0 0 6 4 0' import re re.sub("\s", "", string) On 4/13/06, david brochu jr wrote: > > Hi again, > > Trying to remove whitespace from a string in a text file. > > the string is: > D c a V e r " = d w o r d : 0 0 0 0 0 6 4 0 > > how would i go about doing this? > -- > http://mail.python.org/mailman/listinfo/python-list > > From jelleferinga at gmail.com Fri Apr 21 09:16:23 2006 From: jelleferinga at gmail.com (jelle) Date: 21 Apr 2006 06:16:23 -0700 Subject: are docstrings for variables a bad idea? In-Reply-To: <4as2n8FpmaqcU1@uni-berlin.de> References: <1145615763.943050.170950@j33g2000cwa.googlegroups.com> <4ars48Fucf8sU1@uni-berlin.de> <1145622021.708392.5490@g10g2000cwb.googlegroups.com> <4as2n8FpmaqcU1@uni-berlin.de> Message-ID: <1145625383.881200.307110@j33g2000cwa.googlegroups.com> Hi Diez, please take note, this suggestion does not nessecarily apply to programmers such as you & myself of course for whom any python code is as transparant as the API's we write ;') ---- I feared that you meant that - but wasn't sure. This is one of the often-requested-yet-they-will-never-come features of IDEs for python, as this would mean that you'd have type-information available on f. Consider this simple example: f = someRandomlyInstatiatedObject() Now what is e.g. f. to show? ---- why is this ambigious at all? am i seriously overlooking something? class jelle: def __init__(self): ''' we've been having this for a while, just the helpful constructor docstring ''' '''relates drag to speed''' self.terribleNamedMethod = 'of a programmer i will not disclose' j = jelle() shows the proper docstring al'right.... From fredrik at pythonware.com Mon Apr 17 06:42:00 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 17 Apr 2006 12:42:00 +0200 Subject: XML-RPC server via xinetd References: Message-ID: Nick Craig-Wood wrote: > Look at /usr/lib/python2.4/SimpleXMLRPCServer.py (adjust as per your > distro) and in particular the definition of the CGIXMLRPCRequestHandler class. > > That looks as thought it almost, or maybe completely, does what you > want, ie an XMLRPC subclass which reads from stdin and writes to > stdout. except that if the OP's expecting the other end to use an ordinary XML-RPC library, he needs to implement some minimal HTTP handling as well. import sys import mimetools, xmlrpclib command = sys.stdin.readline() # optional: check command syntax (POST url HTTP/1.X) headers = mimetools.Message(sys.stdin) # optional: check content-type etc bytes = int(headers.get("content-length", 0)) # optional: check request size, etc params, method = xmlrpclib.loads(sys.stdin.read(bytes)) # handle the method result = ... # marshaller expects a tuple result = (result, ) response = xmlrpclib.dumps(result, methodresponse=1) print "HTTP/1.0 200 OK" print "Content-Type: text/xml" print "Content-Length:", len(response) print print response (based on code from http://effbot.org/zone/xmlrpc-cgi.htm ) From eurleif at ecritters.biz Wed Apr 5 14:44:03 2006 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Wed, 05 Apr 2006 14:44:03 -0400 Subject: how to convert string In-Reply-To: <1144261976.640631.9280@e56g2000cwe.googlegroups.com> References: <1144261976.640631.9280@e56g2000cwe.googlegroups.com> Message-ID: <44340faa$0$3700$4d3efbfe@news.sover.net> diffuser78 at gmail.com wrote: > I want to print number 0 to 9 in one line like this > 0 1 2 3 4 5 6 7 8 9 > > if I do like this, it prints in different lines > > for i in xrange(10): > print i for i in xrange(10): print i, > so i tried like this > > str = "" > for i in xrange(10): > str = i + " " > print str > > but i want to know how convert int i to string. s = "" # Don't shadow the str builtin. for i in xrange(10): s += str(i) + " " print s From jussij at zeusedit.com Tue Apr 4 19:56:57 2006 From: jussij at zeusedit.com (jussij at zeusedit.com) Date: 4 Apr 2006 16:56:57 -0700 Subject: running IDLE from another program? References: Message-ID: <1144195014.148980.146200@z34g2000cwc.googlegroups.com> > So it comes down to this: is it possible to run code (that > was created in a separate editor) in IDLE in some kind of > automated way? Using the Zeus for Windows IDE this should be possible. Zeus has many options when it comes to running tools and compilers: http://www.zeusedit.com/forum/viewtopic.php?t=32 It will also capture the tool output and allowing you to click on the errors in the output and have the file load at the correct line number. Jussi Jumppanen Author: Zeus for Windows Note: Zeus is shareware (45 day trial). From UrsusMaximus at gmail.com Thu Apr 6 10:15:38 2006 From: UrsusMaximus at gmail.com (UrsusMaximus at gmail.com) Date: 6 Apr 2006 07:15:38 -0700 Subject: python411 podcast -- problem with the 'modules' podcast? In-Reply-To: References: Message-ID: <1144332938.653920.288360@i40g2000cwc.googlegroups.com> John, I'll go back and look intoi this tonight on the Modules Podcast. Sometimes, the problems are specific to a given user's equipmentn, and I don't always know how to fix them, which is frustrating. But, maybe there is a problem I can fix with that podcast. I'll let you know ton=ight after I get home form my day job ;-)). Ronwww.awaretek.com/python/index.html From john at castleamber.com Wed Apr 26 19:36:50 2006 From: john at castleamber.com (John Bokma) Date: 26 Apr 2006 23:36:50 GMT Subject: (was Re: Xah's Edu Corner: Criticism vs Constructive Criticism) References: <1145992903.834316.198370@u72g2000cwu.googlegroups.com> <4GM3g.3084$TT.1768@twister.nyroc.rr.com> <1146079773.910552.217390@y43g2000cwc.googlegroups.com> Message-ID: "Xah Lee" wrote: > Dear John Bokma, > > This is a public notice that what you are trying to do is getting > close to harrassment from the law's perspective. Which law? You have been harrassing severl groups for too long with your drivel and extremely badly written rants. I guess what you do comes way closer to harrassment then me trying to kick your ass. Lets hope some others join in and see who is going to win. Most trolls give up after they lose a handful of accounts, since it gets more and more expensive. Find a new hobby if CS is too hard. -- John Bokma Freelance software developer & Experienced Perl programmer: http://castleamber.com/ From xah at xahlee.org Thu Apr 27 17:25:45 2006 From: xah at xahlee.org (Xah Lee) Date: 27 Apr 2006 14:25:45 -0700 Subject: Xah's Edu Corner: What Languages to Hate In-Reply-To: <1146172923.830732.187130@i40g2000cwc.googlegroups.com> References: <1145992903.834316.198370@u72g2000cwu.googlegroups.com> <1146172923.830732.187130@i40g2000cwc.googlegroups.com> Message-ID: <1146173145.365211.212100@g10g2000cwb.googlegroups.com> Addendum: Recently I ran into this egregious propaganda: http://www.ibiblio.org/pub/multimedia/video/obp/IntroducingPython.mpg folks, take a look. This is a significant part how things move in the computing community. Xah xah at xahlee.org ? http://xahlee.org/ Xah Lee wrote: > What Languages to Hate > > Xah Lee, 20020718 > > Dear lisp comrades and other concerned parties, > > First, all languages have equal rights. Do not belittle other languages > just because YOUR favorite language is a bit better in this aspect or > that. Different people have different ideas and manners of perception. > Ideas compete and thrive in all unexpected fashions. Societies improve, > inventions progress. Lisp may be a first in this or that, or faster or > flexibler, or higher level than other languages old and new, but then > there are other languages the like of Mathematica & Haskell & Dylan et > al which ridicule lisps in the same way lisp ridicule other languages. > > Just because YOU are used to more functional programing or love lots of > parenthesis doesn't mean they are the only and best concepts. The > so-called Object Oriented programing of Java fame, or the visual > programing of Visual Basic fame, or the logic programing of Prolog > fame, or the format-stable syntax of Python fame, or the ?one line of > Mathematica equals ten to one thousand lines of lisp? of _A New Kind > Of Science_ fame... all are parts of healthy competing concepts, > paradigms, or directions of growth. > > The way some of you deride other languages is like sneering > heterogeneousness. If unchecked, soon you'll only have your sister to > marry to. Cute, but you do not want incest to become the only sex. Next > time your superiority complex makes you sneer at non-lisp or other > non-popular languages, remember this. It is diversity of ideas, that > drives the welfare of progress. > > Now, there is one judgmental criterion, that if a language or computer > technology fits it, then we not only should castigate at their > missionaries, but persecute and harass the language to the harshest > death. That is: utter sloppiness, irresponsibility, and lies. These > things are often borne out of some student's homework or moron's > dirty-work, harbored by ?free? and wanton lies and personal fame, > amassed thru ignorance. > > Of my short but diligent industrial unix computing experience since > 1998, i have identified the following targets: > > * C (and consequences like csh, C++) > * vi > * Perl > * MySQL > * unix, unixism, and things grown out of unix. (languages, > protocols, philosophies, expectations, movements) > > In our software industry, i like to define criminals as those who cause > inordinate harm to society, not necessarily directly. Of the above > things, some of their authors are not such criminals or are forgivable. > While others, are hypocritical fantastic liers selfish to the core. > When dealing with these self-promoting jolly lying humble humorous > priests and their insidious superficially-harmless speeches, there > should be no benefit of doubt. Tell them directly to stop their vicious > lies. Do a face-off. > > As to their brain-washed followers for example the not-yet-hard-core > unix, C, or Perl coders rampant in industry, try to snap them out of > it. This you do by loudly snapping fingers in front of their face, > making it sound like a ear piercing bang. Explain to them the utter > stupidity of the things they are using, and the harm to their brain. > IMPORTANT: _teach_, not _debate_ or _discuss_ or falling back into your > philosophical deliberating indecisiveness. I've seen enough criticisms > among learned programers or academics on these, so i know you know what > i'm talking about. When you see a unixer brainwashed beyond saving, > kick him out of the door. He has became a zombie who cannot be helped. > > There are other languages or technology, by itself technically are > perhaps mediocre but at least is not a egregious irresponsible hack, > therefore does not deserve scorn, but sometimes it comes with > overwhelming popular outrageous lies (euphemized as hype). Java is a > example. For this reason, it is equally deserving the harshest > treatment. Any loud proponents of such should be immediately slapped in > the mouth and kicked in the ass in no ambiguous ways. > > Summary: all languages have equal rights. However, those utterly SLOPPY > and IRRESPONSIBLE HACKS with promoter's LIES should be severely > punished. It is these, that cause computing industry inordinate harm. > Meanwhile, it is wrong to haughtily criticize other languages just > because they are not your cup of tea. Now, please remember this and go > do society good. > ---- > This post is archived at: > http://xahlee.org/UnixResource_dir/writ/language_to_hate.html > > Xah > xah at xahlee.org > ? http://xahlee.org/ From michele.simionato at gmail.com Mon Apr 3 04:17:24 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 3 Apr 2006 01:17:24 -0700 Subject: "definitive" source on advanced python? In-Reply-To: <1144040231.239622.159630@j33g2000cwa.googlegroups.com> References: <1144040231.239622.159630@j33g2000cwa.googlegroups.com> Message-ID: <1144052244.274246.323510@v46g2000cwv.googlegroups.com> I gave a course on advanced Python last year at the ACCU conference. See http://www.reportlab.org/~andy/accu2005/pyuk2005_simionato_wondersofpython.zip Michele Simionato From onurb at xiludom.gro Wed Apr 26 09:44:51 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 26 Apr 2006 15:44:51 +0200 Subject: Inherit from array In-Reply-To: <1146057315.721573.196140@u72g2000cwu.googlegroups.com> References: <1146057315.721573.196140@u72g2000cwu.googlegroups.com> Message-ID: <444f79a8$0$5191$626a54ce@news.free.fr> TG wrote: > Hi there. > > I'm trying to create a simple class called Vector which inherit from > array. Which array ? bruno at bousin ~ $ python Python 2.4.2 (#1, Feb 9 2006, 02:40:32) [GCC 3.4.5 (Gentoo 3.4.5, ssp-3.4.5-1.0, pie-8.7.9)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> array Traceback (most recent call last): File "", line 1, in ? NameError: name 'array' is not defined -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From bray at sent.com Tue Apr 11 15:25:23 2006 From: bray at sent.com (bray at sent.com) Date: Tue, 11 Apr 2006 14:25:23 -0500 Subject: Chicago Python Users Group Thurs April 13 at 7pm Message-ID: <1144783523.18842.258867354@webmail.messagingengine.com> Learn, share, and have fun at ChiPy's Monthly meeting this Thurs, April 13 at 7pm. This is sure to be our best meeting yet. Confirm your attendance: mtobis aat gmail doot com with "ChiPy April" in your subject line. Headliners ---------- * httpy -- (Chad Whitacre) a sane and robust HTTP library. * SCons -- (Atul) Software construction via Python. * testosterone -- (Chad Whitacre) a curses-based testing interface. Module of the Month ------------------- * TBD in the near __future__ Location -------- At the historic Monadnock Building, which in the 1890s was the tallest building in the world. That's 53 W Jackson Blvd, room 826. Here's a map: It's right on the blue line, and two blocks from the red line, and walking distance to all of the Metra termini. Cheap parking is a few blocks away at State and Harrison, more expensive parking is immediately adjacent on Federal between Jackson and Van Buren. Take the Eisenhower all the way in until it turns into Congress, and you'll be right in the neighborhood. Turn right on State or left on Federal if you are looking for the cheap or the convenient recommended parking lots respectively. ***NOTE: PLEASE EMAIL mtobis aat gmail doot com with "ChiPy April" in your subject line to confirm your attendance. About ChiPy ----------- ChiPy is a group of Chicago Python Programmers, l33t, and n00bs. Meetings are held monthly at various locations around Chicago. Also, ChiPy is a proud sponsor of many Open Source and Educational efforts in Chicago. Stay tuned to the mailing list for more info. ChiPy website: ChiPy Mailing List: Python website: ---- Forward this on. From steven.bethard at gmail.com Fri Apr 14 10:42:33 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 14 Apr 2006 08:42:33 -0600 Subject: PEP 359: The "make" Statement In-Reply-To: References: Message-ID: Duncan Booth wrote: > Steven Bethard wrote: > >> Should users of the make statement be able to determine in which dict >> object the code is executed? The make statement could look for a >> ``__make_dict__`` attribute and call it to allow things like:: >> >> make Element html: >> make Element body: >> make Element h1: >> '''First heading text''' >> make Element h1: >> '''Second heading text''' > [snip] > There is another effect which should be considered here. If you allow > Element to create an object to be used as the namespace, then as well as > doing special tracking when values are set in the namespace it can also > pre-seed it with names which magically appear in scope within the make. > > e.g. > > make Element html: > make Element body: > make Element p: > text('But this ') > make Element strong: > text('could') > text(' be made to work') This is nice. I'll have to play around with it a bit to see how hard it would be to make it work. STeVe From deets at nospam.web.de Wed Apr 19 05:14:39 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 19 Apr 2006 11:14:39 +0200 Subject: removing cgi fieldstorage keys References: Message-ID: <4amdceFtv25qU1@uni-berlin.de> Tim Roberts wrote: > Kun wrote: >> >>i don't know what happened but all of a sudden, my cgi.fieldstorage has >>two extra keys, 'x' and 'y', does anyone know how i can remove them in >>python? > > If this is coming from a web site that you created, then you darned well > better figure out where they're coming from! Did you add any hidden> fields? Did you add an image map? AFAIK these come in case of image-submit-buttons, too. Diez From xah at xahlee.org Wed Apr 26 15:29:33 2006 From: xah at xahlee.org (Xah Lee) Date: 26 Apr 2006 12:29:33 -0700 Subject: (was Re: Xah's Edu Corner: Criticism vs Constructive Criticism) In-Reply-To: References: <1145992903.834316.198370@u72g2000cwu.googlegroups.com> <4GM3g.3084$TT.1768@twister.nyroc.rr.com> Message-ID: <1146079773.910552.217390@y43g2000cwc.googlegroups.com> Dear John Bokma, This is a public notice that what you are trying to do is getting close to harrassment from the law's perspective. Thanks. Xah xah at xahlee.org ? http://xahlee.org/ John Bokma wrote: > Eli Gottlieb wrote: > > > Oh, God, not another one. > > Instead of cross posting more garbage, do as follows: > > Email a complaint to the email addresses you can look up yourself and > include the entire message of Xah: > > http://www.spamcop.net/sc?track=72.231.179.135 posting host > http://www.spamcop.net/sc?track=xahlee.org spamvertized site > > > If enough people complain with both, it might stop one day. From bruno at modulix.org Wed Apr 19 16:54:13 2006 From: bruno at modulix.org (bruno de chez modulix en face) Date: 19 Apr 2006 13:54:13 -0700 Subject: accessing a classes code In-Reply-To: References: <444666af$0$12280$626a54ce@news.free.fr> <4446788a$0$31457$626a54ce@news.free.fr> Message-ID: <1145480053.936364.187470@e56g2000cwe.googlegroups.com> > It turns out that what I want to do can be done using the inspect > module which has methods for getsourcecode among other things. I never said that what you wanted to do was impossible (nor even difficult, and FWIW, there are simpler alternatives than using inspect - using a templating system like empy comes to mind...). I only suggest that there are possibly far better solutions, that you seem to dismiss for some unknown reason... From willmcgugan at gmail.com Sun Apr 30 08:33:39 2006 From: willmcgugan at gmail.com (willmcgugan at gmail.com) Date: 30 Apr 2006 05:33:39 -0700 Subject: resume picking items from a previous list In-Reply-To: <1146352140.248299.136880@g10g2000cwb.googlegroups.com> References: <1146352140.248299.136880@g10g2000cwb.googlegroups.com> Message-ID: <1146400419.173078.96860@g10g2000cwb.googlegroups.com> kpp9c wrote: > I have a several list of songs that i pick from, lets, say that there > are 10 songs in each list and there are 2 lists. > > For a time i pick from my songs, but i only play a few of the songs in > that list... now my wife, Jessica Alba, comes home, and i start playing > from Jessica's list of songs. After playing a few songs, Jessica, who > needs her beauty sleep, goes to bed, and i start my play loop which > starts picking from my songs again... > Not sure I follow. Jessica goes to bed, and you... _listen to music_?? From johnjsal at NOSPAMgmail.com Sun Apr 30 19:19:27 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sun, 30 Apr 2006 19:19:27 -0400 Subject: ending a string with a backslash Message-ID: <445546c8$0$13341$c3e8da3@news.astraweb.com> I have this: subdomain = raw_input('Enter subdomain name: ') path = r'C:\Documents and Settings\John Salerno\My Documents\My Webs\1and1\johnjsalerno.com\' + subdomain Obviously the single backslash at the end of 'path' will cause a problem, and escaping it with a backslash seems to fix this problem, but how does escaping work when I already have it as a raw string? When I test it out and then print string, I get something like this: C:\Documents and Settings\John Salerno\My Documents\My Webs\1and1\johnjsalerno.com\\test But I don't see how this is valid, since all the backslashes are single (which is correct) except the last one. Somehow this still works when I tried to create the new directory -- os.mkdir(path) -- but I wasn't sure if this is the right way to go about it, or if there is some other, better way to handle the final backslash. From sushant.sirsikar at gmail.com Wed Apr 5 01:02:06 2006 From: sushant.sirsikar at gmail.com (sushant.sirsikar at gmail.com) Date: 4 Apr 2006 22:02:06 -0700 Subject: Strange problem when running python code In-Reply-To: <1144177272.939450.134720@e56g2000cwe.googlegroups.com> References: <1144175959.412184.187110@g10g2000cwb.googlegroups.com> <9bzYf.1903$No6.42196@news.tufts.edu> <1144177272.939450.134720@e56g2000cwe.googlegroups.com> Message-ID: <1144213326.785282.190240@u72g2000cwu.googlegroups.com> Are U Using any IDE for Python? If yes then check out the setting and make sure that u are running same code. From larry.bates at websafe.com Tue Apr 4 09:47:56 2006 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 04 Apr 2006 08:47:56 -0500 Subject: Windows Services In-Reply-To: <1144155999.790472.297860@i39g2000cwa.googlegroups.com> References: <1144155999.790472.297860@i39g2000cwa.googlegroups.com> Message-ID: <4432790C.5050002@websafe.com> rodmc wrote: > Hello, > > I am trying to figure out how to write a windows service, I am totally > new to it. I have written a simple test case, however it doesn't appear > to do anything. Although it installs and appears to start, when I run a > query of its status (using another app) it says it is not running. As > a note I am running it as the administrator in a Win2k machine to avoid > any problems with permissions - although I would rather not do this for > ever :-) > > I install the software as follows: > > python testservice.py install > python testservice.py start > > I am sure I am missing something out as I am basically working from > code samples for other solutions which I have seen. In particular one > for getting CherryPy to run as a service. > > When I have figured this all out I intend to add in some code I have > already written which runs a server application. > > It may be all rather obvious but I am quite new Python (just a few > months) and totally new to Windows services. > > Thanks in advance for any help. > > Best, > > Rod > > > import win32serviceutil > import win32service > import win32event > import os,sys > > class helloworld: > > def test(self): > x=1 > filename=open("c:test.txt","w") > while x<100000: > print >>filename,x > x=x+1 > > class MyService(win32serviceutil.ServiceFramework): > """NT Service.""" > > _svc_name_ = "Test" > _svc_display_name_ = "Test" > > def __init__(self, args): > win32serviceutil.ServiceFramework.__init__(self, args) > # create an event that SvcDoRun can wait on and SvcStop > # can set. > self.stop_event = win32event.CreateEvent(None, 0, 0, None) > > def SvcDoRun(self): > print "got here" > helloworld.test() > win32event.WaitForSingleObject(self.stop_event, > win32event.INFINITE) > > def SvcStop(self): > self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) > win32event.SetEvent(self.stop_event) > > if __name__ == '__main__': > win32serviceutil.HandleCommandL > I found Mark Hammond and Andy Robinson's book Python Programming on Win32 to be a great resource when I wrote my first service. It has several examples that helped a lot. Remember services run inside of infinite loops. Inside SvcDoRun you must have some construct like: while 1: #----------------------------------------------------------------- # Wait for service stop signal, if I timeout, loop again #----------------------------------------------------------------- rc=win32event.WaitForSingleObject(self.hWaitStop, self.timeout) # # Check to see if self.hWaitStop happened # if rc == win32event.WAIT_OBJECT_0: # # Stop signal encountered # break else: # # Put body of service here # You also should probably change win32event.INFINITE to some number (expressed in milliseconds) or your service gets blocked and doesn't do anything. The sequence goes like this: Inside an infinite loop, sleep for some time Wake up and check if you received a stop signal If you have, exit the infinite loop (by returning from SvcDoRun) If not, run whatever code you want to execute each time you loop Hope this helps. Larry Bates From rrr at ronadam.com Wed Apr 5 00:02:48 2006 From: rrr at ronadam.com (Ron Adam) Date: Tue, 04 Apr 2006 23:02:48 -0500 Subject: xml element tree to html problem In-Reply-To: References: Message-ID: Fredrik Lundh wrote: > here's one way to do it: > > import cElementTree as ET > > tree = ET.XML(""" > > ball > > red > large > > > """) > > MAP = { > "object": ("dl", "object"), > "name": ("dt", "name"), > "desc": ("ul", None), > "color": ("li", "color"), > "size": ("li", "size"), > } > > for elem in tree.getiterator(): > elem.tag, klass = MAP[elem.tag] > if klass: > elem.set("class", klass) > > print ET.tostring(tree) Thanks a *LOT!* :-) This is what I needed. Now I can play with finding the best data structure along with what elements to translate each tag to. This is for a rewrite of PyDoc.py. I'm hoping it will be as easy to write to other formats from the XML as it is to html. Cheers, Ron From rvernica at gmail.com Tue Apr 18 20:59:55 2006 From: rvernica at gmail.com (Rares Vernica) Date: Tue, 18 Apr 2006 17:59:55 -0700 Subject: locale, format monetary values In-Reply-To: References: Message-ID: That's it. Thanks a lot! There is no example on the locale.format in the docs so I was confused. Regards, Ray deelan wrote: > Rares Vernica wrote: >> Hi, >> >> Can I use locale to format monetary values? If yes, how? If no, is >> there something I can use? >> >> E.g., >> I have 10000 and I want to get "$10,000". > > try something like: > > >>> import locale > >>> locale.setlocale(locale.LC_ALL, "en-US") > 'English_United States.1252' > >>> locale.format("%f", 10000, True) > '10,000.000000' > >>> locale.format("$%.2f", 10000, True) > '$10,000.00' > > bye. > From fredrik at pythonware.com Tue Apr 25 03:10:09 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 25 Apr 2006 09:10:09 +0200 Subject: MS VC++ Toolkit 2003, where? References: <1he8pss.1yk7ug81rv7pw2N%aleaxit@yahoo.com> <1145811839.042394.73260@t31g2000cwb.googlegroups.com> <1he8sbx.dqqp3q10n5thaN%aleaxit@yahoo.com> <1145849491.347970.112150@e56g2000cwe.googlegroups.com> <1he9m4m.9d8okx1x7mxeaN%aleaxit@yahoo.com> <444C784F.3000502@v.loewis.de> <1heag4u.19dksfxrbe14wN%aleaxit@yahoo.com> <444D61F9.4040003@v.loewis.de> Message-ID: Robert Kern wrote: > Martin v. L?wis wrote: > > Robert Kern wrote: > > > >>Oh, that's right, you need an import library for Python24.dll . > > > > That shouldn't be a problem: that library is included with Python. > > For mingw, too? I.e. a .a not a .lib? last time I tinkered with mingw, it could link directly against the DLL file. see the last two minutes in "mingw from scratch in 20 minutes" post: http://article.gmane.org/gmane.comp.python.general/388046 the MinGW FAQ says that you can use reimp in cases like this: http://www.mingw.org/mingwfaq.shtml#faq-msvcdll but that didn't seem to be necessary (I assume reimp or something is now integrated in mingw, or maybe I have a magic computer...) however, note that the FAQ entry says that you can use an existing LIB file as well, so Python's standard import library should work. From cesugden at gmail.com Thu Apr 27 15:33:18 2006 From: cesugden at gmail.com (Chris) Date: 27 Apr 2006 12:33:18 -0700 Subject: Twisted and Tkinter In-Reply-To: References: <1146104350.843046.186230@v46g2000cwv.googlegroups.com> <1146161267.955195.308200@g10g2000cwb.googlegroups.com> Message-ID: <1146166398.776657.39760@i40g2000cwc.googlegroups.com> There is no manual that's the problem. The sendLine method is part of LineReceiver which is part of twisted. It's used to send a message over the transport link. I can get it working by overriding twisted's methods for example linereceived() or connectionmade(). But how do I get it to send a message over the transport to the server by clicking a tkinter button? There are no examples or documents on the internet that can help, I've searched for hours. From http Sun Apr 16 11:11:12 2006 From: http (Paul Rubin) Date: 16 Apr 2006 08:11:12 -0700 Subject: Using Python To Create An Encrypted Container References: Message-ID: <7x7j5p8sj3.fsf@ruckus.brouhaha.com> Michael Sperlle writes: > If I could create a large file that could be encrypted, and maybe add > files to it by appending them and putting in some kind of delimiter > between files, maybe a homemade version of truecrypt could be constructed. > Any idea what it would take? If by container you mean a user-level file system with transparent encryption, there are a bunch of ways to do it, but it's system hacking, Python doesn't come into it much. If you just want an encrypted archive, then put your files into a normal zip file and encrypt the zip file. From pmartin at snakecard.com Wed Apr 19 10:25:43 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Wed, 19 Apr 2006 09:25:43 -0500 Subject: datetime question References: <1614927.J7V8dXKGb9@jupiter.g2ctech> <444564bf$1@nntp0.pdx.net> Message-ID: :-) Thanks. Philippe Scott David Daniels wrote: > Jorge Godoy wrote: >> Philippe Martin wrote: >> >>> I need to get the date and time under Windows and Linux but need the >>> information visible to the user (cannot find my words) not the sytem >>> information (ex: a PC setup on greenwich but the date/time displayed are >>> relative to some other place. >> >> Something like this? >> >>>>> import datetime >>>>> datetime.datetime.now() >> ... > > Just so you (Phillipe) know, you are talking about "local time" vs. UTC. > >>> import datetime > >>> print datetime.datetime.now() # local > 2006-04-18 15:25:03.140000 > >>> print datetime.datetime.utcnow() # zulu / utc / gmt > 2006-04-18 22:25:13.625000 > > --Scott David Daniels > scott.daniels at acm.org From sdb1031 at gmail.com Fri Apr 14 17:03:43 2006 From: sdb1031 at gmail.com (sdb1031) Date: 14 Apr 2006 14:03:43 -0700 Subject: Including standalone="no" in XML declaration Message-ID: <1145048623.670698.17920@e56g2000cwe.googlegroups.com> I'm trying to learn about Python and XML. I would like to be able to add standalone="no" to my xml declaration when writing an xml file, but I am unable to figure out how. So far, I have the following code: import xml.dom.minidom doc2 = xml.dom.minidom.Document() print doc2.toxml('iso-8859-1') Which produces the following XML declaration: However, my goal is to have the XML declaration look like the following: The following link mentions "standalone" as a Document class variable, but I am unsure how to make this work or even if I am on the right track. http://epydoc.sourceforge.net/stdlib/private/_xmlplus.dom.minidom.Document-class.html#encoding Any help would be greatly appreciated. Thanks. From sijben at eemvalley.com Thu Apr 20 03:26:01 2006 From: sijben at eemvalley.com (Paul Sijben) Date: Thu, 20 Apr 2006 09:26:01 +0200 Subject: UDP performance Message-ID: <44473787$0$31643$e4fe514c@news.xs4all.nl> I am stumped by the following problem. I have a large multi-threaded server accepting communications on one UDP port (chosen for its supposed speed). I have been profiling the code and found that the UDP communication is my biggest drain on performance! Communication where the client and the server are on the same machine still takes 300ms or sometimes much more per packet on an Athlon64 3000+ running Linux (Fedora Core 5 x64). I must be doing something wrong and would really appreciate feedback on my code below: I open the server port with self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.s.bind((myaddress, myport)) I then open a client port with self.s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.s.connect((host, port)) the client sends data with self.s.sendall(data) and the server with self.s.sendto(data,link.remoteaddress) both receive with buf, address = socket.recvfrom(8192) The sender and receiver are in separate threads (threading.Thread). Does anyone know what is going wrong here, the socket communication, the thread scheduling? Paul Sijben From rogerb at rogerbinns.com Thu Apr 6 00:23:03 2006 From: rogerb at rogerbinns.com (Roger Binns) Date: Wed, 5 Apr 2006 21:23:03 -0700 Subject: Convertion of Unicode to ASCII NIGHTMARE References: <1144079830.734516.8390@z34g2000cwc.googlegroups.com> <1144295335.353840.322190@i40g2000cwc.googlegroups.com> Message-ID: "Serge Orlov" wrote in message news:1144295335.353840.322190 at i40g2000cwc.googlegroups.com... > I have an impression that handling/production of byte order marks is > pretty clear: they are produced/consumed only by two codecs: utf-16 and > utf-8-sig. What is not clear? Are you talking about the C APIs in Python/SQLite (that is what I have been discussing) or the language level? At the C level, SQLite doesn't accept boms. You have to provide UTF-8 or host byte order two bytes per char UTF-16. Roger From lucaberto at libero.it Thu Apr 27 03:41:20 2006 From: lucaberto at libero.it (luca72) Date: 27 Apr 2006 00:41:20 -0700 Subject: Direct acces to db unify on unix sco Message-ID: <1146123680.837469.200940@y43g2000cwc.googlegroups.com> Is it possible or i must use odbc? Rergards Luca From jjl at pobox.com Thu Apr 13 17:01:42 2006 From: jjl at pobox.com (John J. Lee) Date: 13 Apr 2006 21:01:42 +0000 Subject: Python editing with emacs/wordstar key bindings. References: <1144887253.027194.198750@i39g2000cwa.googlegroups.com> Message-ID: <87y7y95gw9.fsf@pobox.com> "Carl Banks" writes: [...] > > 1) When I load a .py file, emacs automatically overrides my wordstar-mode > > with python-mode, forcing all the keybindings back to emacs native keys. > > Why? [...] > Python and wordstar are both major modes. When python-mode is loaded, > it replaces (not sits atop of) wordstar-mode; you can't have two major > modes loaded at the same time. Oh, of course -- didn't occur to me that wordstar-mode might be a major mode. Thomas, why not simply use the standard emacs provisions for key rebinding? Or are the wordstar keys modal or otherwise difficult to implement that way, as is the case with vi bindings? (but viper does a great job of that -- I'm using it right now) [...] > > Is there a better python-mode script I should be using other than the > > default that came with emacs? > > I doubt there's one that solves your problem. Carl is right: changing python-mode is the wrong end to approach this problem. Change the keybindings instead. Like I said, if you're stuck rebinding the keys, try one of the emacs mailing lists / newsgroups. Thanks to the kind help of such people I've been getting away with scandalously little knowledge of my own .emacs for years, and only just now learning a little elisp. :-) John From nogradi at gmail.com Tue Apr 4 06:05:42 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Tue, 4 Apr 2006 12:05:42 +0200 Subject: markup.py - 1.2 - an HTML/XML generator In-Reply-To: References: <5f56302b0604031509r51af902dh2e908561bbf78d44@mail.gmail.com> <1144103244.20245.2.camel@kenshin.CASA> <1144112722.28978.11.camel@kenshin.CASA> Message-ID: <5f56302b0604040305w4998a6bdj84404dcac457c896@mail.gmail.com> > > $ pwd > > /usr/lib/python2.4/site-packages > > $ grep -re klass . | wc -l > > 274 > > $ grep -re class_ . | wc -l > > 897 > > How many of those "class_" instances are really just substrings of > "__class__" and "class_name" and such? On my machine, I see a handful > in the standard library, and _none_ in site-packages (which has only > 1709 .py files, mind you). > > > For me that's enough. "class_" is used at least three times more than > > "klass". Besides, as Scott pointed out, "class_" is prefered by the > > guidelines too. > > Actually what he posted explicitly states that "cls" is preferred. > Following that it says that one should considering appending _ if the > name conflicts with a keyword (and one can assume it means "for all > keywords other than class"). > > >>`cls`, at least, is more commonly used within > >>Python itself (e.g., classmethods). > > > > Yes. cls wouldn't be a good choice. But class_ is. Or maybe even > > css_class. But klass isn't. > > As has been pointed out, klass has a fairly established tradition of > use. (I happen to agree with the PEP and use "cls" exclusively for such > things, and do agree that "klass" is crude.) > It seems there are 3 competing versions: (1) cls (2) class_ (3) klass (1) is encouraged by PEP-8 for class methods (2) is encouraged by the same PEP for keyword arguments if there aren't synonyms available (3) is used widely and doesn't seem ugly to anyone whose language uses 'k' for the first sound in the English pronounciation of the word 'class'. And it happens in English too, although usually not at the beginning of the word, like 'quick', 'break', etc. And there is an additional point in PEP-8, namely one should avoid spelling corruption, so 'print_' is preferred instead of 'prnt' but the best is to invent a synonym. Now the question is whether 'klass' counts as a spelling corruption or it is more like a synonym. I thought it's not a corruption that's why I chose to use it (I must also admit I haven't even thought about (1) or (2) at all or PEP-8 to begin with). So I guess 'klass' is okay, but I'm open to other suggestions, I have only problems with 'class_' as I usually dislike non-alphabetical characters unless they are absolutely necessary. Any further thoughts on this? From steve at REMOVETHIScyber.com.au Thu Apr 13 22:59:02 2006 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Fri, 14 Apr 2006 12:59:02 +1000 Subject: namespace issue References: Message-ID: On Thu, 13 Apr 2006 22:59:52 +0200, Daniel Nogradi wrote: > I would like to give the same name to a keyword argument of a class > method as the name of a function, with the function and the class > living in the same namespace and the class method using the > aforementioned function. That's a problem right there. As soon as you find yourself needing to distinguish between "great_name the function" and "great_name the argument", you have a potential source of API confusion, no matter how great the name is. But if you absolutely must: def _gn(x): return x.upper() great_name = _gn class myclass: def mymethod(self, great_name=False): if great_name: return _gn('something') else: return 'something' -- Steven. From spamspam at spam.eggs Fri Apr 21 19:05:47 2006 From: spamspam at spam.eggs (Ben C) Date: 21 Apr 2006 23:05:47 GMT Subject: lambda References: <1145642409.389741.39680@g10g2000cwb.googlegroups.com> Message-ID: On 2006-04-21, Alexis Roda wrote: > Ben C escribi?: >> On 2006-04-21, Ben C wrote: >> Having said that, I attempted to confirm this using def rather than >> lambda, and encountered something I cannot explain at all-- it appears >> that the functions are getting redefined whenever they are called, to >> effect a kind of "dynamic scoping" behaviour. I would appreciate any >> explanation anyone can give of this: >> >> fns = [] >> for y in range(2): >> def fn(): >> yy = y # exactly the same with yy = int(y) >> print "defining fn that returns", yy >> return yy >> print "Appending at", y >> print fn, fn() >> fns.append(fn) > > > yy = y does assign y's current value (current == fn call time, not fn > definition time). To return 0 and 1 as expected you should create a > "different/private" y for every fn's definition. > > ---------------------------------------- > > fns = [] > for y in range(2): > def fn(y=y): > yy = y > print "defining fn that returns", yy > return yy > print "Appending at", y > print fn, fn() > fns.append(fn) > > > ---------------------------------------- Yes; the difficulty is that the body of the function is executed (obviously) every time you call it. The body of the function reads y which is a global variable and has whatever value it has at the time. The parameters are the only part of a function definition where you get to write some code that initializes things in the function's "frame" when the function is defined rather than when it's called. I got confused because I was thinking of yy = y in the body of fn's definition as an initialization, not as an assignment. In other languages it's possible to distinguish, but not in Python. Really this is what classes are for in Python: def f(x): return x * x class fn(object): def __init__(self, y): # "define-time" things are here self.y = y def __call__(self, x): # "call-time" things are here return f(x) * self.y fns = [fn(i) for i in range(1, 10)] for f in fns: print f(1) is I think quite a good way to do this. From fredrik at pythonware.com Sat Apr 1 08:04:38 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 1 Apr 2006 15:04:38 +0200 Subject: Tkinter divider References: <1143892810.826596.237070@z34g2000cwc.googlegroups.com> Message-ID: Jim Lewis wrote: > Anyone know how to create a draggable divider between two Tkinter > windows? http://effbot.org/tkinterbook/panedwindow.htm might be what you need. From fredrik at pythonware.com Tue Apr 11 04:04:47 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 11 Apr 2006 10:04:47 +0200 Subject: using regex to remove $ sign References: Message-ID: "Kun" wrote: > i have an html/cgi input that takes in values to a mysql database, > however, if i stick in $20 instead of 20, it crashes the program > because of the extra $ sign. I was wondering if anyone has a quick > regular expression in python to remove the $-sign if it is present in > the input. RE? ex-perler? try strip+lstrip instead: >>> text = " $12921 " >>> text.strip().lstrip("$") "12921" From jdferrell3 at gmail.com Wed Apr 26 12:54:12 2006 From: jdferrell3 at gmail.com (JDF) Date: 26 Apr 2006 09:54:12 -0700 Subject: SimpleXMLRPCServer runnning as a Windows Service using win32serviceutil Message-ID: <1146070452.807475.22400@t31g2000cwb.googlegroups.com> I am trying to create a Windows service using SimpleXMLRPCServer and win32serviceutil. The service itself seems to be working properly (starts, stops, etc) and I can connect using an XMLRPC client from the localhost. However when I connect from a remote client, I either get a socket error or an xmlrpclib.ProtocolError error. If I use serve_forever() rather than handle_request(), the remote clients can connect but it breaks the Windows service functionality (can't stop the service). I have tried the same code without the service and that works, both locally and remotely. It would seem that the problem is related to the way the service handles remote connections, but I cannot figure out what the problem is. I have searched around, but can't find any example code. Hopefully someone can point me in the right direction. thanks, John ## XML-RPC Service import win32serviceutil import win32service import win32event import win32evtlogutil import win32file import servicemanager import SimpleXMLRPCServer class OBJECT: def hello(self): return "Hello World" class XMLRPCSERVICE(win32serviceutil.ServiceFramework): _svc_name_ = "XMLRPCSERVICE" _svc_display_name_ = "XMLRPCSERVICE" _svc_description_ = "XMLRPCSERVICE" def __init__(self, args): win32evtlogutil.AddSourceToRegistry(self._svc_display_name_, sys.executable, "Application") win32serviceutil.ServiceFramework.__init__(self, args) self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) self.hSockEvent = win32event.CreateEvent(None, 0, 0, None) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) def SvcDoRun(self): ## Write a started event servicemanager.LogMsg( servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, ' (%s)' % self._svc_name_)) server = SimpleXMLRPCServer.SimpleXMLRPCServer(("", 8080)) object = OBJECT() server.register_instance(object) while 1: win32file.WSAEventSelect(server, self.hSockEvent,win32file.FD_ACCEPT) rc = win32event.WaitForMultipleObjects((self.hWaitStop,self.hSockEvent), 0, win32event.INFINITE) if rc == win32event.WAIT_OBJECT_0: break else: win32file.WSAEventSelect(server,self.hSockEvent, 0) server.handle_request() #server.serve_forever() ## Works, but breaks the Windows service functionality ## Write a stopped event win32evtlogutil.ReportEvent(self._svc_name_, servicemanager.PYS_SERVICE_STOPPED,0, servicemanager.EVENTLOG_INFORMATION_TYPE, (self._svc_name_,"")) if __name__ == '__main__': win32serviceutil.HandleCommandLine(XMLRPCSERVICE) ---------------------------------------------------------------- ##XML-RPC Server without service, this works using handle_request() import SimpleXMLRPCServer #The server object class OBJECT: def hello(self): return "Hello World" object = OBJECT() server = SimpleXMLRPCServer.SimpleXMLRPCServer(("", 8080)) server.register_instance(object) #Go into the main listener loop print "Listening on port 8080" while 1: server.handle_request() ---------------------------------------------------------------- ## XML-RPC Client import xmlrpclib server = xmlrpclib.ServerProxy("http://remoteserver:8080") print server.hello() From ldo at geek-central.gen.new_zealand Mon Apr 10 22:57:41 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 11 Apr 2006 14:57:41 +1200 Subject: how relevant is C today? References: <44381ee4$0$4209$c3e8da3@news.astraweb.com> <44382711.10403@v.loewis.de> <44393fbe$0$19226$c3e8da3@news.astraweb.com> <44398651$0$4206$c3e8da3@news.astraweb.com> <1144632983.039143.203330@u72g2000cwu.googlegroups.com> <443a4e8a$0$21013$626a54ce@news.free.fr> Message-ID: In article <443a4e8a$0$21013$626a54ce at news.free.fr>, bruno at modulix wrote: >gregarican wrote: >> Here are a few languages I recommend most programmers should at least >> have a peek at: >> >(snip) >> 2) Lisp - Along with FORTRAN, one of the oldest programming languages >> still in use. Pure functional programming model > >Err... Even if Lisp is the father of functional programming, it is >definitively not a 'pure' FPL. It _can_ be used as a pure functional language. An interpreter for a pure-functional subset of LISP can be written in functional LISP, in just a couple of dozen lines of code. From fabiofz at gmail.com Fri Apr 21 19:50:13 2006 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Fri, 21 Apr 2006 20:50:13 -0300 Subject: Jython: exec a string In-Reply-To: <83c2g.70526$Jd.51613@newssvr25.news.prodigy.net> References: <1145650854.705377.270060@v46g2000cwv.googlegroups.com> <1145652831.034969.204230@j33g2000cwa.googlegroups.com> <83c2g.70526$Jd.51613@newssvr25.news.prodigy.net> Message-ID: On 4/21/06, Edward Elliott wrote: > > iirc java doesn't like multiple classes in a single file (not counting > anonymous or inner classes). sounds like jython may have the same > restriction... Actually, that's not completely true. The restriction is that you can have only 1 public class in the top-level, but you can have other non-public top-level classes, and jython does not share that restriction. abcd wrote: > > the error i get when i run the exec is, "java.lang.ClassFormatError"... > > > Could you post the examples you're using? In a simple test it works for me. Cheers, Fabio -------------- next part -------------- An HTML attachment was scrubbed... URL: From caleb.hattingh at gmail.com Thu Apr 20 05:26:02 2006 From: caleb.hattingh at gmail.com (Caleb Hattingh) Date: 20 Apr 2006 02:26:02 -0700 Subject: Can one query full name (or version) of selected packages at pypi? Message-ID: <1145525161.975827.277860@u72g2000cwu.googlegroups.com> Hi everyone I suspect this has come up before, but google and group searches for "python package index query" or "pypi query" and the like haven't turned anything up. I want to monitor the versions of the list of packages I like having around, and I expect that the python package index might be a good place to do this. Typically, such packages would include, say, Pyrex and PyParsing, for example. So: I would like to query the package index with a short name (perhaps wildcarded), and retrieve either the full name (from which to strip the ver.) or version number, and compare it with what I have on disk. At this stage, just reporting the differences is fine. I could do these steps myself with normal http access and screen-scraping, but is there already such a system/script somewhere? Alternatively, how do you all keep versions of python addons up-to-date? Manually? regards Caleb From grflanagan at yahoo.co.uk Fri Apr 21 05:02:36 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 21 Apr 2006 02:02:36 -0700 Subject: Strategy Design Pattern References: <1145597529.217734.25600@g10g2000cwb.googlegroups.com> Message-ID: <1145610156.914915.229580@z34g2000cwc.googlegroups.com> Daniel Santa Cruz wrote: > Hello all, > > I've been trying to go over my OO Patterns book, and I decided to try > to implement them in Python this time around. I figured this would > help me learn the language better. > > Well, I've gotten stuck with my first go at OO patterns with Python. I > guess it goes without say that some of the stuff that are taken for > granted in most of the books (ie. Interfaces, Abstract classes) don't > really apply to Python per say, but the idea behind the patterns can be > extracted out still. In the specific case of the Strategy pattern, I > think the goal is to abstract out of the class an algorithm that can > then be reused by some of the inherited classes. This way we don't > repeat ourselves. Maybe I got this all wrong... > > I'm at a loss at how I can do this with Python, any pointers would be > more than welcomed! This is my understanding of the Strategy Pattern: (Perhaps I have a SudokuSolver class that will solve *any* Sudoku puzzle, but it's very slow for simple puzzles because of some unavoidable overhead related only to the more difficult puzzles - so I want to try a simpler but faster method first, if it doesn't succeed then use the more complex method.) class SudokuGrid(object): def __init__(self, solver=None): self.grid = [[-1]*9]*9 if solver is not None: self.solver = solver else: self.solver = SimpleSudokuSolver() def solve(self): self.solver.sudoku = self self.solver.solve() class SimpleSudokuSolver(object): sudoku = None def solve(self): print 'solving %s ...simple algorithm...' % repr(self.sudoku) class DifficultSudokuSolver(object): sudoku = None def solve(self): print 'solving %s ...difficult algorithm...' % repr(self.sudoku) s = SudokuGrid() s.solve() s.solver = DifficultSudokuSolver() s.solve() solving <__main__.SudokuGrid object at 0x0117D390> ...simple algorithm... solving <__main__.SudokuGrid object at 0x0117D390> ...difficult algorithm... HTH Gerard From sybrenUSE at YOURthirdtower.com.imagination Wed Apr 26 10:25:11 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Wed, 26 Apr 2006 16:25:11 +0200 Subject: Python UPnP on Linux? References: <444f3b66$0$31642$e4fe514c@news.xs4all.nl> Message-ID: Paul Sijben enlightened us with: > Googling on this I have found win32 implementations and Twisted > implementations yet I am looking for a way to do it on Linux WITHOUT > Twisted. Twisted is Open Source, so you could browse the source and see how they do it. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From jjl at pobox.com Sat Apr 29 15:19:48 2006 From: jjl at pobox.com (John J Lee) Date: Sat, 29 Apr 2006 19:19:48 +0000 (UTC) Subject: [wwwsearch-general] Re: Urllib2 / add_password method In-Reply-To: <87vessryya.fsf@pobox.com> References: <1146244801.469187.49370@i39g2000cwa.googlegroups.com> <87vessryya.fsf@pobox.com> Message-ID: On Sat, 29 Apr 2006, John J. Lee wrote: > "mrstephengross" writes: > >> I'm working on learning how to use urllib2 to use a proxy server. I've >> looked through the postings on this group, and it's been helpful. I >> have not, however, found complete documentation on the add_password() >> functions. Here's what I've got so far: > > Don't use a password manager with proxy auth in 2.4, it doesn't work: > > http://python.org/sf/1470846 > > [...] >> It works, but I don't really know what I'm doing with the >> proxy_auth_handler part. Specifying username and password make sense, >> but I haven't found documentation on what 'realm' and 'host' are for. >> Shouldn't username & password be sufficient? Oops, didn't read your question. I'm surprised if it worked at all given that bug (maybe you're using an older Python, and I forget all the details of the bug). Anyway, to answer your question: yes, username & password *should* be sufficient, but the password manager classes in urllib2 at present aren't very friendly like that. You can use HTTPPasswordMgrWithDefaultRealm so that at least you can forget about the realm part. (The "realm" is what you see in the title bar of the pop-up that web browsers display. See RFC 2617 for more details.) I'm adding friendlier proxy/auth support to package mechanize ATM (and finding/fixing bugs as I go), so maybe some of that will find its way into Python 2.6. John From jzgoda at o2.usun.pl Fri Apr 21 14:45:16 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Fri, 21 Apr 2006 20:45:16 +0200 Subject: Thanks from the Java Developer In-Reply-To: <1he434n.vosf551izis2eN%aleaxit@yahoo.com> References: <1145474995.143893.31760@z34g2000cwc.googlegroups.com> <1145568613.146056.135230@u72g2000cwu.googlegroups.com> <1he434n.vosf551izis2eN%aleaxit@yahoo.com> Message-ID: Alex Martelli napisa?(a): > At least in the Bay Area, the jobmarket for Python programmers is wild, > right now -- firms such as Google, Pixar, BitTorrent, IronPort, etc, > etc, all hungry for Pythonistas -- BayPIGgies mailing list bitching over > too many job-offer posts, and the nuisance of all those recruiters > haunting our monthly meetings and how much time they take, ...!!! I cann't wait when this rush arrive to my area. During last 3 years I had only 2 Python job offerings, so I decided to "inject" Python to my current organization. ;) -- Jarek Zgoda http://jpa.berlios.de/ From nogradi at gmail.com Tue Apr 18 06:36:53 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Tue, 18 Apr 2006 12:36:53 +0200 Subject: How protect proprietary Python code? (bytecode obfuscation?, what better?) In-Reply-To: References: <1145293384.791678.14450@v46g2000cwv.googlegroups.com> <1145300492.623527.300740@e56g2000cwe.googlegroups.com> <1145352417.100210.266170@e56g2000cwe.googlegroups.com> <5f56302b0604180252je586e83o24ab57a3d9d0909e@mail.gmail.com> Message-ID: <5f56302b0604180336y585a5e20h1a8935e861a37978@mail.gmail.com> > >> char secret_code[] = "print 'moshe'"; > >> > >> int main() > >> { > >> return PyRun_SimpleString(secret_code); > >> } > >> > >> and you need to link with python24.lib or whatever the object file is > >> for your platform. > > > > Are you sure? On a linux platform I tried linking with libpython2.4.so > > (I assume this is the correct object file) but it segfaults in > > PyImport_GetModuleDict( ). > > I still don't understand why you think that embedding the *source code* in a > variable > named "secret" will do a better job than just putting the byte code in some > non-obvious > packaging, but if you insist on embedding the code, reading the > documentation might > help: > > http://docs.python.org/ext/embedding.html > "At the very least, you have to call the function Py_Initialize()" > > http://docs.python.org/ext/high-level-embedding.html > (minimal PyRun_SimpleString example) Well, I was not the original poster in this thread I just picked up the idea of executing python code that is assigned to a string from within C and tried to do it with no particular goal, that's all. And thanks a lot for the links, the docs are pretty clear, I should have checked them before.... From clodoaldo.pinto at gmail.com Fri Apr 7 17:50:06 2006 From: clodoaldo.pinto at gmail.com (Clodoaldo Pinto) Date: 7 Apr 2006 14:50:06 -0700 Subject: Programming Tutorial for absolute beginners References: <1144439148.751062.16590@t31g2000cwb.googlegroups.com> <1144444872.962395.3310@z34g2000cwc.googlegroups.com> Message-ID: <1144446605.916499.24470@i39g2000cwa.googlegroups.com> bill pursell wrote: > 1) in the section on the interactive interpreter you have the sentence: > "In Linux open a shell and type python (must be lower case)". It > would be nice if the word 'python' were in a different font, or perhaps > in quotes, or something. You're targetting the "absolute beginner", so > you should assume the reader is not familiar with the CLI. Done, thanks. > > 2) In the section on installing, you begin with: > "Python is an interpreted, interactive, object-oriented programming > language.". The complete novice sees those words and expects > them to be explained, but there is no definition given. I would > recommend simplifying that sentence, or explaining the terms. Ok, i will think about something, or just delete it. Clodoaldo From wietse.j at gmail.com Fri Apr 14 12:18:38 2006 From: wietse.j at gmail.com (wietse) Date: 14 Apr 2006 09:18:38 -0700 Subject: instance variable weirdness Message-ID: <1145031518.658261.324540@e56g2000cwe.googlegroups.com> Hello, I have written the following script to illustrate a problem in my code: class BaseClass(object): def __init__(self): self.collection = [] class MyClass(BaseClass): def __init__(self, name, collection=[]): BaseClass.__init__(self) self.name = name self.collection = collection if __name__ == '__main__': seq = [] inst = None for i in xrange(5): inst = MyClass(str(i)) inst.collection.append(i) seq.append(inst) inst = None for i in xrange(5): inst = MyClass(str(i)+'~', []) inst.collection.append(i) seq.append(inst) inst = None for i in seq: print "Instance '%s'; collection = %s" % (i.name, str(i.collection)) The output I get is: >>> Instance '0'; collection = [0, 1, 2, 3, 4] Instance '1'; collection = [0, 1, 2, 3, 4] Instance '2'; collection = [0, 1, 2, 3, 4] Instance '3'; collection = [0, 1, 2, 3, 4] Instance '4'; collection = [0, 1, 2, 3, 4] Instance '0~'; collection = [0] Instance '1~'; collection = [1] Instance '2~'; collection = [2] Instance '3~'; collection = [3] Instance '4~'; collection = [4] >>> I don't understand why the first loop doesn't give the same result as the second loop. Can somebody enlighten me? Wietse From anon at yahoo.com Fri Apr 21 15:41:26 2006 From: anon at yahoo.com (Marty Christion) Date: Fri, 21 Apr 2006 12:41:26 -0700 Subject: Recommended IDE for creating GUI? Message-ID: <124idf0362d75dd@corp.supernews.com> What are some good free or inexpensive (<$50) IDE's for learning how to program and create GUI's for Python? I'm pretty good with the simple programming aspect of the language, but I'm a little mystified by the world of GUI's, and the options available in python. From mahs at telcopartners.com Sat Apr 8 19:40:50 2006 From: mahs at telcopartners.com (Michael Spencer) Date: Sat, 08 Apr 2006 16:40:50 -0700 Subject: how to make a generator use the last yielded value when it regains control In-Reply-To: <44384257$0$11362$c3e8da3@news.astraweb.com> References: <4435cde3$0$11677$c3e8da3@news.astraweb.com> <1144383206.576767.192570@g10g2000cwb.googlegroups.com> <4435e96d$0$17970$c3e8da3@news.astraweb.com> <44384257$0$11362$c3e8da3@news.astraweb.com> Message-ID: John Salerno wrote: > Michael Spencer wrote: > >> itertools.groupby makes this very straightforward: > > I was considering this function, but then it seemed like it was only > used for determing consecutive numbers like 1, 2, 3 -- not consecutive > equivalent numbers like 1, 1, 1. But is that not right? With one argument, groupby assembles groups of equal consecutive elements: >>> list((key, list(group)) for key, group in groupby("AAABBCAAA")) [('A', ['A', 'A', 'A']), ('B', ['B', 'B']), ('C', ['C']), ('A', ['A', 'A', 'A'])] With a second keyfunc argument, groupby assembles groups where keyfunc(element) is equal for consecutive elements >>> list((key, list(group)) for key, group in groupby("AAAaaaAAA",str.isupper)) [(True, ['A', 'A', 'A']), (False, ['a', 'a', 'a']), (True, ['A', 'A', 'A'])] >>> HTH Michael From tdwdotnet at gmail.com Sun Apr 9 13:28:33 2006 From: tdwdotnet at gmail.com (Tim Williams (gmail)) Date: Sun, 9 Apr 2006 18:28:33 +0100 Subject: Receiving emails with attachments In-Reply-To: References: Message-ID: <9afea2ac0604091028l659a9478jc1604aacaaa49958@mail.gmail.com> On 8 Apr 2006 13:24:20 -0700, tomer.ha at gmail.com wrote: want to develop a script which will receive emails with attachments > from my POP3 account, perform certain actions on it and email it back > to someone else. > > However, I'm not familiar with any Python library which does it. Could > you a guide me to a relevant library which can handle emails? > The poplib module has already been mentioned for downloading from a pop3 mailbox For sending mail you will need the smtplib module. Depending on what actions you need to perform on each email, the email module may also be useful. HTH :) -- Tim Williams -------------- next part -------------- An HTML attachment was scrubbed... URL: From efrat_regev at yahoo.com Thu Apr 6 02:41:39 2006 From: efrat_regev at yahoo.com (efrat) Date: Thu, 06 Apr 2006 09:41:39 +0300 Subject: Python Module for Determining CPU Freq. and Memory? Message-ID: <4434b3c9@news.bezeqint.net> Hello, I'd like to determine at runtime the computer's CPU frequency and memory. Is there a module for these types of queries? platform.platform returns the computer's CPU name and type, but not its frequency; nor does it report how much memory the computer has. In the python help(), I searched for moudles cpu, but non were found. (Please note: I'm interested in hardware stuff, like how much memory the machine has; not how much free memory is available.) Many Thanks, Efrat From bytecolor at yahoo.com Wed Apr 26 14:49:23 2006 From: bytecolor at yahoo.com (bytecolor) Date: 26 Apr 2006 11:49:23 -0700 Subject: win32com short path name on 2k In-Reply-To: References: <1146054018.702204.222710@e56g2000cwe.googlegroups.com> Message-ID: <1146077363.184978.231500@u72g2000cwu.googlegroups.com> I have no idea how Featurecam registers the type library. I did figure out that I can get the full name 'C:\Program Files\Featurecam' from within Featurecam using VBA and the same property I used in Pyhton -> fc.InstallPath. Why would VBA and Python return two different strings? This is really driving me nuts, because I know for a fact I was getting the long name using python on 2k not 3 days ago, but now it's returning the short name and I haven't changed/installed anything. -- bytecolor From me at privacy.net Thu Apr 27 06:23:26 2006 From: me at privacy.net (Dan Sommers) Date: Thu, 27 Apr 2006 06:23:26 -0400 Subject: can anyone advise me References: <1146131326.328919.285430@t31g2000cwb.googlegroups.com> Message-ID: On 27 Apr 2006 02:48:46 -0700, micklee74 at hotmail.com wrote: > why the output of this code : > x = 0 > while x < 10: > z = 0 > print x > x = x + 1 > while z < x: > print z, > z = z + 1 > is > 0 Okay, that was x, from the print statement inside the x-loop. > 0 1 And that's z, from the print statement inside the z-loop. z is 0, and then when z is 1, it's not less than x, so we're done printing z's. And then we get the next x. > 0 1 2 And two more z's, 0 and 1, since x is now 2. And another x. Since this might be homework, I'll stop at a hint: you need to think about when you want each printed line to end, and make sure that you tell python to end it there. Regards, Dan -- Dan Sommers "I wish people would die in alphabetical order." -- My wife, the genealogist From kevin.bell at slcgov.com Tue Apr 25 13:35:46 2006 From: kevin.bell at slcgov.com (Bell, Kevin) Date: Tue, 25 Apr 2006 11:35:46 -0600 Subject: search an entire website given the homepage URL Message-ID: <2387F0EED10A4545A840B231BBAAC7226082CB@slcimail1.slcgov.com> >use a search engine (try the search box in the upper right corner). >using a spider to download the entire site just so you can "search through >it" is bloody impolite. Really? I'd argue that's impolite only if you're an impolite person with a rude agenda, which is not what I had in mind, but thanks for the ethics lecture as well as the pointer ; ) I assure you that I harbor no nefarious scheme. Isn't it common for folks to watch the stock market, or real estate listings, for example? I'll look into to tools you mentioned, and thanks again! From cweimann at k12hq.com Tue Apr 4 17:59:51 2006 From: cweimann at k12hq.com (Christopher Weimann) Date: Tue, 4 Apr 2006 17:59:51 -0400 Subject: Strange problem when running python code In-Reply-To: <1144177272.939450.134720@e56g2000cwe.googlegroups.com> References: <1144175959.412184.187110@g10g2000cwb.googlegroups.com> <9bzYf.1903$No6.42196@news.tufts.edu> <1144177272.939450.134720@e56g2000cwe.googlegroups.com> Message-ID: <20060404215951.GC38629@tektite.k12usa.internal> On 04/04/2006-12:01PM, ishtar2020 wrote: > This is the line where the interpreter finds the error > > if text.list[i].toString() in limits:list)): <- Here is where That line has two extra close parens before the : Can you show the traceback? From kent at kentsjohnson.com Fri Apr 14 08:02:36 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Fri, 14 Apr 2006 08:02:36 -0400 Subject: %g not the same as %e or %f Message-ID: <443f89d1$1_1@newspeer2.tds.net> According to the docs, %g formatting is "Same as "e" if exponent is greater than -4 or less than precision, "f" otherwise." So I would expect that for any num, '%g'%num == '%e'%num or '%g'%num == '%f'%num. But this is not the case in fact: Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. In [1]: num = 1234567898.2345678945 In [2]: print "%g\n%e\n%f" % (num,num,num) 1.23457e+009 1.234568e+009 1234567898.234568 In [3]: num = 1234.456789 In [4]: print "%g\n%e\n%f" % (num,num,num) 1234.46 1.234457e+003 1234.456789 So I'm wondering if the docs are wrong or the implementation is wrong or there's something I don't understand? Thanks, Kent From ishtar2020 at hotmail.com Thu Apr 6 15:27:24 2006 From: ishtar2020 at hotmail.com (ishtar2020) Date: 6 Apr 2006 12:27:24 -0700 Subject: How to create a tear off menu in TKinter. Help Needed Message-ID: <1144351644.629167.115470@g10g2000cwb.googlegroups.com> Hi everybody I'd appreciate some help on creating a tear off menu with TkInter. I've been reading some documentation but still no luck. Please don't get confused: when I mean "tear off" menu I don't mean a drop-down or a pop-up menu, but those options which yield to another batch of sub-options when scrolled over, (as for example, the File->New option from internet explorer). I'm sure TkInter supports those widgets because the IDLE editor is built on it and it's got some tear off options like File->Recent Files. Thank you all in advance From rurpy at yahoo.com Sun Apr 2 17:47:12 2006 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 2 Apr 2006 14:47:12 -0700 Subject: Doc suggestions In-Reply-To: References: <1142964085.356976.166620@t31g2000cwb.googlegroups.com> <1143762250.537475.115420@t31g2000cwb.googlegroups.com> Message-ID: <1144014432.869077.318440@i40g2000cwc.googlegroups.com> "Terry Reedy" wrote: > wrote in message > > "Terry Reedy" wrote: > Yes, there have been claims that doc patches have to be in Latex or are > otherwise not welcome. But these mostly (all?) have lacked relevant > concrete data, which would be actual responses to actual submissions to the > Python SourceForge change trackers. Yes, I have seen here many times, and read in the doc footnotes, that any form of doc patches are acceptable. I never thought or claimed otherwise. >... > Some time ago, Alex Martelli submitted several style change suggestions for > at least one of the docs. As I remember, at least most of them were > accepted. In any case, all were considered. And there have since been > other changes that I have been involved with that were arguably style > upgrades rather than corrections. Given Alex Martelli's level of competence that is neither surprising or representative. > A few organizational changes might be considered, especially if accompanied > by an offer to make at least a prototype, but someone with fundamentally > different ideas should write their own doc under their own name. That puts a pretty high bar in place for the Language Reference which has no hope if becoming good without major organizational changes. >... > Suggestion: You could submit the one improved sentence you previously > suggested. But the overhead of any change is a bit high for just that. So > gather at least a few suggestions, put them in order, include section > number and identifier for each, and cut-and-paste urls from current docs at > python.org. What I am questioning is why those barriers are so high. Why does fixing a even a clear, obvious, fault in the documentation require someone to log in to sourceforge, create a bug or patch entry, have someone else review it, comment it, change a half dozen words in the source, close it... Why can't the folks doing the docs be more proactive? > Offer: If you submit your 'text patch' to SourceForge and let me know, I > will review it right away. [...] I appreciate the offer, but special treatment for someone who raises a public stink is not going to fix the underlying problem, is it? Here is a 30000' view. I posted about a clear (admittedly very minor) doc problem 8 days ago. Since then there have been 30+ postings in this thread. Insults and bad feelings have flown. Two people setup wikis and uploaded the tutorial. I don't know how many people have visited or made changes. After all that I look at the current 2.5 docs, and what do I see? The same, trivial, problem is still there. Am I the only one who sees something wrong with this picture? That change was simple and uncontroversial enough so that someone should have simply done it. Why is a formal change procedure needed for this level of change? My guess is the people taking care of the docs are Python developers whose main interest is Python but who also generously volunteer to handle docs issues. And probably most don't even read c.l.p. Is that close? Around christmas time there was a long discussion here and on the python doc mailing list about how to fix things. I was gone at the time but I read a lot of it when I returned. One thing stuck out like a sore thumb. There were hundreds of messages about redit vs latex, html vs xml, toolchains, wikis, patch managers, software packages. There were almost no messages about *WRITING* and *EDITING*. Part of the problem is undeniably the need for a good infrastructure. But... The other half, which has been nearly unaddressed as far as I can tell, is PEOPLE! The docs problem is a people problem, and won't be solved by technology. (Unless someone here is very good with AI :-) Here is how I would arrange things if I could... =================================== A psf project or sig or some other discrete unit chartered to work on the docs. Active, encouraging, solicitation of people with good (natural) language skills to participate. Detailed written style guidelines and document scopes so that everyone is, if not on, at least near the same page. Division of volunteers into (roughly) Czar or small committee, Editors, Writers, Everyone else. Top level czar or small committee sets overall doc policy and standards, resolves differences of opinion. Editors responsible for ensuring the docs have consistent style and appropriate content/level. (By rewriting and editing more than by rejecting submissions.) Writers who create new material and correct/improve existing material. Everyone else who will be encouraged to report doc errors, unclarities, suggest improvements, etc. Specific areas of interest assigned publicly to specific writers/editors (voluntarily of course), both to provide them with public recognition and as a minor incentive for them to get something done. A definition of what constitutes an minor change and the ability of volunteers to make such changes unilaterally. Facilitation of a fast-path communication channel between the person maintaining the docs for a package, and the developers/maintainers of that package, so questions can get asked and answered quickly. Use of a wiki or similar for: - Collaborative work among the writer and editors - Collection of comments and suggestions from users about both the released python docs, and the in-progress fixes/improvements (this part is what FL has prototyped). Foster a nurturing environment where people are not afraid to make changes. ================================ This may be too top heavy for some people. But the bottom line is that an effort has to be made to get PEOPLE involved in WRITING and EDITING. I personally think it will require more than waiting for a wiki to self-organise. From rschroev_nospam_ml at fastmail.fm Thu Apr 13 10:39:13 2006 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Thu, 13 Apr 2006 16:39:13 +0200 Subject: New Karrigel page in Wikipedia In-Reply-To: <9afea2ac0604130644t734a5034l717da793fec0e017@mail.gmail.com> References: <1144867025.095969.92870@e56g2000cwe.googlegroups.com> <9afea2ac0604130644t734a5034l717da793fec0e017@mail.gmail.com> Message-ID: <443E6291.6040107@fastmail.fm> Tim Williams (gmail) schreef: > > > On 13/04/06, *Roel Schroeven* < rschroev_nospam_ml at fastmail.fm > > wrote: > > > > There's something I don't quite get regarding the Karrigell- and > CherryPy-style frameworks. With PHP or mod_python I can put any number > of different applications in different directories on a web server, > which is very convenient: > > [SNIP] > How do other people do this? Only one application on each (virtual) > server? Or is there something I am missing? > > > Karrigell will happily run multiple karrigell "applications" on a single > server . In your example simply by having different applications at > http://foo.example.com/app1 and http://foo.example.com/app2 will do the > trick. But I still need to allocate a port for each one, right? And write rewrite rules to rewrite the urls: http://foo.example.com/app1 -> http://foo.example.com:port1 http://foo.example.com/app2 -> http://foo.example.com:port2 I don't like to have to run separate processes for each application, but I guess it will work. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From fredrik at pythonware.com Mon Apr 17 17:17:26 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 17 Apr 2006 23:17:26 +0200 Subject: Missing interfaces in Python... References: <1145306373.781129.305840@z34g2000cwc.googlegroups.com> <20060417210541.GV7561@vulcan.cprogrammer.org> Message-ID: Jonathan Daugherty wrote_ > # In Python, you would simply call the functions you need. No need to > # make things that rigidly defined. > > Except when you need to handle exceptions when those methods don't > exist. I think interfaces can definitely be useful. so with interfaces, missing methods will suddenly appear out of thin air ? From kairosenthal at tiscali.de Tue Apr 11 04:58:16 2006 From: kairosenthal at tiscali.de (kai) Date: 11 Apr 2006 01:58:16 -0700 Subject: dircache.listdir() or os.listdir() Message-ID: <1144745896.553391.74910@i39g2000cwa.googlegroups.com> Hello, I use dircache.listdir(myDir) in my module repeatedly. On OS WIN 2000 listdir() will re-read the directory structure! But on AIX, listdir() will not re-read the directory structure (see Python Library Reference). I work with python version 2.2. Now my 2 questions: Why does dircache.listdir() work different? Can I change in my modules dircache.listdir() with os.listdir() without problems. I want to use the re-read functionality. Thanks for your hints, Kai. From williams.jasonscott at gmail.com Thu Apr 27 18:54:27 2006 From: williams.jasonscott at gmail.com (williams.jasonscott at gmail.com) Date: 27 Apr 2006 15:54:27 -0700 Subject: C API []-style access to instance objects In-Reply-To: <2390280.fNMSP0QDYS@news.perlig.de> References: <1146091866.503475.73910@u72g2000cwu.googlegroups.com> <2390280.fNMSP0QDYS@news.perlig.de> Message-ID: <1146178467.488094.11750@i39g2000cwa.googlegroups.com> That worked! Thank You! I'd also like to say this group is great at fast accurate responses! Cheers! thanks.... ~jason From amorgan at xenon.Stanford.EDU Wed Apr 12 18:36:47 2006 From: amorgan at xenon.Stanford.EDU (Alan Morgan) Date: Wed, 12 Apr 2006 15:36:47 -0700 (PDT) Subject: list.clear() missing?!? References: <1144767680.583085.310160@v46g2000cwv.googlegroups.com> <1144870852.886477.238570@u72g2000cwu.googlegroups.com> Message-ID: In article <1144870852.886477.238570 at u72g2000cwu.googlegroups.com>, Raymond Hettinger wrote: >[Steven Bethard] >> I think these are all good reasons for adding a clear method, but being >> that it has been so hotly contended in the past, I don't think it will >> get added without a PEP. Anyone out there willing to take out the best >> examples from this thread and turn it into a PEP? > >Something this small doesn't need a PEP. I'll just send a note to >Guido asking for a pronouncement. > >Here's a draft list of pros and cons (any changes or suggestions are >welcome): > >Pros: >----- > >* s.clear() is more obvious in intent Serious question: Should it work more like "s=[]" or more like "s[:]=[]". I'm assuming the latter, but the fact that there is a difference is an argument for not hiding this operation behind some syntactic sugar. Alan -- Defendit numerus From groups at theyoungfamily.co.uk Thu Apr 20 08:34:37 2006 From: groups at theyoungfamily.co.uk (Ben) Date: 20 Apr 2006 05:34:37 -0700 Subject: Missing interfaces in Python... In-Reply-To: <1he15id.pxmsobvfopabN%aleaxit@yahoo.com> References: <1145306373.781129.305840@z34g2000cwc.googlegroups.com> <1145430546.625634.194710@g10g2000cwb.googlegroups.com> <7lrb429tg5c6dt1bt99d1131cafuulvqap@4ax.com> <4445f7f8$0$9451$626a54ce@news.free.fr> <1145438118.179643.140390@e56g2000cwe.googlegroups.com> <1he15id.pxmsobvfopabN%aleaxit@yahoo.com> Message-ID: <1145536477.118542.185180@v46g2000cwv.googlegroups.com> Oh I agree entirely. They are just equivalent ways of managing the complexity of large projects. I guess interfaces are "providing" specifications, and generics are "receiving" specifications, so single dispatch methods can be identical to interfaces only "inverted". Therefore, as there is no interface equivalent of full multi-methods, it shows that multimethods are the only primative you need to implement all of the above Cheers, Ben From tjreedy at udel.edu Sat Apr 22 00:56:22 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 22 Apr 2006 00:56:22 -0400 Subject: R Paul Johnson is out of the office. References: <1145644902.203297.124420@e56g2000cwe.googlegroups.com> Message-ID: "RK" wrote in message news:1145644902.203297.124420 at e56g2000cwe.googlegroups.com... > ok, who's been playing with mailman? I am sure the problem is a mis-configured auto-responder robot. Nothing like telling the world that you are not around to watch your home or office, Reminds me of when newspapers used to carry society notices of people going off on trips, like to Europe. The more common misbehavior is to privately spam posters on the list rather than the list itself. The message really should just say Ex Y. Zeta is not responding to email (until ...). No reason to say why. Terry Jan Reedy From paul at boddie.org.uk Tue Apr 4 12:58:49 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 4 Apr 2006 09:58:49 -0700 Subject: Convertion of Unicode to ASCII NIGHTMARE References: <1144079830.734516.8390@z34g2000cwc.googlegroups.com> <1144081137.137744.253790@i39g2000cwa.googlegroups.com> <34b9g3-ku8.ln1@home.rogerbinns.com> Message-ID: <1144169929.449801.98520@t31g2000cwb.googlegroups.com> Robert Kern wrote: > Roger Binns wrote: > > "Paul Boddie" wrote > >>It looks like you may have Unicode objects that you're presenting to > >>sqlite. In any case, with earlier versions of pysqlite that I've used, > >>you need to connect with a special unicode_results parameter, Note that I've since mentioned client_encoding which seems to matter for pysqlite 1.x. > > He is using apsw. apsw correctly handles unicode. In fact it won't > > accept a str with bytes >127 as they will be an unknown encoding and > > SQLite only uses Unicode internally. It does have a blob type > > using buffer for situations where binary data needs to be stored. > > pysqlite's mishandling of Unicode is one of the things that drove > > me to writing apsw in the first place. For pysqlite 2.x, it appears that Unicode objects can be handed straight to the API methods, and I'd be interested to hear about your problems with pysqlite, Unicode and what actually made you write apsw instead. > Ah, I misread the OP's traceback. > > Okay, the OP is getting regular strings, which are probably encoded in > ISO-8859-1 if I had to guess, from the Oracle DB. He is trying to pass them in > to SQLiteCur.execute() which tries to make a unicode string from the input: [...] There's an Oracle environment variable that appears to make a difference: NLS_CHARSET, perhaps - it's been a while since I've had to deal with Oracle, and I'm not looking for another adventure into Oracle's hideous documentation to find out. > *Now*, my advice to the OP is to figure out the encoding of the strings that are > being returned from Oracle. As I said, ISO-8859-1 is probably a good guess. > Then, he would *decode* the string to a unicode string using the encoding. E.g.: > > row = row.decode('iso-8859-1') > > Then everything should be peachy. I hope. Yes, just find out what Oracle wants first, then set it all up, noting that without looking into the Oracle wrapper being used, I can't suggest an easier way. Paul From scott.daniels at acm.org Mon Apr 10 12:58:02 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 10 Apr 2006 09:58:02 -0700 Subject: how relevant is C today? In-Reply-To: <1144632983.039143.203330@u72g2000cwu.googlegroups.com> References: <44381ee4$0$4209$c3e8da3@news.astraweb.com> <44382711.10403@v.loewis.de> <44393fbe$0$19226$c3e8da3@news.astraweb.com> <44398651$0$4206$c3e8da3@news.astraweb.com> <1144632983.039143.203330@u72g2000cwu.googlegroups.com> Message-ID: <443a8bb0$1@nntp0.pdx.net> gregarican wrote: > Here are a few languages I recommend most programmers should at least > have a peek at: > > 1) Smalltalk - The original object oriented programming language. > Influenced anything from Mac/Windows GUI to Java language. Terse, clean > syntax. IDE rolled into an operating system rolled into a set of core > libraries. Simula actually is the "original o-o language (as Smalltalk's authors freely admit). > 2) Lisp - Along with FORTRAN, one of the oldest programming languages > still in use. Pure functional programming model that is extensible and > has many derivatives. Great for mathematical purposes. Easy to learn if > you can get past all of the nested parenthesis :-) The functional style is not what was unique to LISP. LISP was the first language whose behavior was fully specified before it was implemented (and that definition was completely machine-independent). > 3) C - The "Latin" of modern programming languages. Used in low level > tasks (e.g. - hardware drivers) as well as larger projects (e.g. - > operating systems and other programming languages). Logcal, explicit > flow albeit a bit wordy. --Scott David Daniels scott.daniels at acm.org From tzot at sil-tec.gr Sun Apr 2 08:06:00 2006 From: tzot at sil-tec.gr (Christos Georgiou) Date: Sun, 02 Apr 2006 15:06:00 +0300 Subject: ipv6 validation References: <1142705173.912345.301840@g10g2000cwb.googlegroups.com> <1143747608.788079.241550@i39g2000cwa.googlegroups.com> Message-ID: On 30 Mar 2006 11:40:08 -0800, rumours say that jiri.juranek at kctdata.cz might have written: >thanks a lot for this solution. >Next thing: how may i find out that that address is multicast one? is >there some easy possibility or i have to use regex now? To quote a Google reply: "IPv6 multicast addresses are distinguished from unicast addresses by the value of the high-order octet of the addresses: a value of 0xFF (binary 11111111) identifies an address as a multicast address; any other value identifies an address as a unicast address." -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From john_zenger at yahoo.com Sat Apr 15 23:43:46 2006 From: john_zenger at yahoo.com (John Zenger) Date: Sat, 15 Apr 2006 23:43:46 -0400 Subject: multiple parameters in if statement In-Reply-To: References: Message-ID: <_ZudnWpYp5DpINzZRVn-vA@comcast.com> Try this: if form.get("delete_id","") != "" and form.get("delete_data","") != "" and... the "get" method lets you have an optional second argument that gets returned if the key is not in the dictionary. Also, am I reading your code right? If I enter some fields but not all, you print a message that says "Nothing entered." Nothing? The other thing I'd recommend is stick that long list of fields in a list, and then do operations on that list: fields = ['delete_id', 'delete_date', 'delete_purchasetype', 'delete_price', 'delete_comment'] then to see if all those fields are empty: everything = "" for field in fields: everything += form.get(field,"") if everything == "": print "Absolutely nothing entered!" Kun wrote: > I am trying to make an if-statement that will not do anything and print > 'nothing entered' if there is nothing entered in a form. I have the > following code that does that, however, now even if I enter something > into the form, the code still outputs 'nothing entered'. This violates > the if statement and I am wondering what I did wrong. > > if form.has_key("delete_id") and form["delete_id"].value != "" and > form.has_key("delete_date") and form["delete_date"].value != "" and > form.has_key("delete_purchasetype") and > form["delete_purchasetype"].value != "" and form.has_key("delete_price") > and form["delete_price"].value != "" and form.has_key("delete_comment") > and form["delete_comment"].value != "": > delete_id=form['delete_id'].value > delete_date=form['delete_date'].value > delete_purchasetype=form['delete_purchasetype'].value > delete_price=form['delete_price'].value > delete_comment=form['delete_comment'].value > else: > print "ERROR: Nothing entered!" > raise Exception > From fredrik at pythonware.com Sun Apr 2 18:44:57 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 3 Apr 2006 00:44:57 +0200 Subject: Sending a file to a remote server. References: Message-ID: Jose Carlos Balderas Alberico wrote: > Hi. I posted a message in the list a couple of days ago about sending a file > to a remote SimpleXMLRPCServer. Well. my doubt still remains, so I come to > you again in search of a clearer answer. > > The thing is I want to send a ZIP file to a server, and what I basically do > is enclose the file data into a Binary object by doing something like "data > = Binary(f.read())". Then I call a function in the server, passing the > object as a parameter, and have the server process the same file by doing > something like > > f = open("somefile.zip", 'w') > f.write(binaryObject.data) > > Since I've never programmed server/client before, I've never faced the fact > of sending a file to a remote machine. > > I just want to know if what I've done to send the file is acceptable, and if > you know of a better way to send files to a SimpleXMLRPCServer. since ZIP files can contain arbitrary data, wrapping the data in the Binary wrapper is the only way to you can transfer it over XML-RPC. note, however, that XML-RPC (as well as any other XML-based transport) needs to encode the bytes, which typically adds ~33% overhead. if you're on a slow connection, or your files are really large, plain HTTP transfers (or rsync etc.) are more efficient (but often somewhat harder to implement). From brennan162 at sbcglobal.net Tue Apr 4 17:47:56 2006 From: brennan162 at sbcglobal.net (fxe) Date: Tue, 4 Apr 2006 14:47:56 -0700 (PDT) Subject: tkinter canvas Message-ID: <3753823.post@talk.nabble.com> Hi, I am using tkinter and I have a canvas that with several rectangles drawn on it. The rectangles need to have bindings to move and resize them. No problem here, but I also need to display a grid on the same canvas, for which I am using create_line. My problem is I do not want the grid lines to be able to move and resize . Is this doable or any suggestions on an alternative.Maybe another way to display my grid on top of the canvas? Tom -- View this message in context: http://www.nabble.com/tkinter-canvas-t1395807.html#a3753823 Sent from the Python - python-list forum at Nabble.com. From sturlamolden at yahoo.no Tue Apr 25 18:20:51 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 25 Apr 2006 15:20:51 -0700 Subject: MinGW and Python In-Reply-To: <444E7FC0.9070705@v.loewis.de> References: <1145861223.509630.247350@y43g2000cwc.googlegroups.com> <444C79D7.4060007@v.loewis.de> <1145967287.536182.311970@g10g2000cwb.googlegroups.com> <444E7FC0.9070705@v.loewis.de> Message-ID: <1146003651.424530.300610@j33g2000cwa.googlegroups.com> Martin v. L?wis wrote: > Please believe me: there is currently no build process that > gives the same results as the build process used. It might > be fairly easy to create one, but none exists as of today. I tried to build with MinGW this eveing and it failed. I believe you We need to make a build process for MinGW. From michaeltaft at gmail.com Thu Apr 27 11:02:09 2006 From: michaeltaft at gmail.com (mwt) Date: 27 Apr 2006 08:02:09 -0700 Subject: urllib.urlopen() with pages that requires cookies. In-Reply-To: References: Message-ID: <1146150129.077680.266490@y43g2000cwc.googlegroups.com> Fredrik Lundh wrote: > ?yvind ?stlund wrote: > > > I am trying to visit a limited amount of web pages that requires cookies. I > > will get redirected if my application does not handle them. I am using > > urllib.urlopen() to visit the pages right now. And I need a push in the > > right direction to find out how to deal with pages that requires cookies. > > Anyone have any idea how to go about this? > > use urllib2 and cookielib. here's an outline: > > import urllib2, cookielib > > # set things up > jar = cookielib.CookieJar() > handler = urllib2.HTTPCookieProcessor(jar) > opener = urllib2.build_opener(handler) > urllib2.install_opener(opener) > > data = urllib2.urlopen(someurl).read() > > # ... > > data = urllib2.urlopen(someotherurl).read() > > # ... > > # dump cookie jar contents (for debugging) > for cookie in jar: > print cookie > > How would this outline be changed/expanded if it also needed to handle basic authentication? From ccurvey at gmail.com Tue Apr 4 10:28:23 2006 From: ccurvey at gmail.com (Chris Curvey) Date: 4 Apr 2006 07:28:23 -0700 Subject: warning users of problems with logging In-Reply-To: References: <1144155093.493100.232740@i39g2000cwa.googlegroups.com> Message-ID: <1144160903.035607.315440@j33g2000cwa.googlegroups.com> So it is. Great! From g.brandl-nospam at gmx.net Wed Apr 12 11:38:02 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Wed, 12 Apr 2006 17:38:02 +0200 Subject: just one more question about the python challenge In-Reply-To: References: Message-ID: John Salerno wrote: > Sorry to post here about this again, but the hint forums are dead, and > the hints that are already there are absolutely no help (mostly it's > just people saying they are stuck, then responding to themselves saying > the figured it out! not to mention that most of the hints require > getting past a certain point in the puzzle before they make sense, and > i'm just clueless). > > Anyway, I'm on level 12 and I not only don't know what to do, but I just > don't care at this point to work with images anymore. I'd still like to > read a description of what to do, if one exists somewhere (can't find > one at all, though), but at this point I'd be happy with the next URL so > I can just move on. I've been stagnating for a few days and I need to > use Python again! :) Have you found the file? You'll have to distribute that file bytewise in 5 "piles". Georg From http Thu Apr 13 11:41:31 2006 From: http (Paul Rubin) Date: 13 Apr 2006 08:41:31 -0700 Subject: New Karrigel page in Wikipedia References: <1144867025.095969.92870@e56g2000cwe.googlegroups.com> <9afea2ac0604130644t734a5034l717da793fec0e017@mail.gmail.com> <1144942378.521619.238210@u72g2000cwu.googlegroups.com> Message-ID: <7xpsjlfpp0.fsf@ruckus.brouhaha.com> "Pierre Quentel" writes: > For http://foo.example.com/app1 the server will search for an index > file in this directory and serve it. You can also specify the script > you want : http://foo.example.com/app1/default.py. Same thing for app2 > of course. Absolutely no need to start two instances of the server on > different ports But they're the same Python interpreter and so there's no protection between one application and another, right? That might be ok for a single user running multiple apps, but think of PHP hosting farms that have thousands of users with separate virtual hosts. It would be disastrous if they could see each others' data. From steven.bethard at gmail.com Thu Apr 13 11:39:28 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 13 Apr 2006 09:39:28 -0600 Subject: list.clear() missing?!? In-Reply-To: <1144870852.886477.238570@u72g2000cwu.googlegroups.com> References: <1144767680.583085.310160@v46g2000cwv.googlegroups.com> <1144792144.168802.146310@i39g2000cwa.googlegroups.com> <1144870852.886477.238570@u72g2000cwu.googlegroups.com> Message-ID: Raymond Hettinger wrote: > [Steven Bethard] >> I think these are all good reasons for adding a clear method, but being >> that it has been so hotly contended in the past, I don't think it will >> get added without a PEP. Anyone out there willing to take out the best >> examples from this thread and turn it into a PEP? > > Something this small doesn't need a PEP. I'll just send a note to > Guido asking for a pronouncement. Thanks. It'd be nice to have something to refer to the next time this comes up. > Here's a draft list of pros and cons (any changes or suggestions are > welcome): > > Pros: > ----- > > * s.clear() is more obvious in intent > > * easier to figure-out, look-up, and remember than either s[:]=[] or > del s[:] > > * parallels the api for dicts, sets, and deques (increasing the > expecation that lists will too) > > * the existing alternatives are a bit perlish > I'd snip the one below. It doesn't really contribute anything, and was sarcastic in the first place. ;) > * the OP is shocked, SHOCKED that python got by for 16 years without > list.clear() > > > Cons: > ----- > > * makes the api fatter (there are already two ways to do it) > > * expanding the api makes it more difficult to write classes that can > be polymorphically substituted for lists > > * learning slices is basic to the language (this lesson shouldn't be > skipped) > > * while there are valid use cases for re-using lists, the technique is > already overused for unsuccessful attempts to micro-optimize (creating > new lists is surprisingly fast) > In fairness, if we're going to drop the "SHOCKED" comment, we should drop the first two clauses of the point below (but the "relevant idiom" part is clearly a good point). > * the request is inane, the underlying problem is trivial, and the > relevant idiom is fundamental (api expansions should be saved for rich > new functionality and not become cluttered with infrequently used > redundant entries) Other than those minor edits, I think you've pretty much gotten everything. I look forward to a pronouncement. Thanks again! STeVe From xah at xahlee.org Wed Apr 19 18:50:16 2006 From: xah at xahlee.org (Xah Lee) Date: 19 Apr 2006 15:50:16 -0700 Subject: Generating Thumbnail Images of a Photo Gallery In-Reply-To: <1145486179.679980.172310@i39g2000cwa.googlegroups.com> References: <1145486179.679980.172310@i39g2000cwa.googlegroups.com> Message-ID: <1145487016.597440.277170@v46g2000cwv.googlegroups.com> The Python code is archived at: http://xahlee.org/perl-python/tn_gen.html Xah xah at xahlee.org ? http://xahlee.org/ Xah Lee wrote: > The following is a program to generate thumbnail images for a website. > Useful, if you want to do that. > > It is used to generate the thumbnails for my ?Banners, Damsels, and > Mores? project gallery. ( > http://xahlee.org/Periodic_dosage_dir/lanci/lanci.html ) > > Comments and versions in other lang welcome. From nobody at 127.0.0.1 Thu Apr 27 15:22:23 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Thu, 27 Apr 2006 19:22:23 GMT Subject: OOP techniques in Python References: <1146158190.320947.108480@t31g2000cwb.googlegroups.com> Message-ID: Panos Laganakos wrote: > i.e. we usually define private properties and provide public functions > to access them, in the form of: > get { ... } set { ... } > > Should we do the same in Python: > Or there's no point in doing so? > > Some other techniques come to mind, but I think that Python tends to > allow the programmer to access stuff he wants even though he shouldn't > or in the form of a dict or list, rather than a method to do so. There's no point. Private access can only be advisory anyway -- there are ways around it in every language. Convention serves just as well, people know that touching _foo is done at their own risk. It's not creating extra hoops to jump through the few times you really do need to touch a private var. Others already mentioned how to transparently change attributes to properties. If you're worried about enforcing restrictions in your code base, get a lint checker to flag any expression of the form name._foo where name isn't 'self'. Yes you can still access _foo other ways, but you'll never get perfect enforcement anyway. Maybe the extra step will make you think twice, if that's what you want (and it seems to be). From peter at engcorp.com Mon Apr 10 11:08:10 2006 From: peter at engcorp.com (Peter Hansen) Date: Mon, 10 Apr 2006 11:08:10 -0400 Subject: Query : sys.excepthook exception in Python In-Reply-To: <6C11F971A507DF4B951EA4153880BDFA031736EA@inblrm999msx.in002.siemens.net> References: <6C11F971A507DF4B951EA4153880BDFA031736EA@inblrm999msx.in002.siemens.net> Message-ID: Pramod, TK wrote: > Sometimes during execution of python scripts below mentioned error > string is displayed on the console. > > *"Unhandled exception in thread started by Error in sys.excepthook: * > *Original exception was:"* > > The scripts are not terminated, they continue to execute normally. Are you certain they are not terminated? I've only ever seen this when the entire application was shutting down, and "daemon" threads which were still running (as they do right up until almost the moment the process exits) are going nuts because of the shutdown/cleanup processing of the interpreter. (The key item is that at one stage the interpreter walks through all loaded modules, rebinding all global names in each one to None, and this causes havoc in most code. The exceptions that are raised cannot be displayed successfully either, for the same reason, resulting in what you see above.) I've also seen this in CherryPy in "development" mode, because it is shutting down and restarting, so although it doesn't look like it terminated, in effect the problem is the same. -Peter From phil_nospam_schmidt at yahoo.com Sun Apr 30 22:55:35 2006 From: phil_nospam_schmidt at yahoo.com (phil_nospam_schmidt at yahoo.com) Date: 30 Apr 2006 19:55:35 -0700 Subject: How to prevent this from happening? Message-ID: <1146452135.108199.109180@e56g2000cwe.googlegroups.com> Regarding this expression: 1 << x I had a bug in my code that made x become Very Large - much larger than I had intended. This caused Python, and my PC, to lock up tight as a drum, and it appeared that the Python task (Windows XP) was happily and rapidly consuming all available virtual memory. Presumably, Python was trying to create a really really long integer, just as I had asked it. Is there a way to put a limit on Python, much like there is a stack limit, so that this sort of thing can't get out of hand? From paddy3118 at netscape.net Mon Apr 3 17:09:37 2006 From: paddy3118 at netscape.net (Paddy) Date: 3 Apr 2006 14:09:37 -0700 Subject: overloading constructor in python? In-Reply-To: <1144092500.618489.204740@e56g2000cwe.googlegroups.com> References: <1144092500.618489.204740@e56g2000cwe.googlegroups.com> Message-ID: <1144098577.732202.314090@t31g2000cwb.googlegroups.com> I guess in python we use two idioms to cover most of the uses of mulltiple constructors: 1) Duck typing were for example if you do: class C1(object): def __init__(self, n): n = float(n) n could be an integer, a floating point number,, or a string representing a float. 2) Default values to parameters: class C2(object): def __init__(self, x=None, y=None, s=""): pass C2 can be initialised with any one, two, three, or zero arguments; those not given would take the default values shown to the right of the equals sign above. - Cheers, Paddy. -- Signs of spring here in the west-country. From danmcleran at yahoo.com Fri Apr 21 11:19:55 2006 From: danmcleran at yahoo.com (danmcleran at yahoo.com) Date: 21 Apr 2006 08:19:55 -0700 Subject: how to append to a list twice? In-Reply-To: References: Message-ID: <1145632795.489980.138620@e56g2000cwe.googlegroups.com> Not sure if this is simpler or better, but here's a way to do it with a generator: value = 100 count = 0 def valueGen(): global value global count while(value >= 0): if(value == 100): yield value value -= 1 else: if(count & 1): yield value else: yield value value -= 1 count = count + 1 series = [] gen = valueGen() for item in gen: print item series.append(item) print series From eddie at holyrood.ed.ac.uk Mon Apr 3 14:36:22 2006 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Mon, 3 Apr 2006 18:36:22 +0000 (UTC) Subject: String pattern matching References: <1143888648.234963.326000@j33g2000cwa.googlegroups.com> <4431571b$1_3@newspeer2.tds.net> Message-ID: Kent Johnson writes: >Eddie Corns wrote: >> If I get time I'll try to get this working in Sam Wilmott's Python pattern >> matching library. >> >> What fun! >Cool! I have to get in on the fun :-) >This program uses Sam Wilmott's library to find one solution. It is a >simple translation of your program above. I couldn't figure out how to >get multiple solutions. Nice! FWIW, import string from patterns_b import * # investigate captured text and force a failure for backtracking. # A bit clumsy perhaps! passing a lambda would be more elegant. class DumpP (Pattern): def Match (self, subject): print print 'v =', subject['v'] print 'w =', subject['w'] print 'x =', subject['x'] print 'y =', subject['y'] print 'z =', subject['z'] if 1 == 2: yield None subject = MatchingInput ('/abcaaab/abca/eeabcac/') Letters = AnyOfP(string.letters)[1:] while True: subject ^ FenceP() & IsP('/') & Letters >> 'x' & Letters >> 'y' & Letters >> 'z' & IsP('/') \ & AnotherP('x') & AnotherP('y') & IsP('/') \ & Letters >> 'v' & AnotherP('x') & Letters >> 'w' & IsP('/') & DumpP() Not sure if it's supposed to exit in quite the way it does. With a more compact notation, I think this beats regexs for many uses especially when dealing with end users. Note: if anyone else plays with this interesting pattern library, note there are a couple of small bugs in it. Eddie From fredrik at pythonware.com Wed Apr 26 09:57:08 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 26 Apr 2006 15:57:08 +0200 Subject: MinGW and Python References: <1145861223.509630.247350@y43g2000cwc.googlegroups.com><444C79D7.4060007@v.loewis.de><1145968496.649214.100040@i40g2000cwc.googlegroups.com><1hec9xh.m7rzefh64am3N%aleaxit@yahoo.com> Message-ID: Neal Becker wrote: >> What I did just post on another thread over the last couple of days is >> about MacOSX, which also uses gcc: 14% faster pybench using Python 2.4.3 >> under Win2000 under Parallels Workstation beta, compared to 2.4.3 >> Universal directly on MacOSX -- the standard build of 2.4.3 in either >> cause, i.e., the one built with MS compilers on Windows, vs the one >> built with Apple's gcc on MacOSX. > Please when quoting such benchmarks include gcc version. gcc >= 4.1 is > supposed to have a lot of performance improvements. This is the current > release. Since mingw is usually current, I haven't checked, but they may > be using 4.1 now. does "the standard build of 2.4.3 in either case" do you have trouble understanding ? (what makes you think that 2.4.3 for windows is compiled with the best possible compiler for the windows environment?) From duncan.booth at invalid.invalid Tue Apr 25 07:29:22 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 25 Apr 2006 11:29:22 GMT Subject: OOP / language design question References: <1145961248.794496.80220@j33g2000cwa.googlegroups.com> <1145963311.348482.15080@i40g2000cwc.googlegroups.com> Message-ID: cctv.star at gmail.com wrote: > Heiko Wundram wrote: >> Because sometimes you don't want to call the base classes constructors? > Sounds strange to me at the moment, but I'll try to adjust to this > thought. It makes sense in more static languages such as C++. The base class is initialised by the constructor, so you have to do everything possible to ensure that initialisation is done before you actually try to use any part of the base class. Weird things can still happen in C++ if you start calling methods too soon (e.g. to calculate some of the base constructor's parameters): you can find uninitialised member variables and you might not get exactly the virtual methods you expected. Python is more laid back about these things. The object itself already exists when __init__ is first called. It already has a type, which (unlike C++) isn't going to change part way through. All that is missing are a few attributes, and if you try to access them too soon you'll get an exception rather than a random value. It makes sense therefore to give the programmer the scope to override the expected sequence of initialisation for those rare cases where it actually matters. The programmer also gets enough scope to shoot themselves in the foot, but Python programmers are expected to be intelligent enough not to do that accidentally. Usually though, if a subclass doesn't immediately call the base class constructors as the first thing it does in __init__ it indicates poor code and should be refactored. BTW, the same arguments apply to destructors: if you have a __del__ method and need to call the base __del__ methods you have to do that manually as well. From michaeltaft at gmail.com Thu Apr 13 13:35:26 2006 From: michaeltaft at gmail.com (mwt) Date: 13 Apr 2006 10:35:26 -0700 Subject: Tkinter vs PyGTK In-Reply-To: <1144948018.313278.150210@z34g2000cwc.googlegroups.com> References: <1144825422.167548.153860@z34g2000cwc.googlegroups.com> <1144826842.238389.63170@t31g2000cwb.googlegroups.com> <7xfykjmd9c.fsf@ruckus.brouhaha.com> <1144829749.490901.16830@v46g2000cwv.googlegroups.com> <7xbqv7mas8.fsf@ruckus.brouhaha.com> <1144848267.412008.257230@z34g2000cwc.googlegroups.com> <1144852602.826618.124620@i39g2000cwa.googlegroups.com> <1144948018.313278.150210@z34g2000cwc.googlegroups.com> Message-ID: <1144949726.285523.187050@j33g2000cwa.googlegroups.com> I've had a good experience with Pygtk. I made a small app called "Protein Think" that monitors a folding at home client. The front end is extremely simple - basically a notebook with five small pages. It runs well and was a breeze to create. Looks much better than Tkinter, if that matters at all to you. From andrew.mccall at gmail.com Mon Apr 10 05:15:41 2006 From: andrew.mccall at gmail.com (Andrew McCall) Date: 10 Apr 2006 02:15:41 -0700 Subject: Giving your C/C++ Application a Python Command Line... Message-ID: <1144660541.801879.87450@e56g2000cwe.googlegroups.com> Hi Folks, I am building an application under multiple OS's, and I wanted to give my application For example, the test application I am working on is a calculator and I would like to have a menu in the GUI option to open a command line where you can use Python commands to perfom the functions of the application within the Python command line. For example, if I wanted to clear the display or display the about screen I would be able type the command in the Python coimmand line. To do this I think I need to embed Python in my application, and then expose my C/C++ functions to Python. I have read the documents on embedding Python and I can give my application a command line, but I am having issues exposing my C/C++ functions to Python. Does anyone know of any tutorials or example code that show how to do this? Thanks, Andrew McCall From paddy3118 at netscape.net Thu Apr 6 02:40:28 2006 From: paddy3118 at netscape.net (Paddy) Date: 5 Apr 2006 23:40:28 -0700 Subject: pre-PEP: The create statement In-Reply-To: <59Wdnbd8EazRCqnZnZ2dnUVZ_vudnZ2d@comcast.com> References: <59Wdnbd8EazRCqnZnZ2dnUVZ_vudnZ2d@comcast.com> Message-ID: <1144305628.618445.202920@e56g2000cwe.googlegroups.com> I wonder if the resulting code would look like Python. It seems a great way to unify how things are defined, but I would not want to mix the syntax with the current style. - Pad. From robert.kern at gmail.com Thu Apr 13 08:18:53 2006 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 13 Apr 2006 07:18:53 -0500 Subject: Why new Python 2.5 feature "class C()" return old-style class ? In-Reply-To: References: <1144752553.305591.88050@j33g2000cwa.googlegroups.com> <443bbdbe$0$15517$626a54ce@news.free.fr> <443c22d1$0$11341$636a55ce@news.free.fr> Message-ID: Petr Prikryl wrote: > "Aahz" wrote... > >>Bruno Desthuilliers wrote: >> >>>Aahz a ?crit : > > [...] > >>>>>Please repeat this 101 times each morning: >>>>>"thou shall not use old-style classes for they are deprecated". >>>> >>>>Classic classes are *NOT* deprecated. >>> >>>Perhaps not *officially* yet... >> >>Not even unofficially. The point at which we have deprecation is when >>PEP8 gets changed to say that new-style classes are required for >>contributions. > > My question: Could the old classes be treated in > a new Python treated as new classes with "implicit" > base object? (I know the Zen... ;-) > > Example: I use usually a very simple classes. When I add > "(object)" to my class definitions, the code continues to > works fine -- plus I have new features to use. > Why this cannot be done automatically? What could > be broken in the old code if it was threated so? Method resolution order in class hierarchies that have multiple inheritance. -- Robert Kern robert.kern at gmail.com "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From raims at dot.com Sun Apr 16 20:15:26 2006 From: raims at dot.com (Lawrence Oluyede) Date: Mon, 17 Apr 2006 02:15:26 +0200 Subject: Upgrading and modules References: <1145023656.353186.114000@z34g2000cwc.googlegroups.com> Message-ID: <87psjhawgx.fsf@voodoo.myself> Brian Elmegaard writes: > I don't it includes every possible module, e.g., py2exe, ctypes, > mysqldb, wxpython... Right but since Python doesn't have a full-integrated central packaging (despite the ongoing Pypi project and Eby's efforts in setuptools) you have to do it manually :) How many modules do you really use? It's a matter of minutes. -- Lawrence - http://www.oluyede.org/blog "Nothing is more dangerous than an idea if it's the only one you have" - E. A. Chartier From adam.deprince at gmail.com Mon Apr 3 10:37:19 2006 From: adam.deprince at gmail.com (Adam DePrince) Date: Mon, 03 Apr 2006 10:37:19 -0400 Subject: Newbie: splitting dictionary definition across two .py files In-Reply-To: <1143837982.398448.229550@u72g2000cwu.googlegroups.com> References: <1143766251.793448.191380@i40g2000cwc.googlegroups.com> <1143837982.398448.229550@u72g2000cwu.googlegroups.com> Message-ID: <1144075039.3136.33.camel@localhost.localdomain> On Fri, 2006-03-31 at 12:46 -0800, Karthik Gurusamy wrote: > Ben Finney wrote: > > kar1107 at gmail.com writes: > > > > > I'm fairly new to python. I like to define a big dictionary in two > > > files and use it my main file, build.py > > > > > > I want the definition to go into build_cfg.py and build_cfg_static.py. > > > > That sounds like a very confusing architecture, and smells very much > > like some kind of premature optimisation. What leads you to that > > design? It's very likely a better design can be suggested to meet your > > actual requirements. > > > I work in a source tree of 100s of .c files. The make file builds the > various .o files from the .c files. It takes a while to finish on the > first run. When I make changes to a .c file, I need to compile to get > the .o and also quickly fix any compilation errors. I don't want to > use the make infrastructure, as it takes a while to resolve the > dependencies. Dependencies for 100 files? - Adam From steve at holdenweb.com Sun Apr 2 09:08:25 2006 From: steve at holdenweb.com (Steve Holden) Date: Sun, 02 Apr 2006 09:08:25 -0400 Subject: RELEASED Python 2.4.3, release candidate 1 In-Reply-To: <1143180905.948803.38490@i40g2000cwc.googlegroups.com> References: <1143180905.948803.38490@i40g2000cwc.googlegroups.com> Message-ID: <442FCCC9.8080300@holdenweb.com> Paddy wrote: > I just Googled and found the Python-Dev thread 'About "Coverity Study > Ranks LAMP Code Quality" '. I was heartened by the type of issues > raised in the discussion - it leaves me content with whats > 'under-the-hood' in Python. > > You maintainers don't seem to bang your own drum, which is a good > thing, but since I'm not a maintainer, I'd just like to roll out the > drums (http://www.yakudo.com/) and shout > > THANKS GUYS - IT'S APPRECIATED! > > (boy am I gonna get it for this post :-) > i presume you must have been trying to imply that your significant other would cause problems if they discovered you had been spending time on comp.lang.python. You can see by the enormous number of posts following your up and complaining about your shouted thanks that nobody else is as grateful to the developers as you are. [For those who read this out of context: not one single complaint was raised about Paddy's shouted thanks in the week following his post. This message should be read with irony sensors fully activated]. The thing about developers is, you tell them how wonderful they are, and how much you appreciate what they do, pay them large salaries and give them pleasant offices, then the next thing you know you have Java to program in and they are telling you that you have to change your style and do things their way. Much better to keep them in a dark cellar and throw them the occasional crust of stale bread. That way they are pathetically grateful to meet someone who'll even consider using their code. Keeps the power semantics right - see http://www.wussu.com/humour/semantic.htm regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd www.holdenweb.com Love me, love my blog holdenweb.blogspot.com From kent at kentsjohnson.com Tue Apr 4 09:54:22 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Tue, 04 Apr 2006 09:54:22 -0400 Subject: scraping nested tables with BeautifulSoup In-Reply-To: <1144142334.695498.293650@u72g2000cwu.googlegroups.com> References: <1144142334.695498.293650@u72g2000cwu.googlegroups.com> Message-ID: <4432753a$1_2@newspeer2.tds.net> Gonzillaaa at gmail.com wrote: > I'm trying to get the data on the "Central London Property Price Guide" > box at the left hand side of this page > http://www.findaproperty.com/regi0018.html > > I have managed to get the data :) but when I start looking for tables I > only get tables of depth 1 how do I go about accessing inner tables? > same happens for links... > > this is what I've go so far > > import sys > from urllib import urlopen > from BeautifulSoup import BeautifulSoup > > data = urlopen('http://www.findaproperty.com/regi0018.html').read() > soup = BeautifulSoup(data) > > for tables in soup('table'): > table = tables('table') > if not table: continue > print table #this returns only 1 table There's something fishy here. soup('table') should yield all the tables in the document, even nested ones. For example, this program: data = '''
Stuff
''' from BeautifulSoup import BeautifulSoup as BS soup = BS(data) for table in soup('table'): print table.get('width') prints: 100% 150 Another tidbit - if I open the page in Firefox and save it, then open that file into BeautifulSoup, it finds 25 tables and this code finds the table you want: from BeautifulSoup import BeautifulSoup data2 = open('regi0018-firefox.html') soup = BeautifulSoup(data2) print len(soup('table')) priceGuide = soup('table', dict(bgcolor="#e0f0f8", border="0", cellpadding="2", cellspacing="2", width="150"))[1] print priceGuide.tr prints: 25

Central London Property Price Guide
", record[col], "", str(record[col]).replace("00:00:00.0", ""), " > If it's possible/plausible that other fields might have such a value > reasonably, then you'd want to do a check, something like > > > THEDATECOL = 42 > for col in range(0, numcols): > foo = record[col] > if col == THEDATECOL: > foo = foo.replace("00:00:00.00", "") > print "%s%s%s